@openid4vc/openid4vci 0.3.0-alpha-20250922085649 → 0.3.0-alpha-20251017082202

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,2615 +1,1959 @@
1
- // src/credential-offer/credential-offer.ts
2
- import {
3
- InvalidFetchResponseError,
4
- Oauth2Error,
5
- authorizationCodeGrantIdentifier,
6
- getAuthorizationServerMetadataFromList,
7
- preAuthorizedCodeGrantIdentifier as preAuthorizedCodeGrantIdentifier2
8
- } from "@openid4vc/oauth2";
9
- import {
10
- ContentType,
11
- URL,
12
- URLSearchParams,
13
- ValidationError,
14
- createZodFetcher,
15
- encodeToBase64Url,
16
- getQueryParams,
17
- objectToQueryParams,
18
- parseWithErrorHandling
19
- } from "@openid4vc/utils";
1
+ import { ContentType, URL, URLSearchParams, ValidationError, arrayEqualsIgnoreOrder, createZodFetcher, dateToSeconds, encodeToBase64Url, formatZodError, getGlobalConfig, getQueryParams, isResponseContentType, joinUriParts, objectToQueryParams, parseWithErrorHandling, setGlobalConfig, zHttpsUrl, zInteger, zIs } from "@openid4vc/utils";
2
+ import { InvalidFetchResponseError, Oauth2AuthorizationServer, Oauth2Client, Oauth2ClientAuthorizationChallengeError, Oauth2Error, Oauth2ErrorCodes, Oauth2JwtVerificationError, Oauth2ServerErrorResponseError, authorizationCodeGrantIdentifier, createClientAttestationJwt, decodeJwt, fetchAuthorizationServerMetadata, fetchWellKnownMetadata, getAuthorizationServerMetadataFromList, isJwkInSet, jwtHeaderFromJwtSigner, jwtSignerFromJwt, preAuthorizedCodeGrantIdentifier, resourceRequest, verifyJwt, zAuthorizationServerMetadata, zCompactJwt, zJwk, zJwtHeader, zJwtPayload } from "@openid4vc/oauth2";
3
+ import z from "zod";
20
4
 
21
- // src/version.ts
22
- var Openid4vciDraftVersion = /* @__PURE__ */ ((Openid4vciDraftVersion2) => {
23
- Openid4vciDraftVersion2["Draft16"] = "Draft16";
24
- Openid4vciDraftVersion2["Draft15"] = "Draft15";
25
- Openid4vciDraftVersion2["Draft14"] = "Draft14";
26
- Openid4vciDraftVersion2["Draft11"] = "Draft11";
27
- return Openid4vciDraftVersion2;
28
- })(Openid4vciDraftVersion || {});
5
+ //#region src/version.ts
6
+ let Openid4vciDraftVersion = /* @__PURE__ */ function(Openid4vciDraftVersion$1) {
7
+ Openid4vciDraftVersion$1["Draft16"] = "Draft16";
8
+ Openid4vciDraftVersion$1["Draft15"] = "Draft15";
9
+ Openid4vciDraftVersion$1["Draft14"] = "Draft14";
10
+ Openid4vciDraftVersion$1["Draft11"] = "Draft11";
11
+ return Openid4vciDraftVersion$1;
12
+ }({});
29
13
 
30
- // src/credential-offer/z-credential-offer.ts
31
- import {
32
- preAuthorizedCodeGrantIdentifier
33
- } from "@openid4vc/oauth2";
34
- import { zHttpsUrl } from "@openid4vc/utils";
35
- import z from "zod";
36
- var zTxCode = z.object({
37
- input_mode: z.union([z.literal("numeric"), z.literal("text")]).optional(),
38
- length: z.number().int().optional(),
39
- description: z.string().max(300).optional()
14
+ //#endregion
15
+ //#region src/credential-offer/z-credential-offer.ts
16
+ const zTxCode = z.object({
17
+ input_mode: z.union([z.literal("numeric"), z.literal("text")]).optional(),
18
+ length: z.number().int().optional(),
19
+ description: z.string().max(300).optional()
40
20
  }).passthrough();
41
- var zCredentialOfferGrants = z.object({
42
- authorization_code: z.object({
43
- issuer_state: z.string().optional(),
44
- authorization_server: zHttpsUrl.optional()
45
- }).passthrough().optional(),
46
- [preAuthorizedCodeGrantIdentifier]: z.object({
47
- "pre-authorized_code": z.string(),
48
- tx_code: zTxCode.optional(),
49
- authorization_server: zHttpsUrl.optional()
50
- }).passthrough().optional()
21
+ const zCredentialOfferGrants = z.object({
22
+ authorization_code: z.object({
23
+ issuer_state: z.string().optional(),
24
+ authorization_server: zHttpsUrl.optional()
25
+ }).passthrough().optional(),
26
+ [preAuthorizedCodeGrantIdentifier]: z.object({
27
+ "pre-authorized_code": z.string(),
28
+ tx_code: zTxCode.optional(),
29
+ authorization_server: zHttpsUrl.optional()
30
+ }).passthrough().optional()
51
31
  }).passthrough();
52
- var zCredentialOfferObjectDraft14 = z.object({
53
- credential_issuer: zHttpsUrl,
54
- credential_configuration_ids: z.array(z.string()),
55
- grants: z.optional(zCredentialOfferGrants)
32
+ const zCredentialOfferObjectDraft14 = z.object({
33
+ credential_issuer: zHttpsUrl,
34
+ credential_configuration_ids: z.array(z.string()),
35
+ grants: z.optional(zCredentialOfferGrants)
56
36
  }).passthrough();
57
- var zCredentialOfferObjectDraft11To14 = z.object({
58
- credential_issuer: zHttpsUrl,
59
- // We don't support the inline offer objects from draft 11
60
- credentials: z.array(
61
- z.string({ message: "Only string credential identifiers are supported for draft 11 credential offers" })
62
- ),
63
- grants: z.optional(
64
- z.object({
65
- // Has extra param in draft 14, but doesn't matter for transform purposes
66
- authorization_code: zCredentialOfferGrants.shape.authorization_code,
67
- [preAuthorizedCodeGrantIdentifier]: z.object({
68
- "pre-authorized_code": z.string(),
69
- user_pin_required: z.optional(z.boolean())
70
- }).passthrough().optional()
71
- })
72
- )
73
- }).passthrough().transform(({ credentials, grants, ...rest }) => {
74
- const v14 = {
75
- ...rest,
76
- credential_configuration_ids: credentials
77
- };
78
- if (grants) {
79
- v14.grants = { ...grants };
80
- if (grants[preAuthorizedCodeGrantIdentifier]) {
81
- const { user_pin_required, ...restGrants } = grants[preAuthorizedCodeGrantIdentifier];
82
- v14.grants[preAuthorizedCodeGrantIdentifier] = {
83
- ...restGrants
84
- };
85
- if (user_pin_required) {
86
- v14.grants[preAuthorizedCodeGrantIdentifier].tx_code = {
87
- input_mode: "text"
88
- };
89
- }
90
- }
91
- }
92
- return v14;
37
+ const zCredentialOfferObjectDraft11To14 = z.object({
38
+ credential_issuer: zHttpsUrl,
39
+ credentials: z.array(z.string({ message: "Only string credential identifiers are supported for draft 11 credential offers" })),
40
+ grants: z.optional(z.object({
41
+ authorization_code: zCredentialOfferGrants.shape.authorization_code,
42
+ [preAuthorizedCodeGrantIdentifier]: z.object({
43
+ "pre-authorized_code": z.string(),
44
+ user_pin_required: z.optional(z.boolean())
45
+ }).passthrough().optional()
46
+ }))
47
+ }).passthrough().transform(({ credentials, grants,...rest }) => {
48
+ const v14 = {
49
+ ...rest,
50
+ credential_configuration_ids: credentials
51
+ };
52
+ if (grants) {
53
+ v14.grants = { ...grants };
54
+ if (grants[preAuthorizedCodeGrantIdentifier]) {
55
+ const { user_pin_required,...restGrants } = grants[preAuthorizedCodeGrantIdentifier];
56
+ v14.grants[preAuthorizedCodeGrantIdentifier] = { ...restGrants };
57
+ if (user_pin_required) v14.grants[preAuthorizedCodeGrantIdentifier].tx_code = { input_mode: "text" };
58
+ }
59
+ }
60
+ return v14;
93
61
  }).pipe(zCredentialOfferObjectDraft14);
94
- var zCredentialOfferObject = z.union([
95
- // First prioritize draft 14 (and 13)
96
- zCredentialOfferObjectDraft14,
97
- // Then try parsing draft 11 and transform into draft 14
98
- zCredentialOfferObjectDraft11To14
99
- ]);
62
+ const zCredentialOfferObject = z.union([zCredentialOfferObjectDraft14, zCredentialOfferObjectDraft11To14]);
100
63
 
101
- // src/credential-offer/credential-offer.ts
64
+ //#endregion
65
+ //#region src/credential-offer/credential-offer.ts
66
+ /**
67
+ * Resolve a credential offer, optionally fetching it if the credential_offer_uri is provided.
68
+ */
102
69
  async function resolveCredentialOffer(credentialOffer, options) {
103
- const parsedQueryParams = getQueryParams(credentialOffer);
104
- let credentialOfferParseResult;
105
- if (parsedQueryParams.credential_offer_uri) {
106
- const fetchWithZod = createZodFetcher(options?.fetch);
107
- const { response, result } = await fetchWithZod(
108
- zCredentialOfferObject,
109
- ContentType.Json,
110
- parsedQueryParams.credential_offer_uri
111
- );
112
- if (!response.ok || !result) {
113
- throw new InvalidFetchResponseError(
114
- `Fetching credential offer from '${parsedQueryParams.credential_offer_uri}' resulted in an unsuccessful response with status '${response.status}'`,
115
- await response.clone().text(),
116
- response
117
- );
118
- }
119
- credentialOfferParseResult = result;
120
- } else if (parsedQueryParams.credential_offer) {
121
- let credentialOfferJson;
122
- try {
123
- credentialOfferJson = JSON.parse(decodeURIComponent(parsedQueryParams.credential_offer));
124
- } catch (error) {
125
- throw new Oauth2Error(`Error parsing JSON from 'credential_offer' param in credential offer '${credentialOffer}'`);
126
- }
127
- credentialOfferParseResult = zCredentialOfferObject.safeParse(credentialOfferJson);
128
- } else {
129
- throw new Oauth2Error(`Credential offer did not contain either 'credential_offer' or 'credential_offer_uri' param.`);
130
- }
131
- if (credentialOfferParseResult.error) {
132
- throw new ValidationError(
133
- `Error parsing credential offer in draft 11, 13 or 14 format extracted from credential offer '${credentialOffer}'`,
134
- credentialOfferParseResult.error
135
- );
136
- }
137
- return credentialOfferParseResult.data;
70
+ const parsedQueryParams = getQueryParams(credentialOffer);
71
+ let credentialOfferParseResult;
72
+ if (parsedQueryParams.credential_offer_uri) {
73
+ const { response, result } = await createZodFetcher(options?.fetch)(zCredentialOfferObject, ContentType.Json, parsedQueryParams.credential_offer_uri);
74
+ if (!response.ok || !result) throw new InvalidFetchResponseError(`Fetching credential offer from '${parsedQueryParams.credential_offer_uri}' resulted in an unsuccessful response with status '${response.status}'`, await response.clone().text(), response);
75
+ credentialOfferParseResult = result;
76
+ } else if (parsedQueryParams.credential_offer) {
77
+ let credentialOfferJson;
78
+ try {
79
+ credentialOfferJson = JSON.parse(decodeURIComponent(parsedQueryParams.credential_offer));
80
+ } catch (_error) {
81
+ throw new Oauth2Error(`Error parsing JSON from 'credential_offer' param in credential offer '${credentialOffer}'`);
82
+ }
83
+ credentialOfferParseResult = zCredentialOfferObject.safeParse(credentialOfferJson);
84
+ } else throw new Oauth2Error(`Credential offer did not contain either 'credential_offer' or 'credential_offer_uri' param.`);
85
+ if (credentialOfferParseResult.error) throw new ValidationError(`Error parsing credential offer in draft 11, 13 or 14 format extracted from credential offer '${credentialOffer}'`, credentialOfferParseResult.error);
86
+ return credentialOfferParseResult.data;
138
87
  }
139
88
  function determineAuthorizationServerForCredentialOffer(options) {
140
- const authorizationServers = options.issuerMetadata.credentialIssuer.authorization_servers;
141
- let authorizationServer;
142
- if (options.grantAuthorizationServer) {
143
- authorizationServer = options.grantAuthorizationServer;
144
- if (!authorizationServers) {
145
- throw new Oauth2Error(
146
- `Credential offer grant contains 'authorization_server' with value '${options.grantAuthorizationServer}' but credential issuer metadata does not have an 'authorization_servers' property to match the value against.`
147
- );
148
- }
149
- if (!authorizationServers.includes(authorizationServer)) {
150
- throw new Oauth2Error(
151
- `Credential offer grant contains 'authorization_server' with value '${options.grantAuthorizationServer}' but credential issuer metadata does not include this authorization server. Available 'authorization_server' values are ${authorizationServers.join(", ")}.`
152
- );
153
- }
154
- } else if (!authorizationServers) {
155
- authorizationServer = options.issuerMetadata.credentialIssuer.credential_issuer;
156
- } else {
157
- if (authorizationServers.length === 0) {
158
- throw new Oauth2Error(`Credential issuer metadata has 'authorization_servers' value with length of 0`);
159
- }
160
- if (authorizationServers.length > 1) {
161
- throw new Oauth2Error(
162
- `Credential issuer metadata has 'authorization_server' with multiple entries, but the credential offer grant did not specify which authorization server to use.`
163
- );
164
- }
165
- authorizationServer = authorizationServers[0];
166
- }
167
- return authorizationServer;
89
+ const authorizationServers = options.issuerMetadata.credentialIssuer.authorization_servers;
90
+ let authorizationServer;
91
+ if (options.grantAuthorizationServer) {
92
+ authorizationServer = options.grantAuthorizationServer;
93
+ if (!authorizationServers) throw new Oauth2Error(`Credential offer grant contains 'authorization_server' with value '${options.grantAuthorizationServer}' but credential issuer metadata does not have an 'authorization_servers' property to match the value against.`);
94
+ if (!authorizationServers.includes(authorizationServer)) throw new Oauth2Error(`Credential offer grant contains 'authorization_server' with value '${options.grantAuthorizationServer}' but credential issuer metadata does not include this authorization server. Available 'authorization_server' values are ${authorizationServers.join(", ")}.`);
95
+ } else if (!authorizationServers) authorizationServer = options.issuerMetadata.credentialIssuer.credential_issuer;
96
+ else {
97
+ if (authorizationServers.length === 0) throw new Oauth2Error(`Credential issuer metadata has 'authorization_servers' value with length of 0`);
98
+ if (authorizationServers.length > 1) throw new Oauth2Error(`Credential issuer metadata has 'authorization_server' with multiple entries, but the credential offer grant did not specify which authorization server to use.`);
99
+ authorizationServer = authorizationServers[0];
100
+ }
101
+ return authorizationServer;
168
102
  }
169
103
  async function createCredentialOffer(options) {
170
- const {
171
- [preAuthorizedCodeGrantIdentifier2]: preAuthorizedCodeGrant,
172
- [authorizationCodeGrantIdentifier]: authorizationCodeGrant,
173
- ...restGrants
174
- } = options.grants;
175
- const grants = { ...restGrants };
176
- if (authorizationCodeGrant) {
177
- determineAuthorizationServerForCredentialOffer({
178
- issuerMetadata: options.issuerMetadata,
179
- grantAuthorizationServer: authorizationCodeGrant.authorization_server
180
- });
181
- grants[authorizationCodeGrantIdentifier] = authorizationCodeGrant;
182
- }
183
- if (preAuthorizedCodeGrant) {
184
- determineAuthorizationServerForCredentialOffer({
185
- issuerMetadata: options.issuerMetadata,
186
- grantAuthorizationServer: preAuthorizedCodeGrant.authorization_server
187
- });
188
- grants[preAuthorizedCodeGrantIdentifier2] = {
189
- ...preAuthorizedCodeGrant,
190
- "pre-authorized_code": preAuthorizedCodeGrant["pre-authorized_code"] ?? encodeToBase64Url(await options.callbacks.generateRandom(32))
191
- };
192
- const txCode = grants[preAuthorizedCodeGrantIdentifier2].tx_code;
193
- if (txCode && options.issuerMetadata.originalDraftVersion === "Draft11" /* Draft11 */) {
194
- grants[preAuthorizedCodeGrantIdentifier2].user_pin_required = txCode !== void 0;
195
- }
196
- }
197
- const idsNotInMetadata = options.credentialConfigurationIds.filter(
198
- (id) => options.issuerMetadata.credentialIssuer.credential_configurations_supported[id] === void 0
199
- );
200
- if (idsNotInMetadata.length > 0) {
201
- throw new Oauth2Error(
202
- `Credential configuration ids ${idsNotInMetadata} not found in the credential issuer metadata 'credential_configurations_supported'. Available ids are ${Object.keys(options.issuerMetadata.credentialIssuer.credential_configurations_supported).join(", ")}.`
203
- );
204
- }
205
- const credentialOfferScheme = options.credentialOfferScheme ?? "openid-credential-offer://";
206
- const credentialOfferObject = parseWithErrorHandling(zCredentialOfferObject, {
207
- credential_issuer: options.issuerMetadata.credentialIssuer.credential_issuer,
208
- credential_configuration_ids: options.credentialConfigurationIds,
209
- grants,
210
- ...options.additionalPayload
211
- });
212
- if (options.issuerMetadata.originalDraftVersion === "Draft11" /* Draft11 */) {
213
- credentialOfferObject.credentials = credentialOfferObject.credential_configuration_ids;
214
- }
215
- const url = new URL(credentialOfferScheme);
216
- url.search = `?${new URLSearchParams([
217
- ...url.searchParams.entries(),
218
- ...objectToQueryParams({
219
- credential_offer_uri: options.credentialOfferUri,
220
- // Only add credential_offer is uri is undefined
221
- credential_offer: options.credentialOfferUri ? void 0 : credentialOfferObject
222
- }).entries()
223
- ]).toString()}`;
224
- return {
225
- credentialOffer: url.toString(),
226
- credentialOfferObject
227
- };
104
+ const { [preAuthorizedCodeGrantIdentifier]: preAuthorizedCodeGrant, [authorizationCodeGrantIdentifier]: authorizationCodeGrant,...restGrants } = options.grants;
105
+ const grants = { ...restGrants };
106
+ if (authorizationCodeGrant) {
107
+ determineAuthorizationServerForCredentialOffer({
108
+ issuerMetadata: options.issuerMetadata,
109
+ grantAuthorizationServer: authorizationCodeGrant.authorization_server
110
+ });
111
+ grants[authorizationCodeGrantIdentifier] = authorizationCodeGrant;
112
+ }
113
+ if (preAuthorizedCodeGrant) {
114
+ determineAuthorizationServerForCredentialOffer({
115
+ issuerMetadata: options.issuerMetadata,
116
+ grantAuthorizationServer: preAuthorizedCodeGrant.authorization_server
117
+ });
118
+ grants[preAuthorizedCodeGrantIdentifier] = {
119
+ ...preAuthorizedCodeGrant,
120
+ "pre-authorized_code": preAuthorizedCodeGrant["pre-authorized_code"] ?? encodeToBase64Url(await options.callbacks.generateRandom(32))
121
+ };
122
+ const txCode = grants[preAuthorizedCodeGrantIdentifier].tx_code;
123
+ if (txCode && options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft11) grants[preAuthorizedCodeGrantIdentifier].user_pin_required = txCode !== void 0;
124
+ }
125
+ const idsNotInMetadata = options.credentialConfigurationIds.filter((id) => options.issuerMetadata.credentialIssuer.credential_configurations_supported[id] === void 0);
126
+ if (idsNotInMetadata.length > 0) throw new Oauth2Error(`Credential configuration ids ${idsNotInMetadata} not found in the credential issuer metadata 'credential_configurations_supported'. Available ids are ${Object.keys(options.issuerMetadata.credentialIssuer.credential_configurations_supported).join(", ")}.`);
127
+ const credentialOfferScheme = options.credentialOfferScheme ?? "openid-credential-offer://";
128
+ const credentialOfferObject = parseWithErrorHandling(zCredentialOfferObject, {
129
+ credential_issuer: options.issuerMetadata.credentialIssuer.credential_issuer,
130
+ credential_configuration_ids: options.credentialConfigurationIds,
131
+ grants,
132
+ ...options.additionalPayload
133
+ });
134
+ if (options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft11) credentialOfferObject.credentials = credentialOfferObject.credential_configuration_ids;
135
+ const url = new URL(credentialOfferScheme);
136
+ url.search = `?${new URLSearchParams([...url.searchParams.entries(), ...objectToQueryParams({
137
+ credential_offer_uri: options.credentialOfferUri,
138
+ credential_offer: options.credentialOfferUri ? void 0 : credentialOfferObject
139
+ }).entries()]).toString()}`;
140
+ return {
141
+ credentialOffer: url.toString(),
142
+ credentialOfferObject
143
+ };
228
144
  }
229
145
 
230
- // src/index.ts
231
- import { getGlobalConfig, setGlobalConfig } from "@openid4vc/utils";
232
-
233
- // src/credential-request/credential-request-configurations.ts
234
- import { arrayEqualsIgnoreOrder } from "@openid4vc/utils";
235
-
236
- // src/metadata/credential-issuer/credential-issuer-metadata.ts
237
- import { Oauth2Error as Oauth2Error2, fetchWellKnownMetadata } from "@openid4vc/oauth2";
238
- import { joinUriParts } from "@openid4vc/utils";
239
-
240
- // src/metadata/credential-issuer/z-credential-issuer-metadata.ts
241
- import { zCompactJwt } from "@openid4vc/oauth2";
242
- import { zHttpsUrl as zHttpsUrl2 } from "@openid4vc/utils";
243
- import z13 from "zod";
244
-
245
- // src/formats/credential/mso-mdoc/z-mso-mdoc.ts
246
- import z5 from "zod";
247
-
248
- // src/metadata/credential-issuer/z-claims-description.ts
249
- import z2 from "zod";
250
- var zCredentialConfigurationSupportedClaimsDraft14 = z2.object({
251
- mandatory: z2.boolean().optional(),
252
- value_type: z2.string().optional(),
253
- display: z2.object({
254
- name: z2.string().optional(),
255
- locale: z2.string().optional()
256
- }).passthrough().optional()
146
+ //#endregion
147
+ //#region src/metadata/credential-issuer/z-claims-description.ts
148
+ const zCredentialConfigurationSupportedClaimsDescriptionDraft14 = z.object({
149
+ mandatory: z.boolean().optional(),
150
+ value_type: z.string().optional(),
151
+ display: z.array(z.object({
152
+ name: z.string().optional(),
153
+ locale: z.string().optional()
154
+ }).passthrough()).optional()
257
155
  }).passthrough();
258
- var zClaimsDescriptionPath = z2.array(z2.union([z2.string(), z2.number().int().nonnegative(), z2.null()])).nonempty();
259
- var zMsoMdocClaimsDescriptionPath = z2.tuple([z2.string(), z2.string()], {
260
- message: "mso_mdoc claims description path MUST be an array with exactly two string elements, pointing to the namespace and element identifier within an mdoc credential"
261
- });
262
- var zIssuerMetadataClaimsDescription = z2.object({
263
- path: zClaimsDescriptionPath,
264
- mandatory: z2.boolean().optional(),
265
- display: z2.array(
266
- z2.object({
267
- name: z2.string().optional(),
268
- locale: z2.string().optional()
269
- }).passthrough()
270
- ).optional()
156
+ const zCredentialConfigurationSupportedClaimsDraft14 = z.record(z.string(), z.union([zCredentialConfigurationSupportedClaimsDescriptionDraft14, z.lazy(() => zCredentialConfigurationSupportedClaimsDraft14)]));
157
+ const zClaimsDescriptionPath = z.array(z.union([
158
+ z.string(),
159
+ z.number().int().nonnegative(),
160
+ z.null()
161
+ ])).nonempty();
162
+ const zMsoMdocClaimsDescriptionPath = z.tuple([z.string(), z.string()], { message: "mso_mdoc claims description path MUST be an array with exactly two string elements, pointing to the namespace and element identifier within an mdoc credential" });
163
+ const zIssuerMetadataClaimsDescription = z.object({
164
+ path: zClaimsDescriptionPath,
165
+ mandatory: z.boolean().optional(),
166
+ display: z.array(z.object({
167
+ name: z.string().optional(),
168
+ locale: z.string().optional()
169
+ }).passthrough()).optional()
271
170
  }).passthrough();
272
- var zMsoMdocIssuerMetadataClaimsDescription = zIssuerMetadataClaimsDescription.extend({
273
- path: zMsoMdocClaimsDescriptionPath
274
- });
275
-
276
- // src/metadata/credential-issuer/z-credential-configuration-supported-common.ts
277
- import z4 from "zod";
171
+ const zMsoMdocIssuerMetadataClaimsDescription = zIssuerMetadataClaimsDescription.extend({ path: zMsoMdocClaimsDescriptionPath });
278
172
 
279
- // src/key-attestation/z-key-attestation.ts
280
- import { zJwk, zJwtHeader, zJwtPayload } from "@openid4vc/oauth2";
281
- import { zInteger } from "@openid4vc/utils";
282
- import z3 from "zod";
283
- var zKeyAttestationJwtHeader = z3.object({
284
- ...zJwtHeader.shape,
285
- typ: z3.literal("keyattestation+jwt").or(
286
- // Draft 16
287
- z3.literal("key-attestation+jwt")
288
- )
289
- }).passthrough().refine(({ kid, jwk }) => jwk === void 0 || kid === void 0, {
290
- message: `Both 'jwk' and 'kid' are defined. Only one is allowed`
291
- }).refine(({ trust_chain, kid }) => !trust_chain || !kid, {
292
- message: `When 'trust_chain' is provided, 'kid' is required`
293
- });
294
- var zIso18045 = z3.enum(["iso_18045_high", "iso_18045_moderate", "iso_18045_enhanced-basic", "iso_18045_basic"]);
295
- var zIso18045OrStringArray = z3.array(z3.union([zIso18045, z3.string()]));
296
- var zKeyAttestationJwtPayload = z3.object({
297
- ...zJwtPayload.shape,
298
- iat: zInteger,
299
- attested_keys: z3.array(zJwk),
300
- key_storage: z3.optional(zIso18045OrStringArray),
301
- user_authentication: z3.optional(zIso18045OrStringArray),
302
- certification: z3.optional(z3.string().url())
173
+ //#endregion
174
+ //#region src/key-attestation/z-key-attestation.ts
175
+ const zKeyAttestationJwtHeader = z.object({
176
+ ...zJwtHeader.shape,
177
+ typ: z.literal("keyattestation+jwt").or(z.literal("key-attestation+jwt"))
178
+ }).passthrough().refine(({ kid, jwk }) => jwk === void 0 || kid === void 0, { message: `Both 'jwk' and 'kid' are defined. Only one is allowed` }).refine(({ trust_chain, kid }) => !trust_chain || !kid, { message: `When 'trust_chain' is provided, 'kid' is required` });
179
+ const zIso18045 = z.enum([
180
+ "iso_18045_high",
181
+ "iso_18045_moderate",
182
+ "iso_18045_enhanced-basic",
183
+ "iso_18045_basic"
184
+ ]);
185
+ const zIso18045OrStringArray = z.array(z.union([zIso18045, z.string()]));
186
+ const zKeyAttestationJwtPayload = z.object({
187
+ ...zJwtPayload.shape,
188
+ iat: zInteger,
189
+ attested_keys: z.array(zJwk),
190
+ key_storage: z.optional(zIso18045OrStringArray),
191
+ user_authentication: z.optional(zIso18045OrStringArray),
192
+ certification: z.optional(z.string().url())
303
193
  }).passthrough();
304
- var zKeyAttestationJwtPayloadForUse = (use) => z3.object({
305
- ...zKeyAttestationJwtPayload.shape,
306
- // REQUIRED when used as proof_type.attesation directly
307
- nonce: use === "proof_type.attestation" ? z3.string({
308
- message: `Nonce must be defined when key attestation is used as 'proof_type.attestation' directly`
309
- }) : z3.optional(z3.string()),
310
- // REQUIRED when used within header of proof_type.jwt
311
- exp: use === "proof_type.jwt" ? zInteger : z3.optional(zInteger)
194
+ const zKeyAttestationJwtPayloadForUse = (use) => z.object({
195
+ ...zKeyAttestationJwtPayload.shape,
196
+ nonce: use === "proof_type.attestation" ? z.string({ message: `Nonce must be defined when key attestation is used as 'proof_type.attestation' directly` }) : z.optional(z.string()),
197
+ exp: use === "proof_type.jwt" ? zInteger : z.optional(zInteger)
312
198
  }).passthrough();
313
199
 
314
- // src/metadata/credential-issuer/z-credential-configuration-supported-common.ts
315
- var zCredentialConfigurationSupportedDisplayEntry = z4.object({
316
- name: z4.string(),
317
- locale: z4.string().optional(),
318
- logo: z4.object({
319
- // FIXME: make required again, but need to support draft 11 first
320
- uri: z4.string().optional(),
321
- alt_text: z4.string().optional()
322
- }).passthrough().optional(),
323
- description: z4.string().optional(),
324
- background_color: z4.string().optional(),
325
- background_image: z4.object({
326
- // TODO: should be required, but paradym's metadata is wrong here.
327
- uri: z4.string().optional()
328
- }).passthrough().optional(),
329
- text_color: z4.string().optional()
200
+ //#endregion
201
+ //#region src/metadata/credential-issuer/z-credential-configuration-supported-common.ts
202
+ const zCredentialConfigurationSupportedDisplayEntry = z.object({
203
+ name: z.string(),
204
+ locale: z.string().optional(),
205
+ logo: z.object({
206
+ uri: z.string().optional(),
207
+ alt_text: z.string().optional()
208
+ }).passthrough().optional(),
209
+ description: z.string().optional(),
210
+ background_color: z.string().optional(),
211
+ background_image: z.object({ uri: z.string().optional() }).passthrough().optional(),
212
+ text_color: z.string().optional()
330
213
  }).passthrough();
331
- var zCredentialConfigurationSupportedCommonCredentialMetadata = z4.object({
332
- display: z4.array(zCredentialConfigurationSupportedDisplayEntry).optional()
333
- });
334
- var zCredentialConfigurationSupportedCommon = z4.object({
335
- format: z4.string(),
336
- scope: z4.string().optional(),
337
- cryptographic_binding_methods_supported: z4.array(z4.string()).optional(),
338
- credential_signing_alg_values_supported: z4.array(z4.string()).or(z4.array(z4.number())).optional(),
339
- proof_types_supported: z4.record(
340
- z4.union([z4.literal("jwt"), z4.literal("attestation"), z4.string()]),
341
- z4.object({
342
- proof_signing_alg_values_supported: z4.array(z4.string()),
343
- key_attestations_required: z4.object({
344
- key_storage: zIso18045OrStringArray.optional(),
345
- user_authentication: zIso18045OrStringArray.optional()
346
- }).passthrough().optional()
347
- })
348
- ).optional(),
349
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.optional(),
350
- // For typing purposes. Can be removed once we drop support for draft <= 15.
351
- claims: z4.optional(z4.never())
214
+ const zCredentialConfigurationSupportedCommonCredentialMetadata = z.object({ display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional() });
215
+ const zCredentialConfigurationSupportedCommon = z.object({
216
+ format: z.string(),
217
+ scope: z.string().optional(),
218
+ cryptographic_binding_methods_supported: z.array(z.string()).optional(),
219
+ credential_signing_alg_values_supported: z.array(z.string()).or(z.array(z.number())).optional(),
220
+ proof_types_supported: z.record(z.union([
221
+ z.literal("jwt"),
222
+ z.literal("attestation"),
223
+ z.string()
224
+ ]), z.object({
225
+ proof_signing_alg_values_supported: z.array(z.string()),
226
+ key_attestations_required: z.object({
227
+ key_storage: zIso18045OrStringArray.optional(),
228
+ user_authentication: zIso18045OrStringArray.optional()
229
+ }).passthrough().optional()
230
+ })).optional(),
231
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.optional(),
232
+ claims: z.optional(z.never())
352
233
  }).passthrough();
353
- var zCredentialConfigurationSupportedCommonDraft15 = z4.object({
354
- format: z4.string(),
355
- scope: z4.string().optional(),
356
- cryptographic_binding_methods_supported: z4.array(z4.string()).optional(),
357
- credential_signing_alg_values_supported: z4.array(z4.string()).or(z4.array(z4.number())).optional(),
358
- proof_types_supported: z4.record(
359
- z4.union([z4.literal("jwt"), z4.literal("attestation"), z4.string()]),
360
- z4.object({
361
- proof_signing_alg_values_supported: z4.array(z4.string()),
362
- key_attestations_required: z4.object({
363
- key_storage: zIso18045OrStringArray.optional(),
364
- user_authentication: zIso18045OrStringArray.optional()
365
- }).passthrough().optional()
366
- })
367
- ).optional(),
368
- display: z4.array(zCredentialConfigurationSupportedDisplayEntry).optional(),
369
- // For typing purposes.
370
- credential_metadata: z4.optional(z4.never())
234
+ const zCredentialConfigurationSupportedCommonDraft15 = z.object({
235
+ format: z.string(),
236
+ scope: z.string().optional(),
237
+ cryptographic_binding_methods_supported: z.array(z.string()).optional(),
238
+ credential_signing_alg_values_supported: z.array(z.string()).or(z.array(z.number())).optional(),
239
+ proof_types_supported: z.record(z.union([
240
+ z.literal("jwt"),
241
+ z.literal("attestation"),
242
+ z.string()
243
+ ]), z.object({
244
+ proof_signing_alg_values_supported: z.array(z.string()),
245
+ key_attestations_required: z.object({
246
+ key_storage: zIso18045OrStringArray.optional(),
247
+ user_authentication: zIso18045OrStringArray.optional()
248
+ }).passthrough().optional()
249
+ })).optional(),
250
+ display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional(),
251
+ credential_metadata: z.optional(z.never())
371
252
  }).passthrough();
372
253
 
373
- // src/formats/credential/mso-mdoc/z-mso-mdoc.ts
374
- var zMsoMdocFormatIdentifier = z5.literal("mso_mdoc");
375
- var zMsoMdocCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
376
- format: zMsoMdocFormatIdentifier,
377
- doctype: z5.string(),
378
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
379
- claims: z5.array(zMsoMdocIssuerMetadataClaimsDescription).optional()
380
- }).optional()
254
+ //#endregion
255
+ //#region src/formats/credential/mso-mdoc/z-mso-mdoc.ts
256
+ const zMsoMdocFormatIdentifier = z.literal("mso_mdoc");
257
+ const zMsoMdocCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
258
+ format: zMsoMdocFormatIdentifier,
259
+ doctype: z.string(),
260
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional() }).optional()
381
261
  });
382
- var zMsoMdocCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
383
- format: zMsoMdocFormatIdentifier,
384
- doctype: z5.string(),
385
- claims: z5.array(zMsoMdocIssuerMetadataClaimsDescription).optional()
262
+ const zMsoMdocCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
263
+ format: zMsoMdocFormatIdentifier,
264
+ doctype: z.string(),
265
+ claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional()
386
266
  });
387
- var zMsoMdocCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
388
- format: zMsoMdocFormatIdentifier,
389
- doctype: z5.string(),
390
- claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),
391
- order: z5.optional(z5.array(z5.string()))
267
+ const zMsoMdocCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
268
+ format: zMsoMdocFormatIdentifier,
269
+ doctype: z.string(),
270
+ claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),
271
+ order: z.optional(z.array(z.string()))
392
272
  });
393
- var zMsoMdocCredentialRequestFormatDraft14 = z5.object({
394
- format: zMsoMdocFormatIdentifier,
395
- doctype: z5.string(),
396
- // Format based request is removed in Draft 15, so only old claims syntax supported.
397
- claims: z5.optional(zCredentialConfigurationSupportedClaimsDraft14)
273
+ const zMsoMdocCredentialRequestFormatDraft14 = z.object({
274
+ format: zMsoMdocFormatIdentifier,
275
+ doctype: z.string(),
276
+ claims: zCredentialConfigurationSupportedClaimsDraft14.optional()
398
277
  });
399
278
 
400
- // src/formats/credential/sd-jwt-vc/z-sd-jwt-vc.ts
401
- import z6 from "zod";
402
- var zLegacySdJwtVcFormatIdentifier = z6.literal("vc+sd-jwt");
403
- var zLegacySdJwtVcCredentialIssuerMetadataDraft16 = zCredentialConfigurationSupportedCommon.extend({
404
- vct: z6.string(),
405
- format: zLegacySdJwtVcFormatIdentifier,
406
- order: z6.optional(z6.array(z6.string())),
407
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
408
- claims: z6.array(zCredentialConfigurationSupportedClaimsDraft14).optional()
409
- }).optional(),
410
- credential_definition: z6.optional(z6.never())
279
+ //#endregion
280
+ //#region src/formats/credential/sd-jwt-dc/z-sd-jwt-dc.ts
281
+ const zSdJwtDcFormatIdentifier = z.literal("dc+sd-jwt");
282
+ const zSdJwtDcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
283
+ vct: z.string(),
284
+ format: zSdJwtDcFormatIdentifier,
285
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional()
411
286
  });
412
- var zLegacySdJwtVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
413
- vct: z6.string(),
414
- format: zLegacySdJwtVcFormatIdentifier,
415
- claims: z6.optional(zCredentialConfigurationSupportedClaimsDraft14),
416
- order: z6.optional(z6.array(z6.string())),
417
- credential_definition: z6.optional(z6.never())
418
- });
419
- var zLegacySdJwtVcCredentialRequestFormatDraft14 = z6.object({
420
- format: zLegacySdJwtVcFormatIdentifier,
421
- vct: z6.string(),
422
- claims: z6.optional(zCredentialConfigurationSupportedClaimsDraft14),
423
- credential_definition: z6.optional(z6.never())
287
+ const zSdJwtDcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
288
+ vct: z.string(),
289
+ format: zSdJwtDcFormatIdentifier,
290
+ claims: z.array(zIssuerMetadataClaimsDescription).optional()
424
291
  });
425
292
 
426
- // src/formats/credential/sd-jwt-dc/z-sd-jwt-dc.ts
427
- import z7 from "zod";
428
- var zSdJwtDcFormatIdentifier = z7.literal("dc+sd-jwt");
429
- var zSdJwtDcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
430
- vct: z7.string(),
431
- format: zSdJwtDcFormatIdentifier,
432
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
433
- claims: z7.array(zIssuerMetadataClaimsDescription).optional()
434
- }).optional()
293
+ //#endregion
294
+ //#region src/formats/credential/sd-jwt-vc/z-sd-jwt-vc.ts
295
+ /**
296
+ * @deprecated format has been deprecated in favor of "dc+sd-jwt" since Draft 23
297
+ * of the OpenID for Verifiable Presentations specification. Please update your
298
+ * implementations accordingly.
299
+ */
300
+ const zLegacySdJwtVcFormatIdentifier = z.literal("vc+sd-jwt");
301
+ /**
302
+ * @deprecated format has been deprecated in favor of "dc+sd-jwt" since Draft 23
303
+ * of the OpenID for Verifiable Presentations specification. Please update your
304
+ * implementations accordingly.
305
+ */
306
+ const zLegacySdJwtVcCredentialIssuerMetadataDraft16 = zCredentialConfigurationSupportedCommon.extend({
307
+ vct: z.string(),
308
+ format: zLegacySdJwtVcFormatIdentifier,
309
+ order: z.optional(z.array(z.string())),
310
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional(),
311
+ credential_definition: z.optional(z.never())
435
312
  });
436
- var zSdJwtDcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
437
- vct: z7.string(),
438
- format: zSdJwtDcFormatIdentifier,
439
- claims: z7.array(zIssuerMetadataClaimsDescription).optional()
313
+ /**
314
+ * @deprecated format has been deprecated in favor of "dc+sd-jwt" since Draft 23
315
+ * of the OpenID for Verifiable Presentations specification. Please update your
316
+ * implementations accordingly.
317
+ */
318
+ const zLegacySdJwtVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
319
+ vct: z.string(),
320
+ format: zLegacySdJwtVcFormatIdentifier,
321
+ claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),
322
+ order: z.optional(z.array(z.string())),
323
+ credential_definition: z.optional(z.never())
324
+ });
325
+ /**
326
+ * @deprecated format has been deprecated in favor of "dc+sd-jwt" since Draft 23
327
+ * of the OpenID for Verifiable Presentations specification. Please update your
328
+ * implementations accordingly.
329
+ */
330
+ const zLegacySdJwtVcCredentialRequestFormatDraft14 = z.object({
331
+ format: zLegacySdJwtVcFormatIdentifier,
332
+ vct: z.string(),
333
+ claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),
334
+ credential_definition: z.optional(z.never())
440
335
  });
441
336
 
442
- // src/formats/credential/w3c-vc/z-w3c-ldp-vc.ts
443
- import z9 from "zod";
444
-
445
- // src/formats/credential/w3c-vc/z-w3c-vc-common.ts
446
- import z8 from "zod";
447
- var zCredentialSubjectLeafTypeDraft14 = z8.object({
448
- mandatory: z8.boolean().optional(),
449
- value_type: z8.string().optional(),
450
- display: z8.array(
451
- z8.object({
452
- name: z8.string().optional(),
453
- locale: z8.string().optional()
454
- }).passthrough()
455
- ).optional()
337
+ //#endregion
338
+ //#region src/formats/credential/w3c-vc/z-w3c-vc-common.ts
339
+ const zCredentialSubjectLeafTypeDraft14 = z.object({
340
+ mandatory: z.boolean().optional(),
341
+ value_type: z.string().optional(),
342
+ display: z.array(z.object({
343
+ name: z.string().optional(),
344
+ locale: z.string().optional()
345
+ }).passthrough()).optional()
456
346
  }).passthrough();
457
- var zClaimValueSchemaDraft14 = z8.union([
458
- z8.array(z8.any()),
459
- z8.record(z8.string(), z8.any()),
460
- zCredentialSubjectLeafTypeDraft14
347
+ const zClaimValueSchemaDraft14 = z.union([
348
+ z.array(z.any()),
349
+ z.record(z.string(), z.any()),
350
+ zCredentialSubjectLeafTypeDraft14
461
351
  ]);
462
- var zW3cVcCredentialSubjectDraft14 = z8.record(z8.string(), zClaimValueSchemaDraft14);
463
- var zW3cVcJsonLdCredentialDefinition = z8.object({
464
- "@context": z8.array(z8.string()),
465
- type: z8.array(z8.string()).nonempty()
352
+ const zW3cVcCredentialSubjectDraft14 = z.record(z.string(), zClaimValueSchemaDraft14);
353
+ const zW3cVcJsonLdCredentialDefinition = z.object({
354
+ "@context": z.array(z.string()),
355
+ type: z.array(z.string()).nonempty()
466
356
  }).passthrough();
467
- var zW3cVcJsonLdCredentialDefinitionDraft14 = zW3cVcJsonLdCredentialDefinition.extend({
468
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
469
- });
357
+ const zW3cVcJsonLdCredentialDefinitionDraft14 = zW3cVcJsonLdCredentialDefinition.extend({ credentialSubject: zW3cVcCredentialSubjectDraft14.optional() });
470
358
 
471
- // src/formats/credential/w3c-vc/z-w3c-ldp-vc.ts
472
- var zLdpVcFormatIdentifier = z9.literal("ldp_vc");
473
- var zLdpVcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
474
- format: zLdpVcFormatIdentifier,
475
- credential_definition: zW3cVcJsonLdCredentialDefinition,
476
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
477
- claims: zIssuerMetadataClaimsDescription.optional()
478
- }).optional()
359
+ //#endregion
360
+ //#region src/formats/credential/w3c-vc/z-w3c-jwt-vc-json.ts
361
+ const zJwtVcJsonFormatIdentifier = z.literal("jwt_vc_json");
362
+ const zJwtVcJsonCredentialDefinition = z.object({ type: z.array(z.string()).nonempty() }).passthrough();
363
+ const zJwtVcJsonCredentialDefinitionDraft14 = zJwtVcJsonCredentialDefinition.extend({ credentialSubject: zW3cVcCredentialSubjectDraft14.optional() });
364
+ const zJwtVcJsonCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
365
+ format: zJwtVcJsonFormatIdentifier,
366
+ credential_definition: zJwtVcJsonCredentialDefinition,
367
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional()
479
368
  });
480
- var zLdpVcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
481
- format: zLdpVcFormatIdentifier,
482
- credential_definition: zW3cVcJsonLdCredentialDefinition,
483
- claims: zIssuerMetadataClaimsDescription.optional()
369
+ const zJwtVcJsonCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
370
+ format: zJwtVcJsonFormatIdentifier,
371
+ credential_definition: zJwtVcJsonCredentialDefinition,
372
+ claims: z.array(zIssuerMetadataClaimsDescription).optional()
484
373
  });
485
- var zLdpVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
486
- format: zLdpVcFormatIdentifier,
487
- credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,
488
- order: z9.array(z9.string()).optional()
374
+ const zJwtVcJsonCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
375
+ format: zJwtVcJsonFormatIdentifier,
376
+ credential_definition: zJwtVcJsonCredentialDefinitionDraft14,
377
+ order: z.array(z.string()).optional()
489
378
  });
490
- var zLdpVcCredentialIssuerMetadataDraft11 = z9.object({
491
- order: z9.array(z9.string()).optional(),
492
- format: zLdpVcFormatIdentifier,
493
- // Credential definition was spread on top level instead of a separatey property in v11
494
- // As well as using types instead of type
495
- "@context": z9.array(z9.string()),
496
- types: z9.array(z9.string()),
497
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
379
+ const zJwtVcJsonCredentialIssuerMetadataDraft11 = z.object({
380
+ format: zJwtVcJsonFormatIdentifier,
381
+ order: z.array(z.string()).optional(),
382
+ types: z.array(z.string()),
383
+ credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
498
384
  }).passthrough();
499
- var zLdpVcCredentialIssuerMetadataDraft11To14 = zLdpVcCredentialIssuerMetadataDraft11.transform(
500
- ({ "@context": context, types, credentialSubject, ...rest }) => ({
501
- ...rest,
502
- credential_definition: {
503
- "@context": context,
504
- type: types,
505
- // Prevent weird typing issue with optional vs undefined
506
- ...credentialSubject ? { credentialSubject } : {}
507
- }
508
- })
509
- );
510
- var zLdpVcCredentialIssuerMetadataDraft14To11 = zLdpVcCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({
511
- ...rest,
512
- ...credentialDefinition,
513
- types: type
514
- })).pipe(zLdpVcCredentialIssuerMetadataDraft11);
515
- var zLdpVcCredentialRequestFormatDraft14 = z9.object({
516
- format: zLdpVcFormatIdentifier,
517
- credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14
385
+ const zJwtVcJsonCredentialIssuerMetadataDraft11To14 = zJwtVcJsonCredentialIssuerMetadataDraft11.transform(({ types, credentialSubject,...rest }) => ({
386
+ ...rest,
387
+ credential_definition: {
388
+ type: types,
389
+ ...credentialSubject ? { credentialSubject } : {}
390
+ }
391
+ }));
392
+ const zJwtVcJsonCredentialIssuerMetadataDraft14To11 = zJwtVcJsonCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type,...credentialDefinition },...rest }) => ({
393
+ ...rest,
394
+ types: type,
395
+ ...credentialDefinition
396
+ })).pipe(zJwtVcJsonCredentialIssuerMetadataDraft11);
397
+ const zJwtVcJsonCredentialRequestFormatDraft14 = z.object({
398
+ format: zJwtVcJsonFormatIdentifier,
399
+ credential_definition: zJwtVcJsonCredentialDefinition
518
400
  });
519
- var zLdpVcCredentialRequestDraft11 = z9.object({
520
- format: zLdpVcFormatIdentifier,
521
- credential_definition: z9.object({
522
- "@context": z9.array(z9.string()),
523
- // credential_definition was using types instead of type in v11
524
- types: z9.array(z9.string()),
525
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
526
- })
401
+ const zJwtVcJsonCredentialRequestDraft11 = z.object({
402
+ format: zJwtVcJsonFormatIdentifier,
403
+ types: z.array(z.string()),
404
+ credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14)
527
405
  }).passthrough();
528
- var zLdpVcCredentialRequestDraft11To14 = zLdpVcCredentialRequestDraft11.transform(
529
- ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({
530
- ...rest,
531
- credential_definition: {
532
- ...restCredentialDefinition,
533
- type: types
534
- }
535
- })
536
- );
537
- var zLdpVcCredentialRequestDraft14To11 = zLdpVcCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({
538
- ...rest,
539
- credential_definition: {
540
- ...restCredentialDefinition,
541
- types: type
542
- }
543
- })).pipe(zLdpVcCredentialRequestDraft11);
406
+ const zJwtVcJsonCredentialRequestDraft11To14 = zJwtVcJsonCredentialRequestDraft11.transform(({ types, credentialSubject,...rest }) => {
407
+ return {
408
+ ...rest,
409
+ credential_definition: {
410
+ type: types,
411
+ ...credentialSubject ? { credentialSubject } : {}
412
+ }
413
+ };
414
+ });
415
+ const zJwtVcJsonCredentialRequestDraft14To11 = zJwtVcJsonCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type,...credentialDefinition },...rest }) => ({
416
+ ...rest,
417
+ types: type,
418
+ ...credentialDefinition
419
+ })).pipe(zJwtVcJsonCredentialRequestDraft11);
544
420
 
545
- // src/formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld.ts
546
- import z10 from "zod";
547
- var zJwtVcJsonLdFormatIdentifier = z10.literal("jwt_vc_json-ld");
548
- var zJwtVcJsonLdCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
549
- format: zJwtVcJsonLdFormatIdentifier,
550
- credential_definition: zW3cVcJsonLdCredentialDefinition,
551
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
552
- claims: zIssuerMetadataClaimsDescription.optional()
553
- }).optional()
421
+ //#endregion
422
+ //#region src/formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld.ts
423
+ const zJwtVcJsonLdFormatIdentifier = z.literal("jwt_vc_json-ld");
424
+ const zJwtVcJsonLdCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
425
+ format: zJwtVcJsonLdFormatIdentifier,
426
+ credential_definition: zW3cVcJsonLdCredentialDefinition,
427
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional()
554
428
  });
555
- var zJwtVcJsonLdCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
556
- format: zJwtVcJsonLdFormatIdentifier,
557
- credential_definition: zW3cVcJsonLdCredentialDefinition,
558
- claims: zIssuerMetadataClaimsDescription.optional()
429
+ const zJwtVcJsonLdCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
430
+ format: zJwtVcJsonLdFormatIdentifier,
431
+ credential_definition: zW3cVcJsonLdCredentialDefinition,
432
+ claims: z.array(zIssuerMetadataClaimsDescription).optional()
559
433
  });
560
- var zJwtVcJsonLdCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
561
- format: zJwtVcJsonLdFormatIdentifier,
562
- credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,
563
- order: z10.optional(z10.array(z10.string()))
434
+ const zJwtVcJsonLdCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
435
+ format: zJwtVcJsonLdFormatIdentifier,
436
+ credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,
437
+ order: z.optional(z.array(z.string()))
564
438
  });
565
- var zJwtVcJsonLdCredentialIssuerMetadataDraft11 = z10.object({
566
- order: z10.array(z10.string()).optional(),
567
- format: zJwtVcJsonLdFormatIdentifier,
568
- // Credential definition was spread on top level instead of a separatey property in v11
569
- // As well as using types instead of type
570
- "@context": z10.array(z10.string()),
571
- types: z10.array(z10.string()),
572
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
439
+ const zJwtVcJsonLdCredentialIssuerMetadataDraft11 = z.object({
440
+ order: z.array(z.string()).optional(),
441
+ format: zJwtVcJsonLdFormatIdentifier,
442
+ "@context": z.array(z.string()),
443
+ types: z.array(z.string()),
444
+ credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
573
445
  }).passthrough();
574
- var zJwtVcJsonLdCredentialIssuerMetadataDraft11To14 = zJwtVcJsonLdCredentialIssuerMetadataDraft11.transform(
575
- ({ "@context": context, types, credentialSubject, ...rest }) => ({
576
- ...rest,
577
- credential_definition: {
578
- "@context": context,
579
- type: types,
580
- // Prevent weird typing issue with optional vs undefined
581
- ...credentialSubject ? { credentialSubject } : {}
582
- }
583
- })
584
- );
585
- var zJwtVcJsonLdCredentialIssuerMetadataDraft14To11 = zJwtVcJsonLdCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({
586
- ...rest,
587
- ...credentialDefinition,
588
- types: type
446
+ const zJwtVcJsonLdCredentialIssuerMetadataDraft11To14 = zJwtVcJsonLdCredentialIssuerMetadataDraft11.transform(({ "@context": context, types, credentialSubject,...rest }) => ({
447
+ ...rest,
448
+ credential_definition: {
449
+ "@context": context,
450
+ type: types,
451
+ ...credentialSubject ? { credentialSubject } : {}
452
+ }
453
+ }));
454
+ const zJwtVcJsonLdCredentialIssuerMetadataDraft14To11 = zJwtVcJsonLdCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type,...credentialDefinition },...rest }) => ({
455
+ ...rest,
456
+ ...credentialDefinition,
457
+ types: type
589
458
  })).pipe(zJwtVcJsonLdCredentialIssuerMetadataDraft11);
590
- var zJwtVcJsonLdCredentialRequestFormatDraft14 = z10.object({
591
- format: zJwtVcJsonLdFormatIdentifier,
592
- credential_definition: zW3cVcJsonLdCredentialDefinition
459
+ const zJwtVcJsonLdCredentialRequestFormatDraft14 = z.object({
460
+ format: zJwtVcJsonLdFormatIdentifier,
461
+ credential_definition: zW3cVcJsonLdCredentialDefinition
593
462
  });
594
- var zJwtVcJsonLdCredentialRequestDraft11 = z10.object({
595
- format: zJwtVcJsonLdFormatIdentifier,
596
- credential_definition: z10.object({
597
- "@context": z10.array(z10.string()),
598
- // credential_definition was using types instead of type in v11
599
- types: z10.array(z10.string()),
600
- credentialSubject: z10.optional(zW3cVcCredentialSubjectDraft14)
601
- }).passthrough()
463
+ const zJwtVcJsonLdCredentialRequestDraft11 = z.object({
464
+ format: zJwtVcJsonLdFormatIdentifier,
465
+ credential_definition: z.object({
466
+ "@context": z.array(z.string()),
467
+ types: z.array(z.string()),
468
+ credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14)
469
+ }).passthrough()
602
470
  }).passthrough();
603
- var zJwtVcJsonLdCredentialRequestDraft11To14 = zJwtVcJsonLdCredentialRequestDraft11.transform(
604
- ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({
605
- ...rest,
606
- credential_definition: {
607
- ...restCredentialDefinition,
608
- type: types
609
- }
610
- })
611
- );
612
- var zJwtVcJsonLdCredentialRequestDraft14To11 = zJwtVcJsonLdCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({
613
- ...rest,
614
- credential_definition: {
615
- ...restCredentialDefinition,
616
- types: type
617
- }
471
+ const zJwtVcJsonLdCredentialRequestDraft11To14 = zJwtVcJsonLdCredentialRequestDraft11.transform(({ credential_definition: { types,...restCredentialDefinition },...rest }) => ({
472
+ ...rest,
473
+ credential_definition: {
474
+ ...restCredentialDefinition,
475
+ type: types
476
+ }
477
+ }));
478
+ const zJwtVcJsonLdCredentialRequestDraft14To11 = zJwtVcJsonLdCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type,...restCredentialDefinition },...rest }) => ({
479
+ ...rest,
480
+ credential_definition: {
481
+ ...restCredentialDefinition,
482
+ types: type
483
+ }
618
484
  })).pipe(zJwtVcJsonLdCredentialRequestDraft11);
619
485
 
620
- // src/formats/credential/w3c-vc/z-w3c-jwt-vc-json.ts
621
- import z11 from "zod";
622
- var zJwtVcJsonFormatIdentifier = z11.literal("jwt_vc_json");
623
- var zJwtVcJsonCredentialDefinition = z11.object({
624
- type: z11.array(z11.string()).nonempty()
625
- }).passthrough();
626
- var zJwtVcJsonCredentialDefinitionDraft14 = zJwtVcJsonCredentialDefinition.extend({
627
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
486
+ //#endregion
487
+ //#region src/formats/credential/w3c-vc/z-w3c-ldp-vc.ts
488
+ const zLdpVcFormatIdentifier = z.literal("ldp_vc");
489
+ const zLdpVcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
490
+ format: zLdpVcFormatIdentifier,
491
+ credential_definition: zW3cVcJsonLdCredentialDefinition,
492
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional()
628
493
  });
629
- var zJwtVcJsonCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
630
- format: zJwtVcJsonFormatIdentifier,
631
- credential_definition: zJwtVcJsonCredentialDefinition,
632
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
633
- claims: zIssuerMetadataClaimsDescription.optional()
634
- }).optional()
494
+ const zLdpVcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
495
+ format: zLdpVcFormatIdentifier,
496
+ credential_definition: zW3cVcJsonLdCredentialDefinition,
497
+ claims: z.array(zIssuerMetadataClaimsDescription).optional()
635
498
  });
636
- var zJwtVcJsonCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
637
- format: zJwtVcJsonFormatIdentifier,
638
- credential_definition: zJwtVcJsonCredentialDefinition,
639
- claims: zIssuerMetadataClaimsDescription.optional()
499
+ const zLdpVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
500
+ format: zLdpVcFormatIdentifier,
501
+ credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,
502
+ order: z.array(z.string()).optional()
640
503
  });
641
- var zJwtVcJsonCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({
642
- format: zJwtVcJsonFormatIdentifier,
643
- credential_definition: zJwtVcJsonCredentialDefinitionDraft14,
644
- order: z11.array(z11.string()).optional()
645
- });
646
- var zJwtVcJsonCredentialIssuerMetadataDraft11 = z11.object({
647
- format: zJwtVcJsonFormatIdentifier,
648
- order: z11.array(z11.string()).optional(),
649
- // Credential definition was spread on top level instead of a separatey property in v11
650
- // As well as using types instead of type
651
- types: z11.array(z11.string()),
652
- credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
504
+ const zLdpVcCredentialIssuerMetadataDraft11 = z.object({
505
+ order: z.array(z.string()).optional(),
506
+ format: zLdpVcFormatIdentifier,
507
+ "@context": z.array(z.string()),
508
+ types: z.array(z.string()),
509
+ credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
653
510
  }).passthrough();
654
- var zJwtVcJsonCredentialIssuerMetadataDraft11To14 = zJwtVcJsonCredentialIssuerMetadataDraft11.transform(
655
- ({ types, credentialSubject, ...rest }) => ({
656
- ...rest,
657
- credential_definition: {
658
- type: types,
659
- // Prevent weird typing issue with optional vs undefined
660
- ...credentialSubject ? { credentialSubject } : {}
661
- }
662
- })
663
- );
664
- var zJwtVcJsonCredentialIssuerMetadataDraft14To11 = zJwtVcJsonCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({
665
- ...rest,
666
- types: type,
667
- ...credentialDefinition
668
- })).pipe(zJwtVcJsonCredentialIssuerMetadataDraft11);
669
- var zJwtVcJsonCredentialRequestFormatDraft14 = z11.object({
670
- format: zJwtVcJsonFormatIdentifier,
671
- credential_definition: zJwtVcJsonCredentialDefinition
511
+ const zLdpVcCredentialIssuerMetadataDraft11To14 = zLdpVcCredentialIssuerMetadataDraft11.transform(({ "@context": context, types, credentialSubject,...rest }) => ({
512
+ ...rest,
513
+ credential_definition: {
514
+ "@context": context,
515
+ type: types,
516
+ ...credentialSubject ? { credentialSubject } : {}
517
+ }
518
+ }));
519
+ const zLdpVcCredentialIssuerMetadataDraft14To11 = zLdpVcCredentialIssuerMetadataDraft14.passthrough().transform(({ credential_definition: { type,...credentialDefinition },...rest }) => ({
520
+ ...rest,
521
+ ...credentialDefinition,
522
+ types: type
523
+ })).pipe(zLdpVcCredentialIssuerMetadataDraft11);
524
+ const zLdpVcCredentialRequestFormatDraft14 = z.object({
525
+ format: zLdpVcFormatIdentifier,
526
+ credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14
672
527
  });
673
- var zJwtVcJsonCredentialRequestDraft11 = z11.object({
674
- format: zJwtVcJsonFormatIdentifier,
675
- // Credential definition was spread on top level instead of a separatey property in v11
676
- // As well as using types instead of type
677
- types: z11.array(z11.string()),
678
- credentialSubject: z11.optional(zW3cVcCredentialSubjectDraft14)
528
+ const zLdpVcCredentialRequestDraft11 = z.object({
529
+ format: zLdpVcFormatIdentifier,
530
+ credential_definition: z.object({
531
+ "@context": z.array(z.string()),
532
+ types: z.array(z.string()),
533
+ credentialSubject: zW3cVcCredentialSubjectDraft14.optional()
534
+ })
679
535
  }).passthrough();
680
- var zJwtVcJsonCredentialRequestDraft11To14 = zJwtVcJsonCredentialRequestDraft11.transform(
681
- ({ types, credentialSubject, ...rest }) => {
682
- return {
683
- ...rest,
684
- credential_definition: {
685
- type: types,
686
- // Prevent weird typing issue with optional vs undefined
687
- ...credentialSubject ? { credentialSubject } : {}
688
- }
689
- };
690
- }
691
- );
692
- var zJwtVcJsonCredentialRequestDraft14To11 = zJwtVcJsonCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({
693
- ...rest,
694
- types: type,
695
- ...credentialDefinition
696
- })).pipe(zJwtVcJsonCredentialRequestDraft11);
536
+ const zLdpVcCredentialRequestDraft11To14 = zLdpVcCredentialRequestDraft11.transform(({ credential_definition: { types,...restCredentialDefinition },...rest }) => ({
537
+ ...rest,
538
+ credential_definition: {
539
+ ...restCredentialDefinition,
540
+ type: types
541
+ }
542
+ }));
543
+ const zLdpVcCredentialRequestDraft14To11 = zLdpVcCredentialRequestFormatDraft14.passthrough().transform(({ credential_definition: { type,...restCredentialDefinition },...rest }) => ({
544
+ ...rest,
545
+ credential_definition: {
546
+ ...restCredentialDefinition,
547
+ types: type
548
+ }
549
+ })).pipe(zLdpVcCredentialRequestDraft11);
697
550
 
698
- // src/formats/credential/w3c-vc/z-w3c-sd-jwt-vc.ts
699
- import z12 from "zod";
700
- var zSdJwtW3VcFormatIdentifier = z12.literal("vc+sd-jwt");
701
- var zSdJwtW3VcCredentialDefinition = z12.object({
702
- type: z12.array(z12.string()).nonempty()
703
- }).passthrough();
704
- var zSdJwtW3VcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
705
- format: zSdJwtW3VcFormatIdentifier,
706
- credential_definition: zSdJwtW3VcCredentialDefinition,
707
- credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({
708
- claims: zIssuerMetadataClaimsDescription.optional()
709
- }).optional(),
710
- // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.
711
- vct: z12.optional(z12.never())
551
+ //#endregion
552
+ //#region src/formats/credential/w3c-vc/z-w3c-sd-jwt-vc.ts
553
+ const zSdJwtW3VcFormatIdentifier = z.literal("vc+sd-jwt");
554
+ const zSdJwtW3VcCredentialDefinition = z.object({ type: z.array(z.string()).nonempty() }).passthrough();
555
+ const zSdJwtW3VcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({
556
+ format: zSdJwtW3VcFormatIdentifier,
557
+ credential_definition: zSdJwtW3VcCredentialDefinition,
558
+ credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.extend({ claims: z.array(zIssuerMetadataClaimsDescription).optional() }).optional(),
559
+ vct: z.optional(z.never())
560
+ });
561
+ const zSdJwtW3VcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({
562
+ format: zSdJwtW3VcFormatIdentifier,
563
+ credential_definition: zSdJwtW3VcCredentialDefinition,
564
+ claims: z.array(zIssuerMetadataClaimsDescription).optional(),
565
+ vct: z.optional(z.never())
712
566
  });
713
- var zSdJwtW3VcCredentialRequestFormatDraft14 = z12.object({
714
- format: zSdJwtW3VcFormatIdentifier,
715
- credential_definition: zSdJwtW3VcCredentialDefinition,
716
- // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.
717
- vct: z12.optional(z12.never())
567
+ const zSdJwtW3VcCredentialRequestFormatDraft14 = z.object({
568
+ format: zSdJwtW3VcFormatIdentifier,
569
+ credential_definition: zSdJwtW3VcCredentialDefinition,
570
+ vct: z.optional(z.never())
718
571
  });
719
572
 
720
- // src/metadata/credential-issuer/z-credential-issuer-metadata.ts
721
- var allCredentialIssuerMetadataFormats = [
722
- zSdJwtDcCredentialIssuerMetadata,
723
- zMsoMdocCredentialIssuerMetadata,
724
- zJwtVcJsonLdCredentialIssuerMetadata,
725
- zLdpVcCredentialIssuerMetadata,
726
- zJwtVcJsonCredentialIssuerMetadata,
727
- zSdJwtW3VcCredentialIssuerMetadata,
728
- zLegacySdJwtVcCredentialIssuerMetadataDraft16,
729
- zSdJwtDcCredentialIssuerMetadataDraft15,
730
- zMsoMdocCredentialIssuerMetadataDraft15,
731
- zJwtVcJsonLdCredentialIssuerMetadataDraft15,
732
- zLdpVcCredentialIssuerMetadataDraft15,
733
- zJwtVcJsonCredentialIssuerMetadataDraft15,
734
- zMsoMdocCredentialIssuerMetadataDraft14,
735
- zLegacySdJwtVcCredentialIssuerMetadataDraft14,
736
- zJwtVcJsonLdCredentialIssuerMetadataDraft14,
737
- zLdpVcCredentialIssuerMetadataDraft14,
738
- zJwtVcJsonCredentialIssuerMetadataDraft14
573
+ //#endregion
574
+ //#region src/metadata/credential-issuer/z-credential-issuer-metadata.ts
575
+ const allCredentialIssuerMetadataFormats = [
576
+ zSdJwtDcCredentialIssuerMetadata,
577
+ zMsoMdocCredentialIssuerMetadata,
578
+ zJwtVcJsonLdCredentialIssuerMetadata,
579
+ zLdpVcCredentialIssuerMetadata,
580
+ zJwtVcJsonCredentialIssuerMetadata,
581
+ zSdJwtW3VcCredentialIssuerMetadata,
582
+ zSdJwtW3VcCredentialIssuerMetadataDraft15,
583
+ zLegacySdJwtVcCredentialIssuerMetadataDraft16,
584
+ zSdJwtDcCredentialIssuerMetadataDraft15,
585
+ zMsoMdocCredentialIssuerMetadataDraft15,
586
+ zJwtVcJsonLdCredentialIssuerMetadataDraft15,
587
+ zLdpVcCredentialIssuerMetadataDraft15,
588
+ zJwtVcJsonCredentialIssuerMetadataDraft15,
589
+ zMsoMdocCredentialIssuerMetadataDraft14,
590
+ zLegacySdJwtVcCredentialIssuerMetadataDraft14,
591
+ zJwtVcJsonLdCredentialIssuerMetadataDraft14,
592
+ zLdpVcCredentialIssuerMetadataDraft14,
593
+ zJwtVcJsonCredentialIssuerMetadataDraft14
739
594
  ];
740
- var allCredentialIssuerMetadataFormatIdentifiers = allCredentialIssuerMetadataFormats.map(
741
- (format) => format.shape.format.value
742
- );
743
- var zCredentialConfigurationSupportedWithFormats = z13.union([zCredentialConfigurationSupportedCommon, zCredentialConfigurationSupportedCommonDraft15]).transform((data, ctx) => {
744
- if (!allCredentialIssuerMetadataFormatIdentifiers.includes(data.format)) return data;
745
- const validators = allCredentialIssuerMetadataFormats.filter(
746
- (formatValidator) => formatValidator.shape.format.value === data.format
747
- );
748
- const result = z13.object({}).passthrough().and(
749
- validators.length > 1 ? z13.union(
750
- validators
751
- ) : validators[0]
752
- ).safeParse(data);
753
- if (result.success) {
754
- return result.data;
755
- }
756
- for (const issue of result.error.issues) {
757
- ctx.addIssue(issue);
758
- }
759
- return z13.NEVER;
595
+ const allCredentialIssuerMetadataFormatIdentifiers = allCredentialIssuerMetadataFormats.map((format) => format.shape.format.value);
596
+ const zCredentialConfigurationSupportedWithFormats = z.union([zCredentialConfigurationSupportedCommon, zCredentialConfigurationSupportedCommonDraft15]).transform((data, ctx) => {
597
+ if (!allCredentialIssuerMetadataFormatIdentifiers.includes(data.format)) return data;
598
+ const validators = allCredentialIssuerMetadataFormats.filter((formatValidator) => formatValidator.shape.format.value === data.format);
599
+ const result = z.object({}).passthrough().and(validators.length > 1 ? z.union(validators) : validators[0]).safeParse(data);
600
+ if (result.success) return result.data;
601
+ for (const issue of result.error.issues) ctx.addIssue(issue);
602
+ return z.NEVER;
760
603
  });
761
- var zCredentialIssuerMetadataDisplayEntry = z13.object({
762
- name: z13.string().optional(),
763
- locale: z13.string().optional(),
764
- logo: z13.object({
765
- // FIXME: make required again, but need to support draft 11 first
766
- uri: z13.string().optional(),
767
- alt_text: z13.string().optional()
768
- }).passthrough().optional()
604
+ const zCredentialIssuerMetadataDisplayEntry = z.object({
605
+ name: z.string().optional(),
606
+ locale: z.string().optional(),
607
+ logo: z.object({
608
+ uri: z.string().optional(),
609
+ alt_text: z.string().optional()
610
+ }).passthrough().optional()
769
611
  }).passthrough();
770
- var zCredentialIssuerMetadataDraft14Draft15Draft16 = z13.object({
771
- credential_issuer: zHttpsUrl2,
772
- authorization_servers: z13.array(zHttpsUrl2).optional(),
773
- credential_endpoint: zHttpsUrl2,
774
- deferred_credential_endpoint: zHttpsUrl2.optional(),
775
- notification_endpoint: zHttpsUrl2.optional(),
776
- // Added after draft 14, but needed for proper
777
- nonce_endpoint: zHttpsUrl2.optional(),
778
- credential_response_encryption: z13.object({
779
- alg_values_supported: z13.array(z13.string()),
780
- enc_values_supported: z13.array(z13.string()),
781
- encryption_required: z13.boolean()
782
- }).passthrough().optional(),
783
- batch_credential_issuance: z13.object({
784
- batch_size: z13.number().positive()
785
- }).passthrough().optional(),
786
- signed_metadata: zCompactJwt.optional(),
787
- display: z13.array(zCredentialIssuerMetadataDisplayEntry).optional(),
788
- credential_configurations_supported: z13.record(z13.string(), zCredentialConfigurationSupportedWithFormats)
612
+ const zCredentialIssuerMetadataDraft14Draft15Draft16 = z.object({
613
+ credential_issuer: zHttpsUrl,
614
+ authorization_servers: z.array(zHttpsUrl).optional(),
615
+ credential_endpoint: zHttpsUrl,
616
+ deferred_credential_endpoint: zHttpsUrl.optional(),
617
+ notification_endpoint: zHttpsUrl.optional(),
618
+ nonce_endpoint: zHttpsUrl.optional(),
619
+ credential_response_encryption: z.object({
620
+ alg_values_supported: z.array(z.string()),
621
+ enc_values_supported: z.array(z.string()),
622
+ encryption_required: z.boolean()
623
+ }).passthrough().optional(),
624
+ batch_credential_issuance: z.object({ batch_size: z.number().positive() }).passthrough().optional(),
625
+ signed_metadata: zCompactJwt.optional(),
626
+ display: z.array(zCredentialIssuerMetadataDisplayEntry).optional(),
627
+ credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedWithFormats)
789
628
  }).passthrough();
790
- var zCredentialConfigurationSupportedDraft11To16 = z13.object({
791
- id: z13.string().optional(),
792
- format: z13.string(),
793
- cryptographic_suites_supported: z13.array(z13.string()).optional(),
794
- display: z13.array(
795
- z13.object({
796
- logo: z13.object({
797
- url: z13.string().url().optional()
798
- }).passthrough().optional(),
799
- background_image: z13.object({
800
- url: z13.string().url().optional()
801
- }).passthrough().optional()
802
- }).passthrough()
803
- ).optional(),
804
- claims: z13.any().optional()
805
- }).passthrough().transform(({ cryptographic_suites_supported, display, claims, id, ...rest }) => ({
806
- ...rest,
807
- ...cryptographic_suites_supported ? { credential_signing_alg_values_supported: cryptographic_suites_supported } : {},
808
- ...claims || display ? {
809
- credential_metadata: {
810
- ...claims ? { claims } : {},
811
- ...display ? {
812
- display: display.map(({ logo, background_image, ...displayRest }) => ({
813
- ...displayRest,
814
- // url became uri and also required
815
- // so if there's no url in the logo, we remove the whole logo object
816
- ...logo?.url ? {
817
- // TODO: we should add the other params from logo as well
818
- logo: {
819
- uri: logo.url
820
- }
821
- } : {},
822
- // TODO: we should add the other params from background_image as well
823
- // url became uri and also required
824
- // so if there's no url in the background_image, we remove the whole logo object
825
- ...background_image?.url ? {
826
- background_image: {
827
- uri: background_image.url
828
- }
829
- } : {}
830
- }))
831
- } : {}
832
- }
833
- } : {}
629
+ const zCredentialConfigurationSupportedDraft11To16 = z.object({
630
+ id: z.string().optional(),
631
+ format: z.string(),
632
+ cryptographic_suites_supported: z.array(z.string()).optional(),
633
+ display: z.array(z.object({
634
+ logo: z.object({ url: z.string().url().optional() }).passthrough().optional(),
635
+ background_image: z.object({ url: z.string().url().optional() }).passthrough().optional()
636
+ }).passthrough()).optional(),
637
+ claims: z.any().optional()
638
+ }).passthrough().transform(({ cryptographic_suites_supported, display, claims, id,...rest }) => ({
639
+ ...rest,
640
+ ...cryptographic_suites_supported ? { credential_signing_alg_values_supported: cryptographic_suites_supported } : {},
641
+ ...claims || display ? { credential_metadata: {
642
+ ...claims ? { claims } : {},
643
+ ...display ? { display: display.map(({ logo, background_image,...displayRest }) => ({
644
+ ...displayRest,
645
+ ...logo?.url ? { logo: { uri: logo.url } } : {},
646
+ ...background_image?.url ? { background_image: { uri: background_image.url } } : {}
647
+ })) } : {}
648
+ } } : {}
834
649
  })).transform((data, ctx) => {
835
- const formatSpecificTransformations = {
836
- [zLdpVcFormatIdentifier.value]: zLdpVcCredentialIssuerMetadataDraft11To14,
837
- [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialIssuerMetadataDraft11To14,
838
- [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialIssuerMetadataDraft11To14
839
- };
840
- if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
841
- const schema = formatSpecificTransformations[data.format];
842
- const result = schema.safeParse(data);
843
- if (result.success) return result.data;
844
- for (const issue of result.error.issues) {
845
- ctx.addIssue(issue);
846
- }
847
- return z13.NEVER;
650
+ const formatSpecificTransformations = {
651
+ [zLdpVcFormatIdentifier.value]: zLdpVcCredentialIssuerMetadataDraft11To14,
652
+ [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialIssuerMetadataDraft11To14,
653
+ [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialIssuerMetadataDraft11To14
654
+ };
655
+ if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
656
+ const result = formatSpecificTransformations[data.format].safeParse(data);
657
+ if (result.success) return result.data;
658
+ for (const issue of result.error.issues) ctx.addIssue(issue);
659
+ return z.NEVER;
848
660
  }).pipe(zCredentialConfigurationSupportedWithFormats);
849
- var zCredentialConfigurationSupportedDraft16To15 = zCredentialConfigurationSupportedWithFormats.transform(
850
- ({ credential_metadata, ...rest }) => ({
851
- ...credential_metadata,
852
- ...rest
853
- })
854
- );
855
- var zCredentialConfigurationSupportedDraft16To11 = zCredentialConfigurationSupportedDraft16To15.and(
856
- z13.object({
857
- id: z13.string()
858
- }).passthrough()
859
- ).transform(({ id, credential_signing_alg_values_supported, display, proof_types_supported, scope, ...rest }) => ({
860
- ...rest,
861
- ...credential_signing_alg_values_supported ? { cryptographic_suites_supported: credential_signing_alg_values_supported } : {},
862
- ...display ? {
863
- display: display.map(({ logo, background_image, ...displayRest }) => {
864
- const { uri: logoUri, ...logoRest } = logo ?? {};
865
- const { uri: backgroundImageUri, ...backgroundImageRest } = background_image ?? {};
866
- return {
867
- ...displayRest,
868
- // draft 11 uses url, draft 13/14 uses uri
869
- ...logoUri ? { logo: { url: logoUri, ...logoRest } } : {},
870
- // draft 11 uses url, draft 13/14 uses uri
871
- ...backgroundImageUri ? { logo: { url: backgroundImageUri, ...backgroundImageRest } } : {}
872
- };
873
- })
874
- } : {},
875
- id
876
- })).pipe(
877
- z13.union([
878
- zLdpVcCredentialIssuerMetadataDraft14To11,
879
- zJwtVcJsonCredentialIssuerMetadataDraft14To11,
880
- zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,
881
- // To handle unrecognized formats and not error immediately we allow the common format as well
882
- // but they can't use any of the format identifiers that have a specific transformation. This way if a format is
883
- // has a transformation it NEEDS to use the format specific transformation, and otherwise we fall back to the common validation
884
- z13.object({
885
- format: z13.string().refine(
886
- (input) => ![
887
- zLdpVcFormatIdentifier.value,
888
- zJwtVcJsonFormatIdentifier.value,
889
- zJwtVcJsonLdFormatIdentifier.value
890
- ].includes(input)
891
- )
892
- }).passthrough()
893
- ])
894
- );
895
- var zCredentialIssuerMetadataDraft11To16 = z13.object({
896
- authorization_server: z13.string().optional(),
897
- credentials_supported: z13.array(
898
- z13.object({
899
- id: z13.string().optional()
900
- }).passthrough()
901
- )
902
- }).passthrough().transform(({ authorization_server, credentials_supported, ...rest }) => {
903
- return {
904
- ...rest,
905
- ...authorization_server ? { authorization_servers: [authorization_server] } : {},
906
- // Go from array to map but keep v11 structure
907
- credential_configurations_supported: Object.fromEntries(
908
- credentials_supported.map((supported) => supported.id ? [supported.id, supported] : void 0).filter((i) => i !== void 0)
909
- )
910
- };
911
- }).pipe(
912
- z13.object({
913
- // Update from v11 structure to v14 structure
914
- credential_configurations_supported: z13.record(z13.string(), zCredentialConfigurationSupportedDraft11To16)
915
- }).passthrough()
916
- ).pipe(zCredentialIssuerMetadataDraft14Draft15Draft16);
917
- var zCredentialIssuerMetadataWithDraft11 = zCredentialIssuerMetadataDraft14Draft15Draft16.transform((issuerMetadata) => ({
918
- ...issuerMetadata,
919
- ...issuerMetadata.authorization_servers ? { authorization_server: issuerMetadata.authorization_servers[0] } : {},
920
- credentials_supported: Object.entries(issuerMetadata.credential_configurations_supported).map(([id, value]) => ({
921
- ...value,
922
- id
923
- }))
924
- })).pipe(
925
- zCredentialIssuerMetadataDraft14Draft15Draft16.extend({
926
- credentials_supported: z13.array(zCredentialConfigurationSupportedDraft16To11)
927
- })
928
- );
929
- var zCredentialIssuerMetadata = z13.union([
930
- // First prioritize draft 16/15/14 (and 13)
931
- zCredentialIssuerMetadataDraft14Draft15Draft16,
932
- // Then try parsing draft 11 and transform into draft 16
933
- zCredentialIssuerMetadataDraft11To16
934
- ]);
935
- var zCredentialIssuerMetadataWithDraftVersion = z13.union([
936
- zCredentialIssuerMetadataDraft14Draft15Draft16.transform((credentialIssuerMetadata) => {
937
- const credentialConfigurations = Object.values(credentialIssuerMetadata.credential_configurations_supported);
938
- const isDraft15 = credentialConfigurations.some((configuration) => {
939
- const knownConfiguration = configuration;
940
- if (knownConfiguration.format === zSdJwtDcFormatIdentifier.value) return true;
941
- if (Array.isArray(knownConfiguration.claims)) return true;
942
- if (Object.values(knownConfiguration.proof_types_supported ?? {}).some(
943
- (proofType) => proofType.key_attestations_required !== void 0
944
- ))
945
- return true;
946
- return false;
947
- });
948
- const isDraft16 = credentialConfigurations.some((configuration) => {
949
- return configuration.credential_metadata;
950
- });
951
- return {
952
- credentialIssuerMetadata,
953
- originalDraftVersion: isDraft16 ? "Draft16" /* Draft16 */ : isDraft15 ? "Draft15" /* Draft15 */ : "Draft14" /* Draft14 */
954
- };
955
- }),
956
- // Then try parsing draft 11 and transform into draft 14
957
- zCredentialIssuerMetadataDraft11To16.transform((credentialIssuerMetadata) => ({
958
- credentialIssuerMetadata,
959
- originalDraftVersion: "Draft11" /* Draft11 */
960
- }))
961
- ]);
661
+ const zCredentialConfigurationSupportedDraft16To11 = zCredentialConfigurationSupportedWithFormats.transform(({ credential_metadata,...rest }) => ({
662
+ ...credential_metadata,
663
+ ...rest
664
+ })).and(z.object({ id: z.string() }).passthrough()).transform(({ id, credential_signing_alg_values_supported, display, proof_types_supported, scope,...rest }) => ({
665
+ ...rest,
666
+ ...credential_signing_alg_values_supported ? { cryptographic_suites_supported: credential_signing_alg_values_supported } : {},
667
+ ...display ? { display: display.map(({ logo, background_image,...displayRest }) => {
668
+ const { uri: logoUri,...logoRest } = logo ?? {};
669
+ const { uri: backgroundImageUri,...backgroundImageRest } = background_image ?? {};
670
+ return {
671
+ ...displayRest,
672
+ ...logoUri ? { logo: {
673
+ url: logoUri,
674
+ ...logoRest
675
+ } } : {},
676
+ ...backgroundImageUri ? { logo: {
677
+ url: backgroundImageUri,
678
+ ...backgroundImageRest
679
+ } } : {}
680
+ };
681
+ }) } : {},
682
+ id
683
+ })).pipe(z.union([
684
+ zLdpVcCredentialIssuerMetadataDraft14To11,
685
+ zJwtVcJsonCredentialIssuerMetadataDraft14To11,
686
+ zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,
687
+ z.object({ format: z.string().refine((input) => ![
688
+ zLdpVcFormatIdentifier.value,
689
+ zJwtVcJsonFormatIdentifier.value,
690
+ zJwtVcJsonLdFormatIdentifier.value
691
+ ].includes(input)) }).passthrough()
692
+ ]));
693
+ const zCredentialIssuerMetadataDraft11To16 = z.object({
694
+ authorization_server: z.string().optional(),
695
+ credentials_supported: z.array(z.object({ id: z.string().optional() }).passthrough())
696
+ }).passthrough().transform(({ authorization_server, credentials_supported,...rest }) => {
697
+ return {
698
+ ...rest,
699
+ ...authorization_server ? { authorization_servers: [authorization_server] } : {},
700
+ credential_configurations_supported: Object.fromEntries(credentials_supported.map((supported) => supported.id ? [supported.id, supported] : void 0).filter((i) => i !== void 0))
701
+ };
702
+ }).pipe(z.object({ credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedDraft11To16) }).passthrough()).pipe(zCredentialIssuerMetadataDraft14Draft15Draft16);
703
+ const zCredentialIssuerMetadataWithDraft11 = zCredentialIssuerMetadataDraft14Draft15Draft16.transform((issuerMetadata) => ({
704
+ ...issuerMetadata,
705
+ ...issuerMetadata.authorization_servers ? { authorization_server: issuerMetadata.authorization_servers[0] } : {},
706
+ credentials_supported: Object.entries(issuerMetadata.credential_configurations_supported).map(([id, value]) => ({
707
+ ...value,
708
+ id
709
+ }))
710
+ })).pipe(zCredentialIssuerMetadataDraft14Draft15Draft16.extend({ credentials_supported: z.array(zCredentialConfigurationSupportedDraft16To11) }));
711
+ const zCredentialIssuerMetadata = z.union([zCredentialIssuerMetadataDraft14Draft15Draft16, zCredentialIssuerMetadataDraft11To16]);
712
+ const zCredentialIssuerMetadataWithDraftVersion = z.union([zCredentialIssuerMetadataDraft14Draft15Draft16.transform((credentialIssuerMetadata) => {
713
+ const credentialConfigurations = Object.values(credentialIssuerMetadata.credential_configurations_supported);
714
+ const isDraft15 = credentialConfigurations.some((configuration) => {
715
+ const knownConfiguration = configuration;
716
+ if (knownConfiguration.format === zSdJwtDcFormatIdentifier.value) return true;
717
+ if (Array.isArray(knownConfiguration.claims)) return true;
718
+ if (Object.values(knownConfiguration.proof_types_supported ?? {}).some((proofType) => proofType.key_attestations_required !== void 0)) return true;
719
+ return false;
720
+ });
721
+ return {
722
+ credentialIssuerMetadata,
723
+ originalDraftVersion: credentialConfigurations.some((configuration) => {
724
+ return configuration.credential_metadata;
725
+ }) ? Openid4vciDraftVersion.Draft16 : isDraft15 ? Openid4vciDraftVersion.Draft15 : Openid4vciDraftVersion.Draft14
726
+ };
727
+ }), zCredentialIssuerMetadataDraft11To16.transform((credentialIssuerMetadata) => ({
728
+ credentialIssuerMetadata,
729
+ originalDraftVersion: Openid4vciDraftVersion.Draft11
730
+ }))]);
962
731
 
963
- // src/metadata/credential-issuer/credential-issuer-metadata.ts
964
- var wellKnownCredentialIssuerSuffix = ".well-known/openid-credential-issuer";
732
+ //#endregion
733
+ //#region src/metadata/credential-issuer/credential-issuer-metadata.ts
734
+ const wellKnownCredentialIssuerSuffix = ".well-known/openid-credential-issuer";
735
+ /**
736
+ * @inheritdoc {@link fetchWellKnownMetadata}
737
+ */
965
738
  async function fetchCredentialIssuerMetadata(credentialIssuer, fetch) {
966
- const wellKnownMetadataUrl = joinUriParts(credentialIssuer, [wellKnownCredentialIssuerSuffix]);
967
- const result = await fetchWellKnownMetadata(wellKnownMetadataUrl, zCredentialIssuerMetadataWithDraftVersion, fetch);
968
- if (result && result.credentialIssuerMetadata.credential_issuer !== credentialIssuer) {
969
- throw new Oauth2Error2(
970
- `The 'credential_issuer' parameter '${result.credentialIssuerMetadata.credential_issuer}' in the well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`
971
- );
972
- }
973
- return result;
739
+ const wellKnownMetadataUrl = joinUriParts(credentialIssuer, [wellKnownCredentialIssuerSuffix]);
740
+ const result = await fetchWellKnownMetadata(wellKnownMetadataUrl, zCredentialIssuerMetadataWithDraftVersion, fetch);
741
+ if (result && result.credentialIssuerMetadata.credential_issuer !== credentialIssuer) throw new Oauth2Error(`The 'credential_issuer' parameter '${result.credentialIssuerMetadata.credential_issuer}' in the well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`);
742
+ return result;
974
743
  }
744
+ /**
745
+ * Extract credential configuration supported entries where the `format` is known to this
746
+ * library. Should be ran only after verifying the credential issuer metadata structure, so
747
+ * we can be certain that if the `format` matches the other format specific requirements are also met.
748
+ *
749
+ * Validation is done when resolving issuer metadata, or when calling `createIssuerMetadata`.
750
+ */
975
751
  function extractKnownCredentialConfigurationSupportedFormats(credentialConfigurationsSupported) {
976
- return Object.fromEntries(
977
- Object.entries(credentialConfigurationsSupported).filter(
978
- (entry) => allCredentialIssuerMetadataFormatIdentifiers.includes(entry[1].format)
979
- )
980
- );
752
+ return Object.fromEntries(Object.entries(credentialConfigurationsSupported).filter((entry) => allCredentialIssuerMetadataFormatIdentifiers.includes(entry[1].format)));
981
753
  }
982
754
  function getCredentialConfigurationSupportedById(credentialConfigurations, credentialConfigurationId) {
983
- const configuration = credentialConfigurations[credentialConfigurationId];
984
- if (!configuration) {
985
- throw new Oauth2Error2(
986
- `Credential configuration with id '${credentialConfigurationId}' not found in credential configurations supported.`
987
- );
988
- }
989
- return configuration;
755
+ const configuration = credentialConfigurations[credentialConfigurationId];
756
+ if (!configuration) throw new Oauth2Error(`Credential configuration with id '${credentialConfigurationId}' not found in credential configurations supported.`);
757
+ return configuration;
990
758
  }
991
759
 
992
- // src/credential-request/credential-request-configurations.ts
993
- function getCredentialConfigurationsMatchingRequestFormat({
994
- requestFormat,
995
- credentialConfigurations
996
- }) {
997
- const knownCredentialConfigurations = extractKnownCredentialConfigurationSupportedFormats(credentialConfigurations);
998
- return Object.fromEntries(
999
- Object.entries(knownCredentialConfigurations).filter(([, credentialConfiguration]) => {
1000
- if (credentialConfiguration.format !== requestFormat.format) return false;
1001
- const r = requestFormat;
1002
- const c = credentialConfiguration;
1003
- if ((c.format === "ldp_vc" || c.format === "jwt_vc_json-ld") && r.format === c.format) {
1004
- return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type) && arrayEqualsIgnoreOrder(r.credential_definition["@context"], c.credential_definition["@context"]);
1005
- }
1006
- if (c.format === "jwt_vc_json" && r.format === c.format) {
1007
- return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type);
1008
- }
1009
- if (c.format === "vc+sd-jwt" && r.format === c.format) {
1010
- if (r.vct && c.vct) {
1011
- return r.vct === c.vct;
1012
- }
1013
- if (c.credential_definition && r.credential_definition) {
1014
- return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type);
1015
- }
1016
- }
1017
- if (c.format === "mso_mdoc" && r.format === c.format) {
1018
- return r.doctype === c.doctype;
1019
- }
1020
- return false;
1021
- })
1022
- );
760
+ //#endregion
761
+ //#region src/credential-request/credential-request-configurations.ts
762
+ function getCredentialConfigurationsMatchingRequestFormat({ requestFormat, credentialConfigurations }) {
763
+ const knownCredentialConfigurations = extractKnownCredentialConfigurationSupportedFormats(credentialConfigurations);
764
+ return Object.fromEntries(Object.entries(knownCredentialConfigurations).filter(([, credentialConfiguration]) => {
765
+ if (credentialConfiguration.format !== requestFormat.format) return false;
766
+ const r = requestFormat;
767
+ const c = credentialConfiguration;
768
+ if ((c.format === "ldp_vc" || c.format === "jwt_vc_json-ld") && r.format === c.format) return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type) && arrayEqualsIgnoreOrder(r.credential_definition["@context"], c.credential_definition["@context"]);
769
+ if (c.format === "jwt_vc_json" && r.format === c.format) return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type);
770
+ if (c.format === "vc+sd-jwt" && r.format === c.format) {
771
+ if (r.vct && c.vct) return r.vct === c.vct;
772
+ if (c.credential_definition && r.credential_definition) return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type);
773
+ }
774
+ if (c.format === "mso_mdoc" && r.format === c.format) return r.doctype === c.doctype;
775
+ return false;
776
+ }));
1023
777
  }
1024
778
 
1025
- // src/error/Openid4vciError.ts
779
+ //#endregion
780
+ //#region src/error/Openid4vciError.ts
1026
781
  var Openid4vciError = class extends Error {
1027
- constructor(message, options) {
1028
- const errorMessage = message ?? "Unknown error occured.";
1029
- const causeMessage = options?.cause instanceof Error ? ` ${options.cause.message}` : options?.cause ? ` ${options?.cause}` : "";
1030
- super(`${errorMessage}${causeMessage}`);
1031
- this.cause = options?.cause;
1032
- }
782
+ constructor(message, options) {
783
+ const errorMessage = message ?? "Unknown error occured.";
784
+ const causeMessage = options?.cause instanceof Error ? ` ${options.cause.message}` : options?.cause ? ` ${options?.cause}` : "";
785
+ super(`${errorMessage}${causeMessage}`);
786
+ this.cause = options?.cause;
787
+ }
1033
788
  };
1034
789
 
1035
- // src/error/Openid4vciRetrieveCredentialsError.ts
1036
- import { formatZodError } from "@openid4vc/utils";
790
+ //#endregion
791
+ //#region src/error/Openid4vciRetrieveCredentialsError.ts
1037
792
  var Openid4vciRetrieveCredentialsError = class extends Openid4vciError {
1038
- constructor(message, response, responseText) {
1039
- const errorData = response.credentialResponseResult?.data ?? response.credentialErrorResponseResult?.data ?? (response.credentialResponseResult?.error ? formatZodError(response.credentialResponseResult.error) : void 0) ?? responseText;
1040
- super(`${message}
1041
- ${JSON.stringify(errorData, null, 2)}`);
1042
- this.response = response;
1043
- }
793
+ constructor(message, response, responseText) {
794
+ const errorData = response.credentialResponseResult?.data ?? response.credentialErrorResponseResult?.data ?? (response.credentialResponseResult?.error ? formatZodError(response.credentialResponseResult.error) : void 0) ?? responseText;
795
+ super(`${message}\n${JSON.stringify(errorData, null, 2)}`);
796
+ this.response = response;
797
+ }
1044
798
  };
1045
799
 
1046
- // src/error/Openid4vciSendNotificationError.ts
800
+ //#endregion
801
+ //#region src/error/Openid4vciSendNotificationError.ts
1047
802
  var Openid4vciSendNotificationError = class extends Openid4vciError {
1048
- constructor(message, response) {
1049
- super(message);
1050
- this.response = response;
1051
- }
803
+ constructor(message, response) {
804
+ super(message);
805
+ this.response = response;
806
+ }
1052
807
  };
1053
808
 
1054
- // src/key-attestation/key-attestation.ts
1055
- import { decodeJwt, jwtHeaderFromJwtSigner } from "@openid4vc/oauth2";
1056
- import { jwtSignerFromJwt, verifyJwt } from "@openid4vc/oauth2";
1057
- import { dateToSeconds, parseWithErrorHandling as parseWithErrorHandling2 } from "@openid4vc/utils";
809
+ //#endregion
810
+ //#region src/key-attestation/key-attestation.ts
1058
811
  async function createKeyAttestationJwt(options) {
1059
- const header = parseWithErrorHandling2(zKeyAttestationJwtHeader, {
1060
- ...jwtHeaderFromJwtSigner(options.signer),
1061
- typ: "keyattestation+jwt"
1062
- });
1063
- const payload = parseWithErrorHandling2(zKeyAttestationJwtPayloadForUse(options.use), {
1064
- iat: dateToSeconds(options.issuedAt),
1065
- exp: options.expiresAt ? dateToSeconds(options.expiresAt) : void 0,
1066
- nonce: options.nonce,
1067
- attested_keys: options.attestedKeys,
1068
- user_authentication: options.userAuthentication,
1069
- key_storage: options.keyStorage,
1070
- certification: options.certification,
1071
- ...options.additionalPayload
1072
- });
1073
- const { jwt } = await options.callbacks.signJwt(options.signer, { header, payload });
1074
- return jwt;
812
+ const header = parseWithErrorHandling(zKeyAttestationJwtHeader, {
813
+ ...jwtHeaderFromJwtSigner(options.signer),
814
+ typ: "keyattestation+jwt"
815
+ });
816
+ const payload = parseWithErrorHandling(zKeyAttestationJwtPayloadForUse(options.use), {
817
+ iat: dateToSeconds(options.issuedAt),
818
+ exp: options.expiresAt ? dateToSeconds(options.expiresAt) : void 0,
819
+ nonce: options.nonce,
820
+ attested_keys: options.attestedKeys,
821
+ user_authentication: options.userAuthentication,
822
+ key_storage: options.keyStorage,
823
+ certification: options.certification,
824
+ ...options.additionalPayload
825
+ });
826
+ const { jwt } = await options.callbacks.signJwt(options.signer, {
827
+ header,
828
+ payload
829
+ });
830
+ return jwt;
1075
831
  }
1076
832
  function parseKeyAttestationJwt({ keyAttestationJwt, use }) {
1077
- return decodeJwt({
1078
- jwt: keyAttestationJwt,
1079
- headerSchema: zKeyAttestationJwtHeader,
1080
- payloadSchema: zKeyAttestationJwtPayloadForUse(use)
1081
- });
833
+ return decodeJwt({
834
+ jwt: keyAttestationJwt,
835
+ headerSchema: zKeyAttestationJwtHeader,
836
+ payloadSchema: zKeyAttestationJwtPayloadForUse(use)
837
+ });
1082
838
  }
1083
839
  async function verifyKeyAttestationJwt(options) {
1084
- const { header, payload } = parseKeyAttestationJwt({ keyAttestationJwt: options.keyAttestationJwt, use: options.use });
1085
- const now = options.now?.getTime() ?? Date.now();
1086
- if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {
1087
- throw new Openid4vciError("Nonce used for key attestation jwt expired");
1088
- }
1089
- const { signer } = await verifyJwt({
1090
- compact: options.keyAttestationJwt,
1091
- header,
1092
- payload,
1093
- signer: jwtSignerFromJwt({ header, payload }),
1094
- verifyJwtCallback: options.callbacks.verifyJwt,
1095
- errorMessage: "Error verifiying key attestation jwt",
1096
- expectedNonce: options.expectedNonce,
1097
- now: options.now
1098
- });
1099
- return {
1100
- header,
1101
- payload,
1102
- signer
1103
- };
840
+ const { header, payload } = parseKeyAttestationJwt({
841
+ keyAttestationJwt: options.keyAttestationJwt,
842
+ use: options.use
843
+ });
844
+ const now = options.now?.getTime() ?? Date.now();
845
+ if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) throw new Openid4vciError("Nonce used for key attestation jwt expired");
846
+ const { signer } = await verifyJwt({
847
+ compact: options.keyAttestationJwt,
848
+ header,
849
+ payload,
850
+ signer: jwtSignerFromJwt({
851
+ header,
852
+ payload
853
+ }),
854
+ verifyJwtCallback: options.callbacks.verifyJwt,
855
+ errorMessage: "Error verifiying key attestation jwt",
856
+ expectedNonce: options.expectedNonce,
857
+ now: options.now
858
+ });
859
+ return {
860
+ header,
861
+ payload,
862
+ signer
863
+ };
1104
864
  }
1105
865
 
1106
- // src/metadata/credential-issuer/credential-configurations.ts
1107
- import { Oauth2Error as Oauth2Error3 } from "@openid4vc/oauth2";
1108
- import { ValidationError as ValidationError2 } from "@openid4vc/utils";
866
+ //#endregion
867
+ //#region src/metadata/credential-issuer/credential-configurations.ts
1109
868
  function extractScopesForCredentialConfigurationIds(options) {
1110
- const scopes = /* @__PURE__ */ new Set();
1111
- for (const credentialConfigurationId of options.credentialConfigurationIds) {
1112
- const credentialConfiguration = options.issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId];
1113
- if (!credentialConfiguration) {
1114
- throw new Oauth2Error3(
1115
- `Credential configuration with id '${credentialConfigurationId}' not found in metadata from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`
1116
- );
1117
- }
1118
- const scope = credentialConfiguration.scope;
1119
- if (scope) scopes.add(scope);
1120
- else if (!scope && options.throwOnConfigurationWithoutScope) {
1121
- throw new Oauth2Error3(
1122
- `Credential configuration with id '${credentialConfigurationId}' does not have a 'scope' configured, and 'throwOnConfigurationWithoutScope' was enabled.`
1123
- );
1124
- }
1125
- }
1126
- return scopes.size > 0 ? Array.from(scopes) : void 0;
869
+ const scopes = /* @__PURE__ */ new Set();
870
+ for (const credentialConfigurationId of options.credentialConfigurationIds) {
871
+ const credentialConfiguration = options.issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId];
872
+ if (!credentialConfiguration) throw new Oauth2Error(`Credential configuration with id '${credentialConfigurationId}' not found in metadata from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`);
873
+ const scope = credentialConfiguration.scope;
874
+ if (scope) scopes.add(scope);
875
+ else if (!scope && options.throwOnConfigurationWithoutScope) throw new Oauth2Error(`Credential configuration with id '${credentialConfigurationId}' does not have a 'scope' configured, and 'throwOnConfigurationWithoutScope' was enabled.`);
876
+ }
877
+ return scopes.size > 0 ? Array.from(scopes) : void 0;
1127
878
  }
879
+ /**
880
+ * Transforms draft 11 credentials supported syntax to credential configurations supported
881
+ *
882
+ * @throws if a credentials supported entry without id is passed
883
+ * @throws if a credentials supported entry with invalid structure or format specific properties is passed
884
+ */
1128
885
  function credentialsSupportedToCredentialConfigurationsSupported(credentialsSupported) {
1129
- const credentialConfigurationsSupported = {};
1130
- for (let index = 0; index < credentialsSupported.length; index++) {
1131
- const credentialSupported = credentialsSupported[index];
1132
- if (!credentialSupported.id) {
1133
- throw new Openid4vciError(
1134
- `Credential supported at index '${index}' does not have an 'id' property. Credential configuration requires the 'id' property as key`
1135
- );
1136
- }
1137
- const parseResult = zCredentialConfigurationSupportedDraft11To16.safeParse(credentialSupported);
1138
- if (!parseResult.success) {
1139
- throw new ValidationError2(
1140
- `Error transforming credential supported with id '${credentialSupported.id}' to credential configuration supported format`,
1141
- parseResult.error
1142
- );
1143
- }
1144
- credentialConfigurationsSupported[credentialSupported.id] = parseResult.data;
1145
- }
1146
- return credentialConfigurationsSupported;
886
+ const credentialConfigurationsSupported = {};
887
+ for (let index = 0; index < credentialsSupported.length; index++) {
888
+ const credentialSupported = credentialsSupported[index];
889
+ if (!credentialSupported.id) throw new Openid4vciError(`Credential supported at index '${index}' does not have an 'id' property. Credential configuration requires the 'id' property as key`);
890
+ const parseResult = zCredentialConfigurationSupportedDraft11To16.safeParse(credentialSupported);
891
+ if (!parseResult.success) throw new ValidationError(`Error transforming credential supported with id '${credentialSupported.id}' to credential configuration supported format`, parseResult.error);
892
+ credentialConfigurationsSupported[credentialSupported.id] = parseResult.data;
893
+ }
894
+ return credentialConfigurationsSupported;
1147
895
  }
1148
896
 
1149
- // src/Openid4vciClient.ts
1150
- import {
1151
- Oauth2Client,
1152
- Oauth2ClientAuthorizationChallengeError,
1153
- Oauth2Error as Oauth2Error7,
1154
- Oauth2ErrorCodes as Oauth2ErrorCodes2,
1155
- authorizationCodeGrantIdentifier as authorizationCodeGrantIdentifier2,
1156
- getAuthorizationServerMetadataFromList as getAuthorizationServerMetadataFromList2,
1157
- preAuthorizedCodeGrantIdentifier as preAuthorizedCodeGrantIdentifier3
1158
- } from "@openid4vc/oauth2";
1159
-
1160
- // src/credential-request/format-payload.ts
1161
- import { zIs } from "@openid4vc/utils";
897
+ //#endregion
898
+ //#region src/credential-request/format-payload.ts
1162
899
  function getCredentialRequestFormatPayloadForCredentialConfigurationId(options) {
1163
- const credentialConfiguration = getCredentialConfigurationSupportedById(
1164
- options.issuerMetadata.credentialIssuer.credential_configurations_supported,
1165
- options.credentialConfigurationId
1166
- );
1167
- if (zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft16, credentialConfiguration) || zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft14, credentialConfiguration)) {
1168
- return {
1169
- format: credentialConfiguration.format,
1170
- vct: credentialConfiguration.vct
1171
- };
1172
- }
1173
- if (zIs(zMsoMdocCredentialIssuerMetadata, credentialConfiguration) || zIs(zMsoMdocCredentialIssuerMetadataDraft14, credentialConfiguration)) {
1174
- return {
1175
- format: credentialConfiguration.format,
1176
- doctype: credentialConfiguration.doctype
1177
- };
1178
- }
1179
- if (zIs(zLdpVcCredentialIssuerMetadata, credentialConfiguration) || zIs(zLdpVcCredentialIssuerMetadataDraft14, credentialConfiguration)) {
1180
- return {
1181
- format: credentialConfiguration.format,
1182
- credential_definition: {
1183
- "@context": credentialConfiguration.credential_definition["@context"],
1184
- type: credentialConfiguration.credential_definition.type
1185
- }
1186
- };
1187
- }
1188
- if (zIs(zJwtVcJsonLdCredentialIssuerMetadata, credentialConfiguration) || zIs(zJwtVcJsonLdCredentialIssuerMetadataDraft14, credentialConfiguration)) {
1189
- return {
1190
- format: credentialConfiguration.format,
1191
- credential_definition: {
1192
- "@context": credentialConfiguration.credential_definition["@context"],
1193
- type: credentialConfiguration.credential_definition.type
1194
- }
1195
- };
1196
- }
1197
- if (zIs(zJwtVcJsonCredentialIssuerMetadata, credentialConfiguration) || zIs(zJwtVcJsonCredentialIssuerMetadataDraft14, credentialConfiguration)) {
1198
- return {
1199
- format: credentialConfiguration.format,
1200
- credential_definition: {
1201
- type: credentialConfiguration.credential_definition.type
1202
- }
1203
- };
1204
- }
1205
- if (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration)) {
1206
- throw new Openid4vciError(
1207
- `Credential configuration id '${options.credentialConfigurationId}' with format ${zLegacySdJwtVcFormatIdentifier.value} does not support credential request based on 'format'. Use 'credential_configuration_id' directly.`
1208
- );
1209
- }
1210
- if (zIs(zSdJwtW3VcCredentialIssuerMetadata, credentialConfiguration)) {
1211
- return {
1212
- format: credentialConfiguration.format,
1213
- credential_definition: {
1214
- type: credentialConfiguration.credential_definition.type
1215
- }
1216
- };
1217
- }
1218
- throw new Openid4vciError(
1219
- `Unknown format '${credentialConfiguration.format}' in credential configuration with id '${options.credentialConfigurationId}' for credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`
1220
- );
900
+ const credentialConfiguration = getCredentialConfigurationSupportedById(options.issuerMetadata.credentialIssuer.credential_configurations_supported, options.credentialConfigurationId);
901
+ if (zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft16, credentialConfiguration) || zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft14, credentialConfiguration)) return {
902
+ format: credentialConfiguration.format,
903
+ vct: credentialConfiguration.vct
904
+ };
905
+ if (zIs(zMsoMdocCredentialIssuerMetadata, credentialConfiguration) || zIs(zMsoMdocCredentialIssuerMetadataDraft14, credentialConfiguration)) return {
906
+ format: credentialConfiguration.format,
907
+ doctype: credentialConfiguration.doctype
908
+ };
909
+ if (zIs(zLdpVcCredentialIssuerMetadata, credentialConfiguration) || zIs(zLdpVcCredentialIssuerMetadataDraft14, credentialConfiguration)) return {
910
+ format: credentialConfiguration.format,
911
+ credential_definition: {
912
+ "@context": credentialConfiguration.credential_definition["@context"],
913
+ type: credentialConfiguration.credential_definition.type
914
+ }
915
+ };
916
+ if (zIs(zJwtVcJsonLdCredentialIssuerMetadata, credentialConfiguration) || zIs(zJwtVcJsonLdCredentialIssuerMetadataDraft14, credentialConfiguration)) return {
917
+ format: credentialConfiguration.format,
918
+ credential_definition: {
919
+ "@context": credentialConfiguration.credential_definition["@context"],
920
+ type: credentialConfiguration.credential_definition.type
921
+ }
922
+ };
923
+ if (zIs(zJwtVcJsonCredentialIssuerMetadata, credentialConfiguration) || zIs(zJwtVcJsonCredentialIssuerMetadataDraft14, credentialConfiguration)) return {
924
+ format: credentialConfiguration.format,
925
+ credential_definition: { type: credentialConfiguration.credential_definition.type }
926
+ };
927
+ if (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration)) throw new Openid4vciError(`Credential configuration id '${options.credentialConfigurationId}' with format ${zLegacySdJwtVcFormatIdentifier.value} does not support credential request based on 'format'. Use 'credential_configuration_id' directly.`);
928
+ if (zIs(zSdJwtW3VcCredentialIssuerMetadata, credentialConfiguration)) return {
929
+ format: credentialConfiguration.format,
930
+ credential_definition: { type: credentialConfiguration.credential_definition.type }
931
+ };
932
+ throw new Openid4vciError(`Unknown format '${credentialConfiguration.format}' in credential configuration with id '${options.credentialConfigurationId}' for credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`);
1221
933
  }
1222
934
 
1223
- // src/credential-request/retrieve-credentials.ts
1224
- import {
1225
- Oauth2Error as Oauth2Error4,
1226
- resourceRequest
1227
- } from "@openid4vc/oauth2";
1228
- import { ContentType as ContentType2, isResponseContentType, parseWithErrorHandling as parseWithErrorHandling3 } from "@openid4vc/utils";
1229
-
1230
- // src/credential-request/z-credential-request.ts
1231
- import { zJwk as zJwk3 } from "@openid4vc/oauth2";
1232
- import z17 from "zod";
1233
-
1234
- // src/credential-request/z-credential-request-common.ts
1235
- import { zJwk as zJwk2 } from "@openid4vc/oauth2";
1236
- import z16 from "zod";
1237
-
1238
- // src/formats/proof-type/jwt/z-jwt-proof-type.ts
1239
- import { zCompactJwt as zCompactJwt2, zJwtHeader as zJwtHeader2, zJwtPayload as zJwtPayload2 } from "@openid4vc/oauth2";
1240
- import { zHttpsUrl as zHttpsUrl3, zInteger as zInteger2 } from "@openid4vc/utils";
1241
- import z14 from "zod";
1242
- var zJwtProofTypeIdentifier = z14.literal("jwt");
1243
- var jwtProofTypeIdentifier = zJwtProofTypeIdentifier.value;
1244
- var zCredentialRequestProofJwt = z14.object({
1245
- proof_type: zJwtProofTypeIdentifier,
1246
- jwt: zCompactJwt2
935
+ //#endregion
936
+ //#region src/formats/proof-type/attestation/z-attestation-proof-type.ts
937
+ const zAttestationProofTypeIdentifier = z.literal("attestation");
938
+ const attestationProofTypeIdentifier = zAttestationProofTypeIdentifier.value;
939
+ const zCredentialRequestProofAttestation = z.object({
940
+ proof_type: zAttestationProofTypeIdentifier,
941
+ attestation: zCompactJwt
1247
942
  });
1248
- var zCredentialRequestJwtProofTypeHeader = zJwtHeader2.merge(
1249
- z14.object({
1250
- key_attestation: z14.optional(zCompactJwt2),
1251
- typ: z14.literal("openid4vci-proof+jwt")
1252
- })
1253
- ).passthrough().refine(({ kid, jwk }) => jwk === void 0 || kid === void 0, {
1254
- message: `Both 'jwk' and 'kid' are defined. Only one is allowed`
1255
- }).refine(({ trust_chain, kid }) => !trust_chain || !kid, {
1256
- message: `When 'trust_chain' is provided, 'kid' is required`
1257
- });
1258
- var zCredentialRequestJwtProofTypePayload = z14.object({
1259
- ...zJwtPayload2.shape,
1260
- aud: zHttpsUrl3,
1261
- iat: zInteger2
1262
- }).passthrough();
943
+ const zCredentialRequestAttestationProofTypePayload = zKeyAttestationJwtPayloadForUse("proof_type.attestation");
1263
944
 
1264
- // src/formats/proof-type/attestation/z-attestation-proof-type.ts
1265
- import { zCompactJwt as zCompactJwt3 } from "@openid4vc/oauth2";
1266
- import z15 from "zod";
1267
- var zAttestationProofTypeIdentifier = z15.literal("attestation");
1268
- var attestationProofTypeIdentifier = zAttestationProofTypeIdentifier.value;
1269
- var zCredentialRequestProofAttestation = z15.object({
1270
- proof_type: zAttestationProofTypeIdentifier,
1271
- attestation: zCompactJwt3
945
+ //#endregion
946
+ //#region src/formats/proof-type/jwt/z-jwt-proof-type.ts
947
+ const zJwtProofTypeIdentifier = z.literal("jwt");
948
+ const jwtProofTypeIdentifier = zJwtProofTypeIdentifier.value;
949
+ const zCredentialRequestProofJwt = z.object({
950
+ proof_type: zJwtProofTypeIdentifier,
951
+ jwt: zCompactJwt
1272
952
  });
1273
- var zCredentialRequestAttestationProofTypePayload = zKeyAttestationJwtPayloadForUse("proof_type.attestation");
1274
-
1275
- // src/credential-request/z-credential-request-common.ts
1276
- var zCredentialRequestProofCommon = z16.object({
1277
- proof_type: z16.string()
953
+ const zCredentialRequestJwtProofTypeHeader = zJwtHeader.merge(z.object({
954
+ key_attestation: z.optional(zCompactJwt),
955
+ typ: z.literal("openid4vci-proof+jwt")
956
+ })).passthrough().refine(({ kid, jwk }) => jwk === void 0 || kid === void 0, { message: `Both 'jwk' and 'kid' are defined. Only one is allowed` }).refine(({ trust_chain, kid }) => !trust_chain || !kid, { message: `When 'trust_chain' is provided, 'kid' is required` });
957
+ const zCredentialRequestJwtProofTypePayload = z.object({
958
+ ...zJwtPayload.shape,
959
+ aud: zHttpsUrl,
960
+ iat: zInteger
1278
961
  }).passthrough();
1279
- var allCredentialRequestProofs = [zCredentialRequestProofJwt, zCredentialRequestProofAttestation];
1280
- var zCredentialRequestProof = z16.union([
1281
- zCredentialRequestProofCommon,
1282
- z16.discriminatedUnion("proof_type", allCredentialRequestProofs)
1283
- ]);
1284
- var zCredentialRequestProofsCommon = z16.record(z16.string(), z16.array(z16.unknown()));
1285
- var zCredentialRequestProofs = z16.object({
1286
- [zJwtProofTypeIdentifier.value]: z16.optional(z16.array(zCredentialRequestProofJwt.shape.jwt)),
1287
- [zAttestationProofTypeIdentifier.value]: z16.optional(z16.array(zCredentialRequestProofAttestation.shape.attestation))
1288
- });
1289
- var zCredentialRequestCommon = z16.object({
1290
- proof: zCredentialRequestProof.optional(),
1291
- proofs: z16.optional(
1292
- z16.intersection(zCredentialRequestProofsCommon, zCredentialRequestProofs).refine((proofs) => Object.values(proofs).length === 1, {
1293
- message: `The 'proofs' object in a credential request should contain exactly one attribute`
1294
- })
1295
- ),
1296
- credential_response_encryption: z16.object({
1297
- jwk: zJwk2,
1298
- alg: z16.string(),
1299
- enc: z16.string()
1300
- }).passthrough().optional()
1301
- }).passthrough().refine(({ proof, proofs }) => !(proof !== void 0 && proofs !== void 0), {
1302
- message: `Both 'proof' and 'proofs' are defined. Only one is allowed`
962
+
963
+ //#endregion
964
+ //#region src/credential-request/z-credential-request-common.ts
965
+ const zCredentialRequestProofCommon = z.object({ proof_type: z.string() }).passthrough();
966
+ const allCredentialRequestProofs = [zCredentialRequestProofJwt, zCredentialRequestProofAttestation];
967
+ const zCredentialRequestProof = z.union([zCredentialRequestProofCommon, z.discriminatedUnion("proof_type", allCredentialRequestProofs)]);
968
+ const zCredentialRequestProofsCommon = z.record(z.string(), z.array(z.unknown()));
969
+ const zCredentialRequestProofs = z.object({
970
+ [zJwtProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofJwt.shape.jwt)),
971
+ [zAttestationProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofAttestation.shape.attestation))
1303
972
  });
973
+ const zCredentialRequestCommon = z.object({
974
+ proof: zCredentialRequestProof.optional(),
975
+ proofs: z.optional(z.intersection(zCredentialRequestProofsCommon, zCredentialRequestProofs).refine((proofs) => Object.values(proofs).length === 1, { message: `The 'proofs' object in a credential request should contain exactly one attribute` })),
976
+ credential_response_encryption: z.object({
977
+ jwk: zJwk,
978
+ alg: z.string(),
979
+ enc: z.string()
980
+ }).passthrough().optional()
981
+ }).passthrough().refine(({ proof, proofs }) => !(proof !== void 0 && proofs !== void 0), { message: `Both 'proof' and 'proofs' are defined. Only one is allowed` });
1304
982
 
1305
- // src/credential-request/z-credential-request.ts
1306
- var allCredentialRequestFormats = [
1307
- zSdJwtW3VcCredentialRequestFormatDraft14,
1308
- zMsoMdocCredentialRequestFormatDraft14,
1309
- zLdpVcCredentialRequestFormatDraft14,
1310
- zJwtVcJsonLdCredentialRequestFormatDraft14,
1311
- zJwtVcJsonCredentialRequestFormatDraft14,
1312
- zLegacySdJwtVcCredentialRequestFormatDraft14
983
+ //#endregion
984
+ //#region src/credential-request/z-credential-request.ts
985
+ const allCredentialRequestFormats = [
986
+ zSdJwtW3VcCredentialRequestFormatDraft14,
987
+ zMsoMdocCredentialRequestFormatDraft14,
988
+ zLdpVcCredentialRequestFormatDraft14,
989
+ zJwtVcJsonLdCredentialRequestFormatDraft14,
990
+ zJwtVcJsonCredentialRequestFormatDraft14,
991
+ zLegacySdJwtVcCredentialRequestFormatDraft14
1313
992
  ];
1314
- var allCredentialRequestFormatIdentifiers = allCredentialRequestFormats.map(
1315
- (format) => format.shape.format.value
1316
- );
1317
- var zCredentialRequestCredentialConfigurationId = z17.object({
1318
- credential_configuration_id: z17.string(),
1319
- format: z17.never({ message: "'format' cannot be defined when 'credential_configuration_id' is set." }).optional(),
1320
- credential_identifier: z17.never({ message: "'credential_identifier' cannot be defined when 'credential_configuration_id' is set." }).optional()
993
+ const allCredentialRequestFormatIdentifiers = allCredentialRequestFormats.map((format) => format.shape.format.value);
994
+ const zCredentialRequestCredentialConfigurationId = z.object({
995
+ credential_configuration_id: z.string(),
996
+ format: z.never({ message: "'format' cannot be defined when 'credential_configuration_id' is set." }).optional(),
997
+ credential_identifier: z.never({ message: "'credential_identifier' cannot be defined when 'credential_configuration_id' is set." }).optional()
1321
998
  });
1322
- var zAuthorizationDetailsCredentialRequest = z17.object({
1323
- credential_identifier: z17.string(),
1324
- credential_configuration_id: z17.never({ message: "'credential_configuration_id' cannot be defined when 'credential_identifier' is set." }).optional(),
1325
- // Cannot be present if credential identifier is present
1326
- format: z17.never({ message: "'format' cannot be defined when 'credential_identifier' is set." }).optional()
999
+ const zAuthorizationDetailsCredentialRequest = z.object({
1000
+ credential_identifier: z.string(),
1001
+ credential_configuration_id: z.never({ message: "'credential_configuration_id' cannot be defined when 'credential_identifier' is set." }).optional(),
1002
+ format: z.never({ message: "'format' cannot be defined when 'credential_identifier' is set." }).optional()
1327
1003
  });
1328
- var zCredentialRequestFormat = z17.object({
1329
- format: z17.string(),
1330
- credential_identifier: z17.never({ message: "'credential_identifier' cannot be defined when 'format' is set." }).optional(),
1331
- credential_configuration_id: z17.never({ message: "'credential_configuration_id' cannot be defined when 'format' is set." }).optional()
1004
+ const zCredentialRequestFormat = z.object({
1005
+ format: z.string(),
1006
+ credential_identifier: z.never({ message: "'credential_identifier' cannot be defined when 'format' is set." }).optional(),
1007
+ credential_configuration_id: z.never({ message: "'credential_configuration_id' cannot be defined when 'format' is set." }).optional()
1332
1008
  }).passthrough();
1333
- var zCredentialRequestDraft14WithFormat = zCredentialRequestCommon.and(zCredentialRequestFormat).transform((data, ctx) => {
1334
- if (!allCredentialRequestFormatIdentifiers.includes(
1335
- data.format
1336
- ))
1337
- return data;
1338
- const result = z17.object({}).passthrough().and(z17.union(allCredentialRequestFormats)).safeParse(data);
1339
- if (result.success) {
1340
- return result.data;
1341
- }
1342
- for (const issue of result.error.issues) {
1343
- ctx.addIssue(issue);
1344
- }
1345
- return z17.NEVER;
1009
+ const zCredentialRequestDraft14WithFormat = zCredentialRequestCommon.and(zCredentialRequestFormat).transform((data, ctx) => {
1010
+ if (!allCredentialRequestFormatIdentifiers.includes(data.format)) return data;
1011
+ const result = z.object({}).passthrough().and(z.union(allCredentialRequestFormats)).safeParse(data);
1012
+ if (result.success) return result.data;
1013
+ for (const issue of result.error.issues) ctx.addIssue(issue);
1014
+ return z.NEVER;
1346
1015
  });
1347
- var zCredentialRequestDraft15 = z17.union([
1348
- zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest),
1349
- zCredentialRequestCommon.and(zCredentialRequestCredentialConfigurationId)
1350
- ]);
1351
- var zCredentialRequestDraft14 = z17.union([
1352
- zCredentialRequestDraft14WithFormat,
1353
- zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest)
1354
- ]);
1355
- var zCredentialRequestDraft11To14 = zCredentialRequestCommon.and(zCredentialRequestFormat).transform((data, ctx) => {
1356
- const formatSpecificTransformations = {
1357
- [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft11To14,
1358
- [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft11To14,
1359
- [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft11To14
1360
- };
1361
- if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
1362
- const schema = formatSpecificTransformations[data.format];
1363
- const result = schema.safeParse(data);
1364
- if (result.success) return result.data;
1365
- for (const issue of result.error.issues) {
1366
- ctx.addIssue(issue);
1367
- }
1368
- return z17.NEVER;
1016
+ const zCredentialRequestDraft15 = z.union([zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest), zCredentialRequestCommon.and(zCredentialRequestCredentialConfigurationId)]);
1017
+ const zCredentialRequestDraft14 = z.union([zCredentialRequestDraft14WithFormat, zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest)]);
1018
+ const zCredentialRequestDraft11To14 = zCredentialRequestCommon.and(zCredentialRequestFormat).transform((data, ctx) => {
1019
+ const formatSpecificTransformations = {
1020
+ [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft11To14,
1021
+ [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft11To14,
1022
+ [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft11To14
1023
+ };
1024
+ if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
1025
+ const result = formatSpecificTransformations[data.format].safeParse(data);
1026
+ if (result.success) return result.data;
1027
+ for (const issue of result.error.issues) ctx.addIssue(issue);
1028
+ return z.NEVER;
1369
1029
  }).pipe(zCredentialRequestDraft14);
1370
- var zCredentialRequestDraft14To11 = zCredentialRequestDraft14.refine(
1371
- (data) => data.credential_identifier === void 0,
1372
- `'credential_identifier' is not supported in OpenID4VCI draft 11`
1373
- ).transform((data, ctx) => {
1374
- const formatSpecificTransformations = {
1375
- [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft14To11,
1376
- [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft14To11,
1377
- [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft14To11
1378
- };
1379
- if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
1380
- const schema = formatSpecificTransformations[data.format];
1381
- const result = schema.safeParse(data);
1382
- if (result.success) return result.data;
1383
- for (const issue of result.error.issues) {
1384
- ctx.addIssue(issue);
1385
- }
1386
- return z17.NEVER;
1030
+ const zCredentialRequestDraft14To11 = zCredentialRequestDraft14.refine((data) => data.credential_identifier === void 0, `'credential_identifier' is not supported in OpenID4VCI draft 11`).transform((data, ctx) => {
1031
+ const formatSpecificTransformations = {
1032
+ [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft14To11,
1033
+ [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft14To11,
1034
+ [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft14To11
1035
+ };
1036
+ if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data;
1037
+ const result = formatSpecificTransformations[data.format].safeParse(data);
1038
+ if (result.success) return result.data;
1039
+ for (const issue of result.error.issues) ctx.addIssue(issue);
1040
+ return z.NEVER;
1387
1041
  });
1388
- var zCredentialRequest = z17.union([
1389
- zCredentialRequestDraft15,
1390
- zCredentialRequestDraft14,
1391
- zCredentialRequestDraft11To14
1042
+ const zCredentialRequest = z.union([
1043
+ zCredentialRequestDraft15,
1044
+ zCredentialRequestDraft14,
1045
+ zCredentialRequestDraft11To14
1392
1046
  ]);
1393
- var zDeferredCredentialRequest = z17.object({
1394
- transaction_id: z17.string().nonempty(),
1395
- credential_response_encryption: z17.object({
1396
- jwk: zJwk3,
1397
- alg: z17.string(),
1398
- enc: z17.string()
1399
- }).passthrough().optional()
1047
+ const zDeferredCredentialRequest = z.object({
1048
+ transaction_id: z.string().nonempty(),
1049
+ credential_response_encryption: z.object({
1050
+ jwk: zJwk,
1051
+ alg: z.string(),
1052
+ enc: z.string()
1053
+ }).passthrough().optional()
1400
1054
  });
1401
1055
 
1402
- // src/credential-request/z-credential-response.ts
1403
- import z19 from "zod";
1404
-
1405
- // ../oauth2/src/common/z-oauth2-error.ts
1406
- import z18 from "zod";
1407
- var Oauth2ErrorCodes = /* @__PURE__ */ ((Oauth2ErrorCodes4) => {
1408
- Oauth2ErrorCodes4["ServerError"] = "server_error";
1409
- Oauth2ErrorCodes4["InvalidTarget"] = "invalid_target";
1410
- Oauth2ErrorCodes4["InvalidRequest"] = "invalid_request";
1411
- Oauth2ErrorCodes4["InvalidToken"] = "invalid_token";
1412
- Oauth2ErrorCodes4["InsufficientScope"] = "insufficient_scope";
1413
- Oauth2ErrorCodes4["InvalidGrant"] = "invalid_grant";
1414
- Oauth2ErrorCodes4["InvalidClient"] = "invalid_client";
1415
- Oauth2ErrorCodes4["UnauthorizedClient"] = "unauthorized_client";
1416
- Oauth2ErrorCodes4["UnsupportedGrantType"] = "unsupported_grant_type";
1417
- Oauth2ErrorCodes4["InvalidScope"] = "invalid_scope";
1418
- Oauth2ErrorCodes4["InvalidDpopProof"] = "invalid_dpop_proof";
1419
- Oauth2ErrorCodes4["UseDpopNonce"] = "use_dpop_nonce";
1420
- Oauth2ErrorCodes4["RedirectToWeb"] = "redirect_to_web";
1421
- Oauth2ErrorCodes4["InvalidSession"] = "invalid_session";
1422
- Oauth2ErrorCodes4["InsufficientAuthorization"] = "insufficient_authorization";
1423
- Oauth2ErrorCodes4["InvalidCredentialRequest"] = "invalid_credential_request";
1424
- Oauth2ErrorCodes4["CredentialRequestDenied"] = "credential_request_denied";
1425
- Oauth2ErrorCodes4["InvalidProof"] = "invalid_proof";
1426
- Oauth2ErrorCodes4["InvalidNonce"] = "invalid_nonce";
1427
- Oauth2ErrorCodes4["InvalidEncryptionParameters"] = "invalid_encryption_parameters";
1428
- Oauth2ErrorCodes4["UnknownCredentialConfiguration"] = "unknown_credential_configuration";
1429
- Oauth2ErrorCodes4["UnknownCredentialIdentifier"] = "unknown_credential_identifier";
1430
- Oauth2ErrorCodes4["InvalidTransactionId"] = "invalid_transaction_id";
1431
- Oauth2ErrorCodes4["UnsupportedCredentialType"] = "unsupported_credential_type";
1432
- Oauth2ErrorCodes4["UnsupportedCredentialFormat"] = "unsupported_credential_format";
1433
- Oauth2ErrorCodes4["InvalidRequestUri"] = "invalid_request_uri";
1434
- Oauth2ErrorCodes4["InvalidRequestObject"] = "invalid_request_object";
1435
- Oauth2ErrorCodes4["RequestNotSupported"] = "request_not_supported";
1436
- Oauth2ErrorCodes4["RequestUriNotSupported"] = "request_uri_not_supported";
1437
- Oauth2ErrorCodes4["VpFormatsNotSupported"] = "vp_formats_not_supported";
1438
- Oauth2ErrorCodes4["AccessDenied"] = "access_denied";
1439
- Oauth2ErrorCodes4["InvalidPresentationDefinitionUri"] = "invalid_presentation_definition_uri";
1440
- Oauth2ErrorCodes4["InvalidPresentationDefinitionReference"] = "invalid_presentation_definition_reference";
1441
- Oauth2ErrorCodes4["InvalidRequestUriMethod"] = "invalid_request_uri_method";
1442
- Oauth2ErrorCodes4["InvalidTransactionData"] = "invalid_transaction_data";
1443
- Oauth2ErrorCodes4["WalletUnavailable"] = "wallet_unavailable";
1444
- return Oauth2ErrorCodes4;
1445
- })(Oauth2ErrorCodes || {});
1446
- var zOauth2ErrorResponse = z18.object({
1447
- error: z18.union([z18.nativeEnum(Oauth2ErrorCodes), z18.string()]),
1448
- error_description: z18.string().optional(),
1449
- error_uri: z18.string().optional()
1056
+ //#endregion
1057
+ //#region ../oauth2/src/common/z-oauth2-error.ts
1058
+ let Oauth2ErrorCodes$1 = /* @__PURE__ */ function(Oauth2ErrorCodes$2) {
1059
+ Oauth2ErrorCodes$2["ServerError"] = "server_error";
1060
+ Oauth2ErrorCodes$2["InvalidTarget"] = "invalid_target";
1061
+ Oauth2ErrorCodes$2["InvalidRequest"] = "invalid_request";
1062
+ Oauth2ErrorCodes$2["InvalidToken"] = "invalid_token";
1063
+ Oauth2ErrorCodes$2["InsufficientScope"] = "insufficient_scope";
1064
+ Oauth2ErrorCodes$2["InvalidGrant"] = "invalid_grant";
1065
+ Oauth2ErrorCodes$2["InvalidClient"] = "invalid_client";
1066
+ Oauth2ErrorCodes$2["UnauthorizedClient"] = "unauthorized_client";
1067
+ Oauth2ErrorCodes$2["UnsupportedGrantType"] = "unsupported_grant_type";
1068
+ Oauth2ErrorCodes$2["InvalidScope"] = "invalid_scope";
1069
+ Oauth2ErrorCodes$2["InvalidDpopProof"] = "invalid_dpop_proof";
1070
+ Oauth2ErrorCodes$2["UseDpopNonce"] = "use_dpop_nonce";
1071
+ Oauth2ErrorCodes$2["RedirectToWeb"] = "redirect_to_web";
1072
+ Oauth2ErrorCodes$2["InvalidSession"] = "invalid_session";
1073
+ Oauth2ErrorCodes$2["InsufficientAuthorization"] = "insufficient_authorization";
1074
+ Oauth2ErrorCodes$2["InvalidCredentialRequest"] = "invalid_credential_request";
1075
+ Oauth2ErrorCodes$2["CredentialRequestDenied"] = "credential_request_denied";
1076
+ Oauth2ErrorCodes$2["InvalidProof"] = "invalid_proof";
1077
+ Oauth2ErrorCodes$2["InvalidNonce"] = "invalid_nonce";
1078
+ Oauth2ErrorCodes$2["InvalidEncryptionParameters"] = "invalid_encryption_parameters";
1079
+ Oauth2ErrorCodes$2["UnknownCredentialConfiguration"] = "unknown_credential_configuration";
1080
+ Oauth2ErrorCodes$2["UnknownCredentialIdentifier"] = "unknown_credential_identifier";
1081
+ Oauth2ErrorCodes$2["InvalidTransactionId"] = "invalid_transaction_id";
1082
+ Oauth2ErrorCodes$2["UnsupportedCredentialType"] = "unsupported_credential_type";
1083
+ Oauth2ErrorCodes$2["UnsupportedCredentialFormat"] = "unsupported_credential_format";
1084
+ Oauth2ErrorCodes$2["InvalidRequestUri"] = "invalid_request_uri";
1085
+ Oauth2ErrorCodes$2["InvalidRequestObject"] = "invalid_request_object";
1086
+ Oauth2ErrorCodes$2["RequestNotSupported"] = "request_not_supported";
1087
+ Oauth2ErrorCodes$2["RequestUriNotSupported"] = "request_uri_not_supported";
1088
+ Oauth2ErrorCodes$2["VpFormatsNotSupported"] = "vp_formats_not_supported";
1089
+ Oauth2ErrorCodes$2["AccessDenied"] = "access_denied";
1090
+ Oauth2ErrorCodes$2["InvalidPresentationDefinitionUri"] = "invalid_presentation_definition_uri";
1091
+ Oauth2ErrorCodes$2["InvalidPresentationDefinitionReference"] = "invalid_presentation_definition_reference";
1092
+ Oauth2ErrorCodes$2["InvalidRequestUriMethod"] = "invalid_request_uri_method";
1093
+ Oauth2ErrorCodes$2["InvalidTransactionData"] = "invalid_transaction_data";
1094
+ Oauth2ErrorCodes$2["WalletUnavailable"] = "wallet_unavailable";
1095
+ return Oauth2ErrorCodes$2;
1096
+ }({});
1097
+ const zOauth2ErrorResponse = z.object({
1098
+ error: z.union([z.nativeEnum(Oauth2ErrorCodes$1), z.string()]),
1099
+ error_description: z.string().optional(),
1100
+ error_uri: z.string().optional()
1450
1101
  }).passthrough();
1451
1102
 
1452
- // src/credential-request/z-credential-response.ts
1453
- var zCredentialEncoding = z19.union([z19.string(), z19.record(z19.string(), z19.any())]);
1454
- var zBaseCredentialResponse = z19.object({
1455
- credentials: z19.union([
1456
- // Draft >= 15
1457
- z19.array(z19.object({ credential: zCredentialEncoding })),
1458
- // Draft < 15
1459
- z19.array(zCredentialEncoding)
1460
- ]).optional(),
1461
- interval: z19.number().int().positive().optional(),
1462
- notification_id: z19.string().optional()
1103
+ //#endregion
1104
+ //#region src/credential-request/z-credential-response.ts
1105
+ const zCredentialEncoding = z.union([z.string(), z.record(z.string(), z.any())]);
1106
+ const zBaseCredentialResponse = z.object({
1107
+ credentials: z.union([z.array(z.object({ credential: zCredentialEncoding })), z.array(zCredentialEncoding)]).optional(),
1108
+ interval: z.number().int().positive().optional(),
1109
+ notification_id: z.string().optional()
1463
1110
  }).passthrough();
1464
- var zCredentialResponse = zBaseCredentialResponse.extend({
1465
- credential: z19.optional(zCredentialEncoding),
1466
- transaction_id: z19.string().optional(),
1467
- c_nonce: z19.string().optional(),
1468
- c_nonce_expires_in: z19.number().int().optional()
1111
+ const zCredentialResponse = zBaseCredentialResponse.extend({
1112
+ credential: z.optional(zCredentialEncoding),
1113
+ transaction_id: z.string().optional(),
1114
+ c_nonce: z.string().optional(),
1115
+ c_nonce_expires_in: z.number().int().optional()
1469
1116
  }).passthrough().superRefine((value, ctx) => {
1470
- const { credential, credentials, transaction_id, interval, notification_id } = value;
1471
- if ([credential, credentials, transaction_id].filter((i) => i !== void 0).length !== 1) {
1472
- ctx.addIssue({
1473
- code: z19.ZodIssueCode.custom,
1474
- message: `Exactly one of 'credential', 'credentials', or 'transaction_id' MUST be defined.`
1475
- });
1476
- }
1477
- if (transaction_id && !interval) {
1478
- ctx.addIssue({
1479
- code: z19.ZodIssueCode.custom,
1480
- message: `'interval' MUST be defined when 'transaction_id' is defined.`
1481
- });
1482
- }
1483
- if (notification_id && !(credentials || credential)) {
1484
- ctx.addIssue({
1485
- code: z19.ZodIssueCode.custom,
1486
- message: `'notification_id' MUST NOT be defined when 'credential' or 'credentials' are not defined.`
1487
- });
1488
- }
1117
+ const { credential, credentials, transaction_id, interval, notification_id } = value;
1118
+ if ([
1119
+ credential,
1120
+ credentials,
1121
+ transaction_id
1122
+ ].filter((i) => i !== void 0).length !== 1) ctx.addIssue({
1123
+ code: z.ZodIssueCode.custom,
1124
+ message: `Exactly one of 'credential', 'credentials', or 'transaction_id' MUST be defined.`
1125
+ });
1126
+ if (transaction_id && !interval) ctx.addIssue({
1127
+ code: z.ZodIssueCode.custom,
1128
+ message: `'interval' MUST be defined when 'transaction_id' is defined.`
1129
+ });
1130
+ if (notification_id && !(credentials || credential)) ctx.addIssue({
1131
+ code: z.ZodIssueCode.custom,
1132
+ message: `'notification_id' MUST NOT be defined when 'credential' or 'credentials' are not defined.`
1133
+ });
1489
1134
  });
1490
- var zCredentialErrorResponse = z19.object({
1491
- ...zOauth2ErrorResponse.shape,
1492
- c_nonce: z19.string().optional(),
1493
- c_nonce_expires_in: z19.number().int().optional()
1135
+ const zCredentialErrorResponse = z.object({
1136
+ ...zOauth2ErrorResponse.shape,
1137
+ c_nonce: z.string().optional(),
1138
+ c_nonce_expires_in: z.number().int().optional()
1494
1139
  }).passthrough();
1495
- var zDeferredCredentialResponse = zBaseCredentialResponse.refine(
1496
- (value) => {
1497
- const { credentials, interval } = value;
1498
- return [credentials, interval].filter((i) => i !== void 0).length === 1;
1499
- },
1500
- {
1501
- message: `Exactly one of 'credentials' or 'interval' MUST be defined.`
1502
- }
1503
- );
1140
+ const zDeferredCredentialResponse = zBaseCredentialResponse.refine((value) => {
1141
+ const { credentials, interval } = value;
1142
+ return [credentials, interval].filter((i) => i !== void 0).length === 1;
1143
+ }, { message: `Exactly one of 'credentials' or 'interval' MUST be defined.` });
1504
1144
 
1505
- // src/credential-request/retrieve-credentials.ts
1145
+ //#endregion
1146
+ //#region src/credential-request/retrieve-credentials.ts
1506
1147
  async function retrieveCredentialsWithCredentialConfigurationId(options) {
1507
- if (options.issuerMetadata.originalDraftVersion !== "Draft15" /* Draft15 */ && options.issuerMetadata.originalDraftVersion !== "Draft16" /* Draft16 */) {
1508
- throw new Openid4vciError(
1509
- "Requesting credentials based on credential configuration ID is not supported in OpenID4VCI below draft 15. Make sure to provide the format and format specific claims in the request."
1510
- );
1511
- }
1512
- getCredentialConfigurationSupportedById(
1513
- options.issuerMetadata.credentialIssuer.credential_configurations_supported,
1514
- options.credentialConfigurationId
1515
- );
1516
- const credentialRequest = {
1517
- ...options.additionalRequestPayload,
1518
- credential_configuration_id: options.credentialConfigurationId,
1519
- proof: options.proof,
1520
- proofs: options.proofs
1521
- };
1522
- return retrieveCredentials({
1523
- callbacks: options.callbacks,
1524
- credentialRequest,
1525
- issuerMetadata: options.issuerMetadata,
1526
- accessToken: options.accessToken,
1527
- dpop: options.dpop
1528
- });
1148
+ if (options.issuerMetadata.originalDraftVersion !== Openid4vciDraftVersion.Draft15 && options.issuerMetadata.originalDraftVersion !== Openid4vciDraftVersion.Draft16) throw new Openid4vciError("Requesting credentials based on credential configuration ID is not supported in OpenID4VCI below draft 15. Make sure to provide the format and format specific claims in the request.");
1149
+ getCredentialConfigurationSupportedById(options.issuerMetadata.credentialIssuer.credential_configurations_supported, options.credentialConfigurationId);
1150
+ const credentialRequest = {
1151
+ ...options.additionalRequestPayload,
1152
+ credential_configuration_id: options.credentialConfigurationId,
1153
+ proof: options.proof,
1154
+ proofs: options.proofs
1155
+ };
1156
+ return retrieveCredentials({
1157
+ callbacks: options.callbacks,
1158
+ credentialRequest,
1159
+ issuerMetadata: options.issuerMetadata,
1160
+ accessToken: options.accessToken,
1161
+ dpop: options.dpop
1162
+ });
1529
1163
  }
1530
1164
  async function retrieveCredentialsWithFormat(options) {
1531
- if (options.issuerMetadata.originalDraftVersion === "Draft15" /* Draft15 */ || options.issuerMetadata.originalDraftVersion === "Draft16" /* Draft16 */) {
1532
- throw new Openid4vciError(
1533
- "Requesting credentials based on format is not supported in OpenID4VCI draft 15. Provide the credential configuration id directly in the request."
1534
- );
1535
- }
1536
- const credentialRequest = {
1537
- ...options.formatPayload,
1538
- ...options.additionalRequestPayload,
1539
- proof: options.proof,
1540
- proofs: options.proofs
1541
- };
1542
- return retrieveCredentials({
1543
- callbacks: options.callbacks,
1544
- credentialRequest,
1545
- issuerMetadata: options.issuerMetadata,
1546
- accessToken: options.accessToken,
1547
- dpop: options.dpop
1548
- });
1165
+ if (options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft15 || options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft16) throw new Openid4vciError("Requesting credentials based on format is not supported in OpenID4VCI draft 15. Provide the credential configuration id directly in the request.");
1166
+ const credentialRequest = {
1167
+ ...options.formatPayload,
1168
+ ...options.additionalRequestPayload,
1169
+ proof: options.proof,
1170
+ proofs: options.proofs
1171
+ };
1172
+ return retrieveCredentials({
1173
+ callbacks: options.callbacks,
1174
+ credentialRequest,
1175
+ issuerMetadata: options.issuerMetadata,
1176
+ accessToken: options.accessToken,
1177
+ dpop: options.dpop
1178
+ });
1549
1179
  }
1180
+ /**
1181
+ * internal method
1182
+ */
1550
1183
  async function retrieveCredentials(options) {
1551
- const credentialEndpoint = options.issuerMetadata.credentialIssuer.credential_endpoint;
1552
- let credentialRequest = parseWithErrorHandling3(
1553
- zCredentialRequest,
1554
- options.credentialRequest,
1555
- "Error validating credential request"
1556
- );
1557
- if (credentialRequest.proofs) {
1558
- const { batch_credential_issuance } = options.issuerMetadata.credentialIssuer;
1559
- if (options.issuerMetadata.originalDraftVersion === "Draft11" /* Draft11 */) {
1560
- throw new Oauth2Error4(
1561
- `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support batch credential issuance using the 'proofs' request property. Only 'proof' is supported.`
1562
- );
1563
- }
1564
- const proofs = Object.values(credentialRequest.proofs)[0];
1565
- if (proofs.length > (batch_credential_issuance?.batch_size ?? 1)) {
1566
- throw new Oauth2Error4(
1567
- `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' supports batch issuance, but the max batch size is '${batch_credential_issuance?.batch_size ?? 1}'. A total of '${proofs.length}' proofs were provided.`
1568
- );
1569
- }
1570
- }
1571
- if (options.issuerMetadata.originalDraftVersion === "Draft11" /* Draft11 */) {
1572
- credentialRequest = parseWithErrorHandling3(
1573
- zCredentialRequestDraft14To11,
1574
- credentialRequest,
1575
- `Error transforming credential request from ${"Draft14" /* Draft14 */} to ${"Draft11" /* Draft11 */}`
1576
- );
1577
- }
1578
- const resourceResponse = await resourceRequest({
1579
- dpop: options.dpop,
1580
- accessToken: options.accessToken,
1581
- callbacks: options.callbacks,
1582
- url: credentialEndpoint,
1583
- requestOptions: {
1584
- method: "POST",
1585
- headers: {
1586
- "Content-Type": ContentType2.Json
1587
- },
1588
- body: JSON.stringify(credentialRequest)
1589
- }
1590
- });
1591
- if (!resourceResponse.ok) {
1592
- const credentialErrorResponseResult = isResponseContentType(ContentType2.Json, resourceResponse.response) ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1593
- return {
1594
- ...resourceResponse,
1595
- credentialErrorResponseResult
1596
- };
1597
- }
1598
- const credentialResponseResult = isResponseContentType(ContentType2.Json, resourceResponse.response) ? zCredentialResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1599
- if (!credentialResponseResult?.success) {
1600
- return {
1601
- ...resourceResponse,
1602
- ok: false,
1603
- credentialResponseResult
1604
- };
1605
- }
1606
- return {
1607
- ...resourceResponse,
1608
- credentialResponse: credentialResponseResult.data
1609
- };
1184
+ const credentialEndpoint = options.issuerMetadata.credentialIssuer.credential_endpoint;
1185
+ let credentialRequest = parseWithErrorHandling(zCredentialRequest, options.credentialRequest, "Error validating credential request");
1186
+ if (credentialRequest.proofs) {
1187
+ const { batch_credential_issuance } = options.issuerMetadata.credentialIssuer;
1188
+ if (options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft11) throw new Oauth2Error(`Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support batch credential issuance using the 'proofs' request property. Only 'proof' is supported.`);
1189
+ const proofs = Object.values(credentialRequest.proofs)[0];
1190
+ if (proofs.length > (batch_credential_issuance?.batch_size ?? 1)) throw new Oauth2Error(`Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' supports batch issuance, but the max batch size is '${batch_credential_issuance?.batch_size ?? 1}'. A total of '${proofs.length}' proofs were provided.`);
1191
+ }
1192
+ if (options.issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft11) credentialRequest = parseWithErrorHandling(zCredentialRequestDraft14To11, credentialRequest, `Error transforming credential request from ${Openid4vciDraftVersion.Draft14} to ${Openid4vciDraftVersion.Draft11}`);
1193
+ const resourceResponse = await resourceRequest({
1194
+ dpop: options.dpop,
1195
+ accessToken: options.accessToken,
1196
+ callbacks: options.callbacks,
1197
+ url: credentialEndpoint,
1198
+ requestOptions: {
1199
+ method: "POST",
1200
+ headers: { "Content-Type": ContentType.Json },
1201
+ body: JSON.stringify(credentialRequest)
1202
+ }
1203
+ });
1204
+ if (!resourceResponse.ok) {
1205
+ const credentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response) ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1206
+ return {
1207
+ ...resourceResponse,
1208
+ credentialErrorResponseResult
1209
+ };
1210
+ }
1211
+ const credentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response) ? zCredentialResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1212
+ if (!credentialResponseResult?.success) return {
1213
+ ...resourceResponse,
1214
+ ok: false,
1215
+ credentialResponseResult
1216
+ };
1217
+ return {
1218
+ ...resourceResponse,
1219
+ credentialResponse: credentialResponseResult.data
1220
+ };
1610
1221
  }
1611
1222
  async function retrieveDeferredCredentials(options) {
1612
- const credentialEndpoint = options.issuerMetadata.credentialIssuer.deferred_credential_endpoint;
1613
- if (!credentialEndpoint) {
1614
- throw new Openid4vciError(
1615
- `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support deferred credential retrieval.`
1616
- );
1617
- }
1618
- const deferredCredentialRequest = parseWithErrorHandling3(
1619
- zDeferredCredentialRequest,
1620
- {
1621
- transaction_id: options.transactionId,
1622
- ...options.additionalRequestPayload
1623
- },
1624
- "Error validating deferred credential request"
1625
- );
1626
- const resourceResponse = await resourceRequest({
1627
- dpop: options.dpop,
1628
- accessToken: options.accessToken,
1629
- callbacks: options.callbacks,
1630
- url: credentialEndpoint,
1631
- requestOptions: {
1632
- method: "POST",
1633
- headers: {
1634
- "Content-Type": ContentType2.Json
1635
- },
1636
- body: JSON.stringify(deferredCredentialRequest)
1637
- }
1638
- });
1639
- if (!resourceResponse.ok) {
1640
- const deferredCredentialErrorResponseResult = isResponseContentType(ContentType2.Json, resourceResponse.response) ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1641
- return {
1642
- ...resourceResponse,
1643
- deferredCredentialErrorResponseResult
1644
- };
1645
- }
1646
- const deferredCredentialResponseResult = isResponseContentType(ContentType2.Json, resourceResponse.response) ? zDeferredCredentialResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1647
- if (!deferredCredentialResponseResult?.success) {
1648
- return {
1649
- ...resourceResponse,
1650
- ok: false,
1651
- deferredCredentialResponseResult
1652
- };
1653
- }
1654
- return {
1655
- ...resourceResponse,
1656
- deferredCredentialResponse: deferredCredentialResponseResult.data
1657
- };
1223
+ const credentialEndpoint = options.issuerMetadata.credentialIssuer.deferred_credential_endpoint;
1224
+ if (!credentialEndpoint) throw new Openid4vciError(`Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support deferred credential retrieval.`);
1225
+ const deferredCredentialRequest = parseWithErrorHandling(zDeferredCredentialRequest, {
1226
+ transaction_id: options.transactionId,
1227
+ ...options.additionalRequestPayload
1228
+ }, "Error validating deferred credential request");
1229
+ const resourceResponse = await resourceRequest({
1230
+ dpop: options.dpop,
1231
+ accessToken: options.accessToken,
1232
+ callbacks: options.callbacks,
1233
+ url: credentialEndpoint,
1234
+ requestOptions: {
1235
+ method: "POST",
1236
+ headers: { "Content-Type": ContentType.Json },
1237
+ body: JSON.stringify(deferredCredentialRequest)
1238
+ }
1239
+ });
1240
+ if (!resourceResponse.ok) {
1241
+ const deferredCredentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response) ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1242
+ return {
1243
+ ...resourceResponse,
1244
+ deferredCredentialErrorResponseResult
1245
+ };
1246
+ }
1247
+ const deferredCredentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response) ? zDeferredCredentialResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1248
+ if (!deferredCredentialResponseResult?.success) return {
1249
+ ...resourceResponse,
1250
+ ok: false,
1251
+ deferredCredentialResponseResult
1252
+ };
1253
+ return {
1254
+ ...resourceResponse,
1255
+ deferredCredentialResponse: deferredCredentialResponseResult.data
1256
+ };
1658
1257
  }
1659
1258
 
1660
- // src/formats/proof-type/jwt/jwt-proof-type.ts
1661
- import { decodeJwt as decodeJwt2, isJwkInSet, jwtHeaderFromJwtSigner as jwtHeaderFromJwtSigner2 } from "@openid4vc/oauth2";
1662
- import { jwtSignerFromJwt as jwtSignerFromJwt2, verifyJwt as verifyJwt2 } from "@openid4vc/oauth2";
1663
- import { dateToSeconds as dateToSeconds2, parseWithErrorHandling as parseWithErrorHandling4 } from "@openid4vc/utils";
1259
+ //#endregion
1260
+ //#region src/formats/proof-type/jwt/jwt-proof-type.ts
1664
1261
  async function createCredentialRequestJwtProof(options) {
1665
- const header = parseWithErrorHandling4(zCredentialRequestJwtProofTypeHeader, {
1666
- ...jwtHeaderFromJwtSigner2(options.signer),
1667
- key_attestation: options.keyAttestationJwt,
1668
- typ: "openid4vci-proof+jwt"
1669
- });
1670
- const payload = parseWithErrorHandling4(zCredentialRequestJwtProofTypePayload, {
1671
- nonce: options.nonce,
1672
- aud: options.credentialIssuer,
1673
- iat: dateToSeconds2(options.issuedAt),
1674
- iss: options.clientId
1675
- });
1676
- const { jwt, signerJwk } = await options.callbacks.signJwt(options.signer, { header, payload });
1677
- if (options.keyAttestationJwt) {
1678
- const decodedKeyAttestation = decodeJwt2({
1679
- jwt: options.keyAttestationJwt,
1680
- headerSchema: zKeyAttestationJwtHeader,
1681
- payloadSchema: zKeyAttestationJwtPayload
1682
- });
1683
- const isSigedWithAttestedKey = await isJwkInSet({
1684
- jwk: signerJwk,
1685
- jwks: decodedKeyAttestation.payload.attested_keys,
1686
- callbacks: options.callbacks
1687
- });
1688
- if (!isSigedWithAttestedKey) {
1689
- throw new Openid4vciError(
1690
- `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`
1691
- );
1692
- }
1693
- }
1694
- return jwt;
1262
+ const header = parseWithErrorHandling(zCredentialRequestJwtProofTypeHeader, {
1263
+ ...jwtHeaderFromJwtSigner(options.signer),
1264
+ key_attestation: options.keyAttestationJwt,
1265
+ typ: "openid4vci-proof+jwt"
1266
+ });
1267
+ const payload = parseWithErrorHandling(zCredentialRequestJwtProofTypePayload, {
1268
+ nonce: options.nonce,
1269
+ aud: options.credentialIssuer,
1270
+ iat: dateToSeconds(options.issuedAt),
1271
+ iss: options.clientId
1272
+ });
1273
+ const { jwt, signerJwk } = await options.callbacks.signJwt(options.signer, {
1274
+ header,
1275
+ payload
1276
+ });
1277
+ if (options.keyAttestationJwt) {
1278
+ if (!await isJwkInSet({
1279
+ jwk: signerJwk,
1280
+ jwks: decodeJwt({
1281
+ jwt: options.keyAttestationJwt,
1282
+ headerSchema: zKeyAttestationJwtHeader,
1283
+ payloadSchema: zKeyAttestationJwtPayload
1284
+ }).payload.attested_keys,
1285
+ callbacks: options.callbacks
1286
+ })) throw new Openid4vciError(`Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`);
1287
+ }
1288
+ return jwt;
1695
1289
  }
1696
1290
  async function verifyCredentialRequestJwtProof(options) {
1697
- const { header, payload } = decodeJwt2({
1698
- jwt: options.jwt,
1699
- headerSchema: zCredentialRequestJwtProofTypeHeader,
1700
- payloadSchema: zCredentialRequestJwtProofTypePayload
1701
- });
1702
- const now = options.now?.getTime() ?? Date.now();
1703
- if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {
1704
- throw new Openid4vciError("Nonce used for credential request proof expired");
1705
- }
1706
- const { signer } = await verifyJwt2({
1707
- compact: options.jwt,
1708
- header,
1709
- payload,
1710
- signer: jwtSignerFromJwt2({ header, payload }),
1711
- verifyJwtCallback: options.callbacks.verifyJwt,
1712
- errorMessage: "Error verifiying credential request proof jwt.",
1713
- expectedNonce: options.expectedNonce,
1714
- expectedAudience: options.credentialIssuer,
1715
- expectedIssuer: options.clientId,
1716
- now: options.now
1717
- });
1718
- let keyAttestationResult = void 0;
1719
- if (header.key_attestation) {
1720
- keyAttestationResult = await verifyKeyAttestationJwt({
1721
- callbacks: options.callbacks,
1722
- keyAttestationJwt: header.key_attestation,
1723
- use: "proof_type.jwt"
1724
- });
1725
- const isSigedWithAttestedKey = await isJwkInSet({
1726
- jwk: signer.publicJwk,
1727
- jwks: keyAttestationResult.payload.attested_keys,
1728
- callbacks: options.callbacks
1729
- });
1730
- if (!isSigedWithAttestedKey) {
1731
- throw new Openid4vciError(
1732
- `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`
1733
- );
1734
- }
1735
- }
1736
- return {
1737
- header,
1738
- payload,
1739
- signer,
1740
- keyAttestation: keyAttestationResult
1741
- };
1291
+ const { header, payload } = decodeJwt({
1292
+ jwt: options.jwt,
1293
+ headerSchema: zCredentialRequestJwtProofTypeHeader,
1294
+ payloadSchema: zCredentialRequestJwtProofTypePayload
1295
+ });
1296
+ const now = options.now?.getTime() ?? Date.now();
1297
+ if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) throw new Openid4vciError("Nonce used for credential request proof expired");
1298
+ const { signer } = await verifyJwt({
1299
+ compact: options.jwt,
1300
+ header,
1301
+ payload,
1302
+ signer: jwtSignerFromJwt({
1303
+ header,
1304
+ payload
1305
+ }),
1306
+ verifyJwtCallback: options.callbacks.verifyJwt,
1307
+ errorMessage: "Error verifiying credential request proof jwt.",
1308
+ expectedNonce: options.expectedNonce,
1309
+ expectedAudience: options.credentialIssuer,
1310
+ expectedIssuer: options.clientId,
1311
+ now: options.now
1312
+ });
1313
+ let keyAttestationResult;
1314
+ if (header.key_attestation) {
1315
+ keyAttestationResult = await verifyKeyAttestationJwt({
1316
+ callbacks: options.callbacks,
1317
+ keyAttestationJwt: header.key_attestation,
1318
+ use: "proof_type.jwt"
1319
+ });
1320
+ if (!await isJwkInSet({
1321
+ jwk: signer.publicJwk,
1322
+ jwks: keyAttestationResult.payload.attested_keys,
1323
+ callbacks: options.callbacks
1324
+ })) throw new Openid4vciError(`Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`);
1325
+ }
1326
+ return {
1327
+ header,
1328
+ payload,
1329
+ signer,
1330
+ keyAttestation: keyAttestationResult
1331
+ };
1742
1332
  }
1743
1333
 
1744
- // src/metadata/fetch-issuer-metadata.ts
1745
- import {
1746
- Oauth2Error as Oauth2Error5,
1747
- fetchAuthorizationServerMetadata,
1748
- zAuthorizationServerMetadata
1749
- } from "@openid4vc/oauth2";
1750
- import { parseWithErrorHandling as parseWithErrorHandling5 } from "@openid4vc/utils";
1334
+ //#endregion
1335
+ //#region src/metadata/fetch-issuer-metadata.ts
1751
1336
  async function resolveIssuerMetadata(credentialIssuer, options) {
1752
- const allowAuthorizationMetadataFromCredentialIssuerMetadata = options?.allowAuthorizationMetadataFromCredentialIssuerMetadata ?? true;
1753
- const credentialIssuerMetadataWithDraftVersion = await fetchCredentialIssuerMetadata(credentialIssuer, options?.fetch);
1754
- if (!credentialIssuerMetadataWithDraftVersion) {
1755
- throw new Oauth2Error5(`Well known credential issuer metadata for issuer '${credentialIssuer}' not found.`);
1756
- }
1757
- const { credentialIssuerMetadata, originalDraftVersion } = credentialIssuerMetadataWithDraftVersion;
1758
- const authorizationServers = credentialIssuerMetadata.authorization_servers ?? [credentialIssuer];
1759
- const authoriationServersMetadata = [];
1760
- for (const authorizationServer of authorizationServers) {
1761
- if (options?.restrictToAuthorizationServers && !options.restrictToAuthorizationServers.includes(authorizationServer)) {
1762
- continue;
1763
- }
1764
- let authorizationServerMetadata = await fetchAuthorizationServerMetadata(authorizationServer, options?.fetch);
1765
- if (!authorizationServerMetadata && authorizationServer === credentialIssuer && allowAuthorizationMetadataFromCredentialIssuerMetadata) {
1766
- authorizationServerMetadata = parseWithErrorHandling5(
1767
- zAuthorizationServerMetadata,
1768
- {
1769
- token_endpoint: credentialIssuerMetadata.token_endpoint,
1770
- issuer: credentialIssuer
1771
- },
1772
- `Well known authorization server metadata for authorization server '${authorizationServer}' not found, and could also not extract required values from the credential issuer metadata as a fallback.`
1773
- );
1774
- }
1775
- if (!authorizationServerMetadata) {
1776
- throw new Oauth2Error5(
1777
- `Well known openid configuration or authorization server metadata for authorization server '${authorizationServer}' not found.`
1778
- );
1779
- }
1780
- authoriationServersMetadata.push(authorizationServerMetadata);
1781
- }
1782
- return {
1783
- originalDraftVersion,
1784
- credentialIssuer: credentialIssuerMetadata,
1785
- authorizationServers: authoriationServersMetadata
1786
- };
1337
+ const allowAuthorizationMetadataFromCredentialIssuerMetadata = options?.allowAuthorizationMetadataFromCredentialIssuerMetadata ?? true;
1338
+ const credentialIssuerMetadataWithDraftVersion = await fetchCredentialIssuerMetadata(credentialIssuer, options?.fetch);
1339
+ if (!credentialIssuerMetadataWithDraftVersion) throw new Oauth2Error(`Well known credential issuer metadata for issuer '${credentialIssuer}' not found.`);
1340
+ const { credentialIssuerMetadata, originalDraftVersion } = credentialIssuerMetadataWithDraftVersion;
1341
+ const authorizationServers = credentialIssuerMetadata.authorization_servers ?? [credentialIssuer];
1342
+ const authoriationServersMetadata = [];
1343
+ for (const authorizationServer of authorizationServers) {
1344
+ if (options?.restrictToAuthorizationServers && !options.restrictToAuthorizationServers.includes(authorizationServer)) continue;
1345
+ let authorizationServerMetadata = await fetchAuthorizationServerMetadata(authorizationServer, options?.fetch);
1346
+ if (!authorizationServerMetadata && authorizationServer === credentialIssuer && allowAuthorizationMetadataFromCredentialIssuerMetadata) authorizationServerMetadata = parseWithErrorHandling(zAuthorizationServerMetadata, {
1347
+ token_endpoint: credentialIssuerMetadata.token_endpoint,
1348
+ issuer: credentialIssuer
1349
+ }, `Well known authorization server metadata for authorization server '${authorizationServer}' not found, and could also not extract required values from the credential issuer metadata as a fallback.`);
1350
+ if (!authorizationServerMetadata) throw new Oauth2Error(`Well known openid configuration or authorization server metadata for authorization server '${authorizationServer}' not found.`);
1351
+ authoriationServersMetadata.push(authorizationServerMetadata);
1352
+ }
1353
+ return {
1354
+ originalDraftVersion,
1355
+ credentialIssuer: credentialIssuerMetadata,
1356
+ authorizationServers: authoriationServersMetadata
1357
+ };
1787
1358
  }
1788
1359
 
1789
- // src/nonce/nonce-request.ts
1790
- import { InvalidFetchResponseError as InvalidFetchResponseError2 } from "@openid4vc/oauth2";
1791
- import { ContentType as ContentType3, ValidationError as ValidationError3, createZodFetcher as createZodFetcher2, parseWithErrorHandling as parseWithErrorHandling6 } from "@openid4vc/utils";
1792
-
1793
- // src/nonce/z-nonce.ts
1794
- import { zInteger as zInteger3 } from "@openid4vc/utils";
1795
- import z20 from "zod";
1796
- var zNonceResponse = z20.object({
1797
- c_nonce: z20.string(),
1798
- c_nonce_expires_in: z20.optional(zInteger3)
1360
+ //#endregion
1361
+ //#region src/nonce/z-nonce.ts
1362
+ const zNonceResponse = z.object({
1363
+ c_nonce: z.string(),
1364
+ c_nonce_expires_in: z.optional(zInteger)
1799
1365
  }).passthrough();
1800
1366
 
1801
- // src/nonce/nonce-request.ts
1367
+ //#endregion
1368
+ //#region src/nonce/nonce-request.ts
1369
+ /**
1370
+ * Request a nonce from the `nonce_endpoint`
1371
+ *
1372
+ * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata
1373
+ * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response
1374
+ * @throws ValidationError - if validating the nonce response failed
1375
+ */
1802
1376
  async function requestNonce(options) {
1803
- const fetchWithZod = createZodFetcher2(options?.fetch);
1804
- const nonceEndpoint = options.issuerMetadata.credentialIssuer.nonce_endpoint;
1805
- if (!nonceEndpoint) {
1806
- throw new Openid4vciError(
1807
- `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a nonce endpoint.`
1808
- );
1809
- }
1810
- const { response, result } = await fetchWithZod(zNonceResponse, ContentType3.Json, nonceEndpoint, {
1811
- method: "POST"
1812
- });
1813
- if (!response.ok || !result) {
1814
- throw new InvalidFetchResponseError2(
1815
- `Requesting nonce from '${nonceEndpoint}' resulted in an unsuccessful response with status '${response.status}'`,
1816
- await response.clone().text(),
1817
- response
1818
- );
1819
- }
1820
- if (!result.success) {
1821
- throw new ValidationError3("Error parsing nonce response", result.error);
1822
- }
1823
- return result.data;
1377
+ const fetchWithZod = createZodFetcher(options?.fetch);
1378
+ const nonceEndpoint = options.issuerMetadata.credentialIssuer.nonce_endpoint;
1379
+ if (!nonceEndpoint) throw new Openid4vciError(`Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a nonce endpoint.`);
1380
+ const { response, result } = await fetchWithZod(zNonceResponse, ContentType.Json, nonceEndpoint, { method: "POST" });
1381
+ if (!response.ok || !result) throw new InvalidFetchResponseError(`Requesting nonce from '${nonceEndpoint}' resulted in an unsuccessful response with status '${response.status}'`, await response.clone().text(), response);
1382
+ if (!result.success) throw new ValidationError("Error parsing nonce response", result.error);
1383
+ return result.data;
1824
1384
  }
1825
1385
  function createNonceResponse(options) {
1826
- return parseWithErrorHandling6(zNonceResponse, {
1827
- c_nonce: options.cNonce,
1828
- c_nonce_expires_in: options.cNonceExpiresIn,
1829
- ...options.additionalPayload
1830
- });
1386
+ return parseWithErrorHandling(zNonceResponse, {
1387
+ c_nonce: options.cNonce,
1388
+ c_nonce_expires_in: options.cNonceExpiresIn,
1389
+ ...options.additionalPayload
1390
+ });
1831
1391
  }
1832
1392
 
1833
- // src/notification/notification.ts
1834
- import {
1835
- Oauth2Error as Oauth2Error6,
1836
- resourceRequest as resourceRequest2
1837
- } from "@openid4vc/oauth2";
1838
- import { ContentType as ContentType4, isResponseContentType as isResponseContentType2, parseWithErrorHandling as parseWithErrorHandling7 } from "@openid4vc/utils";
1839
-
1840
- // src/notification/z-notification.ts
1841
- import z21 from "zod";
1842
- var zNotificationEvent = z21.enum(["credential_accepted", "credential_failure", "credential_deleted"]);
1843
- var zNotificationRequest = z21.object({
1844
- notification_id: z21.string(),
1845
- event: zNotificationEvent,
1846
- event_description: z21.optional(z21.string())
1847
- }).passthrough();
1848
- var zNotificationErrorResponse = z21.object({
1849
- error: z21.enum(["invalid_notification_id", "invalid_notification_request"])
1393
+ //#endregion
1394
+ //#region src/notification/z-notification.ts
1395
+ const zNotificationEvent = z.enum([
1396
+ "credential_accepted",
1397
+ "credential_failure",
1398
+ "credential_deleted"
1399
+ ]);
1400
+ const zNotificationRequest = z.object({
1401
+ notification_id: z.string(),
1402
+ event: zNotificationEvent,
1403
+ event_description: z.optional(z.string())
1850
1404
  }).passthrough();
1405
+ const zNotificationErrorResponse = z.object({ error: z.enum(["invalid_notification_id", "invalid_notification_request"]) }).passthrough();
1851
1406
 
1852
- // src/notification/notification.ts
1407
+ //#endregion
1408
+ //#region src/notification/notification.ts
1853
1409
  async function sendNotification(options) {
1854
- const notificationEndpoint = options.issuerMetadata.credentialIssuer.notification_endpoint;
1855
- if (!notificationEndpoint) {
1856
- throw new Oauth2Error6(
1857
- `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a notification endpiont configured.`
1858
- );
1859
- }
1860
- const notificationRequest = parseWithErrorHandling7(
1861
- zNotificationRequest,
1862
- {
1863
- event: options.notification.event,
1864
- notification_id: options.notification.notificationId,
1865
- event_description: options.notification.eventDescription
1866
- },
1867
- "Error validating notification request"
1868
- );
1869
- const resourceResponse = await resourceRequest2({
1870
- dpop: options.dpop,
1871
- accessToken: options.accessToken,
1872
- callbacks: options.callbacks,
1873
- url: notificationEndpoint,
1874
- requestOptions: {
1875
- method: "POST",
1876
- headers: {
1877
- "Content-Type": ContentType4.Json
1878
- },
1879
- body: JSON.stringify(notificationRequest)
1880
- }
1881
- });
1882
- if (!resourceResponse.ok) {
1883
- const notificationErrorResponseResult = isResponseContentType2(ContentType4.Json, resourceResponse.response) ? zNotificationErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1884
- return {
1885
- ...resourceResponse,
1886
- notificationErrorResponseResult
1887
- };
1888
- }
1889
- return resourceResponse;
1410
+ const notificationEndpoint = options.issuerMetadata.credentialIssuer.notification_endpoint;
1411
+ if (!notificationEndpoint) throw new Oauth2Error(`Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a notification endpiont configured.`);
1412
+ const notificationRequest = parseWithErrorHandling(zNotificationRequest, {
1413
+ event: options.notification.event,
1414
+ notification_id: options.notification.notificationId,
1415
+ event_description: options.notification.eventDescription
1416
+ }, "Error validating notification request");
1417
+ const resourceResponse = await resourceRequest({
1418
+ dpop: options.dpop,
1419
+ accessToken: options.accessToken,
1420
+ callbacks: options.callbacks,
1421
+ url: notificationEndpoint,
1422
+ requestOptions: {
1423
+ method: "POST",
1424
+ headers: { "Content-Type": ContentType.Json },
1425
+ body: JSON.stringify(notificationRequest)
1426
+ }
1427
+ });
1428
+ if (!resourceResponse.ok) {
1429
+ const notificationErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response) ? zNotificationErrorResponse.safeParse(await resourceResponse.response.clone().json()) : void 0;
1430
+ return {
1431
+ ...resourceResponse,
1432
+ notificationErrorResponseResult
1433
+ };
1434
+ }
1435
+ return resourceResponse;
1890
1436
  }
1891
1437
 
1892
- // src/Openid4vciClient.ts
1893
- var AuthorizationFlow = /* @__PURE__ */ ((AuthorizationFlow2) => {
1894
- AuthorizationFlow2["Oauth2Redirect"] = "Oauth2Redirect";
1895
- AuthorizationFlow2["PresentationDuringIssuance"] = "PresentationDuringIssuance";
1896
- return AuthorizationFlow2;
1897
- })(AuthorizationFlow || {});
1438
+ //#endregion
1439
+ //#region src/Openid4vciClient.ts
1440
+ let AuthorizationFlow = /* @__PURE__ */ function(AuthorizationFlow$1) {
1441
+ AuthorizationFlow$1["Oauth2Redirect"] = "Oauth2Redirect";
1442
+ AuthorizationFlow$1["PresentationDuringIssuance"] = "PresentationDuringIssuance";
1443
+ return AuthorizationFlow$1;
1444
+ }({});
1898
1445
  var Openid4vciClient = class {
1899
- constructor(options) {
1900
- this.options = options;
1901
- this.oauth2Client = new Oauth2Client({
1902
- callbacks: this.options.callbacks
1903
- });
1904
- }
1905
- getKnownCredentialConfigurationsSupported(credentialIssuerMetadata) {
1906
- return extractKnownCredentialConfigurationSupportedFormats(
1907
- credentialIssuerMetadata.credential_configurations_supported
1908
- );
1909
- }
1910
- /**
1911
- * Resolve a credential offer into a credential offer object, handling both
1912
- * 'credential_offer' and 'credential_offer_uri' params.
1913
- */
1914
- async resolveCredentialOffer(credentialOffer) {
1915
- return resolveCredentialOffer(credentialOffer, {
1916
- fetch: this.options.callbacks.fetch
1917
- });
1918
- }
1919
- async resolveIssuerMetadata(credentialIssuer) {
1920
- return resolveIssuerMetadata(credentialIssuer, {
1921
- fetch: this.options.callbacks.fetch
1922
- });
1923
- }
1924
- /**
1925
- * Retrieve an authorization code for a presentation during issuance session
1926
- *
1927
- * This can only be called if an authorization challenge was performed before and returned a
1928
- * `presentation` parameter along with an `auth_session`. If the presentation response included
1929
- * an `presentation_during_issuance_session` parameter it MUST be included in this request as well.
1930
- */
1931
- async retrieveAuthorizationCodeUsingPresentation(options) {
1932
- if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier2]) {
1933
- throw new Oauth2Error7(`Provided credential offer does not include the 'authorization_code' grant.`);
1934
- }
1935
- const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier2];
1936
- const authorizationServer = determineAuthorizationServerForCredentialOffer({
1937
- issuerMetadata: options.issuerMetadata,
1938
- grantAuthorizationServer: authorizationCodeGrant.authorization_server
1939
- });
1940
- const authorizationServerMetadata = getAuthorizationServerMetadataFromList2(
1941
- options.issuerMetadata.authorizationServers,
1942
- authorizationServer
1943
- );
1944
- const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks });
1945
- const { authorizationChallengeResponse, dpop } = await oauth2Client.sendAuthorizationChallengeRequest({
1946
- authorizationServerMetadata,
1947
- authSession: options.authSession,
1948
- presentationDuringIssuanceSession: options.presentationDuringIssuanceSession,
1949
- dpop: options.dpop
1950
- });
1951
- return { authorizationChallengeResponse, dpop };
1952
- }
1953
- /**
1954
- * Initiates authorization for credential issuance. It handles the following cases:
1955
- * - Authorization Challenge
1956
- * - Pushed Authorization Request
1957
- * - Regular Authorization url
1958
- *
1959
- * In case the authorization challenge request returns an error with `insufficient_authorization`
1960
- * with a `presentation` field it means the authorization server expects presentation of credentials
1961
- * before issuance of credentials. If this is the case, the value in `presentation` should be treated
1962
- * as an openid4vp authorization request and submitted to the verifier. Once the presentation response
1963
- * has been submitted, the RP will respond with a `presentation_during_issuance_session` parameter.
1964
- * Together with the `auth_session` parameter returned in this call you can retrieve an `authorization_code`
1965
- * using
1966
- */
1967
- async initiateAuthorization(options) {
1968
- if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier2]) {
1969
- throw new Oauth2Error7(`Provided credential offer does not include the 'authorization_code' grant.`);
1970
- }
1971
- const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier2];
1972
- const authorizationServer = determineAuthorizationServerForCredentialOffer({
1973
- issuerMetadata: options.issuerMetadata,
1974
- grantAuthorizationServer: authorizationCodeGrant.authorization_server
1975
- });
1976
- const authorizationServerMetadata = getAuthorizationServerMetadataFromList2(
1977
- options.issuerMetadata.authorizationServers,
1978
- authorizationServer
1979
- );
1980
- const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks });
1981
- try {
1982
- const result = await oauth2Client.initiateAuthorization({
1983
- clientId: options.clientId,
1984
- pkceCodeVerifier: options.pkceCodeVerifier,
1985
- redirectUri: options.redirectUri,
1986
- scope: options.scope,
1987
- additionalRequestPayload: {
1988
- ...options.additionalRequestPayload,
1989
- issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state
1990
- },
1991
- dpop: options.dpop,
1992
- resource: options.issuerMetadata.credentialIssuer.credential_issuer,
1993
- authorizationServerMetadata
1994
- });
1995
- return {
1996
- ...result,
1997
- authorizationFlow: "Oauth2Redirect" /* Oauth2Redirect */,
1998
- authorizationServer: authorizationServerMetadata.issuer
1999
- };
2000
- } catch (error) {
2001
- if (error instanceof Oauth2ClientAuthorizationChallengeError && error.errorResponse.error === Oauth2ErrorCodes2.InsufficientAuthorization && error.errorResponse.presentation) {
2002
- if (!error.errorResponse.auth_session) {
2003
- throw new Openid4vciError(
2004
- `Expected 'auth_session' to be defined with authorization challenge response error '${error.errorResponse.error}' and 'presentation' parameter`
2005
- );
2006
- }
2007
- return {
2008
- authorizationFlow: "PresentationDuringIssuance" /* PresentationDuringIssuance */,
2009
- openid4vpRequestUrl: error.errorResponse.presentation,
2010
- authSession: error.errorResponse.auth_session,
2011
- authorizationServer: authorizationServerMetadata.issuer
2012
- };
2013
- }
2014
- throw error;
2015
- }
2016
- }
2017
- /**
2018
- * Convenience method around {@link Oauth2Client.createAuthorizationRequestUrl}
2019
- * but specifically focused on a credential offer
2020
- */
2021
- async createAuthorizationRequestUrlFromOffer(options) {
2022
- if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier2]) {
2023
- throw new Oauth2Error7(`Provided credential offer does not include the 'authorization_code' grant.`);
2024
- }
2025
- const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier2];
2026
- const authorizationServer = determineAuthorizationServerForCredentialOffer({
2027
- issuerMetadata: options.issuerMetadata,
2028
- grantAuthorizationServer: authorizationCodeGrant.authorization_server
2029
- });
2030
- const authorizationServerMetadata = getAuthorizationServerMetadataFromList2(
2031
- options.issuerMetadata.authorizationServers,
2032
- authorizationServer
2033
- );
2034
- const { authorizationRequestUrl, pkce, dpop } = await this.oauth2Client.createAuthorizationRequestUrl({
2035
- authorizationServerMetadata,
2036
- clientId: options.clientId,
2037
- additionalRequestPayload: {
2038
- ...options.additionalRequestPayload,
2039
- issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state
2040
- },
2041
- resource: options.issuerMetadata.credentialIssuer.credential_issuer,
2042
- redirectUri: options.redirectUri,
2043
- scope: options.scope,
2044
- pkceCodeVerifier: options.pkceCodeVerifier,
2045
- dpop: options.dpop
2046
- });
2047
- return {
2048
- authorizationRequestUrl,
2049
- pkce,
2050
- dpop,
2051
- authorizationServer: authorizationServerMetadata.issuer
2052
- };
2053
- }
2054
- /**
2055
- * Convenience method around {@link Oauth2Client.retrievePreAuthorizedCodeAccessToken}
2056
- * but specifically focused on a credential offer
2057
- */
2058
- async retrievePreAuthorizedCodeAccessTokenFromOffer({
2059
- credentialOffer,
2060
- issuerMetadata,
2061
- additionalRequestPayload,
2062
- txCode,
2063
- dpop
2064
- }) {
2065
- if (!credentialOffer.grants?.[preAuthorizedCodeGrantIdentifier3]) {
2066
- throw new Oauth2Error7(`The credential offer does not contain the '${preAuthorizedCodeGrantIdentifier3}' grant.`);
2067
- }
2068
- if (credentialOffer.grants[preAuthorizedCodeGrantIdentifier3].tx_code && !txCode) {
2069
- throw new Oauth2Error7(
2070
- `Retrieving access token requires a 'tx_code' in the request, but the 'txCode' parameter was not provided.`
2071
- );
2072
- }
2073
- const preAuthorizedCode = credentialOffer.grants[preAuthorizedCodeGrantIdentifier3]["pre-authorized_code"];
2074
- const authorizationServer = determineAuthorizationServerForCredentialOffer({
2075
- grantAuthorizationServer: credentialOffer.grants[preAuthorizedCodeGrantIdentifier3].authorization_server,
2076
- issuerMetadata
2077
- });
2078
- const authorizationServerMetadata = getAuthorizationServerMetadataFromList2(
2079
- issuerMetadata.authorizationServers,
2080
- authorizationServer
2081
- );
2082
- const result = await this.oauth2Client.retrievePreAuthorizedCodeAccessToken({
2083
- authorizationServerMetadata,
2084
- preAuthorizedCode,
2085
- txCode,
2086
- resource: issuerMetadata.credentialIssuer.credential_issuer,
2087
- additionalRequestPayload,
2088
- dpop
2089
- });
2090
- return {
2091
- ...result,
2092
- authorizationServer
2093
- };
2094
- }
2095
- /**
2096
- * Convenience method around {@link Oauth2Client.retrieveAuthorizationCodeAccessTokenFrom}
2097
- * but specifically focused on a credential offer
2098
- */
2099
- async retrieveAuthorizationCodeAccessTokenFromOffer({
2100
- issuerMetadata,
2101
- additionalRequestPayload,
2102
- credentialOffer,
2103
- authorizationCode,
2104
- pkceCodeVerifier,
2105
- redirectUri,
2106
- dpop
2107
- }) {
2108
- if (!credentialOffer.grants?.[authorizationCodeGrantIdentifier2]) {
2109
- throw new Oauth2Error7(`The credential offer does not contain the '${authorizationCodeGrantIdentifier2}' grant.`);
2110
- }
2111
- const authorizationServer = determineAuthorizationServerForCredentialOffer({
2112
- grantAuthorizationServer: credentialOffer.grants[authorizationCodeGrantIdentifier2].authorization_server,
2113
- issuerMetadata
2114
- });
2115
- const authorizationServerMetadata = getAuthorizationServerMetadataFromList2(
2116
- issuerMetadata.authorizationServers,
2117
- authorizationServer
2118
- );
2119
- const result = await this.oauth2Client.retrieveAuthorizationCodeAccessToken({
2120
- authorizationServerMetadata,
2121
- authorizationCode,
2122
- pkceCodeVerifier,
2123
- additionalRequestPayload,
2124
- dpop,
2125
- redirectUri,
2126
- resource: issuerMetadata.credentialIssuer.credential_issuer
2127
- });
2128
- return {
2129
- ...result,
2130
- authorizationServer
2131
- };
2132
- }
2133
- /**
2134
- * Request a nonce to be used in credential request proofs from the `nonce_endpoint`
2135
- *
2136
- * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata
2137
- * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response
2138
- * @throws ValidationError - if validating the nonce response failed
2139
- */
2140
- async requestNonce(options) {
2141
- return requestNonce({
2142
- ...options,
2143
- fetch: this.options.callbacks.fetch
2144
- });
2145
- }
2146
- /**
2147
- * Creates the jwt proof payload and header to be included in a credential request.
2148
- */
2149
- async createCredentialRequestJwtProof(options) {
2150
- const credentialConfiguration = options.issuerMetadata.credentialIssuer.credential_configurations_supported[options.credentialConfigurationId];
2151
- if (!credentialConfiguration) {
2152
- throw new Openid4vciError(
2153
- `Credential configuration with '${options.credentialConfigurationId}' not found in 'credential_configurations_supported' from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`
2154
- );
2155
- }
2156
- if (credentialConfiguration.proof_types_supported) {
2157
- if (!credentialConfiguration.proof_types_supported.jwt) {
2158
- throw new Openid4vciError(
2159
- `Credential configuration with id '${options.credentialConfigurationId}' does not support the 'jwt' proof type.`
2160
- );
2161
- }
2162
- if (!credentialConfiguration.proof_types_supported.jwt.proof_signing_alg_values_supported.includes(
2163
- options.signer.alg
2164
- )) {
2165
- throw new Openid4vciError(
2166
- `Credential configuration with id '${options.credentialConfigurationId}' does not support the '${options.signer.alg}' alg for 'jwt' proof type.`
2167
- );
2168
- }
2169
- if (credentialConfiguration.proof_types_supported.jwt.key_attestations_required && !options.keyAttestationJwt) {
2170
- throw new Openid4vciError(
2171
- `Credential configuration with id '${options.credentialConfigurationId}' requires key attestations for 'jwt' proof type but no 'keyAttestationJwt' was provided`
2172
- );
2173
- }
2174
- }
2175
- const jwt = await createCredentialRequestJwtProof({
2176
- credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,
2177
- signer: options.signer,
2178
- clientId: options.clientId,
2179
- issuedAt: options.issuedAt,
2180
- nonce: options.nonce,
2181
- keyAttestationJwt: options.keyAttestationJwt,
2182
- callbacks: this.options.callbacks
2183
- });
2184
- return {
2185
- jwt
2186
- };
2187
- }
2188
- /**
2189
- * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response
2190
- * @throws ValidationError - if validation of the credential request failed
2191
- * @throws Openid4vciError - if the `credentialConfigurationId` couldn't be found, or if the the format specific request couldn't be constructed
2192
- */
2193
- async retrieveCredentials({
2194
- issuerMetadata,
2195
- proof,
2196
- proofs,
2197
- credentialConfigurationId,
2198
- additionalRequestPayload,
2199
- accessToken,
2200
- dpop
2201
- }) {
2202
- let credentialResponse;
2203
- if (issuerMetadata.originalDraftVersion === "Draft15" /* Draft15 */ || issuerMetadata.originalDraftVersion === "Draft16" /* Draft16 */) {
2204
- credentialResponse = await retrieveCredentialsWithCredentialConfigurationId({
2205
- accessToken,
2206
- credentialConfigurationId,
2207
- issuerMetadata,
2208
- additionalRequestPayload,
2209
- proof,
2210
- proofs,
2211
- callbacks: this.options.callbacks,
2212
- dpop
2213
- });
2214
- } else {
2215
- const formatPayload = getCredentialRequestFormatPayloadForCredentialConfigurationId({
2216
- credentialConfigurationId,
2217
- issuerMetadata
2218
- });
2219
- credentialResponse = await retrieveCredentialsWithFormat({
2220
- accessToken,
2221
- formatPayload,
2222
- issuerMetadata,
2223
- additionalRequestPayload,
2224
- proof,
2225
- proofs,
2226
- callbacks: this.options.callbacks,
2227
- dpop
2228
- });
2229
- }
2230
- if (!credentialResponse.ok) {
2231
- throw new Openid4vciRetrieveCredentialsError(
2232
- `Error retrieving credentials from '${issuerMetadata.credentialIssuer.credential_issuer}'`,
2233
- credentialResponse,
2234
- await credentialResponse.response.clone().text()
2235
- );
2236
- }
2237
- return credentialResponse;
2238
- }
2239
- /**
2240
- * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response
2241
- * @throws ValidationError - if validation of the credential request failed
2242
- */
2243
- async retrieveDeferredCredentials(options) {
2244
- const credentialResponse = await retrieveDeferredCredentials({
2245
- ...options,
2246
- callbacks: this.options.callbacks
2247
- });
2248
- if (!credentialResponse.ok) {
2249
- throw new Openid4vciRetrieveCredentialsError(
2250
- `Error retrieving deferred credentials from '${options.issuerMetadata.credentialIssuer.credential_issuer}'`,
2251
- credentialResponse,
2252
- await credentialResponse.response.clone().text()
2253
- );
2254
- }
2255
- return credentialResponse;
2256
- }
2257
- /**
2258
- * @throws Openid4vciSendNotificationError - if an unsuccessful response
2259
- * @throws ValidationError - if validation of the notification request failed
2260
- */
2261
- async sendNotification({
2262
- issuerMetadata,
2263
- notification,
2264
- additionalRequestPayload,
2265
- accessToken,
2266
- dpop
2267
- }) {
2268
- const notificationResponse = await sendNotification({
2269
- accessToken,
2270
- issuerMetadata,
2271
- additionalRequestPayload,
2272
- callbacks: this.options.callbacks,
2273
- dpop,
2274
- notification
2275
- });
2276
- if (!notificationResponse.ok) {
2277
- throw new Openid4vciSendNotificationError(
2278
- `Error sending notification to '${issuerMetadata.credentialIssuer.credential_issuer}'`,
2279
- notificationResponse
2280
- );
2281
- }
2282
- return notificationResponse;
2283
- }
1446
+ constructor(options) {
1447
+ this.options = options;
1448
+ this.oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks });
1449
+ }
1450
+ getKnownCredentialConfigurationsSupported(credentialIssuerMetadata) {
1451
+ return extractKnownCredentialConfigurationSupportedFormats(credentialIssuerMetadata.credential_configurations_supported);
1452
+ }
1453
+ /**
1454
+ * Resolve a credential offer into a credential offer object, handling both
1455
+ * 'credential_offer' and 'credential_offer_uri' params.
1456
+ */
1457
+ async resolveCredentialOffer(credentialOffer) {
1458
+ return resolveCredentialOffer(credentialOffer, { fetch: this.options.callbacks.fetch });
1459
+ }
1460
+ async resolveIssuerMetadata(credentialIssuer) {
1461
+ return resolveIssuerMetadata(credentialIssuer, { fetch: this.options.callbacks.fetch });
1462
+ }
1463
+ /**
1464
+ * Retrieve an authorization code for a presentation during issuance session
1465
+ *
1466
+ * This can only be called if an authorization challenge was performed before and returned a
1467
+ * `presentation` parameter along with an `auth_session`. If the presentation response included
1468
+ * an `presentation_during_issuance_session` parameter it MUST be included in this request as well.
1469
+ */
1470
+ async retrieveAuthorizationCodeUsingPresentation(options) {
1471
+ if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`);
1472
+ const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier];
1473
+ const authorizationServer = determineAuthorizationServerForCredentialOffer({
1474
+ issuerMetadata: options.issuerMetadata,
1475
+ grantAuthorizationServer: authorizationCodeGrant.authorization_server
1476
+ });
1477
+ const authorizationServerMetadata = getAuthorizationServerMetadataFromList(options.issuerMetadata.authorizationServers, authorizationServer);
1478
+ const { authorizationChallengeResponse, dpop } = await new Oauth2Client({ callbacks: this.options.callbacks }).sendAuthorizationChallengeRequest({
1479
+ authorizationServerMetadata,
1480
+ authSession: options.authSession,
1481
+ presentationDuringIssuanceSession: options.presentationDuringIssuanceSession,
1482
+ dpop: options.dpop
1483
+ });
1484
+ return {
1485
+ authorizationChallengeResponse,
1486
+ dpop
1487
+ };
1488
+ }
1489
+ /**
1490
+ * Initiates authorization for credential issuance. It handles the following cases:
1491
+ * - Authorization Challenge
1492
+ * - Pushed Authorization Request
1493
+ * - Regular Authorization url
1494
+ *
1495
+ * In case the authorization challenge request returns an error with `insufficient_authorization`
1496
+ * with a `presentation` field it means the authorization server expects presentation of credentials
1497
+ * before issuance of credentials. If this is the case, the value in `presentation` should be treated
1498
+ * as an openid4vp authorization request and submitted to the verifier. Once the presentation response
1499
+ * has been submitted, the RP will respond with a `presentation_during_issuance_session` parameter.
1500
+ * Together with the `auth_session` parameter returned in this call you can retrieve an `authorization_code`
1501
+ * using
1502
+ */
1503
+ async initiateAuthorization(options) {
1504
+ if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`);
1505
+ const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier];
1506
+ const authorizationServer = determineAuthorizationServerForCredentialOffer({
1507
+ issuerMetadata: options.issuerMetadata,
1508
+ grantAuthorizationServer: authorizationCodeGrant.authorization_server
1509
+ });
1510
+ const authorizationServerMetadata = getAuthorizationServerMetadataFromList(options.issuerMetadata.authorizationServers, authorizationServer);
1511
+ const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks });
1512
+ try {
1513
+ return {
1514
+ ...await oauth2Client.initiateAuthorization({
1515
+ clientId: options.clientId,
1516
+ pkceCodeVerifier: options.pkceCodeVerifier,
1517
+ redirectUri: options.redirectUri,
1518
+ scope: options.scope,
1519
+ additionalRequestPayload: {
1520
+ ...options.additionalRequestPayload,
1521
+ issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state
1522
+ },
1523
+ dpop: options.dpop,
1524
+ resource: options.issuerMetadata.credentialIssuer.credential_issuer,
1525
+ authorizationServerMetadata
1526
+ }),
1527
+ authorizationFlow: AuthorizationFlow.Oauth2Redirect,
1528
+ authorizationServer: authorizationServerMetadata.issuer
1529
+ };
1530
+ } catch (error) {
1531
+ if (error instanceof Oauth2ClientAuthorizationChallengeError && error.errorResponse.error === Oauth2ErrorCodes.InsufficientAuthorization && error.errorResponse.presentation) {
1532
+ if (!error.errorResponse.auth_session) throw new Openid4vciError(`Expected 'auth_session' to be defined with authorization challenge response error '${error.errorResponse.error}' and 'presentation' parameter`);
1533
+ return {
1534
+ authorizationFlow: AuthorizationFlow.PresentationDuringIssuance,
1535
+ openid4vpRequestUrl: error.errorResponse.presentation,
1536
+ authSession: error.errorResponse.auth_session,
1537
+ authorizationServer: authorizationServerMetadata.issuer
1538
+ };
1539
+ }
1540
+ throw error;
1541
+ }
1542
+ }
1543
+ /**
1544
+ * Convenience method around {@link Oauth2Client.createAuthorizationRequestUrl}
1545
+ * but specifically focused on a credential offer
1546
+ */
1547
+ async createAuthorizationRequestUrlFromOffer(options) {
1548
+ if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`);
1549
+ const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier];
1550
+ const authorizationServer = determineAuthorizationServerForCredentialOffer({
1551
+ issuerMetadata: options.issuerMetadata,
1552
+ grantAuthorizationServer: authorizationCodeGrant.authorization_server
1553
+ });
1554
+ const authorizationServerMetadata = getAuthorizationServerMetadataFromList(options.issuerMetadata.authorizationServers, authorizationServer);
1555
+ const { authorizationRequestUrl, pkce, dpop } = await this.oauth2Client.createAuthorizationRequestUrl({
1556
+ authorizationServerMetadata,
1557
+ clientId: options.clientId,
1558
+ additionalRequestPayload: {
1559
+ ...options.additionalRequestPayload,
1560
+ issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state
1561
+ },
1562
+ resource: options.issuerMetadata.credentialIssuer.credential_issuer,
1563
+ redirectUri: options.redirectUri,
1564
+ scope: options.scope,
1565
+ pkceCodeVerifier: options.pkceCodeVerifier,
1566
+ dpop: options.dpop
1567
+ });
1568
+ return {
1569
+ authorizationRequestUrl,
1570
+ pkce,
1571
+ dpop,
1572
+ authorizationServer: authorizationServerMetadata.issuer
1573
+ };
1574
+ }
1575
+ /**
1576
+ * Convenience method around {@link Oauth2Client.retrievePreAuthorizedCodeAccessToken}
1577
+ * but specifically focused on a credential offer
1578
+ */
1579
+ async retrievePreAuthorizedCodeAccessTokenFromOffer({ credentialOffer, issuerMetadata, additionalRequestPayload, txCode, dpop }) {
1580
+ if (!credentialOffer.grants?.[preAuthorizedCodeGrantIdentifier]) throw new Oauth2Error(`The credential offer does not contain the '${preAuthorizedCodeGrantIdentifier}' grant.`);
1581
+ if (credentialOffer.grants[preAuthorizedCodeGrantIdentifier].tx_code && !txCode) throw new Oauth2Error(`Retrieving access token requires a 'tx_code' in the request, but the 'txCode' parameter was not provided.`);
1582
+ const preAuthorizedCode = credentialOffer.grants[preAuthorizedCodeGrantIdentifier]["pre-authorized_code"];
1583
+ const authorizationServer = determineAuthorizationServerForCredentialOffer({
1584
+ grantAuthorizationServer: credentialOffer.grants[preAuthorizedCodeGrantIdentifier].authorization_server,
1585
+ issuerMetadata
1586
+ });
1587
+ const authorizationServerMetadata = getAuthorizationServerMetadataFromList(issuerMetadata.authorizationServers, authorizationServer);
1588
+ return {
1589
+ ...await this.oauth2Client.retrievePreAuthorizedCodeAccessToken({
1590
+ authorizationServerMetadata,
1591
+ preAuthorizedCode,
1592
+ txCode,
1593
+ resource: issuerMetadata.credentialIssuer.credential_issuer,
1594
+ additionalRequestPayload,
1595
+ dpop
1596
+ }),
1597
+ authorizationServer
1598
+ };
1599
+ }
1600
+ /**
1601
+ * Convenience method around {@link Oauth2Client.retrieveAuthorizationCodeAccessTokenFrom}
1602
+ * but specifically focused on a credential offer
1603
+ */
1604
+ async retrieveAuthorizationCodeAccessTokenFromOffer({ issuerMetadata, additionalRequestPayload, credentialOffer, authorizationCode, pkceCodeVerifier, redirectUri, dpop }) {
1605
+ if (!credentialOffer.grants?.[authorizationCodeGrantIdentifier]) throw new Oauth2Error(`The credential offer does not contain the '${authorizationCodeGrantIdentifier}' grant.`);
1606
+ const authorizationServer = determineAuthorizationServerForCredentialOffer({
1607
+ grantAuthorizationServer: credentialOffer.grants[authorizationCodeGrantIdentifier].authorization_server,
1608
+ issuerMetadata
1609
+ });
1610
+ const authorizationServerMetadata = getAuthorizationServerMetadataFromList(issuerMetadata.authorizationServers, authorizationServer);
1611
+ return {
1612
+ ...await this.oauth2Client.retrieveAuthorizationCodeAccessToken({
1613
+ authorizationServerMetadata,
1614
+ authorizationCode,
1615
+ pkceCodeVerifier,
1616
+ additionalRequestPayload,
1617
+ dpop,
1618
+ redirectUri,
1619
+ resource: issuerMetadata.credentialIssuer.credential_issuer
1620
+ }),
1621
+ authorizationServer
1622
+ };
1623
+ }
1624
+ /**
1625
+ * Request a nonce to be used in credential request proofs from the `nonce_endpoint`
1626
+ *
1627
+ * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata
1628
+ * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response
1629
+ * @throws ValidationError - if validating the nonce response failed
1630
+ */
1631
+ async requestNonce(options) {
1632
+ return requestNonce({
1633
+ ...options,
1634
+ fetch: this.options.callbacks.fetch
1635
+ });
1636
+ }
1637
+ /**
1638
+ * Creates the jwt proof payload and header to be included in a credential request.
1639
+ */
1640
+ async createCredentialRequestJwtProof(options) {
1641
+ const credentialConfiguration = options.issuerMetadata.credentialIssuer.credential_configurations_supported[options.credentialConfigurationId];
1642
+ if (!credentialConfiguration) throw new Openid4vciError(`Credential configuration with '${options.credentialConfigurationId}' not found in 'credential_configurations_supported' from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`);
1643
+ if (credentialConfiguration.proof_types_supported) {
1644
+ if (!credentialConfiguration.proof_types_supported.jwt) throw new Openid4vciError(`Credential configuration with id '${options.credentialConfigurationId}' does not support the 'jwt' proof type.`);
1645
+ if (!credentialConfiguration.proof_types_supported.jwt.proof_signing_alg_values_supported.includes(options.signer.alg)) throw new Openid4vciError(`Credential configuration with id '${options.credentialConfigurationId}' does not support the '${options.signer.alg}' alg for 'jwt' proof type.`);
1646
+ if (credentialConfiguration.proof_types_supported.jwt.key_attestations_required && !options.keyAttestationJwt) throw new Openid4vciError(`Credential configuration with id '${options.credentialConfigurationId}' requires key attestations for 'jwt' proof type but no 'keyAttestationJwt' was provided`);
1647
+ }
1648
+ return { jwt: await createCredentialRequestJwtProof({
1649
+ credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,
1650
+ signer: options.signer,
1651
+ clientId: options.clientId,
1652
+ issuedAt: options.issuedAt,
1653
+ nonce: options.nonce,
1654
+ keyAttestationJwt: options.keyAttestationJwt,
1655
+ callbacks: this.options.callbacks
1656
+ }) };
1657
+ }
1658
+ /**
1659
+ * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response
1660
+ * @throws ValidationError - if validation of the credential request failed
1661
+ * @throws Openid4vciError - if the `credentialConfigurationId` couldn't be found, or if the the format specific request couldn't be constructed
1662
+ */
1663
+ async retrieveCredentials({ issuerMetadata, proof, proofs, credentialConfigurationId, additionalRequestPayload, accessToken, dpop }) {
1664
+ let credentialResponse;
1665
+ if (issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft15 || issuerMetadata.originalDraftVersion === Openid4vciDraftVersion.Draft16) credentialResponse = await retrieveCredentialsWithCredentialConfigurationId({
1666
+ accessToken,
1667
+ credentialConfigurationId,
1668
+ issuerMetadata,
1669
+ additionalRequestPayload,
1670
+ proof,
1671
+ proofs,
1672
+ callbacks: this.options.callbacks,
1673
+ dpop
1674
+ });
1675
+ else credentialResponse = await retrieveCredentialsWithFormat({
1676
+ accessToken,
1677
+ formatPayload: getCredentialRequestFormatPayloadForCredentialConfigurationId({
1678
+ credentialConfigurationId,
1679
+ issuerMetadata
1680
+ }),
1681
+ issuerMetadata,
1682
+ additionalRequestPayload,
1683
+ proof,
1684
+ proofs,
1685
+ callbacks: this.options.callbacks,
1686
+ dpop
1687
+ });
1688
+ if (!credentialResponse.ok) throw new Openid4vciRetrieveCredentialsError(`Error retrieving credentials from '${issuerMetadata.credentialIssuer.credential_issuer}'`, credentialResponse, await credentialResponse.response.clone().text());
1689
+ return credentialResponse;
1690
+ }
1691
+ /**
1692
+ * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response
1693
+ * @throws ValidationError - if validation of the credential request failed
1694
+ */
1695
+ async retrieveDeferredCredentials(options) {
1696
+ const credentialResponse = await retrieveDeferredCredentials({
1697
+ ...options,
1698
+ callbacks: this.options.callbacks
1699
+ });
1700
+ if (!credentialResponse.ok) throw new Openid4vciRetrieveCredentialsError(`Error retrieving deferred credentials from '${options.issuerMetadata.credentialIssuer.credential_issuer}'`, credentialResponse, await credentialResponse.response.clone().text());
1701
+ return credentialResponse;
1702
+ }
1703
+ /**
1704
+ * @throws Openid4vciSendNotificationError - if an unsuccessful response
1705
+ * @throws ValidationError - if validation of the notification request failed
1706
+ */
1707
+ async sendNotification({ issuerMetadata, notification, additionalRequestPayload, accessToken, dpop }) {
1708
+ const notificationResponse = await sendNotification({
1709
+ accessToken,
1710
+ issuerMetadata,
1711
+ additionalRequestPayload,
1712
+ callbacks: this.options.callbacks,
1713
+ dpop,
1714
+ notification
1715
+ });
1716
+ if (!notificationResponse.ok) throw new Openid4vciSendNotificationError(`Error sending notification to '${issuerMetadata.credentialIssuer.credential_issuer}'`, notificationResponse);
1717
+ return notificationResponse;
1718
+ }
2284
1719
  };
2285
1720
 
2286
- // src/Openid4vciIssuer.ts
2287
- import {
2288
- Oauth2AuthorizationServer,
2289
- Oauth2ErrorCodes as Oauth2ErrorCodes3,
2290
- Oauth2JwtVerificationError,
2291
- Oauth2ServerErrorResponseError
2292
- } from "@openid4vc/oauth2";
2293
- import { ValidationError as ValidationError4, parseWithErrorHandling as parseWithErrorHandling11 } from "@openid4vc/utils";
2294
-
2295
- // src/credential-request/credential-response.ts
2296
- import { parseWithErrorHandling as parseWithErrorHandling8 } from "@openid4vc/utils";
1721
+ //#endregion
1722
+ //#region src/credential-request/credential-response.ts
2297
1723
  function createCredentialResponse(options) {
2298
- return parseWithErrorHandling8(zCredentialResponse, {
2299
- c_nonce: options.cNonce,
2300
- c_nonce_expires_in: options.cNonceExpiresInSeconds,
2301
- credential: options.credential,
2302
- credentials: options.credentials,
2303
- notification_id: options.notificationId,
2304
- transaction_id: options.transactionId,
2305
- interval: options.interval,
2306
- // NOTE `format` is removed in draft 13. For now if a format was requested
2307
- // we just always return it in the response as well.
2308
- format: options.credentialRequest.format?.format,
2309
- ...options.additionalPayload
2310
- });
1724
+ return parseWithErrorHandling(zCredentialResponse, {
1725
+ c_nonce: options.cNonce,
1726
+ c_nonce_expires_in: options.cNonceExpiresInSeconds,
1727
+ credential: options.credential,
1728
+ credentials: options.credentials,
1729
+ notification_id: options.notificationId,
1730
+ transaction_id: options.transactionId,
1731
+ interval: options.interval,
1732
+ format: options.credentialRequest.format?.format,
1733
+ ...options.additionalPayload
1734
+ });
2311
1735
  }
2312
1736
  function createDeferredCredentialResponse(options) {
2313
- return parseWithErrorHandling8(zDeferredCredentialResponse, {
2314
- credentials: options.credentials,
2315
- notification_id: options.notificationId,
2316
- interval: options.interval,
2317
- ...options.additionalPayload
2318
- });
1737
+ return parseWithErrorHandling(zDeferredCredentialResponse, {
1738
+ credentials: options.credentials,
1739
+ notification_id: options.notificationId,
1740
+ interval: options.interval,
1741
+ ...options.additionalPayload
1742
+ });
2319
1743
  }
2320
1744
 
2321
- // src/credential-request/parse-credential-request.ts
2322
- import { parseWithErrorHandling as parseWithErrorHandling9 } from "@openid4vc/utils";
2323
- import z22 from "zod";
1745
+ //#endregion
1746
+ //#region src/credential-request/parse-credential-request.ts
2324
1747
  function parseCredentialRequest(options) {
2325
- const credentialRequest = parseWithErrorHandling9(
2326
- zCredentialRequest,
2327
- options.credentialRequest,
2328
- "Error validating credential request"
2329
- );
2330
- let proofs = void 0;
2331
- const knownProofs = zCredentialRequestProofs.strict().safeParse(credentialRequest.proofs);
2332
- if (knownProofs.success) {
2333
- proofs = knownProofs.data;
2334
- }
2335
- const knownProof = z22.union(allCredentialRequestProofs).safeParse(credentialRequest.proof);
2336
- if (knownProof.success && knownProof.data.proof_type === jwtProofTypeIdentifier) {
2337
- proofs = { [jwtProofTypeIdentifier]: [knownProof.data.jwt] };
2338
- } else if (knownProof.success && knownProof.data.proof_type === attestationProofTypeIdentifier) {
2339
- proofs = { [attestationProofTypeIdentifier]: [knownProof.data.attestation] };
2340
- }
2341
- if (credentialRequest.credential_configuration_id) {
2342
- getCredentialConfigurationSupportedById(
2343
- options.issuerMetadata.credentialIssuer.credential_configurations_supported,
2344
- credentialRequest.credential_configuration_id
2345
- );
2346
- const credentialConfigurations = extractKnownCredentialConfigurationSupportedFormats(
2347
- options.issuerMetadata.credentialIssuer.credential_configurations_supported
2348
- );
2349
- return {
2350
- credentialConfiguration: credentialConfigurations[credentialRequest.credential_configuration_id],
2351
- credentialConfigurationId: credentialRequest.credential_configuration_id,
2352
- credentialRequest,
2353
- proofs
2354
- };
2355
- }
2356
- if (credentialRequest.credential_identifier) {
2357
- return {
2358
- credentialIdentifier: credentialRequest.credential_identifier,
2359
- credentialRequest,
2360
- proofs
2361
- };
2362
- }
2363
- if (credentialRequest.format && allCredentialRequestFormatIdentifiers.includes(
2364
- credentialRequest.format
2365
- )) {
2366
- return {
2367
- // Removes all claims that are not specific to this format
2368
- format: parseWithErrorHandling9(
2369
- z22.union(allCredentialRequestFormats),
2370
- credentialRequest,
2371
- "Unable to validate format specific properties from credential request"
2372
- ),
2373
- credentialRequest,
2374
- proofs
2375
- };
2376
- }
2377
- return {
2378
- credentialRequest,
2379
- proofs
2380
- };
1748
+ const credentialRequest = parseWithErrorHandling(zCredentialRequest, options.credentialRequest, "Error validating credential request");
1749
+ let proofs;
1750
+ const knownProofs = zCredentialRequestProofs.strict().safeParse(credentialRequest.proofs);
1751
+ if (knownProofs.success) proofs = knownProofs.data;
1752
+ const knownProof = z.union(allCredentialRequestProofs).safeParse(credentialRequest.proof);
1753
+ if (knownProof.success && knownProof.data.proof_type === jwtProofTypeIdentifier) proofs = { [jwtProofTypeIdentifier]: [knownProof.data.jwt] };
1754
+ else if (knownProof.success && knownProof.data.proof_type === attestationProofTypeIdentifier) proofs = { [attestationProofTypeIdentifier]: [knownProof.data.attestation] };
1755
+ if (credentialRequest.credential_configuration_id) {
1756
+ getCredentialConfigurationSupportedById(options.issuerMetadata.credentialIssuer.credential_configurations_supported, credentialRequest.credential_configuration_id);
1757
+ return {
1758
+ credentialConfiguration: extractKnownCredentialConfigurationSupportedFormats(options.issuerMetadata.credentialIssuer.credential_configurations_supported)[credentialRequest.credential_configuration_id],
1759
+ credentialConfigurationId: credentialRequest.credential_configuration_id,
1760
+ credentialRequest,
1761
+ proofs
1762
+ };
1763
+ }
1764
+ if (credentialRequest.credential_identifier) return {
1765
+ credentialIdentifier: credentialRequest.credential_identifier,
1766
+ credentialRequest,
1767
+ proofs
1768
+ };
1769
+ if (credentialRequest.format && allCredentialRequestFormatIdentifiers.includes(credentialRequest.format)) return {
1770
+ format: parseWithErrorHandling(z.union(allCredentialRequestFormats), credentialRequest, "Unable to validate format specific properties from credential request"),
1771
+ credentialRequest,
1772
+ proofs
1773
+ };
1774
+ return {
1775
+ credentialRequest,
1776
+ proofs
1777
+ };
2381
1778
  }
2382
1779
 
2383
- // src/credential-request/parse-deferred-credential-request.ts
2384
- import { parseWithErrorHandling as parseWithErrorHandling10 } from "@openid4vc/utils";
1780
+ //#endregion
1781
+ //#region src/credential-request/parse-deferred-credential-request.ts
2385
1782
  function parseDeferredCredentialRequest(options) {
2386
- const deferredCredentialRequest = parseWithErrorHandling10(
2387
- zDeferredCredentialRequest,
2388
- options.deferredCredentialRequest,
2389
- "Error validating credential request"
2390
- );
2391
- return {
2392
- deferredCredentialRequest
2393
- };
1783
+ return { deferredCredentialRequest: parseWithErrorHandling(zDeferredCredentialRequest, options.deferredCredentialRequest, "Error validating credential request") };
2394
1784
  }
2395
1785
 
2396
- // src/formats/proof-type/attestation/attestation-proof-type.ts
1786
+ //#endregion
1787
+ //#region src/formats/proof-type/attestation/attestation-proof-type.ts
2397
1788
  async function verifyCredentialRequestAttestationProof(options) {
2398
- const verificationResult = await verifyKeyAttestationJwt({
2399
- ...options,
2400
- use: "proof_type.attestation"
2401
- });
2402
- return verificationResult;
1789
+ return await verifyKeyAttestationJwt({
1790
+ ...options,
1791
+ use: "proof_type.attestation"
1792
+ });
2403
1793
  }
2404
1794
 
2405
- // src/Openid4vciIssuer.ts
1795
+ //#endregion
1796
+ //#region src/Openid4vciIssuer.ts
2406
1797
  var Openid4vciIssuer = class {
2407
- constructor(options) {
2408
- this.options = options;
2409
- }
2410
- getCredentialIssuerMetadataDraft11(credentialIssuerMetadata) {
2411
- return parseWithErrorHandling11(zCredentialIssuerMetadataWithDraft11, credentialIssuerMetadata);
2412
- }
2413
- getKnownCredentialConfigurationsSupported(credentialIssuerMetadata) {
2414
- return extractKnownCredentialConfigurationSupportedFormats(
2415
- credentialIssuerMetadata.credential_configurations_supported
2416
- );
2417
- }
2418
- /**
2419
- * Create issuer metadata and validates the structure is correct
2420
- */
2421
- createCredentialIssuerMetadata(credentialIssuerMetadata) {
2422
- return parseWithErrorHandling11(
2423
- zCredentialIssuerMetadata,
2424
- credentialIssuerMetadata,
2425
- "Error validating credential issuer metadata"
2426
- );
2427
- }
2428
- async createCredentialOffer(options) {
2429
- return createCredentialOffer({
2430
- callbacks: this.options.callbacks,
2431
- credentialConfigurationIds: options.credentialConfigurationIds,
2432
- grants: options.grants,
2433
- issuerMetadata: options.issuerMetadata,
2434
- additionalPayload: options.additionalPayload,
2435
- credentialOfferScheme: options.credentialOfferScheme,
2436
- credentialOfferUri: options.credentialOfferUri
2437
- });
2438
- }
2439
- /**
2440
- * @throws Oauth2ServerErrorResponseError - if verification of the jwt failed. You can extract
2441
- * the credential error response from this.
2442
- */
2443
- async verifyCredentialRequestJwtProof(options) {
2444
- try {
2445
- return await verifyCredentialRequestJwtProof({
2446
- callbacks: this.options.callbacks,
2447
- credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,
2448
- expectedNonce: options.expectedNonce,
2449
- nonceExpiresAt: options.nonceExpiresAt,
2450
- jwt: options.jwt,
2451
- clientId: options.clientId,
2452
- now: options.now
2453
- });
2454
- } catch (error) {
2455
- throw new Oauth2ServerErrorResponseError(
2456
- {
2457
- error: Oauth2ErrorCodes3.InvalidProof,
2458
- error_description: (
2459
- // TODO: error should have a internalErrorMessage and a publicErrorMessage
2460
- error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError ? error.message : "Invalid proof"
2461
- )
2462
- },
2463
- {
2464
- internalMessage: "Error verifying credential request proof jwt",
2465
- cause: error
2466
- }
2467
- );
2468
- }
2469
- }
2470
- /**
2471
- * @throws Oauth2ServerErrorResponseError - if verification of the key attestation failed. You can extract
2472
- * the credential error response from this.
2473
- */
2474
- async verifyCredentialRequestAttestationProof(options) {
2475
- try {
2476
- return await verifyCredentialRequestAttestationProof({
2477
- callbacks: this.options.callbacks,
2478
- expectedNonce: options.expectedNonce,
2479
- keyAttestationJwt: options.keyAttestationJwt,
2480
- nonceExpiresAt: options.nonceExpiresAt,
2481
- now: options.now
2482
- });
2483
- } catch (error) {
2484
- throw new Oauth2ServerErrorResponseError(
2485
- {
2486
- error: Oauth2ErrorCodes3.InvalidProof,
2487
- error_description: (
2488
- // TODO: error should have a internalErrorMessage and a publicErrorMessage
2489
- error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError ? error.message : "Invalid proof"
2490
- )
2491
- },
2492
- {
2493
- internalMessage: "Error verifying credential request proof attestation",
2494
- cause: error
2495
- }
2496
- );
2497
- }
2498
- }
2499
- /**
2500
- * @throws Oauth2ServerErrorResponseError - when validation of the credential request fails
2501
- * You can extract the credential error response from this.
2502
- */
2503
- parseCredentialRequest(options) {
2504
- try {
2505
- return parseCredentialRequest(options);
2506
- } catch (error) {
2507
- throw new Oauth2ServerErrorResponseError(
2508
- {
2509
- error: Oauth2ErrorCodes3.InvalidCredentialRequest,
2510
- error_description: (
2511
- // TODO: error should have a internalErrorMessage and a publicErrorMessage
2512
- error instanceof ValidationError4 ? error.message : "Invalid request"
2513
- )
2514
- },
2515
- {
2516
- internalMessage: "Error verifying credential request proof jwt",
2517
- cause: error
2518
- }
2519
- );
2520
- }
2521
- }
2522
- /**
2523
- * @throws Oauth2ServerErrorResponseError - when validation of the deferred credential request fails
2524
- */
2525
- parseDeferredCredentialRequest(options) {
2526
- try {
2527
- return parseDeferredCredentialRequest(options);
2528
- } catch (error) {
2529
- throw new Oauth2ServerErrorResponseError(
2530
- {
2531
- error: Oauth2ErrorCodes3.InvalidCredentialRequest,
2532
- error_description: error instanceof ValidationError4 ? error.message : "Invalid request"
2533
- },
2534
- {
2535
- internalMessage: "Error parsing deferred credential request",
2536
- cause: error
2537
- }
2538
- );
2539
- }
2540
- }
2541
- /**
2542
- * @throws ValidationError - when validation of the credential response fails
2543
- */
2544
- createCredentialResponse(options) {
2545
- return createCredentialResponse(options);
2546
- }
2547
- /**
2548
- * @throws ValidationError - when validation of the credential response fails
2549
- */
2550
- createDeferredCredentialResponse(options) {
2551
- return createDeferredCredentialResponse(options);
2552
- }
2553
- /**
2554
- * @throws ValidationError - when validation of the nonce response fails
2555
- */
2556
- createNonceResponse(options) {
2557
- return createNonceResponse(options);
2558
- }
2559
- async verifyWalletAttestation(options) {
2560
- return new Oauth2AuthorizationServer({
2561
- callbacks: this.options.callbacks
2562
- }).verifyClientAttestation(options);
2563
- }
1798
+ constructor(options) {
1799
+ this.options = options;
1800
+ }
1801
+ getCredentialIssuerMetadataDraft11(credentialIssuerMetadata) {
1802
+ return parseWithErrorHandling(zCredentialIssuerMetadataWithDraft11, credentialIssuerMetadata);
1803
+ }
1804
+ getKnownCredentialConfigurationsSupported(credentialIssuerMetadata) {
1805
+ return extractKnownCredentialConfigurationSupportedFormats(credentialIssuerMetadata.credential_configurations_supported);
1806
+ }
1807
+ /**
1808
+ * Create issuer metadata and validates the structure is correct
1809
+ */
1810
+ createCredentialIssuerMetadata(credentialIssuerMetadata) {
1811
+ return parseWithErrorHandling(zCredentialIssuerMetadata, credentialIssuerMetadata, "Error validating credential issuer metadata");
1812
+ }
1813
+ async createCredentialOffer(options) {
1814
+ return createCredentialOffer({
1815
+ callbacks: this.options.callbacks,
1816
+ credentialConfigurationIds: options.credentialConfigurationIds,
1817
+ grants: options.grants,
1818
+ issuerMetadata: options.issuerMetadata,
1819
+ additionalPayload: options.additionalPayload,
1820
+ credentialOfferScheme: options.credentialOfferScheme,
1821
+ credentialOfferUri: options.credentialOfferUri
1822
+ });
1823
+ }
1824
+ /**
1825
+ * @throws Oauth2ServerErrorResponseError - if verification of the jwt failed. You can extract
1826
+ * the credential error response from this.
1827
+ */
1828
+ async verifyCredentialRequestJwtProof(options) {
1829
+ try {
1830
+ return await verifyCredentialRequestJwtProof({
1831
+ callbacks: this.options.callbacks,
1832
+ credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,
1833
+ expectedNonce: options.expectedNonce,
1834
+ nonceExpiresAt: options.nonceExpiresAt,
1835
+ jwt: options.jwt,
1836
+ clientId: options.clientId,
1837
+ now: options.now
1838
+ });
1839
+ } catch (error) {
1840
+ throw new Oauth2ServerErrorResponseError({
1841
+ error: Oauth2ErrorCodes.InvalidProof,
1842
+ error_description: error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError ? error.message : "Invalid proof"
1843
+ }, {
1844
+ internalMessage: "Error verifying credential request proof jwt",
1845
+ cause: error
1846
+ });
1847
+ }
1848
+ }
1849
+ /**
1850
+ * @throws Oauth2ServerErrorResponseError - if verification of the key attestation failed. You can extract
1851
+ * the credential error response from this.
1852
+ */
1853
+ async verifyCredentialRequestAttestationProof(options) {
1854
+ try {
1855
+ return await verifyCredentialRequestAttestationProof({
1856
+ callbacks: this.options.callbacks,
1857
+ expectedNonce: options.expectedNonce,
1858
+ keyAttestationJwt: options.keyAttestationJwt,
1859
+ nonceExpiresAt: options.nonceExpiresAt,
1860
+ now: options.now
1861
+ });
1862
+ } catch (error) {
1863
+ throw new Oauth2ServerErrorResponseError({
1864
+ error: Oauth2ErrorCodes.InvalidProof,
1865
+ error_description: error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError ? error.message : "Invalid proof"
1866
+ }, {
1867
+ internalMessage: "Error verifying credential request proof attestation",
1868
+ cause: error
1869
+ });
1870
+ }
1871
+ }
1872
+ /**
1873
+ * @throws Oauth2ServerErrorResponseError - when validation of the credential request fails
1874
+ * You can extract the credential error response from this.
1875
+ */
1876
+ parseCredentialRequest(options) {
1877
+ try {
1878
+ return parseCredentialRequest(options);
1879
+ } catch (error) {
1880
+ throw new Oauth2ServerErrorResponseError({
1881
+ error: Oauth2ErrorCodes.InvalidCredentialRequest,
1882
+ error_description: error instanceof ValidationError ? error.message : "Invalid request"
1883
+ }, {
1884
+ internalMessage: "Error verifying credential request proof jwt",
1885
+ cause: error
1886
+ });
1887
+ }
1888
+ }
1889
+ /**
1890
+ * @throws Oauth2ServerErrorResponseError - when validation of the deferred credential request fails
1891
+ */
1892
+ parseDeferredCredentialRequest(options) {
1893
+ try {
1894
+ return parseDeferredCredentialRequest(options);
1895
+ } catch (error) {
1896
+ throw new Oauth2ServerErrorResponseError({
1897
+ error: Oauth2ErrorCodes.InvalidCredentialRequest,
1898
+ error_description: error instanceof ValidationError ? error.message : "Invalid request"
1899
+ }, {
1900
+ internalMessage: "Error parsing deferred credential request",
1901
+ cause: error
1902
+ });
1903
+ }
1904
+ }
1905
+ /**
1906
+ * @throws ValidationError - when validation of the credential response fails
1907
+ */
1908
+ createCredentialResponse(options) {
1909
+ return createCredentialResponse(options);
1910
+ }
1911
+ /**
1912
+ * @throws ValidationError - when validation of the credential response fails
1913
+ */
1914
+ createDeferredCredentialResponse(options) {
1915
+ return createDeferredCredentialResponse(options);
1916
+ }
1917
+ /**
1918
+ * @throws ValidationError - when validation of the nonce response fails
1919
+ */
1920
+ createNonceResponse(options) {
1921
+ return createNonceResponse(options);
1922
+ }
1923
+ async verifyWalletAttestation(options) {
1924
+ return new Oauth2AuthorizationServer({ callbacks: this.options.callbacks }).verifyClientAttestation(options);
1925
+ }
2564
1926
  };
2565
1927
 
2566
- // src/Openid4vciWalletProvider.ts
2567
- import {
2568
- createClientAttestationJwt
2569
- } from "@openid4vc/oauth2";
1928
+ //#endregion
1929
+ //#region src/Openid4vciWalletProvider.ts
2570
1930
  var Openid4vciWalletProvider = class {
2571
- constructor(options) {
2572
- this.options = options;
2573
- }
2574
- async createWalletAttestationJwt(options) {
2575
- const additionalPayload = options.additionalPayload ? {
2576
- wallet_name: options.walletName,
2577
- wallet_link: options.walletLink,
2578
- ...options.additionalPayload
2579
- } : {
2580
- wallet_name: options.walletName,
2581
- wallet_link: options.walletLink
2582
- };
2583
- return await createClientAttestationJwt({
2584
- ...options,
2585
- callbacks: this.options.callbacks,
2586
- additionalPayload
2587
- });
2588
- }
2589
- async createKeyAttestationJwt(options) {
2590
- return await createKeyAttestationJwt({
2591
- callbacks: this.options.callbacks,
2592
- ...options
2593
- });
2594
- }
2595
- };
2596
- export {
2597
- AuthorizationFlow,
2598
- Openid4vciClient,
2599
- Openid4vciDraftVersion,
2600
- Openid4vciError,
2601
- Openid4vciIssuer,
2602
- Openid4vciRetrieveCredentialsError,
2603
- Openid4vciSendNotificationError,
2604
- Openid4vciWalletProvider,
2605
- createKeyAttestationJwt,
2606
- credentialsSupportedToCredentialConfigurationsSupported,
2607
- determineAuthorizationServerForCredentialOffer,
2608
- extractScopesForCredentialConfigurationIds,
2609
- getCredentialConfigurationsMatchingRequestFormat,
2610
- getGlobalConfig,
2611
- parseKeyAttestationJwt,
2612
- setGlobalConfig,
2613
- verifyKeyAttestationJwt
1931
+ constructor(options) {
1932
+ this.options = options;
1933
+ }
1934
+ async createWalletAttestationJwt(options) {
1935
+ const additionalPayload = options.additionalPayload ? {
1936
+ wallet_name: options.walletName,
1937
+ wallet_link: options.walletLink,
1938
+ ...options.additionalPayload
1939
+ } : {
1940
+ wallet_name: options.walletName,
1941
+ wallet_link: options.walletLink
1942
+ };
1943
+ return await createClientAttestationJwt({
1944
+ ...options,
1945
+ callbacks: this.options.callbacks,
1946
+ additionalPayload
1947
+ });
1948
+ }
1949
+ async createKeyAttestationJwt(options) {
1950
+ return await createKeyAttestationJwt({
1951
+ callbacks: this.options.callbacks,
1952
+ ...options
1953
+ });
1954
+ }
2614
1955
  };
1956
+
1957
+ //#endregion
1958
+ export { AuthorizationFlow, Openid4vciClient, Openid4vciDraftVersion, Openid4vciError, Openid4vciIssuer, Openid4vciRetrieveCredentialsError, Openid4vciSendNotificationError, Openid4vciWalletProvider, createKeyAttestationJwt, credentialsSupportedToCredentialConfigurationsSupported, determineAuthorizationServerForCredentialOffer, extractScopesForCredentialConfigurationIds, getCredentialConfigurationsMatchingRequestFormat, getGlobalConfig, parseKeyAttestationJwt, setGlobalConfig, verifyKeyAttestationJwt };
2615
1959
  //# sourceMappingURL=index.mjs.map