@openid4vc/openid4vci 0.4.5-alpha-20260126081433 → 0.4.5-alpha-20260201123930
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 +5 -5
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Oauth2ErrorCodes"],"sources":["../src/version.ts","../src/credential-offer/z-credential-offer.ts","../src/credential-offer/credential-offer.ts","../src/credential-request/credential-request-configurations.ts","../src/error/Openid4vciError.ts","../src/error/Openid4vciRetrieveCredentialsError.ts","../src/error/Openid4vciSendNotificationError.ts","../src/key-attestation/z-key-attestation.ts","../src/key-attestation/key-attestation.ts","../src/metadata/credential-issuer/z-claims-description.ts","../src/metadata/credential-issuer/z-credential-configuration-supported-common.ts","../src/formats/credential/mso-mdoc/z-mso-mdoc.ts","../src/formats/credential/sd-jwt-dc/z-sd-jwt-dc.ts","../src/formats/credential/sd-jwt-vc/z-sd-jwt-vc.ts","../src/formats/credential/w3c-vc/z-w3c-vc-common.ts","../src/formats/credential/w3c-vc/z-w3c-jwt-vc-json.ts","../src/formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld.ts","../src/formats/credential/w3c-vc/z-w3c-ldp-vc.ts","../src/formats/credential/w3c-vc/z-w3c-sd-jwt-vc.ts","../src/metadata/credential-issuer/z-credential-issuer-metadata.ts","../src/metadata/credential-issuer/credential-configurations.ts","../src/metadata/credential-issuer/z-signed-credential-issuer-metadata.ts","../src/metadata/credential-issuer/credential-issuer-metadata.ts","../src/credential-request/format-payload.ts","../src/formats/proof-type/attestation/z-attestation-proof-type.ts","../src/formats/proof-type/jwt/z-jwt-proof-type.ts","../src/credential-request/z-credential-request-common.ts","../src/credential-request/z-credential-request.ts","../../oauth2/src/common/z-oauth2-error.ts","../src/credential-request/z-credential-response.ts","../src/credential-request/retrieve-credentials.ts","../src/formats/proof-type/jwt/jwt-proof-type.ts","../src/metadata/fetch-issuer-metadata.ts","../src/nonce/z-nonce.ts","../src/nonce/nonce-request.ts","../src/notification/z-notification.ts","../src/notification/notification.ts","../src/Openid4vciClient.ts","../src/credential-request/credential-response.ts","../src/credential-request/parse-credential-request.ts","../src/credential-request/parse-deferred-credential-request.ts","../src/formats/proof-type/attestation/attestation-proof-type.ts","../src/metadata/credential-issuer/signed-credential-issuer-metadata.ts","../src/Openid4vciIssuer.ts","../src/Openid4vciWalletProvider.ts"],"sourcesContent":["export enum Openid4vciVersion {\n V1 = 'V1',\n Draft15 = 'Draft15',\n Draft14 = 'Draft14',\n Draft11 = 'Draft11',\n}\n\n/**\n * @deprecated use `OpenId4vciVersion` instead\n */\nexport const Openid4vciDraftVersion = Openid4vciVersion\n","import {\n type AuthorizationCodeGrantIdentifier,\n type PreAuthorizedCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n} from '@openid4vc/oauth2'\nimport { zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\n\nconst zTxCode = z\n .object({\n input_mode: z.union([z.literal('numeric'), z.literal('text')]).optional(),\n length: z.number().int().optional(),\n description: z.string().max(300).optional(),\n })\n .loose()\n\nexport type CredentialOfferPreAuthorizedCodeGrantTxCode = z.input<typeof zTxCode>\n\nexport const zCredentialOfferGrants = z\n .object({\n authorization_code: z\n .object({\n issuer_state: z.string().optional(),\n authorization_server: zHttpsUrl.optional(),\n })\n .loose()\n .optional(),\n [preAuthorizedCodeGrantIdentifier]: z\n .object({\n 'pre-authorized_code': z.string(),\n tx_code: zTxCode.optional(),\n authorization_server: zHttpsUrl.optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nexport type CredentialOfferGrants = z.input<typeof zCredentialOfferGrants>\n\nexport type CredentialOfferPreAuthorizedCodeGrant = CredentialOfferGrants[PreAuthorizedCodeGrantIdentifier]\nexport type CredentialOfferAuthorizationCodeGrant = CredentialOfferGrants[AuthorizationCodeGrantIdentifier]\n\nconst zCredentialOfferObjectDraft14 = z\n .object({\n credential_issuer: zHttpsUrl,\n credential_configuration_ids: z.array(z.string()),\n grants: z.optional(zCredentialOfferGrants),\n })\n .loose()\nexport type CredentialOfferObject = z.input<typeof zCredentialOfferObjectDraft14>\n\nexport const zCredentialOfferObjectDraft11To14 = z\n .object({\n credential_issuer: zHttpsUrl,\n // We don't support the inline offer objects from draft 11\n credentials: z.array(\n z.string({ message: 'Only string credential identifiers are supported for draft 11 credential offers' })\n ),\n grants: z.optional(\n z.object({\n // Has extra param in draft 14, but doesn't matter for transform purposes\n authorization_code: zCredentialOfferGrants.shape.authorization_code,\n\n [preAuthorizedCodeGrantIdentifier]: z\n .object({\n 'pre-authorized_code': z.string(),\n user_pin_required: z.optional(z.boolean()),\n })\n .loose()\n .optional(),\n })\n ),\n })\n .loose()\n .transform(({ credentials, grants, ...rest }) => {\n const v14: CredentialOfferObject = {\n ...rest,\n credential_configuration_ids: credentials,\n }\n\n if (grants) {\n v14.grants = { ...grants }\n\n if (grants[preAuthorizedCodeGrantIdentifier]) {\n const { user_pin_required, ...restGrants } = grants[preAuthorizedCodeGrantIdentifier]\n\n v14.grants[preAuthorizedCodeGrantIdentifier] = {\n ...restGrants,\n }\n\n if (user_pin_required) {\n v14.grants[preAuthorizedCodeGrantIdentifier].tx_code = {\n input_mode: 'text',\n }\n }\n }\n }\n\n return v14\n })\n .pipe(zCredentialOfferObjectDraft14)\n\nexport const zCredentialOfferObject = z.union([\n // First prioritize draft 14 (and 13)\n zCredentialOfferObjectDraft14,\n // Then try parsing draft 11 and transform into draft 14\n zCredentialOfferObjectDraft11To14,\n])\n","import {\n type AuthorizationCodeGrantIdentifier,\n authorizationCodeGrantIdentifier,\n type CallbackContext,\n getAuthorizationServerMetadataFromList,\n InvalidFetchResponseError,\n Oauth2Error,\n type PreAuthorizedCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n} from '@openid4vc/oauth2'\nimport {\n ContentType,\n createZodFetcher,\n encodeToBase64Url,\n type Fetch,\n getQueryParams,\n objectToQueryParams,\n parseWithErrorHandling,\n URL,\n URLSearchParams,\n ValidationError,\n} from '@openid4vc/utils'\nimport type z from 'zod'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport {\n type CredentialOfferAuthorizationCodeGrant,\n type CredentialOfferGrants,\n type CredentialOfferObject,\n type CredentialOfferPreAuthorizedCodeGrant,\n zCredentialOfferObject,\n} from './z-credential-offer'\n\nexport interface ResolveCredentialOfferOptions {\n /**\n * Custom fetch implementation to use\n */\n fetch?: Fetch\n}\n\n/**\n * Resolve a credential offer, optionally fetching it if the credential_offer_uri is provided.\n */\nexport async function resolveCredentialOffer(\n credentialOffer: string,\n options?: ResolveCredentialOfferOptions\n): Promise<CredentialOfferObject> {\n const parsedQueryParams = getQueryParams(credentialOffer)\n\n let credentialOfferParseResult: z.ZodSafeParseResult<z.infer<typeof zCredentialOfferObject>>\n\n if (parsedQueryParams.credential_offer_uri) {\n const fetchWithZod = createZodFetcher(options?.fetch)\n\n const { response, result } = await fetchWithZod(\n zCredentialOfferObject,\n ContentType.Json,\n parsedQueryParams.credential_offer_uri\n )\n if (!response.ok || !result) {\n throw new InvalidFetchResponseError(\n `Fetching credential offer from '${parsedQueryParams.credential_offer_uri}' resulted in an unsuccessful response with status '${response.status}'`,\n await response.clone().text(),\n response\n )\n }\n\n credentialOfferParseResult = result\n } else if (parsedQueryParams.credential_offer) {\n let credentialOfferJson: Record<string, unknown>\n\n try {\n credentialOfferJson = JSON.parse(decodeURIComponent(parsedQueryParams.credential_offer))\n } catch (_error) {\n throw new Oauth2Error(`Error parsing JSON from 'credential_offer' param in credential offer '${credentialOffer}'`)\n }\n\n credentialOfferParseResult = zCredentialOfferObject.safeParse(credentialOfferJson)\n } else {\n throw new Oauth2Error(`Credential offer did not contain either 'credential_offer' or 'credential_offer_uri' param.`)\n }\n\n if (credentialOfferParseResult.error) {\n throw new ValidationError(\n `Error parsing credential offer in draft 11, 13 or 14 format extracted from credential offer '${credentialOffer}'`,\n credentialOfferParseResult.error\n )\n }\n\n return credentialOfferParseResult.data\n}\n\nexport interface CreateCredentialOfferGrantsOptions {\n [preAuthorizedCodeGrantIdentifier]?: Partial<CredentialOfferPreAuthorizedCodeGrant>\n [authorizationCodeGrantIdentifier]?: CredentialOfferAuthorizationCodeGrant\n\n [key: string]: unknown\n}\n\nexport interface CreateCredentialOfferOptions {\n issuerMetadata: IssuerMetadataResult\n\n /**\n * The credential configuration ids to be offered\n */\n credentialConfigurationIds: string[]\n\n /**\n * Grants to include in the credential offer\n */\n grants: CreateCredentialOfferGrantsOptions\n\n /**\n * Additional payload to include in the body of the credential offer. Will be applied\n * after the other fields, allowing to override common properties, so be cautious.\n */\n additionalPayload?: Record<string, unknown>\n\n /**\n * If provided the encoded credential offer will use the `credential_offer_uri` parameter\n * instead of directly adding the `credential_offer`. Requires hosting of the `credential_offer_uri`\n */\n credentialOfferUri?: string\n\n /**\n * The scheme to use for the credential offer.\n *\n * @default `openid-credential-offer://`\n */\n credentialOfferScheme?: string\n\n /**\n * Callbacks used to create credential offer\n */\n callbacks: Pick<CallbackContext, 'generateRandom'>\n}\n\ninterface DetermineAuthorizationServerForGrant {\n issuerMetadata: IssuerMetadataResult\n grantAuthorizationServer?: string\n}\n\nexport function determineAuthorizationServerForCredentialOffer(options: DetermineAuthorizationServerForGrant) {\n const authorizationServers = options.issuerMetadata.credentialIssuer.authorization_servers\n\n let authorizationServer: string\n if (options.grantAuthorizationServer) {\n authorizationServer = options.grantAuthorizationServer\n\n if (!authorizationServers) {\n throw new Oauth2Error(\n `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.`\n )\n }\n if (!authorizationServers.includes(authorizationServer)) {\n throw new Oauth2Error(\n `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(', ')}.`\n )\n }\n } else if (!authorizationServers) {\n authorizationServer = options.issuerMetadata.credentialIssuer.credential_issuer\n } else {\n if (authorizationServers.length === 0) {\n throw new Oauth2Error(`Credential issuer metadata has 'authorization_servers' value with length of 0`)\n }\n if (authorizationServers.length > 1) {\n throw new Oauth2Error(\n `Credential issuer metadata has 'authorization_server' with multiple entries, but the credential offer grant did not specify which authorization server to use.`\n )\n }\n\n authorizationServer = authorizationServers[0]\n }\n\n return authorizationServer\n}\n\nexport async function createCredentialOffer(\n options: CreateCredentialOfferOptions\n): Promise<{ credentialOffer: string; credentialOfferObject: CredentialOfferObject }> {\n const {\n [preAuthorizedCodeGrantIdentifier]: preAuthorizedCodeGrant,\n [authorizationCodeGrantIdentifier]: authorizationCodeGrant,\n ...restGrants\n } = options.grants\n const grants: CredentialOfferGrants = { ...restGrants }\n\n if (authorizationCodeGrant) {\n determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n grants[authorizationCodeGrantIdentifier] = authorizationCodeGrant\n }\n\n if (preAuthorizedCodeGrant) {\n determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: preAuthorizedCodeGrant.authorization_server,\n })\n\n grants[preAuthorizedCodeGrantIdentifier] = {\n ...preAuthorizedCodeGrant,\n 'pre-authorized_code':\n preAuthorizedCodeGrant['pre-authorized_code'] ?? encodeToBase64Url(await options.callbacks.generateRandom(32)),\n }\n\n // Draft 11 support\n const txCode = grants[preAuthorizedCodeGrantIdentifier].tx_code\n if (txCode && options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n grants[preAuthorizedCodeGrantIdentifier].user_pin_required = txCode !== undefined\n }\n }\n\n const idsNotInMetadata = options.credentialConfigurationIds.filter(\n (id) => options.issuerMetadata.credentialIssuer.credential_configurations_supported[id] === undefined\n )\n if (idsNotInMetadata.length > 0) {\n throw new Oauth2Error(\n `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(', ')}.`\n )\n }\n\n const credentialOfferScheme = options.credentialOfferScheme ?? 'openid-credential-offer://'\n const credentialOfferObject = parseWithErrorHandling(zCredentialOfferObject, {\n credential_issuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n credential_configuration_ids: options.credentialConfigurationIds,\n grants,\n ...options.additionalPayload,\n } satisfies CredentialOfferObject)\n\n // Draft 11 support\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n credentialOfferObject.credentials = credentialOfferObject.credential_configuration_ids\n }\n\n const url = new URL(credentialOfferScheme)\n url.search = `?${new URLSearchParams([\n ...url.searchParams.entries(),\n ...objectToQueryParams({\n credential_offer_uri: options.credentialOfferUri,\n // Only add credential_offer is uri is undefined\n credential_offer: options.credentialOfferUri ? undefined : credentialOfferObject,\n }).entries(),\n ]).toString()}`\n\n return {\n credentialOffer: url.toString(),\n credentialOfferObject,\n }\n}\n\n/**\n * Extract the authorization servers from the grants in a credential offer. If no authorization servers\n * are present, null is returned.\n */\nexport function extractAuthorizationServersFromCredentialOfferObject(\n credentialOfferObject: CredentialOfferObject\n): string[] | null {\n const authorizationServers: string[] = []\n\n if (credentialOfferObject.grants?.[preAuthorizedCodeGrantIdentifier]?.authorization_server) {\n authorizationServers.push(credentialOfferObject.grants?.[preAuthorizedCodeGrantIdentifier]?.authorization_server)\n }\n\n if (credentialOfferObject.grants?.authorization_code?.authorization_server) {\n authorizationServers.push(credentialOfferObject.grants?.authorization_code?.authorization_server)\n }\n\n return authorizationServers.length > 0 ? authorizationServers : null\n}\n\nexport interface DetermineAuthorizationForOfferOptions {\n grantType: PreAuthorizedCodeGrantIdentifier | AuthorizationCodeGrantIdentifier\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function determineAuthorizationServerForOffer(options: DetermineAuthorizationForOfferOptions) {\n // Try infer authorization server based on credential offer\n const authorizationServer = options.credentialOffer.grants?.[options.grantType]?.authorization_server\n if (authorizationServer) {\n return getAuthorizationServerMetadataFromList(options.issuerMetadata.authorizationServers, authorizationServer)\n }\n\n // Otherwise if there's only one we can use that\n if (options.issuerMetadata.authorizationServers.length === 1) {\n return options.issuerMetadata.authorizationServers[0]\n }\n\n // We can't safely determine the authorization server\n throw new Oauth2Error(\n `Unable to determine authorization server. Multiple authorization servers available and credential offer does not specify which 'authorization_server' to use for the '${options.grantType}' grant type.`\n )\n}\n","import { arrayEqualsIgnoreOrder } from '@openid4vc/utils'\nimport type { CredentialConfigurationsSupportedWithFormats } from '../metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport type { CredentialRequestFormatSpecific } from './z-credential-request'\n\nexport interface GetCredentialConfigurationsMatchingRequestFormatOptions {\n requestFormat: CredentialRequestFormatSpecific\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function getCredentialConfigurationsMatchingRequestFormat({\n requestFormat,\n issuerMetadata,\n}: GetCredentialConfigurationsMatchingRequestFormatOptions): CredentialConfigurationsSupportedWithFormats {\n // credential request format will only contain known formats\n const knownCredentialConfigurations = issuerMetadata.knownCredentialConfigurations\n\n return Object.fromEntries(\n Object.entries(knownCredentialConfigurations).filter(([, credentialConfiguration]) => {\n // Special case to handle vc+sd-jwt to dc+sd-jwt change\n const isSpecialVcToDcSdJwt =\n credentialConfiguration.format === 'dc+sd-jwt' && requestFormat.format === 'vc+sd-jwt'\n // NOTE: ideally we also check for the draft version fo the original issuer metadata\n // but in case you support multiple draft versions as issuer the original version will be 1.0\n // even though you have backwards support for e.g. Draft 11. If we want to check this we would need\n // to have a min/max version, like we have for OpenID4VP. So for now we just allow requests with formats\n // vc+sd-jwt even if the metadata only contains dc+sd-jwt. You can easily handle it on a higher level\n // if you don't want to support this multi-draft support.\n // [Openid4vciVersion.Draft11, Openid4vciVersion.Draft14].includes(issuerMetadata.originalDraftVersion)\n\n if (credentialConfiguration.format !== requestFormat.format && !isSpecialVcToDcSdJwt) return false\n\n const r = requestFormat\n const c = credentialConfiguration\n\n if ((c.format === 'ldp_vc' || c.format === 'jwt_vc_json-ld') && r.format === c.format) {\n return (\n arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type) &&\n arrayEqualsIgnoreOrder(r.credential_definition['@context'], c.credential_definition['@context'])\n )\n }\n\n if (c.format === 'jwt_vc_json' && r.format === c.format) {\n return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type)\n }\n\n if (r.format === 'vc+sd-jwt' && (c.format === 'vc+sd-jwt' || c.format === 'dc+sd-jwt')) {\n if (r.vct && c.vct) {\n return r.vct === c.vct\n }\n\n if (c.format === 'vc+sd-jwt' && c.credential_definition && r.credential_definition) {\n return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type)\n }\n }\n\n if (c.format === 'mso_mdoc' && r.format === c.format) {\n return r.doctype === c.doctype\n }\n\n return false\n })\n )\n}\n","export interface Openid4vciErrorOptions {\n cause?: unknown\n}\n\nexport class Openid4vciError extends Error {\n public readonly cause?: unknown\n\n public constructor(message?: string, options?: Openid4vciErrorOptions) {\n const errorMessage = message ?? 'Unknown error occurred.'\n const causeMessage =\n options?.cause instanceof Error ? ` ${options.cause.message}` : options?.cause ? ` ${options?.cause}` : ''\n\n super(`${errorMessage}${causeMessage}`)\n this.cause = options?.cause\n }\n}\n","import { formatZodError } from '@openid4vc/utils'\nimport type { RetrieveCredentialsResponseNotOk } from '../credential-request/retrieve-credentials'\nimport { Openid4vciError } from './Openid4vciError'\n\nexport class Openid4vciRetrieveCredentialsError extends Openid4vciError {\n public constructor(\n message: string,\n public response: RetrieveCredentialsResponseNotOk,\n responseText: string\n ) {\n const errorData =\n response.credentialResponseResult?.data ??\n response.credentialErrorResponseResult?.data ??\n (response.credentialResponseResult?.error\n ? formatZodError(response.credentialResponseResult.error)\n : undefined) ??\n responseText\n\n super(`${message}\\n${JSON.stringify(errorData, null, 2)}`)\n }\n}\n","import type { SendNotificationResponseNotOk } from '../notification/notification'\nimport { Openid4vciError } from './Openid4vciError'\n\nexport class Openid4vciSendNotificationError extends Openid4vciError {\n public constructor(\n message: string,\n public response: SendNotificationResponseNotOk\n ) {\n super(message)\n }\n}\n","import { zJwk, zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zInteger } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport type KeyAttestationJwtUse = 'proof_type.jwt' | 'proof_type.attestation'\n\nexport const zKeyAttestationJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z\n // Draft 15\n .literal('keyattestation+jwt')\n .or(\n // Draft 16\n z.literal('key-attestation+jwt')\n ),\n })\n .loose()\n .refine(({ kid, jwk }) => jwk === undefined || kid === undefined, {\n message: `Both 'jwk' and 'kid' are defined. Only one is allowed`,\n })\n .refine(({ trust_chain, kid }) => !trust_chain || !kid, {\n message: `When 'trust_chain' is provided, 'kid' is required`,\n })\n\nexport type KeyAttestationJwtHeader = z.infer<typeof zKeyAttestationJwtHeader>\n\nexport const zIso18045 = z.enum(['iso_18045_high', 'iso_18045_moderate', 'iso_18045_enhanced-basic', 'iso_18045_basic'])\n\nexport type Iso18045 = z.infer<typeof zIso18045>\nexport const zIso18045OrStringArray = z.array(z.union([zIso18045, z.string()]))\n\nexport const zKeyAttestationJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n iat: zInteger,\n\n attested_keys: z.array(zJwk),\n key_storage: z.optional(zIso18045OrStringArray),\n user_authentication: z.optional(zIso18045OrStringArray),\n certification: z.optional(z.url()),\n })\n .loose()\n\nexport const zKeyAttestationJwtPayloadForUse = <Use extends KeyAttestationJwtUse | undefined>(use?: Use) =>\n z\n .object({\n ...zKeyAttestationJwtPayload.shape,\n\n // REQUIRED when used as proof_type.attesation directly\n nonce:\n use === 'proof_type.attestation'\n ? z.string({\n message: `Nonce must be defined when key attestation is used as 'proof_type.attestation' directly`,\n })\n : z.optional(z.string()),\n\n // REQUIRED when used within header of proof_type.jwt\n exp: use === 'proof_type.jwt' ? zInteger : z.optional(zInteger),\n })\n .loose()\n\nexport type KeyAttestationJwtPayload = z.infer<typeof zKeyAttestationJwtPayload>\n","import {\n type CallbackContext,\n decodeJwt,\n type Jwk,\n type JwtSigner,\n jwtHeaderFromJwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling, type StringWithAutoCompletion } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport {\n type Iso18045,\n type KeyAttestationJwtHeader,\n type KeyAttestationJwtPayload,\n type KeyAttestationJwtUse,\n zKeyAttestationJwtHeader,\n zKeyAttestationJwtPayloadForUse,\n} from './z-key-attestation'\n\nexport interface CreateKeyAttestationJwtOptions {\n /**\n * Nonce to use in the key attestation.\n *\n * MUST be present if the attestation is used with the attestation proof\n */\n nonce?: string\n\n /**\n * The date when the key attestation was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The date when the key attestation will expire.\n *\n * MUST be present if the attestation is used with the JWT proof\n */\n expiresAt?: Date\n\n /**\n * The keys that the attestation jwt attests.\n */\n attestedKeys: Jwk[]\n\n /**\n * Optional attack potential resistance of attested keys and key storage\n */\n keyStorage?: StringWithAutoCompletion<Iso18045>[]\n\n /**\n * Optional attack potential resistance of user authentication methods\n */\n userAuthentication?: StringWithAutoCompletion<Iso18045>[]\n\n /**\n * Optional url linking to the certification of the key storage component.\n */\n certification?: string\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n\n /**\n * Signer of the key attestation jwt\n */\n signer: JwtSigner\n\n /**\n * Callbacks used for creating the key attestation jwt\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n\n /**\n * Additional payload to include in the key attestation jwt payload. Will be applied after\n * any default claims that are included, so add claims with caution.\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport async function createKeyAttestationJwt(options: CreateKeyAttestationJwtOptions): Promise<string> {\n const header = parseWithErrorHandling(zKeyAttestationJwtHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: 'keyattestation+jwt',\n } satisfies KeyAttestationJwtHeader)\n\n const payload = parseWithErrorHandling(zKeyAttestationJwtPayloadForUse(options.use), {\n iat: dateToSeconds(options.issuedAt),\n exp: options.expiresAt ? dateToSeconds(options.expiresAt) : undefined,\n nonce: options.nonce,\n attested_keys: options.attestedKeys,\n user_authentication: options.userAuthentication,\n key_storage: options.keyStorage,\n certification: options.certification,\n ...options.additionalPayload,\n } satisfies KeyAttestationJwtPayload)\n\n const { jwt } = await options.callbacks.signJwt(options.signer, { header, payload })\n return jwt\n}\n\nexport interface ParseKeyAttestationJwtOptions {\n /**\n * The compact key attestation jwt\n */\n keyAttestationJwt: string\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n}\n\nexport function parseKeyAttestationJwt({ keyAttestationJwt, use }: ParseKeyAttestationJwtOptions) {\n return decodeJwt({\n jwt: keyAttestationJwt,\n headerSchema: zKeyAttestationJwtHeader,\n payloadSchema: zKeyAttestationJwtPayloadForUse(use),\n })\n}\n\nexport interface VerifyKeyAttestationJwtOptions {\n /**\n * The compact key attestation jwt\n */\n keyAttestationJwt: string\n\n /**\n * Expected nonce. If the key attestation is used directly as proof this should be provided.\n */\n expectedNonce?: string\n\n /**\n * Date at which the nonce will expire\n */\n nonceExpiresAt?: Date\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n\n /**\n * Current time, if not provided a new date instance will be created\n */\n now?: Date\n\n /**\n * Callbacks required for the key attestation jwt verification\n */\n callbacks: Pick<CallbackContext, 'verifyJwt'>\n}\n\nexport type VerifyKeyAttestationJwtReturn = Awaited<ReturnType<typeof verifyKeyAttestationJwt>>\nexport async function verifyKeyAttestationJwt(options: VerifyKeyAttestationJwtOptions) {\n const { header, payload } = parseKeyAttestationJwt({ keyAttestationJwt: options.keyAttestationJwt, use: options.use })\n\n // TODO: if you use stateless nonce, it doesn't make sense to verify the nonce here\n // We should just return the nonce after verification so it can be checked (or actually, it should be checked upfront)\n const now = options.now?.getTime() ?? Date.now()\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new Openid4vciError('Nonce used for key attestation jwt expired')\n }\n\n const { signer } = await verifyJwt({\n compact: options.keyAttestationJwt,\n header,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'Error verifiying key attestation jwt',\n expectedNonce: options.expectedNonce,\n now: options.now,\n })\n\n return {\n header,\n payload,\n signer,\n }\n}\n","import z from 'zod'\n\n// Used up to draft 14\nexport const zCredentialConfigurationSupportedClaimsDescriptionDraft14 = z\n .object({\n mandatory: z.boolean().optional(),\n value_type: z.string().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\n\nexport type CredentialConfigurationSupportedClaimsDraft14 = {\n [key: string]:\n | z.infer<typeof zCredentialConfigurationSupportedClaimsDescriptionDraft14>\n | CredentialConfigurationSupportedClaimsDraft14\n}\n\nexport const zCredentialConfigurationSupportedClaimsDraft14: z.ZodType<CredentialConfigurationSupportedClaimsDraft14> =\n z.record(\n z.string(),\n z.union([\n zCredentialConfigurationSupportedClaimsDescriptionDraft14,\n z.lazy(() => zCredentialConfigurationSupportedClaimsDraft14),\n ])\n )\n\nconst zClaimDescriptionPathValue = z.union([z.string(), z.number().int().nonnegative(), z.null()])\nconst zClaimsDescriptionPath = z.tuple([zClaimDescriptionPathValue], zClaimDescriptionPathValue)\nexport type ClaimsDescriptionPath = z.infer<typeof zClaimsDescriptionPath>\n\nconst zMsoMdocClaimsDescriptionPath = z.tuple([z.string(), z.string()], zClaimDescriptionPathValue, {\n message:\n 'mso_mdoc claims description path MUST be an array with at least two string elements, pointing to the namespace and element identifier within an mdoc credential',\n})\nexport type MsoMdocClaimsDescriptionPath = z.infer<typeof zMsoMdocClaimsDescriptionPath>\n\nexport const zIssuerMetadataClaimsDescription = z\n .object({\n path: zClaimsDescriptionPath,\n mandatory: z.boolean().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\nexport type IssuerMetadataClaimsDescription = z.infer<typeof zIssuerMetadataClaimsDescription>\n\nexport const zMsoMdocIssuerMetadataClaimsDescription = zIssuerMetadataClaimsDescription.extend({\n path: zMsoMdocClaimsDescriptionPath,\n})\nexport type MsoMdocIssuerMetadataClaimsDescription = z.infer<typeof zMsoMdocIssuerMetadataClaimsDescription>\n","import { zDataUrl, zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zIso18045OrStringArray } from '../../key-attestation/z-key-attestation'\n\nconst zCredentialConfigurationSupportedDisplayEntry = z\n .object({\n name: z.string(),\n locale: z.string().optional(),\n logo: z\n .object({\n // FIXME: make required again, but need to support draft 11 first\n uri: zHttpsUrl.or(zDataUrl).optional(),\n alt_text: z.string().optional(),\n })\n .loose()\n .optional(),\n description: z.string().optional(),\n background_color: z.string().optional(),\n background_image: z\n .object({\n // TODO: should be required, but paradym's metadata is wrong here.\n uri: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n text_color: z.string().optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommonCredentialMetadata = z\n .object({\n display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommon = z\n .object({\n format: z.string(),\n scope: z.string().optional(),\n cryptographic_binding_methods_supported: z.array(z.string()).optional(),\n credential_signing_alg_values_supported: z.array(z.string()).or(z.array(z.number())).optional(),\n proof_types_supported: z\n .record(\n z.union([z.literal('jwt'), z.literal('attestation'), z.string()]),\n z.object({\n proof_signing_alg_values_supported: z.array(z.string()),\n key_attestations_required: z\n .object({\n key_storage: zIso18045OrStringArray.optional(),\n user_authentication: zIso18045OrStringArray.optional(),\n })\n .loose()\n .optional(),\n })\n )\n .optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommonDraft15 = z\n .object({\n format: z.string(),\n scope: z.string().optional(),\n cryptographic_binding_methods_supported: z.array(z.string()).optional(),\n // Up until draft 15 it was an array of strings\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n proof_types_supported: z\n .record(\n z.union([z.literal('jwt'), z.literal('attestation'), z.string()]),\n z.object({\n proof_signing_alg_values_supported: z.array(z.string()),\n key_attestations_required: z\n .object({\n key_storage: zIso18045OrStringArray.optional(),\n user_authentication: zIso18045OrStringArray.optional(),\n })\n .loose()\n .optional(),\n })\n )\n .optional(),\n display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional(),\n\n // For typing purposes.\n credential_metadata: z.optional(z.never()),\n })\n .loose()\n","import z from 'zod'\nimport {\n zCredentialConfigurationSupportedClaimsDraft14,\n zMsoMdocIssuerMetadataClaimsDescription,\n} from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zMsoMdocFormatIdentifier = z.literal('mso_mdoc')\nexport type MsoMdocFormatIdentifier = z.infer<typeof zMsoMdocFormatIdentifier>\n\nexport const zMsoMdocCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n credential_signing_alg_values_supported: z.array(z.number()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zMsoMdocCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zMsoMdocCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),\n order: z.optional(z.array(z.string())),\n})\n\nexport const zMsoMdocCredentialRequestFormatDraft14 = z.object({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n // Format based request is removed in Draft 15, so only old claims syntax supported.\n claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),\n})\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zSdJwtDcFormatIdentifier = z.literal('dc+sd-jwt')\nexport type SdJwtDcFormatIdentifier = z.infer<typeof zSdJwtDcFormatIdentifier>\n\nexport const zSdJwtDcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n vct: z.string(),\n format: zSdJwtDcFormatIdentifier,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zSdJwtDcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n vct: z.string(),\n format: zSdJwtDcFormatIdentifier,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n","import z from 'zod'\nimport {\n zCredentialConfigurationSupportedClaimsDraft14,\n zIssuerMetadataClaimsDescription,\n} from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcFormatIdentifier = z.literal('vc+sd-jwt')\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport type LegacySdJwtVcFormatIdentifier = z.infer<typeof zLegacySdJwtVcFormatIdentifier>\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialIssuerMetadataV1 = zCredentialConfigurationSupportedCommon.extend({\n vct: z.string(),\n format: zLegacySdJwtVcFormatIdentifier,\n order: z.optional(z.array(z.string())),\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n credential_definition: z.optional(z.never()),\n})\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n vct: z.string(),\n format: zLegacySdJwtVcFormatIdentifier,\n claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),\n order: z.optional(z.array(z.string())),\n credential_definition: z.optional(z.never()),\n})\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialRequestFormatDraft14 = z.object({\n format: zLegacySdJwtVcFormatIdentifier,\n vct: z.string(),\n claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),\n credential_definition: z.optional(z.never()),\n})\n","import z from 'zod'\n\nconst zCredentialSubjectLeafTypeDraft14 = z\n .object({\n mandatory: z.boolean().optional(),\n value_type: z.string().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\n\nconst zClaimValueSchemaDraft14 = z.union([\n z.array(z.any()),\n z.record(z.string(), z.any()),\n zCredentialSubjectLeafTypeDraft14,\n])\n\nexport const zW3cVcCredentialSubjectDraft14 = z.record(z.string(), zClaimValueSchemaDraft14)\n\nexport const zW3cVcJsonLdCredentialDefinition = z\n .object({\n '@context': z.array(z.string()),\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nexport const zW3cVcJsonLdCredentialDefinitionDraft14 = zW3cVcJsonLdCredentialDefinition.extend({\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n})\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport { zW3cVcCredentialSubjectDraft14 } from './z-w3c-vc-common'\n\nexport const zJwtVcJsonFormatIdentifier = z.literal('jwt_vc_json')\nexport type JwtVcJsonFormatIdentifier = z.infer<typeof zJwtVcJsonFormatIdentifier>\n\nconst zJwtVcJsonCredentialDefinition = z\n .object({\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nconst zJwtVcJsonCredentialDefinitionDraft14 = zJwtVcJsonCredentialDefinition.extend({\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinitionDraft14,\n order: z.array(z.string()).optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft11 = z\n .object({\n format: zJwtVcJsonFormatIdentifier,\n order: z.array(z.string()).optional(),\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft11To14 = zJwtVcJsonCredentialIssuerMetadataDraft11.transform(\n ({ types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft14To11 = zJwtVcJsonCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n types: type,\n ...credentialDefinition,\n }))\n .pipe(zJwtVcJsonCredentialIssuerMetadataDraft11)\n\nexport const zJwtVcJsonCredentialRequestFormatDraft14 = z.object({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n})\n\nexport const zJwtVcJsonCredentialRequestDraft11 = z\n .object({\n format: zJwtVcJsonFormatIdentifier,\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n types: z.tuple([z.string()], z.string()),\n credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14),\n })\n .loose()\n\nexport const zJwtVcJsonCredentialRequestDraft11To14 = zJwtVcJsonCredentialRequestDraft11.transform(\n ({ types, credentialSubject, ...rest }) => {\n return {\n ...rest,\n credential_definition: {\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n }\n }\n)\n\nexport const zJwtVcJsonCredentialRequestDraft14To11 = zJwtVcJsonCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n types: type,\n ...credentialDefinition,\n }))\n .pipe(zJwtVcJsonCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport {\n zW3cVcCredentialSubjectDraft14,\n zW3cVcJsonLdCredentialDefinition,\n zW3cVcJsonLdCredentialDefinitionDraft14,\n} from './z-w3c-vc-common'\n\nexport const zJwtVcJsonLdFormatIdentifier = z.literal('jwt_vc_json-ld')\nexport type JwtVcJsonLdFormatIdentifier = z.infer<typeof zJwtVcJsonLdFormatIdentifier>\n\nexport const zJwtVcJsonLdCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n order: z.optional(z.array(z.string())),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft11 = z\n .object({\n order: z.array(z.string()).optional(),\n format: zJwtVcJsonLdFormatIdentifier,\n // Credential definition was spread on top level instead of a separate property in v11\n // As well as using types instead of type\n '@context': z.array(z.string()),\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft11To14 = zJwtVcJsonLdCredentialIssuerMetadataDraft11.transform(\n ({ '@context': context, types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n '@context': context,\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft14To11 = zJwtVcJsonLdCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n ...credentialDefinition,\n types: type,\n }))\n .pipe(zJwtVcJsonLdCredentialIssuerMetadataDraft11)\n\nexport const zJwtVcJsonLdCredentialRequestFormatDraft14 = z.object({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n})\n\nexport const zJwtVcJsonLdCredentialRequestDraft11 = z\n .object({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: z\n .object({\n '@context': z.array(z.string()),\n // credential_definition was using types instead of type in v11\n types: z.tuple([z.string()], z.string()),\n credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14),\n })\n .loose(),\n })\n .loose()\n\nexport const zJwtVcJsonLdCredentialRequestDraft11To14 = zJwtVcJsonLdCredentialRequestDraft11.transform(\n ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n type: types,\n },\n })\n)\n\nexport const zJwtVcJsonLdCredentialRequestDraft14To11 = zJwtVcJsonLdCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n types: type,\n },\n }))\n .pipe(zJwtVcJsonLdCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport {\n zW3cVcCredentialSubjectDraft14,\n zW3cVcJsonLdCredentialDefinition,\n zW3cVcJsonLdCredentialDefinitionDraft14,\n} from './z-w3c-vc-common'\n\nexport const zLdpVcFormatIdentifier = z.literal('ldp_vc')\nexport type LdpVcFormatIdentifier = z.infer<typeof zLdpVcFormatIdentifier>\n\nexport const zLdpVcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n order: z.array(z.string()).optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft11 = z\n .object({\n order: z.array(z.string()).optional(),\n format: zLdpVcFormatIdentifier,\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n '@context': z.array(z.string()),\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zLdpVcCredentialIssuerMetadataDraft11To14 = zLdpVcCredentialIssuerMetadataDraft11.transform(\n ({ '@context': context, types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n '@context': context,\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zLdpVcCredentialIssuerMetadataDraft14To11 = zLdpVcCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n ...credentialDefinition,\n types: type,\n }))\n .pipe(zLdpVcCredentialIssuerMetadataDraft11)\n\nexport const zLdpVcCredentialRequestFormatDraft14 = z.object({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n})\n\nconst zLdpVcCredentialRequestDraft11 = z\n .object({\n format: zLdpVcFormatIdentifier,\n credential_definition: z.object({\n '@context': z.array(z.string()),\n // credential_definition was using types instead of type in v11\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n }),\n })\n .loose()\n\nexport const zLdpVcCredentialRequestDraft11To14 = zLdpVcCredentialRequestDraft11.transform(\n ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n type: types,\n },\n })\n)\n\nexport const zLdpVcCredentialRequestDraft14To11 = zLdpVcCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n types: type,\n },\n }))\n .pipe(zLdpVcCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zSdJwtW3VcFormatIdentifier = z.literal('vc+sd-jwt')\nexport type SdJwtW3VcFormatIdentifier = z.infer<typeof zSdJwtW3VcFormatIdentifier>\n\nconst zSdJwtW3VcCredentialDefinition = z\n .object({\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nexport const zSdJwtW3VcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n\nexport const zSdJwtW3VcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n\nexport const zSdJwtW3VcCredentialRequestFormatDraft14 = z.object({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n","import {\n fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray,\n jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray,\n} from '@openid4vc/oauth2'\nimport { type InferOutputUnion, type Simplify, zDataUrl, zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n type CredentialFormatIdentifier,\n zJwtVcJsonCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadataDraft11To14,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n zJwtVcJsonCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonCredentialIssuerMetadataDraft15,\n zJwtVcJsonFormatIdentifier,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadataDraft11To14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonLdCredentialIssuerMetadataDraft15,\n zJwtVcJsonLdFormatIdentifier,\n zLdpVcCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadataDraft11To14,\n zLdpVcCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadataDraft14To11,\n zLdpVcCredentialIssuerMetadataDraft15,\n zLdpVcFormatIdentifier,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zMsoMdocCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zMsoMdocCredentialIssuerMetadataDraft15,\n zMsoMdocFormatIdentifier,\n zSdJwtDcCredentialIssuerMetadata,\n zSdJwtDcCredentialIssuerMetadataDraft15,\n zSdJwtDcFormatIdentifier,\n} from '../../formats/credential'\nimport { zLegacySdJwtVcCredentialIssuerMetadataV1 } from '../../formats/credential/sd-jwt-vc/z-sd-jwt-vc'\nimport {\n zSdJwtW3VcCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadataDraft15,\n} from '../../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { Openid4vciVersion } from '../../version'\nimport { claimsObjectToClaimsArray } from './credential-configurations'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonDraft15,\n} from './z-credential-configuration-supported-common'\n\nconst allCredentialIssuerMetadataFormats = [\n zSdJwtDcCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadataDraft15,\n zLegacySdJwtVcCredentialIssuerMetadataV1,\n zSdJwtDcCredentialIssuerMetadataDraft15,\n zMsoMdocCredentialIssuerMetadataDraft15,\n zJwtVcJsonLdCredentialIssuerMetadataDraft15,\n zLdpVcCredentialIssuerMetadataDraft15,\n zJwtVcJsonCredentialIssuerMetadataDraft15,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadataDraft14,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n] as const\ntype CredentialIssuerMetadataFormatValidator = (typeof allCredentialIssuerMetadataFormats)[number]\nexport const allCredentialIssuerMetadataFormatIdentifiers = allCredentialIssuerMetadataFormats.map(\n (format) => format.shape.format.value\n)\n\nexport const zCredentialConfigurationSupportedWithFormats = z\n .union([zCredentialConfigurationSupportedCommon, zCredentialConfigurationSupportedCommonDraft15])\n .transform((data, ctx) => {\n // No additional validation for unknown formats\n if (!allCredentialIssuerMetadataFormatIdentifiers.includes(data.format as CredentialFormatIdentifier)) return data\n\n const validators = allCredentialIssuerMetadataFormats.filter(\n (formatValidator) => formatValidator.shape.format.value === data.format\n ) as CredentialIssuerMetadataFormatValidator[]\n\n const result = z\n // We use object and passthrough as otherwise the non-format specific properties will be stripped\n .object({})\n .loose()\n .and(\n validators.length > 1\n ? z.union(\n validators as [\n CredentialIssuerMetadataFormatValidator,\n CredentialIssuerMetadataFormatValidator,\n ...CredentialIssuerMetadataFormatValidator[],\n ]\n )\n : validators[0]\n )\n .safeParse(data)\n\n if (result.success) {\n return result.data as Simplify<typeof result.data & typeof data>\n }\n\n for (const issue of result.error.issues) {\n // FIXME: this worked with zod 3\n ctx.addIssue({\n ...issue,\n code: issue.code as 'custom',\n })\n }\n\n return z.NEVER\n })\n\ntype CredentialConfigurationSupportedCommon = z.infer<typeof zCredentialConfigurationSupportedCommon>\nexport type CredentialConfigurationSupportedFormatSpecific = InferOutputUnion<typeof allCredentialIssuerMetadataFormats>\nexport type CredentialConfigurationSupportedWithFormats = CredentialConfigurationSupportedFormatSpecific &\n CredentialConfigurationSupportedCommon\nexport type CredentialConfigurationsSupportedWithFormats = Record<string, CredentialConfigurationSupportedWithFormats>\n\nexport type CredentialConfigurationSupported = z.infer<typeof zCredentialConfigurationSupportedWithFormats>\nexport type CredentialConfigurationsSupported = Record<string, CredentialConfigurationSupported>\n\nconst zCredentialIssuerMetadataDisplayEntry = z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n logo: z\n .object({\n // FIXME: make required again, but need to support draft 11 first\n uri: zHttpsUrl.or(zDataUrl).optional(),\n alt_text: z.string().optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\nexport type CredentialIssuerMetadataDisplayEntry = z.infer<typeof zCredentialIssuerMetadataDisplayEntry>\n\nexport type CredentialIssuerMetadata = z.infer<typeof zCredentialIssuerMetadataDraft14Draft15V1>\nexport const zCredentialIssuerMetadataDraft14Draft15V1 = z\n .object({\n credential_issuer: zHttpsUrl,\n authorization_servers: z.array(zHttpsUrl).optional(),\n credential_endpoint: zHttpsUrl,\n deferred_credential_endpoint: zHttpsUrl.optional(),\n notification_endpoint: zHttpsUrl.optional(),\n\n // Added after draft 14, but needed for proper\n nonce_endpoint: zHttpsUrl.optional(),\n credential_response_encryption: z\n .object({\n alg_values_supported: z.array(z.string()),\n enc_values_supported: z.array(z.string()),\n encryption_required: z.boolean(),\n })\n .loose()\n .optional(),\n batch_credential_issuance: z\n .object({\n batch_size: z.number().positive(),\n })\n .loose()\n .optional(),\n display: z.array(zCredentialIssuerMetadataDisplayEntry).optional(),\n credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedCommon),\n })\n .loose()\n\n// Transforms credential supported to credential configuration supported format\n// Ignores unknown formats\nexport const zCredentialConfigurationSupportedDraft11ToV1 = z\n .object({\n id: z.string().optional(),\n format: z.string(),\n cryptographic_suites_supported: z.array(z.string()).optional(),\n display: z\n .array(\n z\n .object({\n logo: z\n .object({\n url: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n background_image: z\n .object({\n url: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n )\n .optional(),\n claims: z\n .any()\n .transform((claims) => claimsObjectToClaimsArray(claims))\n .optional(),\n })\n .loose()\n .transform(({ cryptographic_suites_supported, display, claims, id, format, ...rest }) => ({\n ...rest,\n format: format === 'vc+sd-jwt' && rest.vct ? 'dc+sd-jwt' : format,\n ...(cryptographic_suites_supported\n ? {\n credential_signing_alg_values_supported:\n // For mso_mdoc, transform JWA signature algorithm strings to fully-specified COSE algorithm numbers\n format === zMsoMdocFormatIdentifier.value\n ? jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray(cryptographic_suites_supported)\n : cryptographic_suites_supported,\n }\n : {}),\n ...(claims || display\n ? {\n credential_metadata: {\n ...(claims ? { claims } : {}),\n ...(display\n ? {\n display: display.map(({ logo, background_image, ...displayRest }) => ({\n ...displayRest,\n // url became uri and also required\n // so if there's no url in the logo, we remove the whole logo object\n ...(logo?.url\n ? {\n // TODO: we should add the other params from logo as well\n logo: {\n uri: logo.url,\n },\n }\n : {}),\n\n // TODO: we should add the other params from background_image as well\n // url became uri and also required\n // so if there's no url in the background_image, we remove the whole logo object\n ...(background_image?.url\n ? {\n background_image: {\n uri: background_image.url,\n },\n }\n : {}),\n })),\n }\n : {}),\n },\n }\n : {}),\n }))\n .transform((data, ctx): unknown => {\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialIssuerMetadataDraft11To14,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialIssuerMetadataDraft11To14,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialIssuerMetadataDraft11To14,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n // FIXME: this worked with zod 3\n ctx.addIssue({\n ...issue,\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n .pipe(zCredentialConfigurationSupportedWithFormats)\n\n// Transforms credential configuration supported from draft 16 to draft 15\nconst zCredentialConfigurationSupportedV1ToDraft15 = zCredentialConfigurationSupportedWithFormats.transform(\n ({ credential_metadata, ...rest }) => ({\n ...credential_metadata,\n ...rest,\n })\n)\n\n// Transforms credential configuration supported to credentials_supported format\n// Ignores unknown formats\nconst zCredentialConfigurationSupportedV1ToDraft11 = zCredentialConfigurationSupportedV1ToDraft15\n .transform((configuration, ctx) => {\n if (!configuration.id || typeof configuration.id !== 'string') {\n ctx.addIssue({\n code: 'invalid_type',\n expected: 'string',\n input: configuration.id,\n path: ['id'],\n message: 'Missing required id field',\n })\n return z.NEVER\n }\n\n return {\n ...configuration,\n id: configuration.id,\n // We remove claims when downgrading to draft 11\n claims: undefined,\n }\n })\n .transform(\n ({\n id,\n credential_signing_alg_values_supported,\n display,\n proof_types_supported,\n scope,\n format,\n claims,\n ...rest\n }): unknown => ({\n ...rest,\n // vc+sd-jwt was changed to dc+sd-jwt in draft 15\n format: format === 'dc+sd-jwt' ? 'vc+sd-jwt' : format,\n ...(credential_signing_alg_values_supported\n ? {\n cryptographic_suites_supported:\n // For mso_mdoc, transform fully-specified COSE algorithm numbers to JWA signature algorithm strings\n format === zMsoMdocFormatIdentifier.value &&\n typeof credential_signing_alg_values_supported[0] === 'number'\n ? fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray(\n credential_signing_alg_values_supported as number[]\n )\n : credential_signing_alg_values_supported,\n }\n : {}),\n ...(display\n ? {\n display: display.map(({ logo, background_image, ...displayRest }) => {\n const { uri: logoUri, ...logoRest } = logo ?? {}\n const { uri: backgroundImageUri, ...backgroundImageRest } = background_image ?? {}\n return {\n ...displayRest,\n // draft 11 uses url, draft 13/14 uses uri\n ...(logoUri ? { logo: { url: logoUri, ...logoRest } } : {}),\n // draft 11 uses url, draft 13/14 uses uri\n ...(backgroundImageUri ? { logo: { url: backgroundImageUri, ...backgroundImageRest } } : {}),\n }\n }),\n }\n : {}),\n id,\n })\n )\n .pipe(\n z.union([\n zLdpVcCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,\n // To handle unrecognized formats and not error immediately we allow the common format as well\n // but they can't use any of the format identifiers that have a specific transformation. This way if a format is\n // has a transformation it NEEDS to use the format specific transformation, and otherwise we fall back to the common validation\n z\n .object({\n format: z\n .string()\n .refine(\n (input) =>\n !(\n [\n zLdpVcFormatIdentifier.value,\n zJwtVcJsonFormatIdentifier.value,\n zJwtVcJsonLdFormatIdentifier.value,\n ] as string[]\n ).includes(input)\n ),\n })\n .loose(),\n ])\n )\n\nexport const zCredentialIssuerMetadataDraft11ToV1 = z\n .object({\n authorization_server: z.string().optional(),\n credentials_supported: z.array(\n z\n .object({\n id: z.string().optional(),\n })\n .loose()\n ),\n })\n .loose()\n .transform(({ authorization_server, credentials_supported, ...rest }) => {\n return {\n ...rest,\n ...(authorization_server ? { authorization_servers: [authorization_server] } : {}),\n // Go from array to map but keep v11 structure\n credential_configurations_supported: Object.fromEntries(\n credentials_supported\n .map((supported) => (supported.id ? ([supported.id, supported] as const) : undefined))\n .filter((i): i is Exclude<typeof i, undefined> => i !== undefined)\n ),\n }\n })\n .pipe(\n z\n .object({\n // Update from v11 structure to v14 structure\n credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedDraft11ToV1),\n })\n .loose()\n )\n .pipe(zCredentialIssuerMetadataDraft14Draft15V1)\n\n/**\n * Typing is a bit off on this one\n */\nexport type CredentialIssuerMetadataDraft11 = Simplify<\n CredentialIssuerMetadata & {\n authorization_server?: string\n credentials_supported: z.infer<typeof zCredentialConfigurationSupportedV1ToDraft11>[]\n }\n>\n\nexport const zCredentialIssuerMetadataWithDraft11 = zCredentialIssuerMetadataDraft14Draft15V1\n .transform((issuerMetadata) => ({\n ...issuerMetadata,\n ...(issuerMetadata.authorization_servers ? { authorization_server: issuerMetadata.authorization_servers[0] } : {}),\n credentials_supported: Object.entries(issuerMetadata.credential_configurations_supported).map(\n ([id, value]) =>\n ({\n ...value,\n id,\n }) as (typeof issuerMetadata)['credential_configurations_supported'][typeof id]\n ),\n }))\n .pipe(\n zCredentialIssuerMetadataDraft14Draft15V1.extend({\n credentials_supported: z.array(zCredentialConfigurationSupportedV1ToDraft11),\n })\n )\n\nexport const zCredentialIssuerMetadata = z.union([\n // First prioritize draft 16/15/14 (and 13)\n zCredentialIssuerMetadataDraft14Draft15V1,\n // Then try parsing draft 11 and transform into draft 16\n zCredentialIssuerMetadataDraft11ToV1,\n])\n\nexport const zCredentialIssuerMetadataWithDraftVersion = z.union([\n zCredentialIssuerMetadataDraft14Draft15V1.transform((credentialIssuerMetadata) => {\n const credentialConfigurations = Object.values(credentialIssuerMetadata.credential_configurations_supported)\n\n const isDraft15 = credentialConfigurations.some((configuration) => {\n const knownConfiguration = configuration as CredentialConfigurationSupportedWithFormats\n\n // Added in draft 15, it's not possible to detect with 100% guarantee\n if (knownConfiguration.format === zSdJwtDcFormatIdentifier.value) return true\n if (Array.isArray(knownConfiguration.claims)) return true\n if (\n Object.values(knownConfiguration.proof_types_supported ?? {}).some(\n (proofType) => proofType.key_attestations_required !== undefined\n )\n )\n return true\n\n // For now we assume draft 14 if we don't have any evidence it's draft 15\n return false\n })\n\n // we assume V1 is used when we detect V1\n const isV1 = credentialConfigurations.some(\n (configuration) =>\n // Added in draft 16, but since there's no other breaking changes\n configuration.credential_metadata ||\n // Was changed to COSE algorithms in Draft 16 (which we detect as v1)\n (configuration.format === 'mso_mdoc' &&\n configuration.credential_signing_alg_values_supported?.some((supported) => typeof supported === 'number'))\n )\n\n return {\n credentialIssuerMetadata,\n originalDraftVersion: isV1\n ? Openid4vciVersion.V1\n : isDraft15\n ? Openid4vciVersion.Draft15\n : Openid4vciVersion.Draft14,\n }\n }),\n // Then try parsing draft 11 and transform into draft 16\n zCredentialIssuerMetadataDraft11ToV1.transform((credentialIssuerMetadata) => ({\n credentialIssuerMetadata,\n originalDraftVersion: Openid4vciVersion.Draft11,\n })),\n])\n","import { Oauth2Error } from '@openid4vc/oauth2'\nimport { ValidationError } from '@openid4vc/utils'\nimport type z from 'zod'\nimport { Openid4vciError } from '../../error/Openid4vciError'\nimport type { IssuerMetadataResult } from '../fetch-issuer-metadata'\nimport {\n type IssuerMetadataClaimsDescription,\n zCredentialConfigurationSupportedClaimsDraft14,\n} from './z-claims-description'\nimport {\n type CredentialConfigurationsSupported,\n zCredentialConfigurationSupportedDraft11ToV1,\n} from './z-credential-issuer-metadata'\n\nexport interface ExtractScopesForCredentialConfigurationIdsOptions {\n /**\n * The credential configuration ids to extract the scope from\n */\n credentialConfigurationIds: string[]\n\n /**\n * Whether to throw an error if the corresponding credential configuration\n * for a provided credential configuration id has no scope.\n *\n * @default false\n */\n throwOnConfigurationWithoutScope?: boolean\n\n /**\n * The issuer metadata\n */\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function extractScopesForCredentialConfigurationIds(\n options: ExtractScopesForCredentialConfigurationIdsOptions\n): string[] | undefined {\n const scopes = new Set<string>()\n\n for (const credentialConfigurationId of options.credentialConfigurationIds) {\n const credentialConfiguration =\n options.issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId]\n\n if (!credentialConfiguration) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' not found in metadata from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n }\n\n const scope = credentialConfiguration.scope\n if (scope) scopes.add(scope)\n else if (!scope && options.throwOnConfigurationWithoutScope) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' does not have a 'scope' configured, and 'throwOnConfigurationWithoutScope' was enabled.`\n )\n }\n }\n\n return scopes.size > 0 ? Array.from(scopes) : undefined\n}\n\n/**\n * Transforms draft 11 credentials supported syntax to credential configurations supported\n *\n * @throws if a credentials supported entry without id is passed\n * @throws if a credentials supported entry with invalid structure or format specific properties is passed\n */\nexport function credentialsSupportedToCredentialConfigurationsSupported(\n credentialsSupported: Array<z.input<typeof zCredentialConfigurationSupportedDraft11ToV1>>\n) {\n const credentialConfigurationsSupported: CredentialConfigurationsSupported = {}\n\n for (let index = 0; index < credentialsSupported.length; index++) {\n const credentialSupported = credentialsSupported[index]\n if (!credentialSupported.id) {\n throw new Openid4vciError(\n `Credential supported at index '${index}' does not have an 'id' property. Credential configuration requires the 'id' property as key`\n )\n }\n\n const parseResult = zCredentialConfigurationSupportedDraft11ToV1.safeParse(credentialSupported)\n if (!parseResult.success) {\n throw new ValidationError(\n `Error transforming credential supported with id '${credentialSupported.id}' to credential configuration supported format`,\n parseResult.error\n )\n }\n\n credentialConfigurationsSupported[credentialSupported.id] = parseResult.data\n }\n\n return credentialConfigurationsSupported\n}\n\n/**\n * Transforms draft 14 claims object syntax to the new array-based claims description syntax\n *\n * @param claims - The claims object in draft 14 format\n * @returns Array of claims descriptions or undefined if validation fails\n */\nexport function claimsObjectToClaimsArray(claims: unknown): Array<IssuerMetadataClaimsDescription> | undefined {\n // Validate input\n const parseResult = zCredentialConfigurationSupportedClaimsDraft14.safeParse(claims)\n if (!parseResult.success) {\n return undefined\n }\n\n const result: Array<IssuerMetadataClaimsDescription> = []\n\n /**\n * Recursively process claims object, building up the path from parent keys\n */\n function processClaimsObject(\n claimsObj: Record<string, unknown>,\n parentPath: Array<string | number | null> = []\n ): void {\n for (const [key, value] of Object.entries(claimsObj)) {\n const currentPath = [...parentPath, key]\n\n // Check if this is a leaf node (has claim properties like mandatory, value_type, display)\n if (\n value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n ('mandatory' in value || 'value_type' in value || 'display' in value)\n ) {\n const claimValue = value as Record<string, unknown>\n\n // Create the claim description\n const claimDescription: IssuerMetadataClaimsDescription = {\n path: currentPath as [string | number | null, ...(string | number | null)[]],\n }\n\n // Add optional properties\n if (typeof claimValue.mandatory === 'boolean') {\n claimDescription.mandatory = claimValue.mandatory\n }\n\n if (Array.isArray(claimValue.display)) {\n claimDescription.display = claimValue.display as Array<{\n name?: string\n locale?: string\n }>\n }\n\n // Note: value_type is not included in the new syntax\n\n result.push(claimDescription)\n\n // Check if there are nested claims (excluding the known properties)\n const nestedClaims = Object.entries(claimValue).filter(\n ([k]) => k !== 'mandatory' && k !== 'value_type' && k !== 'display'\n )\n\n if (nestedClaims.length > 0) {\n const nestedObj = Object.fromEntries(nestedClaims)\n processClaimsObject(nestedObj, currentPath)\n }\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n // This is a nested object without claim properties, recurse\n processClaimsObject(value as Record<string, unknown>, currentPath)\n }\n }\n }\n\n processClaimsObject(parseResult.data)\n\n return result\n}\n","import { zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zInteger } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zCredentialIssuerMetadataDraft14Draft15V1 } from './z-credential-issuer-metadata'\n\nexport const zSignedCredentialIssuerMetadataHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z.literal('openidvci-issuer-metadata+jwt'),\n })\n .loose()\n\nexport type SignedCredentialIssuerMetadataHeader = z.infer<typeof zSignedCredentialIssuerMetadataHeader>\n\nexport const zSignedCredentialIssuerMetadataPayload = z\n .object({\n ...zJwtPayload.shape,\n iat: zInteger,\n sub: z.string(),\n\n // NOTE: we don't support older drafts below 14 for signed metadata\n ...zCredentialIssuerMetadataDraft14Draft15V1.shape,\n })\n .loose()\n\nexport type SignedCredentialIssuerMetadataPayload = z.infer<typeof zSignedCredentialIssuerMetadataPayload>\n","import {\n type CallbackContext,\n type DecodeJwtResult,\n decodeJwt,\n fetchWellKnownMetadata,\n type JwtSignerWithJwk,\n jwtSignerFromJwt,\n Oauth2Error,\n verifyJwt,\n zCompactJwt,\n} from '@openid4vc/oauth2'\nimport { ContentType, joinUriParts, OpenId4VcBaseError, parseWithErrorHandling, URL } from '@openid4vc/utils'\nimport type { CredentialFormatIdentifier } from '../../formats/credential'\nimport type { Openid4vciVersion } from '../../version'\nimport type { IssuerMetadataResult } from '../fetch-issuer-metadata'\nimport {\n allCredentialIssuerMetadataFormatIdentifiers,\n type CredentialConfigurationSupportedWithFormats,\n type CredentialConfigurationsSupported,\n type CredentialConfigurationsSupportedWithFormats,\n type CredentialIssuerMetadata,\n zCredentialConfigurationSupportedWithFormats,\n zCredentialIssuerMetadataWithDraftVersion,\n} from './z-credential-issuer-metadata'\nimport {\n zSignedCredentialIssuerMetadataHeader,\n zSignedCredentialIssuerMetadataPayload,\n} from './z-signed-credential-issuer-metadata'\n\nconst wellKnownCredentialIssuerSuffix = '.well-known/openid-credential-issuer'\n\nexport interface FetchCredentialIssuerMetadataOptions {\n /**\n * Callbacks for fetching the credential issur metadata.\n * If no `verifyJwt` callback is provided, the request\n * will not include the `application/jwt` Accept header\n * for signed metadata.\n */\n callbacks?: Partial<Pick<CallbackContext, 'fetch' | 'verifyJwt'>>\n\n /**\n * Only used for verifying signed issuer metadata. If not provided\n * current time will be used\n */\n now?: Date\n}\n\nexport interface CredentialIssuerMetadataSigned {\n jwt: DecodeJwtResult<typeof zSignedCredentialIssuerMetadataHeader, typeof zSignedCredentialIssuerMetadataPayload>\n signer: JwtSignerWithJwk\n}\n\nexport interface FetchCredentialIssuerMetadataReturn {\n /**\n * The credential issuer metadata, optionally transformed to Draft 14+ syntax\n */\n credentialIssuerMetadata: CredentialIssuerMetadata\n\n /**\n * The original draft version of the credential issuer metadata\n */\n originalDraftVersion: Openid4vciVersion\n\n /**\n * Metadata about the signed issuer metadata, if the metadata was signed.\n */\n signed?: CredentialIssuerMetadataSigned\n}\n\n/**\n * @inheritdoc {@link fetchWellKnownMetadata}\n */\nexport async function fetchCredentialIssuerMetadata(\n credentialIssuer: string,\n options?: FetchCredentialIssuerMetadataOptions\n): Promise<FetchCredentialIssuerMetadataReturn | null> {\n const parsedIssuerUrl = new URL(credentialIssuer)\n\n const legacyWellKnownMetadataUrl = joinUriParts(credentialIssuer, [wellKnownCredentialIssuerSuffix])\n const wellKnownMetadataUrl = joinUriParts(parsedIssuerUrl.origin, [\n wellKnownCredentialIssuerSuffix,\n parsedIssuerUrl.pathname,\n ])\n\n // If verify jwt callback is provided, we accept both signed and unsigned issuer metadata\n const acceptedContentType: [ContentType, ...ContentType[]] = options?.callbacks?.verifyJwt\n ? [ContentType.Jwt, ContentType.Json]\n : [ContentType.Json]\n\n // Either unsigned metadata or signed JWT\n const responseSchema = zCredentialIssuerMetadataWithDraftVersion.or(zCompactJwt)\n\n let result = null\n let firstError = null\n\n try {\n result = await fetchWellKnownMetadata(wellKnownMetadataUrl, responseSchema, {\n fetch: options?.callbacks?.fetch,\n acceptedContentType,\n })\n } catch (error) {\n if (error instanceof OpenId4VcBaseError) throw error\n\n // An exception occurs if a CORS-policy blocks the request, i.e. because the URL is invalid due to the legacy path being used\n // The legacy path should still be tried therefore we store the first error to rethrow it later if needed\n firstError = error\n }\n\n // If the metadata is not available at the new URL, fetch it at the legacy URL\n // The legacy url is the same if no subpath is used by the issuer\n if (!result && legacyWellKnownMetadataUrl !== wellKnownMetadataUrl) {\n try {\n result = await fetchWellKnownMetadata(legacyWellKnownMetadataUrl, responseSchema, {\n fetch: options?.callbacks?.fetch,\n acceptedContentType,\n })\n } catch (error) {\n // If the first attempt also errored, rethrow that original error; otherwise rethrow this one\n throw firstError ?? error\n }\n }\n\n if (!result && firstError) {\n throw firstError\n }\n\n let issuerMetadataWithVersion: FetchCredentialIssuerMetadataReturn | null = null\n\n if (typeof result === 'string') {\n // We won't reach this, as we already handle this with accepted content types.\n // Mainly to make TS happy\n if (!options?.callbacks?.verifyJwt) {\n throw new Oauth2Error(\n `Unable to verify signed credential issuer metadata, no 'verifyJwt' callback provided to fetch credential issuer metadata method.`\n )\n }\n const { header, payload, signature } = decodeJwt({\n jwt: result,\n headerSchema: zSignedCredentialIssuerMetadataHeader,\n payloadSchema: zSignedCredentialIssuerMetadataPayload,\n })\n\n if (payload.sub !== credentialIssuer) {\n throw new Oauth2Error(\n `The 'sub' parameter '${payload.sub}' in the signed well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`\n )\n }\n\n // Extract signer of the JWT\n const signer = jwtSignerFromJwt({ header, payload })\n\n const verifyResult = await verifyJwt({\n compact: result,\n header,\n payload,\n verifyJwtCallback: options.callbacks.verifyJwt,\n now: options.now,\n signer,\n errorMessage: 'signed credential issuer metadata jwt verification failed',\n })\n\n const issuerMetadata = parseWithErrorHandling(\n zCredentialIssuerMetadataWithDraftVersion,\n payload,\n 'Unable to determine version for signed issuer metadata'\n )\n\n issuerMetadataWithVersion = {\n ...issuerMetadata,\n signed: {\n signer: verifyResult.signer,\n jwt: {\n header,\n payload,\n signature,\n compact: result,\n },\n },\n }\n } else if (result) {\n issuerMetadataWithVersion = result\n }\n\n // credential issuer param MUST match\n if (\n issuerMetadataWithVersion &&\n issuerMetadataWithVersion.credentialIssuerMetadata.credential_issuer !== credentialIssuer\n ) {\n throw new Oauth2Error(\n `The 'credential_issuer' parameter '${issuerMetadataWithVersion.credentialIssuerMetadata.credential_issuer}' in the well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`\n )\n }\n\n return issuerMetadataWithVersion\n}\n\n/**\n * Extract credential configuration supported entries where the `format` is known to this\n * library and the configuration validates correctly. Should be ran only after verifying\n * the credential issuer metadata structure, so we can be certain that if the `format`\n * matches the other format specific requirements are also met.\n *\n * Validation is done when resolving issuer metadata, or when calling `createIssuerMetadata`.\n */\nexport function extractKnownCredentialConfigurationSupportedFormats(\n credentialConfigurationsSupported: CredentialConfigurationsSupported\n): CredentialConfigurationsSupportedWithFormats {\n return Object.fromEntries(\n Object.entries(credentialConfigurationsSupported).filter(\n (entry): entry is [string, CredentialConfigurationSupportedWithFormats] => {\n // Type guard to ensure that the returned entries have known formats\n const credentialConfiguration = zCredentialConfigurationSupportedWithFormats.safeParse(entry[1]) // Validate structure\n if (!credentialConfiguration.success) {\n return false\n }\n return allCredentialIssuerMetadataFormatIdentifiers.includes(\n credentialConfiguration.data.format as CredentialFormatIdentifier\n )\n }\n )\n )\n}\n\n/**\n * Get a known credential configuration supported by its id, it will throw an error if the configuration\n * is not found or if its found but the credential configuration is invalid.\n */\nexport function getKnownCredentialConfigurationSupportedById(\n issuerMetadata: IssuerMetadataResult,\n credentialConfigurationId: string\n) {\n const configuration = issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId]\n\n if (!configuration) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' not found in credential configurations supported.`\n )\n }\n\n if (!issuerMetadata.knownCredentialConfigurations[credentialConfigurationId]) {\n parseWithErrorHandling(\n zCredentialConfigurationSupportedWithFormats,\n configuration,\n `Credential configuration with id '${credentialConfigurationId}' is not valid`\n )\n }\n\n return issuerMetadata.knownCredentialConfigurations[credentialConfigurationId]\n}\n","import { zIs } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport {\n zJwtVcJsonCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcFormatIdentifier,\n zMsoMdocCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zSdJwtDcCredentialIssuerMetadata,\n} from '../formats/credential'\nimport { zLegacySdJwtVcCredentialIssuerMetadataV1 } from '../formats/credential/sd-jwt-vc/z-sd-jwt-vc'\nimport { zSdJwtW3VcCredentialIssuerMetadata } from '../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport type { CredentialRequestWithFormats } from './z-credential-request'\n\nexport interface GetCredentialRequestFormatPayloadForCredentialConfigurationIdOptions {\n /**\n * The credential configuration id to get the format payload for\n */\n credentialConfigurationId: string\n\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function getCredentialRequestFormatPayloadForCredentialConfigurationId(\n options: GetCredentialRequestFormatPayloadForCredentialConfigurationIdOptions\n): CredentialRequestWithFormats {\n const credentialConfiguration = getKnownCredentialConfigurationSupportedById(\n options.issuerMetadata,\n options.credentialConfigurationId\n )\n\n if (\n zIs(zLegacySdJwtVcCredentialIssuerMetadataV1, credentialConfiguration) ||\n zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft14, credentialConfiguration) ||\n (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration) &&\n (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11 ||\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft14))\n ) {\n return {\n format: 'vc+sd-jwt',\n vct: credentialConfiguration.vct,\n }\n }\n\n if (\n zIs(zMsoMdocCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zMsoMdocCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n doctype: credentialConfiguration.doctype,\n }\n }\n\n if (\n zIs(zLdpVcCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zLdpVcCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n '@context': credentialConfiguration.credential_definition['@context'],\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (\n zIs(zJwtVcJsonLdCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zJwtVcJsonLdCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n '@context': credentialConfiguration.credential_definition['@context'],\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (\n zIs(zJwtVcJsonCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zJwtVcJsonCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration)) {\n throw new Openid4vciError(\n `Credential configuration id '${options.credentialConfigurationId}' with format ${zLegacySdJwtVcFormatIdentifier.value} does not support credential request based on 'format'. Use 'credential_configuration_id' directly.`\n )\n }\n\n if (zIs(zSdJwtW3VcCredentialIssuerMetadata, credentialConfiguration)) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n throw new Openid4vciError(\n `Unknown format '${credentialConfiguration.format}' in credential configuration with id '${options.credentialConfigurationId}' for credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n}\n","import { zCompactJwt } from '@openid4vc/oauth2'\nimport z from 'zod'\nimport {\n type KeyAttestationJwtHeader,\n zKeyAttestationJwtHeader,\n zKeyAttestationJwtPayloadForUse,\n} from '../../../key-attestation/z-key-attestation'\n\nexport const zAttestationProofTypeIdentifier = z.literal('attestation')\nexport const attestationProofTypeIdentifier = zAttestationProofTypeIdentifier.value\nexport type AttestationProofTypeIdentifier = z.infer<typeof zAttestationProofTypeIdentifier>\n\nexport const zCredentialRequestProofAttestation = z.object({\n proof_type: zAttestationProofTypeIdentifier,\n attestation: zCompactJwt,\n})\n\nexport const zCredentialRequestAttestationProofTypeHeader = zKeyAttestationJwtHeader\nexport type CredentialRequestAttestationProofTypeHeader = KeyAttestationJwtHeader\n\nexport const zCredentialRequestAttestationProofTypePayload = zKeyAttestationJwtPayloadForUse('proof_type.attestation')\nexport type CredentialRequestAttestationProofTypePayload = z.infer<typeof zCredentialRequestAttestationProofTypePayload>\n","import { zCompactJwt, zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zHttpsUrl, zInteger } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport const zJwtProofTypeIdentifier = z.literal('jwt')\nexport const jwtProofTypeIdentifier = zJwtProofTypeIdentifier.value\nexport type JwtProofTypeIdentifier = z.infer<typeof zJwtProofTypeIdentifier>\n\nexport const zCredentialRequestProofJwt = z.object({\n proof_type: zJwtProofTypeIdentifier,\n jwt: zCompactJwt,\n})\n\nexport const zCredentialRequestJwtProofTypeHeader = zJwtHeader\n .extend({\n key_attestation: z.optional(zCompactJwt),\n typ: z.literal('openid4vci-proof+jwt'),\n })\n .loose()\n .refine(({ kid, jwk }) => jwk === undefined || kid === undefined, {\n message: `Both 'jwk' and 'kid' are defined. Only one is allowed`,\n })\n .refine(({ trust_chain, kid }) => !trust_chain || !kid, {\n message: `When 'trust_chain' is provided, 'kid' is required`,\n })\n\nexport type CredentialRequestJwtProofTypeHeader = z.infer<typeof zCredentialRequestJwtProofTypeHeader>\n\nexport const zCredentialRequestJwtProofTypePayload = z\n .object({\n ...zJwtPayload.shape,\n aud: z.union([zHttpsUrl, z.array(zHttpsUrl)]),\n iat: zInteger,\n })\n .loose()\n\nexport type CredentialRequestJwtProofTypePayload = z.infer<typeof zCredentialRequestJwtProofTypePayload>\n","import { zJwk } from '@openid4vc/oauth2'\nimport type { InferOutputUnion, Simplify } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n zAttestationProofTypeIdentifier,\n zCredentialRequestProofAttestation,\n zCredentialRequestProofJwt,\n zJwtProofTypeIdentifier,\n} from '../formats/proof-type'\n\nconst zCredentialRequestProofCommon = z\n .object({\n proof_type: z.string(),\n })\n .loose()\n\nexport const allCredentialRequestProofs = [zCredentialRequestProofJwt, zCredentialRequestProofAttestation] as const\n\nexport const zCredentialRequestProof = z.union([\n zCredentialRequestProofCommon,\n z.discriminatedUnion('proof_type', allCredentialRequestProofs),\n])\n\nconst zCredentialRequestProofsCommon = z.record(z.string(), z.array(z.unknown()))\nexport const zCredentialRequestProofs = z.object({\n [zJwtProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofJwt.shape.jwt)),\n [zAttestationProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofAttestation.shape.attestation)),\n})\n\ntype CredentialRequestProofCommon = z.infer<typeof zCredentialRequestProofCommon>\nexport type CredentialRequestProofFormatSpecific = InferOutputUnion<typeof allCredentialRequestProofs>\nexport type CredentialRequestProofWithFormats = Simplify<\n CredentialRequestProofCommon & CredentialRequestProofFormatSpecific\n>\nexport type CredentialRequestProof = z.infer<typeof zCredentialRequestProof>\n\nexport type CredentialRequestProofsCommon = z.infer<typeof zCredentialRequestProofsCommon>\nexport type CredentialRequestProofsFormatSpecific = z.infer<typeof zCredentialRequestProofs>\nexport type CredentialRequestProofsWithFormat = CredentialRequestProofsCommon & CredentialRequestProofsFormatSpecific\nexport type CredentialRequestProofs = z.infer<typeof zCredentialRequestProofs>\n\nexport const zCredentialRequestCommon = z\n .object({\n proof: zCredentialRequestProof.optional(),\n proofs: z.optional(\n z\n .intersection(zCredentialRequestProofsCommon, zCredentialRequestProofs)\n .refine((proofs) => Object.values(proofs).length === 1, {\n message: `The 'proofs' object in a credential request should contain exactly one attribute`,\n })\n ),\n\n credential_response_encryption: z\n .object({\n jwk: zJwk,\n alg: z.string(),\n enc: z.string(),\n })\n .loose()\n .optional(),\n })\n .loose()\n // It's not allowed to provide both proof and proofs\n .refine(({ proof, proofs }) => !(proof !== undefined && proofs !== undefined), {\n message: `Both 'proof' and 'proofs' are defined. Only one is allowed`,\n })\n","import { zJwk } from '@openid4vc/oauth2'\nimport type { InferOutputUnion, Simplify } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n zJwtVcJsonCredentialRequestFormatDraft14,\n zJwtVcJsonLdCredentialRequestFormatDraft14,\n zLdpVcCredentialRequestFormatDraft14,\n zLegacySdJwtVcCredentialRequestFormatDraft14,\n zMsoMdocCredentialRequestFormatDraft14,\n} from '../formats/credential'\nimport {\n zJwtVcJsonCredentialRequestDraft11To14,\n zJwtVcJsonCredentialRequestDraft14To11,\n zJwtVcJsonFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-jwt-vc-json'\nimport {\n zJwtVcJsonLdCredentialRequestDraft11To14,\n zJwtVcJsonLdCredentialRequestDraft14To11,\n zJwtVcJsonLdFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld'\nimport {\n zLdpVcCredentialRequestDraft11To14,\n zLdpVcCredentialRequestDraft14To11,\n zLdpVcFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-ldp-vc'\nimport { zSdJwtW3VcCredentialRequestFormatDraft14 } from '../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { zCredentialRequestCommon } from './z-credential-request-common'\n\nexport const allCredentialRequestFormats = [\n zSdJwtW3VcCredentialRequestFormatDraft14,\n zMsoMdocCredentialRequestFormatDraft14,\n zLdpVcCredentialRequestFormatDraft14,\n zJwtVcJsonLdCredentialRequestFormatDraft14,\n zJwtVcJsonCredentialRequestFormatDraft14,\n zLegacySdJwtVcCredentialRequestFormatDraft14,\n] as const\n\nexport const allCredentialRequestFormatIdentifiers = allCredentialRequestFormats.map(\n (format) => format.shape.format.value\n)\n\n// Credential configuration no format used\nconst zCredentialRequestCredentialConfigurationId = z.object({\n credential_configuration_id: z.string(),\n\n credential_identifier: z\n .never({ message: \"'credential_identifier' cannot be defined when 'credential_configuration_id' is set.\" })\n .optional(),\n})\n\n// Authorization details no format used\nconst zAuthorizationDetailsCredentialRequest = z.object({\n credential_identifier: z.string(),\n\n credential_configuration_id: z\n .never({ message: \"'credential_configuration_id' cannot be defined when 'credential_identifier' is set.\" })\n .optional(),\n})\n\nconst zCredentialRequestFormat = z\n .object({\n format: z.string(),\n\n // We add these nevers here so that if one of these is present, we will always use\n // the new properties rather than the deprecated format\n credential_identifier: z\n .never({ message: \"'credential_identifier' cannot be defined when 'format' is set.\" })\n .optional(),\n\n credential_configuration_id: z\n .never({ message: \"'credential_configuration_id' cannot be defined when 'format' is set.\" })\n .optional(),\n })\n .loose()\n\nexport const zCredentialRequestDraft14WithFormat = zCredentialRequestCommon\n .and(zCredentialRequestFormat)\n .transform((data, ctx) => {\n // No additional validation for unknown formats\n if (\n !allCredentialRequestFormatIdentifiers.includes(\n data.format as (typeof allCredentialRequestFormatIdentifiers)[number]\n )\n )\n return data\n\n const result = z\n // We use object and passthrough as otherwise the non-format specific properties will be stripped\n .object({})\n .loose()\n // FIXME(vc+sd-jwt): use discriminated union when dropping support for legacy vc+sd-jwt format.\n .and(z.union(allCredentialRequestFormats))\n .safeParse(data)\n if (result.success) {\n return result.data as Simplify<typeof result.data & typeof data>\n }\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n\nconst zCredentialRequestDraft15 = z.union([\n zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest),\n zCredentialRequestCommon.and(zCredentialRequestCredentialConfigurationId),\n])\n\nconst zCredentialRequestDraft14 = z.union([\n zCredentialRequestDraft14WithFormat,\n zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest),\n])\n\nexport const zCredentialRequestDraft11To14 = zCredentialRequestCommon\n .and(zCredentialRequestFormat)\n .transform((data, ctx): unknown => {\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft11To14,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft11To14,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft11To14,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n .pipe(zCredentialRequestDraft14)\n\nexport const zCredentialRequestDraft14To11 = zCredentialRequestDraft14.transform((data, ctx) => {\n if (data.credential_identifier !== undefined) {\n ctx.addIssue({\n code: 'custom',\n continue: false,\n message: `'credential_identifier' is not supported in OpenID4VCI draft 11`,\n path: ['credential_identifier'],\n })\n return z.NEVER\n }\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft14To11,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft14To11,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft14To11,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n})\n\nexport const zCredentialRequest = z.union([\n zCredentialRequestDraft15,\n zCredentialRequestDraft14,\n zCredentialRequestDraft11To14,\n])\n\nexport const zDeferredCredentialRequest = z.object({\n transaction_id: z.string().nonempty(),\n credential_response_encryption: z\n .object({\n jwk: zJwk,\n alg: z.string(),\n enc: z.string(),\n })\n .loose()\n .optional(),\n})\n\ntype CredentialRequestCommon = z.infer<typeof zCredentialRequestCommon>\nexport type CredentialRequestFormatSpecific = InferOutputUnion<typeof allCredentialRequestFormats>\nexport type CredentialRequestWithFormats = CredentialRequestCommon & CredentialRequestFormatSpecific\n\nexport type CredentialRequestDraft14 = z.infer<typeof zCredentialRequestDraft14>\nexport type CredentialRequestDraft15 = z.infer<typeof zCredentialRequestDraft15>\nexport type CredentialRequest = CredentialRequestDraft14 | CredentialRequestDraft15\n\nexport type DeferredCredentialRequest = z.infer<typeof zDeferredCredentialRequest>\n","import z from 'zod'\n\nexport enum Oauth2ErrorCodes {\n ServerError = 'server_error',\n\n // Resource Indicators\n InvalidTarget = 'invalid_target',\n\n // Oauth2\n InvalidRequest = 'invalid_request',\n InvalidToken = 'invalid_token',\n InsufficientScope = 'insufficient_scope',\n InvalidGrant = 'invalid_grant',\n InvalidClient = 'invalid_client',\n UnauthorizedClient = 'unauthorized_client',\n UnsupportedGrantType = 'unsupported_grant_type',\n InvalidScope = 'invalid_scope',\n\n // DPoP\n InvalidDpopProof = 'invalid_dpop_proof',\n UseDpopNonce = 'use_dpop_nonce',\n\n // FiPA\n RedirectToWeb = 'redirect_to_web',\n InvalidSession = 'invalid_session',\n InsufficientAuthorization = 'insufficient_authorization',\n\n // OpenID4VCI\n InvalidCredentialRequest = 'invalid_credential_request',\n CredentialRequestDenied = 'credential_request_denied',\n InvalidProof = 'invalid_proof',\n InvalidNonce = 'invalid_nonce',\n InvalidEncryptionParameters = 'invalid_encryption_parameters',\n UnknownCredentialConfiguration = 'unknown_credential_configuration',\n UnknownCredentialIdentifier = 'unknown_credential_identifier',\n InvalidTransactionId = 'invalid_transaction_id',\n // Removed from Draft 16+\n UnsupportedCredentialType = 'unsupported_credential_type',\n UnsupportedCredentialFormat = 'unsupported_credential_format',\n\n // Jar\n InvalidRequestUri = 'invalid_request_uri',\n InvalidRequestObject = 'invalid_request_object',\n RequestNotSupported = 'request_not_supported',\n RequestUriNotSupported = 'request_uri_not_supported',\n\n // OpenID4VP\n VpFormatsNotSupported = 'vp_formats_not_supported',\n AccessDenied = 'access_denied',\n InvalidPresentationDefinitionUri = 'invalid_presentation_definition_uri',\n InvalidPresentationDefinitionReference = 'invalid_presentation_definition_reference',\n InvalidRequestUriMethod = 'invalid_request_uri_method',\n InvalidTransactionData = 'invalid_transaction_data',\n WalletUnavailable = 'wallet_unavailable',\n}\n\nexport const zOauth2ErrorResponse = z\n .object({\n error: z.union([z.enum(Oauth2ErrorCodes), z.string()]),\n error_description: z.string().optional(),\n error_uri: z.string().optional(),\n })\n .loose()\n\nexport type Oauth2ErrorResponse = z.infer<typeof zOauth2ErrorResponse>\n","import z from 'zod'\nimport { zOauth2ErrorResponse } from '../../../oauth2/src/common/z-oauth2-error'\n\nconst zCredentialEncoding = z.union([z.string(), z.record(z.string(), z.any())])\n\nconst zBaseCredentialResponse = z\n .object({\n credentials: z\n .union([\n // Draft >= 15\n z.array(z.object({ credential: zCredentialEncoding })),\n // Draft < 15\n z.array(zCredentialEncoding),\n ])\n .optional(),\n notification_id: z.string().optional(),\n\n transaction_id: z.string().optional(),\n interval: z.number().int().positive().optional(),\n })\n .loose()\n\nexport const zCredentialResponse = zBaseCredentialResponse\n .extend({\n credential: z.optional(zCredentialEncoding),\n\n c_nonce: z.string().optional(),\n c_nonce_expires_in: z.number().int().optional(),\n })\n .loose()\n .superRefine((value, ctx) => {\n const { credential, credentials, transaction_id, interval, notification_id } = value\n\n // NOTE: we allow both credential and credentials to be present, to better work with\n // issuers that return both for backwards compatibility\n if ([credential || credentials, transaction_id].filter((i) => i !== undefined).length !== 1) {\n ctx.addIssue({\n code: 'custom',\n message: `Exactly one of 'credential'/'credentials', or 'transaction_id' MUST be defined.`,\n })\n }\n\n if (transaction_id && !interval) {\n ctx.addIssue({\n code: 'custom',\n message: `'interval' MUST be defined when 'transaction_id' is defined.`,\n })\n }\n\n if (notification_id && !(credentials || credential)) {\n ctx.addIssue({\n code: 'custom',\n message: `'notification_id' MUST NOT be defined when 'credential' or 'credentials' are not defined.`,\n })\n }\n })\n\nexport type CredentialResponse = z.infer<typeof zCredentialResponse>\n\nexport const zCredentialErrorResponse = z\n .object({\n ...zOauth2ErrorResponse.shape,\n\n c_nonce: z.string().optional(),\n c_nonce_expires_in: z.number().int().optional(),\n })\n .loose()\n\nexport type CredentialErrorResponse = z.infer<typeof zCredentialErrorResponse>\n\nexport const zDeferredCredentialResponse = zBaseCredentialResponse.superRefine((value, ctx) => {\n const { credentials, transaction_id, interval, notification_id } = value\n\n if ([credentials, transaction_id].filter((i) => i !== undefined).length !== 1) {\n ctx.addIssue({\n code: 'custom',\n message: `Exactly one of 'credentials', or 'transaction_id' MUST be defined.`,\n })\n }\n\n if (transaction_id && !interval) {\n ctx.addIssue({\n code: 'custom',\n message: `'interval' MUST be defined when 'transaction_id' is defined.`,\n })\n }\n\n if (notification_id && credentials) {\n ctx.addIssue({\n code: 'custom',\n message: `'notification_id' MUST NOT be defined when 'credentials' is not defined.`,\n })\n }\n})\n\nexport type DeferredCredentialResponse = z.infer<typeof zDeferredCredentialResponse>\n","import {\n type CallbackContext,\n Oauth2Error,\n type RequestDpopOptions,\n type ResourceRequestResponseNotOk,\n type ResourceRequestResponseOk,\n resourceRequest,\n type zOauth2ErrorResponse,\n} from '@openid4vc/oauth2'\nimport { ContentType, isResponseContentType, parseWithErrorHandling } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport {\n type CredentialRequest,\n type CredentialRequestWithFormats,\n zCredentialRequest,\n zCredentialRequestDraft14To11,\n zDeferredCredentialRequest,\n} from './z-credential-request'\nimport type { CredentialRequestProof, CredentialRequestProofs } from './z-credential-request-common'\nimport {\n type CredentialResponse,\n type DeferredCredentialResponse,\n zCredentialErrorResponse,\n zCredentialResponse,\n zDeferredCredentialResponse,\n} from './z-credential-response'\n\ninterface RetrieveCredentialsBaseOptions {\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Callback used in retrieve credentials endpoints\n */\n callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'hash' | 'signJwt'>\n\n /**\n * Access token authorized to retrieve the credential(s)\n */\n accessToken: string\n\n /**\n * DPoP options\n */\n dpop?: RequestDpopOptions\n}\n\nexport interface RetrieveCredentialsWithCredentialConfigurationIdOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The credential configuration id to request\n */\n credentialConfigurationId: string\n\n proof?: CredentialRequestProof\n proofs?: CredentialRequestProofs\n}\n\nexport async function retrieveCredentialsWithCredentialConfigurationId(\n options: RetrieveCredentialsWithCredentialConfigurationIdOptions\n) {\n if (\n options.issuerMetadata.originalDraftVersion !== Openid4vciVersion.Draft15 &&\n options.issuerMetadata.originalDraftVersion !== Openid4vciVersion.V1\n ) {\n throw new Openid4vciError(\n '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.'\n )\n }\n\n // This ensures the credential configuration exists\n getKnownCredentialConfigurationSupportedById(options.issuerMetadata, options.credentialConfigurationId)\n\n const credentialRequest: CredentialRequest = {\n ...options.additionalRequestPayload,\n\n credential_configuration_id: options.credentialConfigurationId,\n proof: options.proof,\n proofs: options.proofs,\n }\n\n return retrieveCredentials({\n callbacks: options.callbacks,\n credentialRequest,\n issuerMetadata: options.issuerMetadata,\n accessToken: options.accessToken,\n dpop: options.dpop,\n })\n}\n\nexport interface RetrieveCredentialsWithFormatOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The format specific payload. Needs to at least include the `format` and other params\n * are determined by the format itself\n */\n formatPayload: CredentialRequestWithFormats\n\n proof?: CredentialRequestProof\n proofs?: CredentialRequestProofs\n}\n\nexport async function retrieveCredentialsWithFormat(options: RetrieveCredentialsWithFormatOptions) {\n if (\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft15 ||\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.V1\n ) {\n throw new Openid4vciError(\n 'Requesting credentials based on format is not supported on OpenID4VCI above draft 15. Provide the credential configuration id directly in the request.'\n )\n }\n\n const credentialRequest: CredentialRequest = {\n ...options.formatPayload,\n ...options.additionalRequestPayload,\n\n proof: options.proof,\n proofs: options.proofs,\n }\n\n return retrieveCredentials({\n callbacks: options.callbacks,\n credentialRequest,\n issuerMetadata: options.issuerMetadata,\n accessToken: options.accessToken,\n dpop: options.dpop,\n })\n}\n\nexport interface RetrieveCredentialsOptions extends RetrieveCredentialsBaseOptions {\n /**\n * The credential request\n */\n credentialRequest: CredentialRequest\n}\n\nexport interface RetrieveCredentialsResponseOk extends ResourceRequestResponseOk {\n /**\n * The successful validated (in structure, not the actual contents are validated) credential response payload\n */\n credentialResponse: CredentialResponse\n}\n\nexport interface RetrieveCredentialsResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response itself was successful but the validation of the\n * credential response data structure failed\n */\n credentialResponseResult?: ReturnType<typeof zCredentialResponse.safeParse>\n\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a credential error response. It may be successful or it may not be.\n */\n credentialErrorResponseResult?: ReturnType<typeof zCredentialErrorResponse.safeParse>\n}\n\n/**\n * internal method\n */\nasync function retrieveCredentials(\n options: RetrieveCredentialsOptions\n): Promise<RetrieveCredentialsResponseNotOk | RetrieveCredentialsResponseOk> {\n const credentialEndpoint = options.issuerMetadata.credentialIssuer.credential_endpoint\n\n let credentialRequest = parseWithErrorHandling(\n zCredentialRequest,\n options.credentialRequest,\n 'Error validating credential request'\n )\n\n if (credentialRequest.proofs) {\n const { batch_credential_issuance } = options.issuerMetadata.credentialIssuer\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n throw new Oauth2Error(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support batch credential issuance using the 'proofs' request property. Only 'proof' is supported.`\n )\n }\n\n const proofs = Object.values(credentialRequest.proofs)[0]\n if (proofs.length > (batch_credential_issuance?.batch_size ?? 1)) {\n throw new Oauth2Error(\n `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.`\n )\n }\n }\n\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n credentialRequest = parseWithErrorHandling(\n zCredentialRequestDraft14To11,\n credentialRequest,\n `Error transforming credential request from ${Openid4vciVersion.Draft14} to ${Openid4vciVersion.Draft11}`\n )\n }\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: credentialEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(credentialRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const credentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n credentialErrorResponseResult,\n }\n }\n\n // Try to parse the credential response\n const credentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n if (!credentialResponseResult?.success) {\n return {\n ...resourceResponse,\n ok: false,\n credentialResponseResult,\n }\n }\n\n return {\n ...resourceResponse,\n credentialResponse: credentialResponseResult.data,\n }\n}\n\nexport interface RetrieveDeferredCredentialsOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The transaction ID\n */\n transactionId: string\n}\n\nexport interface RetrieveDeferredCredentialsResponseOk extends ResourceRequestResponseOk {\n /**\n * The successful validated (in structure, not the actual contents are validated) deferred credential response payload\n */\n deferredCredentialResponse: DeferredCredentialResponse\n}\n\nexport interface RetrieveDeferredCredentialsResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response itself was successful but the validation of the\n * credential response data structure failed\n */\n deferredCredentialResponseResult?: ReturnType<typeof zDeferredCredentialResponse.safeParse>\n\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a credential error response. It may be successful or it may not be.\n */\n deferredCredentialErrorResponseResult?: ReturnType<typeof zOauth2ErrorResponse.safeParse>\n}\n\nexport async function retrieveDeferredCredentials(\n options: RetrieveDeferredCredentialsOptions\n): Promise<RetrieveDeferredCredentialsResponseNotOk | RetrieveDeferredCredentialsResponseOk> {\n const credentialEndpoint = options.issuerMetadata.credentialIssuer.deferred_credential_endpoint\n if (!credentialEndpoint) {\n throw new Openid4vciError(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support deferred credential retrieval.`\n )\n }\n\n const deferredCredentialRequest = parseWithErrorHandling(\n zDeferredCredentialRequest,\n {\n transaction_id: options.transactionId,\n ...options.additionalRequestPayload,\n },\n 'Error validating deferred credential request'\n )\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: credentialEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(deferredCredentialRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const deferredCredentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n deferredCredentialErrorResponseResult,\n }\n }\n\n // Try to parse the credential response\n const deferredCredentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zDeferredCredentialResponse\n .refine((response) => response.credentials || response.transaction_id === options.transactionId, {\n error: `Transaction id in deferred credential response does not match transaction id in deferred credential request '${options.transactionId}'`,\n })\n .safeParse(await resourceResponse.response.clone().json())\n : undefined\n if (!deferredCredentialResponseResult?.success) {\n return {\n ...resourceResponse,\n ok: false,\n deferredCredentialResponseResult,\n }\n }\n\n return {\n ...resourceResponse,\n deferredCredentialResponse: deferredCredentialResponseResult.data,\n }\n}\n","import {\n type CallbackContext,\n decodeJwt,\n isJwkInSet,\n type JwtSigner,\n jwtHeaderFromJwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling } from '@openid4vc/utils'\nimport { Openid4vciError } from '../../../error/Openid4vciError'\nimport { type VerifyKeyAttestationJwtReturn, verifyKeyAttestationJwt } from '../../../key-attestation/key-attestation'\nimport { zKeyAttestationJwtHeader, zKeyAttestationJwtPayload } from '../../../key-attestation/z-key-attestation'\nimport {\n type CredentialRequestJwtProofTypeHeader,\n type CredentialRequestJwtProofTypePayload,\n zCredentialRequestJwtProofTypeHeader,\n zCredentialRequestJwtProofTypePayload,\n} from './z-jwt-proof-type'\n\nexport interface CreateCredentialRequestJwtProofOptions {\n /**\n * Nonce to use in the jwt. Should be derived from the c_nonce\n */\n nonce?: string\n\n /**\n * The credential issuer identifier\n */\n credentialIssuer: string\n\n /**\n * The date when the token was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The client id of the wallet requesting the credential. Should not be included when using\n * the pre-authorized code flow\n */\n clientId?: string\n\n /**\n * Key attestation jwt that the proof should based on. In this case it is required that the `signer` uses\n * a key from the `attested_keys` in the key attestation jwt payload.\n */\n keyAttestationJwt?: string\n\n signer: JwtSigner\n callbacks: Pick<CallbackContext, 'signJwt' | 'hash'>\n}\n\nexport async function createCredentialRequestJwtProof(\n options: CreateCredentialRequestJwtProofOptions\n): Promise<string> {\n const header = parseWithErrorHandling(zCredentialRequestJwtProofTypeHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n key_attestation: options.keyAttestationJwt,\n typ: 'openid4vci-proof+jwt',\n } satisfies CredentialRequestJwtProofTypeHeader)\n\n const payload = parseWithErrorHandling(zCredentialRequestJwtProofTypePayload, {\n nonce: options.nonce,\n aud: options.credentialIssuer,\n iat: dateToSeconds(options.issuedAt),\n iss: options.clientId,\n } satisfies CredentialRequestJwtProofTypePayload)\n\n const { jwt, signerJwk } = await options.callbacks.signJwt(options.signer, { header, payload })\n\n // Check the jwt is signed with an key from attested_keys in the key_attestation jwt\n if (options.keyAttestationJwt) {\n const decodedKeyAttestation = decodeJwt({\n jwt: options.keyAttestationJwt,\n headerSchema: zKeyAttestationJwtHeader,\n payloadSchema: zKeyAttestationJwtPayload,\n })\n\n const isSigedWithAttestedKey = await isJwkInSet({\n jwk: signerJwk,\n jwks: decodedKeyAttestation.payload.attested_keys,\n callbacks: options.callbacks,\n })\n\n if (!isSigedWithAttestedKey) {\n throw new Openid4vciError(\n `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`\n )\n }\n }\n\n return jwt\n}\n\nexport interface VerifyCredentialRequestJwtProofOptions {\n /**\n * The proof jwt\n */\n jwt: string\n\n /**\n * Expected nonce. Should be a c_nonce previously shared with the wallet\n */\n expectedNonce?: string\n\n /**\n * Date at which the nonce will expire\n */\n nonceExpiresAt?: Date\n\n /**\n * The credential issuer identifier, will be matched against the `aud` claim.\n */\n credentialIssuer: string\n\n /**\n * The client id of the wallet requesting the credential, if available.\n */\n clientId?: string\n\n /**\n * Current time, if not provided a new date instance will be created\n */\n now?: Date\n\n /**\n * Callbacks required for the jwt verification.\n *\n * Will be used for the jwt proof, and optionally a `key_attestation` in the jwt proof header.\n */\n callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>\n}\n\nexport async function verifyCredentialRequestJwtProof(options: VerifyCredentialRequestJwtProofOptions) {\n const { header, payload } = decodeJwt({\n jwt: options.jwt,\n headerSchema: zCredentialRequestJwtProofTypeHeader,\n payloadSchema: zCredentialRequestJwtProofTypePayload,\n })\n\n const now = options.now?.getTime() ?? Date.now()\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new Openid4vciError('Nonce used for credential request proof expired')\n }\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n header,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'Error verifiying credential request proof jwt.',\n expectedNonce: options.expectedNonce,\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n now: options.now,\n })\n\n let keyAttestationResult: VerifyKeyAttestationJwtReturn | undefined\n // Check the jwt is signed with an key from attested_keys in the key_attestation jwt\n if (header.key_attestation) {\n keyAttestationResult = await verifyKeyAttestationJwt({\n callbacks: options.callbacks,\n keyAttestationJwt: header.key_attestation,\n use: 'proof_type.jwt',\n })\n\n const isSigedWithAttestedKey = await isJwkInSet({\n jwk: signer.publicJwk,\n jwks: keyAttestationResult.payload.attested_keys,\n callbacks: options.callbacks,\n })\n\n if (!isSigedWithAttestedKey) {\n throw new Openid4vciError(\n `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`\n )\n }\n }\n\n return {\n header,\n payload,\n signer,\n keyAttestation: keyAttestationResult,\n }\n}\n","import {\n type AuthorizationServerMetadata,\n type CallbackContext,\n fetchAuthorizationServerMetadata,\n Oauth2Error,\n zAuthorizationServerMetadata,\n} from '@openid4vc/oauth2'\n\nimport { parseWithErrorHandling } from '@openid4vc/utils'\nimport type { Openid4vciVersion } from '../version'\nimport {\n type CredentialIssuerMetadataSigned,\n extractKnownCredentialConfigurationSupportedFormats,\n fetchCredentialIssuerMetadata,\n} from './credential-issuer/credential-issuer-metadata'\nimport type {\n CredentialConfigurationsSupportedWithFormats,\n CredentialIssuerMetadata,\n} from './credential-issuer/z-credential-issuer-metadata'\n\nexport interface ResolveIssuerMetadataOptions {\n /**\n * Only fetch metadata for authorization servers that are part of this list. This can help if you know beforehand\n * which authorization servers will be used. The list is not validated to ensure all entries are also\n * in the issuer metadata.\n */\n restrictToAuthorizationServers?: string[]\n\n /**\n * Allow extracting authorization server metadata from the credential issuer metadata. This is added for backwards\n * compatibility with some implementations that did not host a separate authorization server metadata and will be removed\n * in a future version.\n *\n * @default true\n */\n allowAuthorizationMetadataFromCredentialIssuerMetadata?: boolean\n\n /**\n * Callbacks for fetching the credential issur metadata.\n * If no `verifyJwt` callback is provided, the request\n * will not include the `application/jwt` Accept header\n * for signed metadata.\n */\n callbacks: Partial<Pick<CallbackContext, 'fetch' | 'verifyJwt'>>\n\n /**\n * Only used for verifying signed issuer metadata. If not provided\n * current time will be used\n */\n now?: Date\n}\n\nexport interface IssuerMetadataResult {\n originalDraftVersion: Openid4vciVersion\n credentialIssuer: CredentialIssuerMetadata\n\n /**\n * Metadata about the signed credential issuer metadata,\n * if the issuer metadata was signed\n */\n signedCredentialIssuer?: CredentialIssuerMetadataSigned\n\n authorizationServers: AuthorizationServerMetadata[]\n\n /**\n * Known credential configurations includes all the credential configurations with a known credential format\n * that pass the validation requirements from the OpenID4VCI specification. Recognized formats that do not\n * adhere to the format specific metadata requirements are not included, but also won't result in an error, to\n * to still allow interacting with issuers using invalid metadata for specific configurations.\n */\n knownCredentialConfigurations: CredentialConfigurationsSupportedWithFormats\n}\n\nexport async function resolveIssuerMetadata(\n credentialIssuer: string,\n options?: ResolveIssuerMetadataOptions\n): Promise<IssuerMetadataResult> {\n const allowAuthorizationMetadataFromCredentialIssuerMetadata =\n options?.allowAuthorizationMetadataFromCredentialIssuerMetadata ?? true\n\n const credentialIssuerMetadataWithDraftVersion = await fetchCredentialIssuerMetadata(credentialIssuer, {\n callbacks: options?.callbacks,\n now: options?.now,\n })\n if (!credentialIssuerMetadataWithDraftVersion) {\n throw new Oauth2Error(`Well known credential issuer metadata for issuer '${credentialIssuer}' not found.`)\n }\n\n const { credentialIssuerMetadata, originalDraftVersion, signed } = credentialIssuerMetadataWithDraftVersion\n\n // If no authoriation servers are defined, use the credential issuer as the authorization server\n const authorizationServers = credentialIssuerMetadata.authorization_servers ?? [credentialIssuer]\n\n const authoriationServersMetadata: AuthorizationServerMetadata[] = []\n for (const authorizationServer of authorizationServers) {\n if (\n options?.restrictToAuthorizationServers &&\n !options.restrictToAuthorizationServers.includes(authorizationServer)\n ) {\n continue\n }\n\n let authorizationServerMetadata = await fetchAuthorizationServerMetadata(\n authorizationServer,\n options?.callbacks.fetch\n )\n if (\n !authorizationServerMetadata &&\n authorizationServer === credentialIssuer &&\n allowAuthorizationMetadataFromCredentialIssuerMetadata\n ) {\n authorizationServerMetadata = parseWithErrorHandling(\n zAuthorizationServerMetadata,\n {\n token_endpoint: credentialIssuerMetadata.token_endpoint,\n issuer: credentialIssuer,\n },\n `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.`\n )\n }\n\n if (!authorizationServerMetadata) {\n throw new Oauth2Error(\n `Well known openid configuration or authorization server metadata for authorization server '${authorizationServer}' not found.`\n )\n }\n\n authoriationServersMetadata.push(authorizationServerMetadata)\n }\n\n // Collect all known credential configurations with formats\n const knownCredentialConfigurations = extractKnownCredentialConfigurationSupportedFormats(\n credentialIssuerMetadata.credential_configurations_supported\n )\n\n return {\n originalDraftVersion,\n credentialIssuer: credentialIssuerMetadata,\n signedCredentialIssuer: signed,\n\n authorizationServers: authoriationServersMetadata,\n knownCredentialConfigurations,\n }\n}\n","import { zInteger } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport const zNonceResponse = z\n .object({\n c_nonce: z.string(),\n c_nonce_expires_in: z.optional(zInteger),\n })\n .loose()\nexport type NonceResponse = z.infer<typeof zNonceResponse>\n","import { InvalidFetchResponseError } from '@openid4vc/oauth2'\nimport { ContentType, createZodFetcher, type Fetch, parseWithErrorHandling, ValidationError } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { type NonceResponse, zNonceResponse } from './z-nonce'\n\nexport interface RequestNonceOptions {\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Custom fetch implementation to use\n */\n fetch?: Fetch\n}\n\n/**\n * Request a nonce from the `nonce_endpoint`\n *\n * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata\n * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response\n * @throws ValidationError - if validating the nonce response failed\n */\nexport async function requestNonce(options: RequestNonceOptions): Promise<NonceResponse> {\n const fetchWithZod = createZodFetcher(options?.fetch)\n const nonceEndpoint = options.issuerMetadata.credentialIssuer.nonce_endpoint\n\n if (!nonceEndpoint) {\n throw new Openid4vciError(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a nonce endpoint.`\n )\n }\n\n const { response, result } = await fetchWithZod(zNonceResponse, ContentType.Json, nonceEndpoint, {\n method: 'POST',\n })\n\n if (!response.ok || !result) {\n throw new InvalidFetchResponseError(\n `Requesting nonce from '${nonceEndpoint}' resulted in an unsuccessful response with status '${response.status}'`,\n await response.clone().text(),\n response\n )\n }\n\n if (!result.success) {\n throw new ValidationError('Error parsing nonce response', result.error)\n }\n\n return result.data\n}\n\nexport interface CreateNonceResponseOptions {\n cNonce: string\n cNonceExpiresIn?: number\n\n /**\n * Additional payload to include in the nonce response.\n *\n * Will be applied after default params to allow extension so be cautious\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createNonceResponse(options: CreateNonceResponseOptions) {\n return parseWithErrorHandling(zNonceResponse, {\n c_nonce: options.cNonce,\n c_nonce_expires_in: options.cNonceExpiresIn,\n ...options.additionalPayload,\n } satisfies NonceResponse)\n}\n","import z from 'zod'\n\nconst zNotificationEvent = z.enum(['credential_accepted', 'credential_failure', 'credential_deleted'])\nexport type NotificationEvent = z.infer<typeof zNotificationEvent>\n\nexport const zNotificationRequest = z\n .object({\n notification_id: z.string(),\n event: zNotificationEvent,\n event_description: z.optional(z.string()),\n })\n .loose()\n\nexport type NotificationRequest = z.infer<typeof zNotificationRequest>\n\nexport const zNotificationErrorResponse = z\n .object({\n error: z.enum(['invalid_notification_id', 'invalid_notification_request']),\n })\n .loose()\nexport type NotificationErrorResponse = z.infer<typeof zNotificationErrorResponse>\n","import {\n type CallbackContext,\n Oauth2Error,\n type RequestDpopOptions,\n type ResourceRequestResponseNotOk,\n type ResourceRequestResponseOk,\n resourceRequest,\n} from '@openid4vc/oauth2'\nimport { ContentType, isResponseContentType, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport {\n type NotificationEvent,\n type NotificationRequest,\n zNotificationErrorResponse,\n zNotificationRequest,\n} from './z-notification'\n\nexport interface SendNotificationOptions {\n notification: {\n /**\n * Notification id, as returned in the credential response\n */\n notificationId: string\n\n /**\n * The notification\n */\n event: NotificationEvent\n\n /**\n * Human readable description of the event\n */\n eventDescription?: string\n }\n\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Callback used in notification endpoint\n */\n callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'hash' | 'signJwt'>\n\n /**\n * Access token authorized to retrieve the credential(s)\n */\n accessToken: string\n\n /**\n * DPoP options\n */\n dpop?: RequestDpopOptions\n\n /**\n * Additional payload to include in the notification request.\n */\n additionalRequestPayload?: Record<string, unknown>\n}\n\nexport type SendNotificationResponseOk = ResourceRequestResponseOk\nexport interface SendNotificationResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a notification error response. It may be successful or it may not be.\n */\n notificationErrorResponseResult?: ReturnType<typeof zNotificationErrorResponse.safeParse>\n}\n\nexport async function sendNotification(\n options: SendNotificationOptions\n): Promise<SendNotificationResponseNotOk | SendNotificationResponseOk> {\n const notificationEndpoint = options.issuerMetadata.credentialIssuer.notification_endpoint\n\n if (!notificationEndpoint) {\n throw new Oauth2Error(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a notification endpiont configured.`\n )\n }\n\n const notificationRequest = parseWithErrorHandling(\n zNotificationRequest,\n {\n event: options.notification.event,\n notification_id: options.notification.notificationId,\n event_description: options.notification.eventDescription,\n } satisfies NotificationRequest,\n 'Error validating notification request'\n )\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: notificationEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(notificationRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const notificationErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zNotificationErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n notificationErrorResponseResult,\n }\n }\n\n return resourceResponse\n}\n","import {\n authorizationCodeGrantIdentifier,\n type CallbackContext,\n type CreateAuthorizationRequestUrlOptions,\n type CreatePkceReturn,\n getAuthorizationServerMetadataFromList,\n Oauth2Client,\n Oauth2ClientAuthorizationChallengeError,\n Oauth2Error,\n Oauth2ErrorCodes,\n type ParseAuthorizationResponseOptions,\n parseAuthorizationResponseRedirectUrl,\n preAuthorizedCodeGrantIdentifier,\n type RequestDpopOptions,\n type RetrieveAuthorizationCodeAccessTokenOptions,\n type RetrievePreAuthorizedCodeAccessTokenOptions,\n type VerifyAuthorizationResponseOptions,\n verifyAuthorizationResponse,\n} from '@openid4vc/oauth2'\n\nimport {\n determineAuthorizationServerForCredentialOffer,\n resolveCredentialOffer,\n} from './credential-offer/credential-offer'\nimport type { CredentialOfferObject } from './credential-offer/z-credential-offer'\nimport { getCredentialRequestFormatPayloadForCredentialConfigurationId } from './credential-request/format-payload'\nimport {\n type RetrieveCredentialsResponseNotOk,\n type RetrieveCredentialsResponseOk,\n type RetrieveCredentialsWithFormatOptions,\n type RetrieveDeferredCredentialsOptions,\n type RetrieveDeferredCredentialsResponseOk,\n retrieveCredentialsWithCredentialConfigurationId,\n retrieveCredentialsWithFormat,\n retrieveDeferredCredentials,\n} from './credential-request/retrieve-credentials'\nimport { Openid4vciError } from './error/Openid4vciError'\nimport { Openid4vciRetrieveCredentialsError } from './error/Openid4vciRetrieveCredentialsError'\nimport { Openid4vciSendNotificationError } from './error/Openid4vciSendNotificationError'\nimport {\n type CreateCredentialRequestJwtProofOptions,\n createCredentialRequestJwtProof,\n} from './formats/proof-type/jwt/jwt-proof-type'\nimport { type IssuerMetadataResult, resolveIssuerMetadata } from './metadata/fetch-issuer-metadata'\nimport { type RequestNonceOptions, requestNonce } from './nonce/nonce-request'\nimport { type SendNotificationOptions, sendNotification } from './notification/notification'\nimport { Openid4vciVersion } from './version'\n\nexport enum AuthorizationFlow {\n Oauth2Redirect = 'Oauth2Redirect',\n PresentationDuringIssuance = 'PresentationDuringIssuance',\n}\n\nexport interface Openid4vciClientOptions {\n /**\n * Callbacks required for the openid4vc client\n */\n callbacks: Omit<CallbackContext, 'verifyJwt' | 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Openid4vciClient {\n private oauth2Client: Oauth2Client\n\n public constructor(private options: Openid4vciClientOptions) {\n this.oauth2Client = new Oauth2Client({\n callbacks: this.options.callbacks,\n })\n }\n\n /**\n * Resolve a credential offer into a credential offer object, handling both\n * 'credential_offer' and 'credential_offer_uri' params.\n */\n public async resolveCredentialOffer(credentialOffer: string): Promise<CredentialOfferObject> {\n return resolveCredentialOffer(credentialOffer, {\n fetch: this.options.callbacks.fetch,\n })\n }\n\n public async resolveIssuerMetadata(credentialIssuer: string): Promise<IssuerMetadataResult> {\n return resolveIssuerMetadata(credentialIssuer, {\n callbacks: this.options.callbacks,\n })\n }\n\n /**\n * Retrieve an authorization code for a presentation during issuance session\n *\n * This can only be called if an authorization challenge was performed before and returned a\n * `presentation` parameter along with an `auth_session`. If the presentation response included\n * an `presentation_during_issuance_session` parameter it MUST be included in this request as well.\n */\n public async retrieveAuthorizationCodeUsingPresentation(options: {\n /**\n * Auth session as returned by `{@link Openid4vciClient.initiateAuthorization}\n */\n authSession: string\n\n /**\n * Presentation during issuance session, obtained from the RP after submitting\n * openid4vp authorization response\n */\n presentationDuringIssuanceSession?: string\n\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n\n dpop?: RequestDpopOptions\n }) {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks })\n const { authorizationChallengeResponse, dpop } = await oauth2Client.sendAuthorizationChallengeRequest({\n authorizationServerMetadata,\n authSession: options.authSession,\n presentationDuringIssuanceSession: options.presentationDuringIssuanceSession,\n dpop: options.dpop,\n })\n\n return { authorizationChallengeResponse, dpop }\n }\n\n /**\n * Initiates authorization for credential issuance. It handles the following cases:\n * - Authorization Challenge\n * - Pushed Authorization Request\n * - Regular Authorization url\n *\n * In case the authorization challenge request returns an error with `insufficient_authorization`\n * with a `presentation` field it means the authorization server expects presentation of credentials\n * before issuance of credentials. If this is the case, the value in `presentation` should be treated\n * as an openid4vp authorization request and submitted to the verifier. Once the presentation response\n * has been submitted, the RP will respond with a `presentation_during_issuance_session` parameter.\n * Together with the `auth_session` parameter returned in this call you can retrieve an `authorization_code`\n * using\n */\n public async initiateAuthorization(\n options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks' | 'authorizationServerMetadata'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }\n ): Promise<\n // TODO: cleanup these types\n | {\n authorizationFlow: AuthorizationFlow.PresentationDuringIssuance\n openid4vpRequestUrl: string\n authSession: string\n authorizationServer: string\n }\n | {\n authorizationFlow: AuthorizationFlow.Oauth2Redirect\n authorizationRequestUrl: string\n authorizationServer: string\n pkce?: CreatePkceReturn\n }\n > {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks })\n\n try {\n const result = await oauth2Client.initiateAuthorization({\n clientId: options.clientId,\n pkceCodeVerifier: options.pkceCodeVerifier,\n redirectUri: options.redirectUri,\n scope: options.scope,\n additionalRequestPayload: {\n ...options.additionalRequestPayload,\n issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state,\n },\n dpop: options.dpop,\n resource: options.issuerMetadata.credentialIssuer.credential_issuer,\n authorizationServerMetadata,\n })\n\n return {\n ...result,\n authorizationFlow: AuthorizationFlow.Oauth2Redirect,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n } catch (error) {\n // Authorization server asks us to complete openid4vp request before issuance\n if (\n error instanceof Oauth2ClientAuthorizationChallengeError &&\n error.errorResponse.error === Oauth2ErrorCodes.InsufficientAuthorization &&\n error.errorResponse.presentation\n ) {\n if (!error.errorResponse.auth_session) {\n throw new Openid4vciError(\n `Expected 'auth_session' to be defined with authorization challenge response error '${error.errorResponse.error}' and 'presentation' parameter`\n )\n }\n return {\n authorizationFlow: AuthorizationFlow.PresentationDuringIssuance,\n openid4vpRequestUrl: error.errorResponse.presentation,\n authSession: error.errorResponse.auth_session,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n }\n\n throw error\n }\n }\n\n /**\n * Convenience method around {@link Oauth2Client.createAuthorizationRequestUrl}\n * but specifically focused on a credential offer\n */\n public async createAuthorizationRequestUrlFromOffer(\n options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks' | 'authorizationServerMetadata'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const { authorizationRequestUrl, pkce, dpop } = await this.oauth2Client.createAuthorizationRequestUrl({\n authorizationServerMetadata,\n clientId: options.clientId,\n additionalRequestPayload: {\n ...options.additionalRequestPayload,\n issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state,\n },\n resource: options.issuerMetadata.credentialIssuer.credential_issuer,\n redirectUri: options.redirectUri,\n scope: options.scope,\n pkceCodeVerifier: options.pkceCodeVerifier,\n dpop: options.dpop,\n })\n\n return {\n authorizationRequestUrl,\n pkce,\n dpop,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n }\n\n /**\n * Convenience method around {@link Oauth2Client.retrievePreAuthorizedCodeAccessToken}\n * but specifically focused on a credential offer\n */\n public async retrievePreAuthorizedCodeAccessTokenFromOffer({\n credentialOffer,\n issuerMetadata,\n additionalRequestPayload,\n txCode,\n dpop,\n }: Omit<\n RetrievePreAuthorizedCodeAccessTokenOptions,\n 'callbacks' | 'authorizationServerMetadata' | 'preAuthorizedCode' | 'resource'\n > & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }) {\n if (!credentialOffer.grants?.[preAuthorizedCodeGrantIdentifier]) {\n throw new Oauth2Error(`The credential offer does not contain the '${preAuthorizedCodeGrantIdentifier}' grant.`)\n }\n\n if (credentialOffer.grants[preAuthorizedCodeGrantIdentifier].tx_code && !txCode) {\n // TODO: we could further validate the tx_code, but not sure if that's needed?\n // the server will do that for us as well\n throw new Oauth2Error(\n `Retrieving access token requires a 'tx_code' in the request, but the 'txCode' parameter was not provided.`\n )\n }\n\n const preAuthorizedCode = credentialOffer.grants[preAuthorizedCodeGrantIdentifier]['pre-authorized_code']\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n grantAuthorizationServer: credentialOffer.grants[preAuthorizedCodeGrantIdentifier].authorization_server,\n issuerMetadata,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const result = await this.oauth2Client.retrievePreAuthorizedCodeAccessToken({\n authorizationServerMetadata,\n preAuthorizedCode,\n txCode,\n resource: issuerMetadata.credentialIssuer.credential_issuer,\n additionalRequestPayload,\n dpop,\n })\n\n return {\n ...result,\n authorizationServer,\n }\n }\n\n /**\n * Parses the authorization (error) response redirect url, and verifies the\n * 'iss' value based on the authorization server metadata.\n *\n * If you need values from the authorization response (e.g. state) to retrieve the\n * authorization server metadata, you can manually import and call `parseAuthorizationResponseRedirectUrl` and\n * `verifyAuthorizationResponse`.\n */\n public parseAndVerifyAuthorizationResponseRedirectUrl(\n options: ParseAuthorizationResponseOptions & Omit<VerifyAuthorizationResponseOptions, 'authorizationResponse'>\n ) {\n const authorizationResponse = parseAuthorizationResponseRedirectUrl(options)\n\n verifyAuthorizationResponse({\n ...options,\n authorizationResponse,\n })\n\n return authorizationResponse\n }\n\n /**\n * Convenience method around {@link Oauth2Client.retrieveAuthorizationCodeAccessToken}\n * but specifically focused on a credential offer\n */\n public async retrieveAuthorizationCodeAccessTokenFromOffer({\n issuerMetadata,\n additionalRequestPayload,\n credentialOffer,\n authorizationCode,\n pkceCodeVerifier,\n redirectUri,\n dpop,\n }: Omit<RetrieveAuthorizationCodeAccessTokenOptions, 'authorizationServerMetadata' | 'callbacks'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }) {\n if (!credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`The credential offer does not contain the '${authorizationCodeGrantIdentifier}' grant.`)\n }\n\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n grantAuthorizationServer: credentialOffer.grants[authorizationCodeGrantIdentifier].authorization_server,\n issuerMetadata,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const result = await this.oauth2Client.retrieveAuthorizationCodeAccessToken({\n authorizationServerMetadata,\n authorizationCode,\n pkceCodeVerifier,\n additionalRequestPayload,\n dpop,\n redirectUri,\n resource: issuerMetadata.credentialIssuer.credential_issuer,\n })\n\n return {\n ...result,\n authorizationServer,\n }\n }\n\n /**\n * Request a nonce to be used in credential request proofs from the `nonce_endpoint`\n *\n * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata\n * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response\n * @throws ValidationError - if validating the nonce response failed\n */\n public async requestNonce(options: Pick<RequestNonceOptions, 'issuerMetadata'>) {\n return requestNonce({\n ...options,\n fetch: this.options.callbacks.fetch,\n })\n }\n\n /**\n * Creates the jwt proof payload and header to be included in a credential request.\n */\n public async createCredentialRequestJwtProof(\n options: Pick<\n CreateCredentialRequestJwtProofOptions,\n 'signer' | 'nonce' | 'issuedAt' | 'clientId' | 'keyAttestationJwt'\n > & {\n issuerMetadata: IssuerMetadataResult\n credentialConfigurationId: string\n }\n ) {\n const credentialConfiguration =\n options.issuerMetadata.credentialIssuer.credential_configurations_supported[options.credentialConfigurationId]\n if (!credentialConfiguration) {\n throw new Openid4vciError(\n `Credential configuration with '${options.credentialConfigurationId}' not found in 'credential_configurations_supported' from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n }\n\n if (credentialConfiguration.proof_types_supported) {\n if (!credentialConfiguration.proof_types_supported.jwt) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' does not support the 'jwt' proof type.`\n )\n }\n\n if (\n !credentialConfiguration.proof_types_supported.jwt.proof_signing_alg_values_supported.includes(\n options.signer.alg\n )\n ) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' does not support the '${options.signer.alg}' alg for 'jwt' proof type.`\n )\n }\n\n // TODO: might be beneficial to also decode the key attestation and see if the required level is reached\n if (credentialConfiguration.proof_types_supported.jwt.key_attestations_required && !options.keyAttestationJwt) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' requires key attestations for 'jwt' proof type but no 'keyAttestationJwt' was provided`\n )\n }\n }\n\n const jwt = await createCredentialRequestJwtProof({\n credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n signer: options.signer,\n clientId: options.clientId,\n issuedAt: options.issuedAt,\n nonce: options.nonce,\n keyAttestationJwt: options.keyAttestationJwt,\n callbacks: this.options.callbacks,\n })\n\n return {\n jwt,\n }\n }\n\n /**\n * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response\n * @throws ValidationError - if validation of the credential request failed\n * @throws Openid4vciError - if the `credentialConfigurationId` couldn't be found, or if the the format specific request couldn't be constructed\n */\n public async retrieveCredentials({\n issuerMetadata,\n proof,\n proofs,\n credentialConfigurationId,\n additionalRequestPayload,\n accessToken,\n dpop,\n }: Pick<\n RetrieveCredentialsWithFormatOptions,\n 'accessToken' | 'additionalRequestPayload' | 'issuerMetadata' | 'proof' | 'proofs' | 'dpop'\n > & { credentialConfigurationId: string }) {\n let credentialResponse: RetrieveCredentialsResponseNotOk | RetrieveCredentialsResponseOk\n\n if (\n issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft15 ||\n issuerMetadata.originalDraftVersion === Openid4vciVersion.V1\n ) {\n credentialResponse = await retrieveCredentialsWithCredentialConfigurationId({\n accessToken,\n credentialConfigurationId,\n issuerMetadata,\n additionalRequestPayload,\n proof,\n proofs,\n callbacks: this.options.callbacks,\n dpop,\n })\n } else {\n const formatPayload = getCredentialRequestFormatPayloadForCredentialConfigurationId({\n credentialConfigurationId,\n issuerMetadata,\n })\n\n credentialResponse = await retrieveCredentialsWithFormat({\n accessToken,\n formatPayload,\n issuerMetadata,\n additionalRequestPayload,\n proof,\n proofs,\n callbacks: this.options.callbacks,\n dpop,\n })\n }\n\n if (!credentialResponse.ok) {\n throw new Openid4vciRetrieveCredentialsError(\n `Error retrieving credentials from '${issuerMetadata.credentialIssuer.credential_issuer}'`,\n credentialResponse,\n await credentialResponse.response.clone().text()\n )\n }\n\n return credentialResponse\n }\n\n /**\n * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response\n * @throws ValidationError - if validation of the credential request failed\n */\n public async retrieveDeferredCredentials(\n options: Pick<\n RetrieveDeferredCredentialsOptions,\n 'issuerMetadata' | 'accessToken' | 'transactionId' | 'dpop' | 'additionalRequestPayload'\n >\n ): Promise<RetrieveDeferredCredentialsResponseOk> {\n const credentialResponse = await retrieveDeferredCredentials({\n ...options,\n callbacks: this.options.callbacks,\n })\n\n if (!credentialResponse.ok) {\n throw new Openid4vciRetrieveCredentialsError(\n `Error retrieving deferred credentials from '${options.issuerMetadata.credentialIssuer.credential_issuer}'`,\n credentialResponse,\n await credentialResponse.response.clone().text()\n )\n }\n\n return credentialResponse\n }\n\n /**\n * @throws Openid4vciSendNotificationError - if an unsuccessful response\n * @throws ValidationError - if validation of the notification request failed\n */\n public async sendNotification({\n issuerMetadata,\n notification,\n additionalRequestPayload,\n accessToken,\n dpop,\n }: Pick<\n SendNotificationOptions,\n 'accessToken' | 'additionalRequestPayload' | 'issuerMetadata' | 'dpop' | 'notification'\n >) {\n const notificationResponse = await sendNotification({\n accessToken,\n issuerMetadata,\n additionalRequestPayload,\n callbacks: this.options.callbacks,\n dpop,\n notification,\n })\n\n if (!notificationResponse.ok) {\n throw new Openid4vciSendNotificationError(\n `Error sending notification to '${issuerMetadata.credentialIssuer.credential_issuer}'`,\n notificationResponse\n )\n }\n\n return notificationResponse\n }\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport type { ParseCredentialRequestReturn } from './parse-credential-request'\nimport {\n type CredentialResponse,\n type DeferredCredentialResponse,\n zCredentialResponse,\n zDeferredCredentialResponse,\n} from './z-credential-response'\n\nexport interface CreateCredentialResponseOptions {\n credentialRequest: ParseCredentialRequestReturn\n\n credential?: CredentialResponse['credential']\n credentials?: CredentialResponse['credentials']\n\n transactionId?: string\n interval?: number\n\n cNonce?: string\n cNonceExpiresInSeconds?: number\n\n notificationId?: string\n\n /**\n * Additional payload to include in the credential response\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createCredentialResponse(options: CreateCredentialResponseOptions) {\n return parseWithErrorHandling(zCredentialResponse, {\n c_nonce: options.cNonce,\n c_nonce_expires_in: options.cNonceExpiresInSeconds,\n credential: options.credential,\n credentials: options.credentials,\n notification_id: options.notificationId,\n\n transaction_id: options.transactionId,\n interval: options.interval,\n\n // NOTE `format` is removed in draft 13. For now if a format was requested\n // we just always return it in the response as well.\n format: options.credentialRequest.format?.format,\n ...options.additionalPayload,\n } satisfies CredentialResponse)\n}\n\nexport type CreateDeferredCredentialResponseOptions = (\n | {\n credentials: DeferredCredentialResponse['credentials']\n notificationId?: string\n\n transactionId?: never\n interval?: never\n }\n | {\n /**\n * The `transaction_id` used to identify the deferred issuance transaction.\n */\n transactionId: string\n interval: number\n\n credentials?: never\n notificationId?: never\n }\n) & {\n /**\n * Additional payload to include in the deferred credential response\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createDeferredCredentialResponse(options: CreateDeferredCredentialResponseOptions) {\n return parseWithErrorHandling(zDeferredCredentialResponse, {\n credentials: options.credentials,\n notification_id: options.notificationId,\n\n transaction_id: options.transactionId,\n interval: options.interval,\n\n ...options.additionalPayload,\n } satisfies DeferredCredentialResponse)\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport z from 'zod'\nimport { attestationProofTypeIdentifier } from '../formats/proof-type/attestation/z-attestation-proof-type'\nimport { jwtProofTypeIdentifier } from '../formats/proof-type/jwt/z-jwt-proof-type'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { CredentialConfigurationSupportedWithFormats } from '../metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport {\n allCredentialRequestFormatIdentifiers,\n allCredentialRequestFormats,\n type CredentialRequest,\n type CredentialRequestFormatSpecific,\n zCredentialRequest,\n} from './z-credential-request'\nimport {\n allCredentialRequestProofs,\n type CredentialRequestProofsFormatSpecific,\n zCredentialRequestProofs,\n} from './z-credential-request-common'\n\nexport interface ParseCredentialRequestOptions {\n issuerMetadata: IssuerMetadataResult\n credentialRequest: Record<string, unknown>\n}\n\nexport interface ParseCredentialRequestReturn {\n /**\n * If the request was for a `format` that is known to this library it will have the\n * format specific data defined here. Will not be defined if the request is for an unknown format,\n * or if `credential_identifier` is used.\n */\n format?: CredentialRequestFormatSpecific\n\n /**\n * If the request contains `proof` or `proofs` with a `proof_type` that is known to this\n * library it will have the proof type specific data defined here. Will not be defined\n * if the `proof_type` is not known or no `proof` or `proofs` were included.\n *\n * The `proof` property is parsed to the new proofs structure and the entries will\n * always only have a single entry in this case.\n *\n * NOTE: this value being `undefined` does NOT mean there were no proofs.\n * It means that either there were no proofs, or that the proof format is not\n * known to this library\n */\n proofs?: CredentialRequestProofsFormatSpecific\n\n /**\n * If authorization details were used a `credential_identifier` will be included\n * in the request. Will not be defined if `format` is defined.\n */\n credentialIdentifier?: string\n\n /**\n * Starting from OID4VCI draft 15 the credential request can include a `credential_configuration_id`.\n * This will only be defined if the request included the credential configuration id.\n *\n * An error will be thrown if a credential configuration id was included in the request that is not\n * present in the credential configurations supported of the issuer metadata\n */\n credentialConfigurationId?: string\n\n /**\n * If the request included a `credential_configuration_id` with a known format, it will\n * be included here. It's still possible `credential_configuration_id` was defined, but\n * it's not a known format.\n */\n credentialConfiguration?: CredentialConfigurationSupportedWithFormats\n\n /**\n * The validated credential request. If both `format` and `credentialIdentifier` are\n * undefined you can still handle the request by using this object directly.\n */\n credentialRequest: CredentialRequest\n}\n\nexport function parseCredentialRequest(options: ParseCredentialRequestOptions): ParseCredentialRequestReturn {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequest,\n options.credentialRequest,\n 'Error validating credential request'\n )\n let proofs: CredentialRequestProofsFormatSpecific | undefined\n\n // Try to parse the known proofs from the `proofs` object\n const knownProofs = zCredentialRequestProofs.strict().safeParse(credentialRequest.proofs)\n if (knownProofs.success) {\n proofs = knownProofs.data\n }\n\n // Try to parse the known proof from the `proof`\n const knownProof = z.union(allCredentialRequestProofs).safeParse(credentialRequest.proof)\n if (knownProof.success && knownProof.data.proof_type === jwtProofTypeIdentifier) {\n proofs = { [jwtProofTypeIdentifier]: [knownProof.data.jwt] }\n } else if (knownProof.success && knownProof.data.proof_type === attestationProofTypeIdentifier) {\n proofs = { [attestationProofTypeIdentifier]: [knownProof.data.attestation] }\n }\n\n if (credentialRequest.credential_configuration_id) {\n // This will throw an error if the credential configuration does not exist or is not valid\n getKnownCredentialConfigurationSupportedById(options.issuerMetadata, credentialRequest.credential_configuration_id)\n\n const credentialConfigurations = options.issuerMetadata.knownCredentialConfigurations\n\n return {\n credentialConfiguration: credentialConfigurations[credentialRequest.credential_configuration_id],\n credentialConfigurationId: credentialRequest.credential_configuration_id,\n credentialRequest,\n proofs,\n }\n }\n\n if (credentialRequest.credential_identifier) {\n return {\n credentialIdentifier: credentialRequest.credential_identifier,\n credentialRequest,\n proofs,\n }\n }\n\n if (\n credentialRequest.format &&\n allCredentialRequestFormatIdentifiers.includes(\n credentialRequest.format as (typeof allCredentialRequestFormatIdentifiers)[number]\n )\n ) {\n return {\n // Removes all claims that are not specific to this format\n format: parseWithErrorHandling(\n z.union(allCredentialRequestFormats),\n credentialRequest,\n 'Unable to validate format specific properties from credential request'\n ),\n credentialRequest,\n proofs,\n }\n }\n\n return {\n credentialRequest,\n proofs,\n }\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport { type DeferredCredentialRequest, zDeferredCredentialRequest } from './z-credential-request'\n\nexport interface ParseDeferredCredentialRequestOptions {\n deferredCredentialRequest: Record<string, unknown>\n}\n\nexport interface ParseDeferredCredentialRequestReturn {\n /**\n * The validated credential request. If both `format` and `credentialIdentifier` are\n * undefined you can still handle the request by using this object directly.\n */\n deferredCredentialRequest: DeferredCredentialRequest\n}\n\nexport function parseDeferredCredentialRequest(\n options: ParseDeferredCredentialRequestOptions\n): ParseDeferredCredentialRequestReturn {\n const deferredCredentialRequest = parseWithErrorHandling(\n zDeferredCredentialRequest,\n options.deferredCredentialRequest,\n 'Error validating credential request'\n )\n\n return {\n deferredCredentialRequest,\n }\n}\n","import {\n type CreateKeyAttestationJwtOptions,\n createKeyAttestationJwt,\n type VerifyKeyAttestationJwtOptions,\n verifyKeyAttestationJwt,\n} from '../../../key-attestation/key-attestation'\n\nexport interface CreateCredentialRequestAttestationProofOptions extends Omit<CreateKeyAttestationJwtOptions, 'use'> {\n /**\n * Nonce to use in the attestation. Should be derived from the c_nonce\n *\n * Required because the attestation is created for 'attestation' proof types\n */\n nonce: string\n\n /**\n * The date when the key attestation will expire.\n */\n expiresAt: Date\n}\n\nexport async function createCredentialRequestAttestationProof(\n options: CreateCredentialRequestAttestationProofOptions\n): Promise<string> {\n return createKeyAttestationJwt({\n ...options,\n use: 'proof_type.attestation',\n })\n}\n\nexport interface VerifyCredentialRequestAttestationProofOptions extends Omit<VerifyKeyAttestationJwtOptions, 'use'> {}\nexport async function verifyCredentialRequestAttestationProof(options: VerifyCredentialRequestAttestationProofOptions) {\n const verificationResult = await verifyKeyAttestationJwt({\n ...options,\n use: 'proof_type.attestation',\n })\n\n return verificationResult\n}\n","import { type CallbackContext, type JwtSigner, jwtHeaderFromJwtSigner } from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CredentialIssuerMetadata } from './z-credential-issuer-metadata'\nimport {\n type SignedCredentialIssuerMetadataHeader,\n type SignedCredentialIssuerMetadataPayload,\n zSignedCredentialIssuerMetadataHeader,\n zSignedCredentialIssuerMetadataPayload,\n} from './z-signed-credential-issuer-metadata'\n\nexport interface CreateSignedCredentialIssuerMetadataJwtOptions {\n /**\n * The credential issuer metadata to include in the jwt\n */\n credentialIssuerMetadata: CredentialIssuerMetadata\n\n /**\n * The date when the credential issuer metadata was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The date when the credential issuer metadata will expire.\n */\n expiresAt?: Date\n\n /**\n * Signer of the credential issuer metadata jwt\n */\n signer: JwtSigner\n\n /**\n * The issuer of the issuer metadata jwt. This field is optional\n */\n issuer?: string\n\n /**\n * Callbacks used for creating the credential issuer metadata jwt\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n\n /**\n * Additional payload to include in the credential issuer metadata jwt payload. Will be applied after\n * any default claims that are included, so add claims with caution.\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport async function createSignedCredentialIssuerMetadataJwt(\n options: CreateSignedCredentialIssuerMetadataJwtOptions\n): Promise<string> {\n const header = parseWithErrorHandling(zSignedCredentialIssuerMetadataHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: 'openidvci-issuer-metadata+jwt',\n } satisfies SignedCredentialIssuerMetadataHeader)\n\n const payload = parseWithErrorHandling(zSignedCredentialIssuerMetadataPayload, {\n ...options.credentialIssuerMetadata,\n sub: options.credentialIssuerMetadata.credential_issuer,\n iat: dateToSeconds(options.issuedAt),\n exp: options.expiresAt ? dateToSeconds(options.expiresAt) : undefined,\n iss: options.issuer,\n ...options.additionalPayload,\n } satisfies SignedCredentialIssuerMetadataPayload)\n\n const { jwt } = await options.callbacks.signJwt(options.signer, { header, payload })\n return jwt\n}\n","import {\n type CallbackContext,\n Oauth2AuthorizationServer,\n Oauth2ErrorCodes,\n Oauth2JwtVerificationError,\n Oauth2ServerErrorResponseError,\n} from '@openid4vc/oauth2'\nimport { parseWithErrorHandling, ValidationError } from '@openid4vc/utils'\nimport type { VerifyClientAttestationOptions } from '../../oauth2/src/client-attestation/client-attestation'\nimport { type CreateCredentialOfferOptions, createCredentialOffer } from './credential-offer/credential-offer'\nimport {\n type CreateCredentialResponseOptions,\n type CreateDeferredCredentialResponseOptions,\n createCredentialResponse,\n createDeferredCredentialResponse,\n} from './credential-request/credential-response'\nimport {\n type ParseCredentialRequestOptions,\n type ParseCredentialRequestReturn,\n parseCredentialRequest,\n} from './credential-request/parse-credential-request'\nimport {\n type ParseDeferredCredentialRequestOptions,\n type ParseDeferredCredentialRequestReturn,\n parseDeferredCredentialRequest,\n} from './credential-request/parse-deferred-credential-request'\nimport { Openid4vciError } from './error/Openid4vciError'\nimport {\n type VerifyCredentialRequestAttestationProofOptions,\n verifyCredentialRequestAttestationProof,\n} from './formats/proof-type/attestation/attestation-proof-type'\nimport {\n type VerifyCredentialRequestJwtProofOptions,\n verifyCredentialRequestJwtProof,\n} from './formats/proof-type/jwt/jwt-proof-type'\nimport { extractKnownCredentialConfigurationSupportedFormats } from './metadata/credential-issuer/credential-issuer-metadata'\nimport {\n type CreateSignedCredentialIssuerMetadataJwtOptions,\n createSignedCredentialIssuerMetadataJwt,\n} from './metadata/credential-issuer/signed-credential-issuer-metadata'\nimport {\n type CredentialIssuerMetadata,\n zCredentialIssuerMetadata,\n zCredentialIssuerMetadataWithDraft11,\n} from './metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from './metadata/fetch-issuer-metadata'\nimport { type CreateNonceResponseOptions, createNonceResponse } from './nonce/nonce-request'\n\nexport interface Openid4vciIssuerOptions {\n /**\n * Callbacks required for the openid4vc issuer\n */\n callbacks: Omit<CallbackContext, 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Openid4vciIssuer {\n public constructor(private options: Openid4vciIssuerOptions) {}\n\n public getCredentialIssuerMetadataDraft11(credentialIssuerMetadata: CredentialIssuerMetadata) {\n return parseWithErrorHandling(zCredentialIssuerMetadataWithDraft11, credentialIssuerMetadata)\n }\n\n public getKnownCredentialConfigurationsSupported(credentialIssuerMetadata: CredentialIssuerMetadata) {\n return extractKnownCredentialConfigurationSupportedFormats(\n credentialIssuerMetadata.credential_configurations_supported\n )\n }\n\n /**\n * Create issuer metadata and validates the structure is correct\n */\n public createCredentialIssuerMetadata(credentialIssuerMetadata: CredentialIssuerMetadata): CredentialIssuerMetadata {\n return parseWithErrorHandling(\n zCredentialIssuerMetadata,\n credentialIssuerMetadata,\n 'Error validating credential issuer metadata'\n )\n }\n\n /**\n * Validates credential issuer metadata structure is correct and creates signed credential issuer metadata JWT\n */\n public createSignedCredentialIssuerMetadataJwt(\n options: Omit<CreateSignedCredentialIssuerMetadataJwtOptions, 'callbacks'>\n ): Promise<string> {\n return createSignedCredentialIssuerMetadataJwt({\n callbacks: this.options.callbacks,\n ...options,\n })\n }\n\n public async createCredentialOffer(\n options: Pick<\n CreateCredentialOfferOptions,\n | 'issuerMetadata'\n | 'additionalPayload'\n | 'grants'\n | 'credentialOfferUri'\n | 'credentialOfferScheme'\n | 'credentialConfigurationIds'\n >\n ) {\n return createCredentialOffer({\n callbacks: this.options.callbacks,\n credentialConfigurationIds: options.credentialConfigurationIds,\n grants: options.grants,\n issuerMetadata: options.issuerMetadata,\n additionalPayload: options.additionalPayload,\n credentialOfferScheme: options.credentialOfferScheme,\n credentialOfferUri: options.credentialOfferUri,\n })\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - if verification of the jwt failed. You can extract\n * the credential error response from this.\n */\n public async verifyCredentialRequestJwtProof(\n options: Pick<\n VerifyCredentialRequestJwtProofOptions,\n 'clientId' | 'jwt' | 'now' | 'expectedNonce' | 'nonceExpiresAt'\n > & {\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n try {\n return await verifyCredentialRequestJwtProof({\n callbacks: this.options.callbacks,\n credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n expectedNonce: options.expectedNonce,\n nonceExpiresAt: options.nonceExpiresAt,\n jwt: options.jwt,\n clientId: options.clientId,\n now: options.now,\n })\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidProof,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError\n ? error.message\n : 'Invalid proof',\n },\n\n {\n internalMessage: 'Error verifying credential request proof jwt',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - if verification of the key attestation failed. You can extract\n * the credential error response from this.\n */\n public async verifyCredentialRequestAttestationProof(\n options: Pick<\n VerifyCredentialRequestAttestationProofOptions,\n 'keyAttestationJwt' | 'expectedNonce' | 'nonceExpiresAt' | 'now'\n > & {\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n try {\n return await verifyCredentialRequestAttestationProof({\n callbacks: this.options.callbacks,\n expectedNonce: options.expectedNonce,\n keyAttestationJwt: options.keyAttestationJwt,\n nonceExpiresAt: options.nonceExpiresAt,\n now: options.now,\n })\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidProof,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError\n ? error.message\n : 'Invalid proof',\n },\n\n {\n internalMessage: 'Error verifying credential request proof attestation',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - when validation of the credential request fails\n * You can extract the credential error response from this.\n */\n public parseCredentialRequest(options: ParseCredentialRequestOptions): ParseCredentialRequestReturn {\n try {\n // TODO: method should include reason for parsing - (e.g. unsupported format etc..)\n return parseCredentialRequest(options)\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidCredentialRequest,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof ValidationError ? error.message : 'Invalid request',\n },\n {\n internalMessage: 'Error verifying credential request proof jwt',\n cause: error,\n }\n )\n }\n\n // TODO: might be nice to add some extra validation params here so it's\n // easy for an issuer to verify whether the request matches with the configuration\n // e.g. alg of holder binding, key_attestations_required, proof_types_supported,\n // request matches offer, etc..\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - when validation of the deferred credential request fails\n */\n public parseDeferredCredentialRequest(\n options: ParseDeferredCredentialRequestOptions\n ): ParseDeferredCredentialRequestReturn {\n try {\n return parseDeferredCredentialRequest(options)\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidCredentialRequest,\n error_description: error instanceof ValidationError ? error.message : 'Invalid request',\n },\n {\n internalMessage: 'Error parsing deferred credential request',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws ValidationError - when validation of the credential response fails\n */\n public createCredentialResponse(options: CreateCredentialResponseOptions) {\n return createCredentialResponse(options)\n }\n\n /**\n * @throws ValidationError - when validation of the credential response fails\n */\n public createDeferredCredentialResponse(options: CreateDeferredCredentialResponseOptions) {\n return createDeferredCredentialResponse(options)\n }\n\n /**\n * @throws ValidationError - when validation of the nonce response fails\n */\n public createNonceResponse(options: CreateNonceResponseOptions) {\n return createNonceResponse(options)\n }\n\n public async verifyWalletAttestation(options: Omit<VerifyClientAttestationOptions, 'callbacks'>) {\n return new Oauth2AuthorizationServer({\n callbacks: this.options.callbacks,\n }).verifyClientAttestation(options)\n }\n}\n","import {\n type CallbackContext,\n type CreateClientAttestationJwtOptions,\n createClientAttestationJwt,\n} from '@openid4vc/oauth2'\nimport { type CreateKeyAttestationJwtOptions, createKeyAttestationJwt } from './key-attestation/key-attestation'\n\nexport interface Openid4vciWalletProviderOptions {\n /**\n * Callbacks required for the openid4vc issuer\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n}\n\nexport class Openid4vciWalletProvider {\n public constructor(private options: Openid4vciWalletProviderOptions) {}\n\n public async createWalletAttestationJwt(\n options: Omit<CreateClientAttestationJwtOptions, 'callbacks'> & { walletName?: string; walletLink?: string }\n ) {\n const additionalPayload = options.additionalPayload\n ? {\n wallet_name: options.walletName,\n wallet_link: options.walletLink,\n ...options.additionalPayload,\n }\n : {\n wallet_name: options.walletName,\n wallet_link: options.walletLink,\n }\n\n return await createClientAttestationJwt({\n ...options,\n callbacks: this.options.callbacks,\n additionalPayload,\n })\n }\n\n public async createKeyAttestationJwt(options: Omit<CreateKeyAttestationJwtOptions, 'callbacks'>) {\n return await createKeyAttestationJwt({\n callbacks: this.options.callbacks,\n ...options,\n })\n }\n}\n"],"mappings":";;;;;AAAA,IAAY,kEAAL;AACL;AACA;AACA;AACA;;;;;;AAMF,MAAa,yBAAyB;;;;ACFtC,MAAM,UAAU,EAC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C/B,OAAO;AACd,SAAM,IAAI,+BACR;IACE,OAAO,iBAAiB;IACxB,mBAEE,iBAAiB,kBAAkB,MAAM,UAAU;IACtD,EACD;IACE,iBAAiB;IACjB,OAAO;IACR,CACF;;;;;;CAYL,AAAO,+BACL,SACsC;AACtC,MAAI;AACF,UAAO,+BAA+B,QAAQ;WACvC,OAAO;AACd,SAAM,IAAI,+BACR;IACE,OAAO,iBAAiB;IACxB,mBAAmB,iBAAiB,kBAAkB,MAAM,UAAU;IACvE,EACD;IACE,iBAAiB;IACjB,OAAO;IACR,CACF;;;;;;CAOL,AAAO,yBAAyB,SAA0C;AACxE,SAAO,yBAAyB,QAAQ;;;;;CAM1C,AAAO,iCAAiC,SAAkD;AACxF,SAAO,iCAAiC,QAAQ;;;;;CAMlD,AAAO,oBAAoB,SAAqC;AAC9D,SAAO,oBAAoB,QAAQ;;CAGrC,MAAa,wBAAwB,SAA4D;AAC/F,SAAO,IAAI,0BAA0B,EACnC,WAAW,KAAK,QAAQ,WACzB,CAAC,CAAC,wBAAwB,QAAQ;;;;;;AC9PvC,IAAa,2BAAb,MAAsC;CACpC,AAAO,YAAY,AAAQ,SAA0C;EAA1C;;CAE3B,MAAa,2BACX,SACA;EACA,MAAM,oBAAoB,QAAQ,oBAC9B;GACE,aAAa,QAAQ;GACrB,aAAa,QAAQ;GACrB,GAAG,QAAQ;GACZ,GACD;GACE,aAAa,QAAQ;GACrB,aAAa,QAAQ;GACtB;AAEL,SAAO,MAAM,2BAA2B;GACtC,GAAG;GACH,WAAW,KAAK,QAAQ;GACxB;GACD,CAAC;;CAGJ,MAAa,wBAAwB,SAA4D;AAC/F,SAAO,MAAM,wBAAwB;GACnC,WAAW,KAAK,QAAQ;GACxB,GAAG;GACJ,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["Oauth2ErrorCodes"],"sources":["../src/version.ts","../src/credential-offer/z-credential-offer.ts","../src/credential-offer/credential-offer.ts","../src/credential-request/credential-request-configurations.ts","../src/error/Openid4vciError.ts","../src/error/Openid4vciRetrieveCredentialsError.ts","../src/error/Openid4vciSendNotificationError.ts","../src/key-attestation/z-key-attestation.ts","../src/key-attestation/key-attestation.ts","../src/metadata/credential-issuer/z-claims-description.ts","../src/metadata/credential-issuer/z-credential-configuration-supported-common.ts","../src/formats/credential/mso-mdoc/z-mso-mdoc.ts","../src/formats/credential/sd-jwt-dc/z-sd-jwt-dc.ts","../src/formats/credential/sd-jwt-vc/z-sd-jwt-vc.ts","../src/formats/credential/w3c-vc/z-w3c-vc-common.ts","../src/formats/credential/w3c-vc/z-w3c-jwt-vc-json.ts","../src/formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld.ts","../src/formats/credential/w3c-vc/z-w3c-ldp-vc.ts","../src/formats/credential/w3c-vc/z-w3c-sd-jwt-vc.ts","../src/metadata/credential-issuer/z-credential-issuer-metadata.ts","../src/metadata/credential-issuer/credential-configurations.ts","../src/metadata/credential-issuer/z-signed-credential-issuer-metadata.ts","../src/metadata/credential-issuer/credential-issuer-metadata.ts","../src/credential-request/format-payload.ts","../src/formats/proof-type/attestation/z-attestation-proof-type.ts","../src/formats/proof-type/jwt/z-jwt-proof-type.ts","../src/credential-request/z-credential-request-common.ts","../src/credential-request/z-credential-request.ts","../../oauth2/src/common/z-oauth2-error.ts","../src/credential-request/z-credential-response.ts","../src/credential-request/retrieve-credentials.ts","../src/formats/proof-type/jwt/jwt-proof-type.ts","../src/metadata/fetch-issuer-metadata.ts","../src/nonce/z-nonce.ts","../src/nonce/nonce-request.ts","../src/notification/z-notification.ts","../src/notification/notification.ts","../src/Openid4vciClient.ts","../src/credential-request/credential-response.ts","../src/credential-request/parse-credential-request.ts","../src/credential-request/parse-deferred-credential-request.ts","../src/formats/proof-type/attestation/attestation-proof-type.ts","../src/metadata/credential-issuer/signed-credential-issuer-metadata.ts","../src/Openid4vciIssuer.ts","../src/Openid4vciWalletProvider.ts"],"sourcesContent":["export enum Openid4vciVersion {\n V1 = 'V1',\n Draft15 = 'Draft15',\n Draft14 = 'Draft14',\n Draft11 = 'Draft11',\n}\n\n/**\n * @deprecated use `OpenId4vciVersion` instead\n */\nexport const Openid4vciDraftVersion = Openid4vciVersion\n","import {\n type AuthorizationCodeGrantIdentifier,\n type PreAuthorizedCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n} from '@openid4vc/oauth2'\nimport { zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\n\nconst zTxCode = z\n .object({\n input_mode: z.union([z.literal('numeric'), z.literal('text')]).optional(),\n length: z.number().int().optional(),\n description: z.string().max(300).optional(),\n })\n .loose()\n\nexport type CredentialOfferPreAuthorizedCodeGrantTxCode = z.input<typeof zTxCode>\n\nexport const zCredentialOfferGrants = z\n .object({\n authorization_code: z\n .object({\n issuer_state: z.string().optional(),\n authorization_server: zHttpsUrl.optional(),\n })\n .loose()\n .optional(),\n [preAuthorizedCodeGrantIdentifier]: z\n .object({\n 'pre-authorized_code': z.string(),\n tx_code: zTxCode.optional(),\n authorization_server: zHttpsUrl.optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n\nexport type CredentialOfferGrants = z.input<typeof zCredentialOfferGrants>\n\nexport type CredentialOfferPreAuthorizedCodeGrant = CredentialOfferGrants[PreAuthorizedCodeGrantIdentifier]\nexport type CredentialOfferAuthorizationCodeGrant = CredentialOfferGrants[AuthorizationCodeGrantIdentifier]\n\nconst zCredentialOfferObjectDraft14 = z\n .object({\n credential_issuer: zHttpsUrl,\n credential_configuration_ids: z.array(z.string()),\n grants: z.optional(zCredentialOfferGrants),\n })\n .loose()\nexport type CredentialOfferObject = z.input<typeof zCredentialOfferObjectDraft14>\n\nexport const zCredentialOfferObjectDraft11To14 = z\n .object({\n credential_issuer: zHttpsUrl,\n // We don't support the inline offer objects from draft 11\n credentials: z.array(\n z.string({ message: 'Only string credential identifiers are supported for draft 11 credential offers' })\n ),\n grants: z.optional(\n z.object({\n // Has extra param in draft 14, but doesn't matter for transform purposes\n authorization_code: zCredentialOfferGrants.shape.authorization_code,\n\n [preAuthorizedCodeGrantIdentifier]: z\n .object({\n 'pre-authorized_code': z.string(),\n user_pin_required: z.optional(z.boolean()),\n })\n .loose()\n .optional(),\n })\n ),\n })\n .loose()\n .transform(({ credentials, grants, ...rest }) => {\n const v14: CredentialOfferObject = {\n ...rest,\n credential_configuration_ids: credentials,\n }\n\n if (grants) {\n v14.grants = { ...grants }\n\n if (grants[preAuthorizedCodeGrantIdentifier]) {\n const { user_pin_required, ...restGrants } = grants[preAuthorizedCodeGrantIdentifier]\n\n v14.grants[preAuthorizedCodeGrantIdentifier] = {\n ...restGrants,\n }\n\n if (user_pin_required) {\n v14.grants[preAuthorizedCodeGrantIdentifier].tx_code = {\n input_mode: 'text',\n }\n }\n }\n }\n\n return v14\n })\n .pipe(zCredentialOfferObjectDraft14)\n\nexport const zCredentialOfferObject = z.union([\n // First prioritize draft 14 (and 13)\n zCredentialOfferObjectDraft14,\n // Then try parsing draft 11 and transform into draft 14\n zCredentialOfferObjectDraft11To14,\n])\n","import {\n type AuthorizationCodeGrantIdentifier,\n authorizationCodeGrantIdentifier,\n type CallbackContext,\n getAuthorizationServerMetadataFromList,\n InvalidFetchResponseError,\n Oauth2Error,\n type PreAuthorizedCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n} from '@openid4vc/oauth2'\nimport {\n ContentType,\n createZodFetcher,\n encodeToBase64Url,\n type Fetch,\n getQueryParams,\n objectToQueryParams,\n parseWithErrorHandling,\n URL,\n URLSearchParams,\n ValidationError,\n} from '@openid4vc/utils'\nimport type z from 'zod'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport {\n type CredentialOfferAuthorizationCodeGrant,\n type CredentialOfferGrants,\n type CredentialOfferObject,\n type CredentialOfferPreAuthorizedCodeGrant,\n zCredentialOfferObject,\n} from './z-credential-offer'\n\nexport interface ResolveCredentialOfferOptions {\n /**\n * Custom fetch implementation to use\n */\n fetch?: Fetch\n}\n\n/**\n * Resolve a credential offer, optionally fetching it if the credential_offer_uri is provided.\n */\nexport async function resolveCredentialOffer(\n credentialOffer: string,\n options?: ResolveCredentialOfferOptions\n): Promise<CredentialOfferObject> {\n const parsedQueryParams = getQueryParams(credentialOffer)\n\n let credentialOfferParseResult: z.ZodSafeParseResult<z.infer<typeof zCredentialOfferObject>>\n\n if (parsedQueryParams.credential_offer_uri) {\n const fetchWithZod = createZodFetcher(options?.fetch)\n\n const { response, result } = await fetchWithZod(\n zCredentialOfferObject,\n ContentType.Json,\n parsedQueryParams.credential_offer_uri\n )\n if (!response.ok || !result) {\n throw new InvalidFetchResponseError(\n `Fetching credential offer from '${parsedQueryParams.credential_offer_uri}' resulted in an unsuccessful response with status '${response.status}'`,\n await response.clone().text(),\n response\n )\n }\n\n credentialOfferParseResult = result\n } else if (parsedQueryParams.credential_offer) {\n let credentialOfferJson: Record<string, unknown>\n\n try {\n credentialOfferJson = JSON.parse(decodeURIComponent(parsedQueryParams.credential_offer))\n } catch (_error) {\n throw new Oauth2Error(`Error parsing JSON from 'credential_offer' param in credential offer '${credentialOffer}'`)\n }\n\n credentialOfferParseResult = zCredentialOfferObject.safeParse(credentialOfferJson)\n } else {\n throw new Oauth2Error(`Credential offer did not contain either 'credential_offer' or 'credential_offer_uri' param.`)\n }\n\n if (credentialOfferParseResult.error) {\n throw new ValidationError(\n `Error parsing credential offer in draft 11, 13 or 14 format extracted from credential offer '${credentialOffer}'`,\n credentialOfferParseResult.error\n )\n }\n\n return credentialOfferParseResult.data\n}\n\nexport interface CreateCredentialOfferGrantsOptions {\n [preAuthorizedCodeGrantIdentifier]?: Partial<CredentialOfferPreAuthorizedCodeGrant>\n [authorizationCodeGrantIdentifier]?: CredentialOfferAuthorizationCodeGrant\n\n [key: string]: unknown\n}\n\nexport interface CreateCredentialOfferOptions {\n issuerMetadata: IssuerMetadataResult\n\n /**\n * The credential configuration ids to be offered\n */\n credentialConfigurationIds: string[]\n\n /**\n * Grants to include in the credential offer\n */\n grants: CreateCredentialOfferGrantsOptions\n\n /**\n * Additional payload to include in the body of the credential offer. Will be applied\n * after the other fields, allowing to override common properties, so be cautious.\n */\n additionalPayload?: Record<string, unknown>\n\n /**\n * If provided the encoded credential offer will use the `credential_offer_uri` parameter\n * instead of directly adding the `credential_offer`. Requires hosting of the `credential_offer_uri`\n */\n credentialOfferUri?: string\n\n /**\n * The scheme to use for the credential offer.\n *\n * @default `openid-credential-offer://`\n */\n credentialOfferScheme?: string\n\n /**\n * Callbacks used to create credential offer\n */\n callbacks: Pick<CallbackContext, 'generateRandom'>\n}\n\ninterface DetermineAuthorizationServerForGrant {\n issuerMetadata: IssuerMetadataResult\n grantAuthorizationServer?: string\n}\n\nexport function determineAuthorizationServerForCredentialOffer(options: DetermineAuthorizationServerForGrant) {\n const authorizationServers = options.issuerMetadata.credentialIssuer.authorization_servers\n\n let authorizationServer: string\n if (options.grantAuthorizationServer) {\n authorizationServer = options.grantAuthorizationServer\n\n if (!authorizationServers) {\n throw new Oauth2Error(\n `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.`\n )\n }\n if (!authorizationServers.includes(authorizationServer)) {\n throw new Oauth2Error(\n `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(', ')}.`\n )\n }\n } else if (!authorizationServers) {\n authorizationServer = options.issuerMetadata.credentialIssuer.credential_issuer\n } else {\n if (authorizationServers.length === 0) {\n throw new Oauth2Error(`Credential issuer metadata has 'authorization_servers' value with length of 0`)\n }\n if (authorizationServers.length > 1) {\n throw new Oauth2Error(\n `Credential issuer metadata has 'authorization_server' with multiple entries, but the credential offer grant did not specify which authorization server to use.`\n )\n }\n\n authorizationServer = authorizationServers[0]\n }\n\n return authorizationServer\n}\n\nexport async function createCredentialOffer(\n options: CreateCredentialOfferOptions\n): Promise<{ credentialOffer: string; credentialOfferObject: CredentialOfferObject }> {\n const {\n [preAuthorizedCodeGrantIdentifier]: preAuthorizedCodeGrant,\n [authorizationCodeGrantIdentifier]: authorizationCodeGrant,\n ...restGrants\n } = options.grants\n const grants: CredentialOfferGrants = { ...restGrants }\n\n if (authorizationCodeGrant) {\n determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n grants[authorizationCodeGrantIdentifier] = authorizationCodeGrant\n }\n\n if (preAuthorizedCodeGrant) {\n determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: preAuthorizedCodeGrant.authorization_server,\n })\n\n grants[preAuthorizedCodeGrantIdentifier] = {\n ...preAuthorizedCodeGrant,\n 'pre-authorized_code':\n preAuthorizedCodeGrant['pre-authorized_code'] ?? encodeToBase64Url(await options.callbacks.generateRandom(32)),\n }\n\n // Draft 11 support\n const txCode = grants[preAuthorizedCodeGrantIdentifier].tx_code\n if (txCode && options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n grants[preAuthorizedCodeGrantIdentifier].user_pin_required = txCode !== undefined\n }\n }\n\n const idsNotInMetadata = options.credentialConfigurationIds.filter(\n (id) => options.issuerMetadata.credentialIssuer.credential_configurations_supported[id] === undefined\n )\n if (idsNotInMetadata.length > 0) {\n throw new Oauth2Error(\n `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(', ')}.`\n )\n }\n\n const credentialOfferScheme = options.credentialOfferScheme ?? 'openid-credential-offer://'\n const credentialOfferObject = parseWithErrorHandling(zCredentialOfferObject, {\n credential_issuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n credential_configuration_ids: options.credentialConfigurationIds,\n grants,\n ...options.additionalPayload,\n } satisfies CredentialOfferObject)\n\n // Draft 11 support\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n credentialOfferObject.credentials = credentialOfferObject.credential_configuration_ids\n }\n\n const url = new URL(credentialOfferScheme)\n url.search = `?${new URLSearchParams([\n ...url.searchParams.entries(),\n ...objectToQueryParams({\n credential_offer_uri: options.credentialOfferUri,\n // Only add credential_offer is uri is undefined\n credential_offer: options.credentialOfferUri ? undefined : credentialOfferObject,\n }).entries(),\n ]).toString()}`\n\n return {\n credentialOffer: url.toString(),\n credentialOfferObject,\n }\n}\n\n/**\n * Extract the authorization servers from the grants in a credential offer. If no authorization servers\n * are present, null is returned.\n */\nexport function extractAuthorizationServersFromCredentialOfferObject(\n credentialOfferObject: CredentialOfferObject\n): string[] | null {\n const authorizationServers: string[] = []\n\n if (credentialOfferObject.grants?.[preAuthorizedCodeGrantIdentifier]?.authorization_server) {\n authorizationServers.push(credentialOfferObject.grants?.[preAuthorizedCodeGrantIdentifier]?.authorization_server)\n }\n\n if (credentialOfferObject.grants?.authorization_code?.authorization_server) {\n authorizationServers.push(credentialOfferObject.grants?.authorization_code?.authorization_server)\n }\n\n return authorizationServers.length > 0 ? authorizationServers : null\n}\n\nexport interface DetermineAuthorizationForOfferOptions {\n grantType: PreAuthorizedCodeGrantIdentifier | AuthorizationCodeGrantIdentifier\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function determineAuthorizationServerForOffer(options: DetermineAuthorizationForOfferOptions) {\n // Try infer authorization server based on credential offer\n const authorizationServer = options.credentialOffer.grants?.[options.grantType]?.authorization_server\n if (authorizationServer) {\n return getAuthorizationServerMetadataFromList(options.issuerMetadata.authorizationServers, authorizationServer)\n }\n\n // Otherwise if there's only one we can use that\n if (options.issuerMetadata.authorizationServers.length === 1) {\n return options.issuerMetadata.authorizationServers[0]\n }\n\n // We can't safely determine the authorization server\n throw new Oauth2Error(\n `Unable to determine authorization server. Multiple authorization servers available and credential offer does not specify which 'authorization_server' to use for the '${options.grantType}' grant type.`\n )\n}\n","import { arrayEqualsIgnoreOrder } from '@openid4vc/utils'\nimport type { CredentialConfigurationsSupportedWithFormats } from '../metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport type { CredentialRequestFormatSpecific } from './z-credential-request'\n\nexport interface GetCredentialConfigurationsMatchingRequestFormatOptions {\n requestFormat: CredentialRequestFormatSpecific\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function getCredentialConfigurationsMatchingRequestFormat({\n requestFormat,\n issuerMetadata,\n}: GetCredentialConfigurationsMatchingRequestFormatOptions): CredentialConfigurationsSupportedWithFormats {\n // credential request format will only contain known formats\n const knownCredentialConfigurations = issuerMetadata.knownCredentialConfigurations\n\n return Object.fromEntries(\n Object.entries(knownCredentialConfigurations).filter(([, credentialConfiguration]) => {\n // Special case to handle vc+sd-jwt to dc+sd-jwt change\n const isSpecialVcToDcSdJwt =\n credentialConfiguration.format === 'dc+sd-jwt' && requestFormat.format === 'vc+sd-jwt'\n // NOTE: ideally we also check for the draft version fo the original issuer metadata\n // but in case you support multiple draft versions as issuer the original version will be 1.0\n // even though you have backwards support for e.g. Draft 11. If we want to check this we would need\n // to have a min/max version, like we have for OpenID4VP. So for now we just allow requests with formats\n // vc+sd-jwt even if the metadata only contains dc+sd-jwt. You can easily handle it on a higher level\n // if you don't want to support this multi-draft support.\n // [Openid4vciVersion.Draft11, Openid4vciVersion.Draft14].includes(issuerMetadata.originalDraftVersion)\n\n if (credentialConfiguration.format !== requestFormat.format && !isSpecialVcToDcSdJwt) return false\n\n const r = requestFormat\n const c = credentialConfiguration\n\n if ((c.format === 'ldp_vc' || c.format === 'jwt_vc_json-ld') && r.format === c.format) {\n return (\n arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type) &&\n arrayEqualsIgnoreOrder(r.credential_definition['@context'], c.credential_definition['@context'])\n )\n }\n\n if (c.format === 'jwt_vc_json' && r.format === c.format) {\n return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type)\n }\n\n if (r.format === 'vc+sd-jwt' && (c.format === 'vc+sd-jwt' || c.format === 'dc+sd-jwt')) {\n if (r.vct && c.vct) {\n return r.vct === c.vct\n }\n\n if (c.format === 'vc+sd-jwt' && c.credential_definition && r.credential_definition) {\n return arrayEqualsIgnoreOrder(r.credential_definition.type, c.credential_definition.type)\n }\n }\n\n if (c.format === 'mso_mdoc' && r.format === c.format) {\n return r.doctype === c.doctype\n }\n\n return false\n })\n )\n}\n","export interface Openid4vciErrorOptions {\n cause?: unknown\n}\n\nexport class Openid4vciError extends Error {\n public readonly cause?: unknown\n\n public constructor(message?: string, options?: Openid4vciErrorOptions) {\n const errorMessage = message ?? 'Unknown error occurred.'\n const causeMessage =\n options?.cause instanceof Error ? ` ${options.cause.message}` : options?.cause ? ` ${options?.cause}` : ''\n\n super(`${errorMessage}${causeMessage}`)\n this.cause = options?.cause\n }\n}\n","import { formatZodError } from '@openid4vc/utils'\nimport type { RetrieveCredentialsResponseNotOk } from '../credential-request/retrieve-credentials'\nimport { Openid4vciError } from './Openid4vciError'\n\nexport class Openid4vciRetrieveCredentialsError extends Openid4vciError {\n public constructor(\n message: string,\n public response: RetrieveCredentialsResponseNotOk,\n responseText: string\n ) {\n const errorData =\n response.credentialResponseResult?.data ??\n response.credentialErrorResponseResult?.data ??\n (response.credentialResponseResult?.error\n ? formatZodError(response.credentialResponseResult.error)\n : undefined) ??\n responseText\n\n super(`${message}\\n${JSON.stringify(errorData, null, 2)}`)\n }\n}\n","import type { SendNotificationResponseNotOk } from '../notification/notification'\nimport { Openid4vciError } from './Openid4vciError'\n\nexport class Openid4vciSendNotificationError extends Openid4vciError {\n public constructor(\n message: string,\n public response: SendNotificationResponseNotOk\n ) {\n super(message)\n }\n}\n","import { zJwk, zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport type KeyAttestationJwtUse = 'proof_type.jwt' | 'proof_type.attestation'\n\nexport const zKeyAttestationJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z\n // Draft 15\n .literal('keyattestation+jwt')\n .or(\n // Draft 16\n z.literal('key-attestation+jwt')\n ),\n })\n .loose()\n .refine(({ kid, jwk }) => jwk === undefined || kid === undefined, {\n message: `Both 'jwk' and 'kid' are defined. Only one is allowed`,\n })\n .refine(({ trust_chain, kid }) => !trust_chain || !kid, {\n message: `When 'trust_chain' is provided, 'kid' is required`,\n })\n\nexport type KeyAttestationJwtHeader = z.infer<typeof zKeyAttestationJwtHeader>\n\nexport const zIso18045 = z.enum(['iso_18045_high', 'iso_18045_moderate', 'iso_18045_enhanced-basic', 'iso_18045_basic'])\n\nexport type Iso18045 = z.infer<typeof zIso18045>\nexport const zIso18045OrStringArray = z.array(z.union([zIso18045, z.string()]))\n\nexport const zKeyAttestationJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n iat: zNumericDate,\n\n attested_keys: z.array(zJwk),\n key_storage: z.optional(zIso18045OrStringArray),\n user_authentication: z.optional(zIso18045OrStringArray),\n certification: z.optional(z.url()),\n })\n .loose()\n\nexport const zKeyAttestationJwtPayloadForUse = <Use extends KeyAttestationJwtUse | undefined>(use?: Use) =>\n z\n .object({\n ...zKeyAttestationJwtPayload.shape,\n\n // REQUIRED when used as proof_type.attesation directly\n nonce:\n use === 'proof_type.attestation'\n ? z.string({\n message: `Nonce must be defined when key attestation is used as 'proof_type.attestation' directly`,\n })\n : z.optional(z.string()),\n\n // REQUIRED when used within header of proof_type.jwt\n exp: use === 'proof_type.jwt' ? zNumericDate : z.optional(zNumericDate),\n })\n .loose()\n\nexport type KeyAttestationJwtPayload = z.infer<typeof zKeyAttestationJwtPayload>\n","import {\n type CallbackContext,\n decodeJwt,\n type Jwk,\n type JwtSigner,\n jwtHeaderFromJwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling, type StringWithAutoCompletion } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport {\n type Iso18045,\n type KeyAttestationJwtHeader,\n type KeyAttestationJwtPayload,\n type KeyAttestationJwtUse,\n zKeyAttestationJwtHeader,\n zKeyAttestationJwtPayloadForUse,\n} from './z-key-attestation'\n\nexport interface CreateKeyAttestationJwtOptions {\n /**\n * Nonce to use in the key attestation.\n *\n * MUST be present if the attestation is used with the attestation proof\n */\n nonce?: string\n\n /**\n * The date when the key attestation was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The date when the key attestation will expire.\n *\n * MUST be present if the attestation is used with the JWT proof\n */\n expiresAt?: Date\n\n /**\n * The keys that the attestation jwt attests.\n */\n attestedKeys: Jwk[]\n\n /**\n * Optional attack potential resistance of attested keys and key storage\n */\n keyStorage?: StringWithAutoCompletion<Iso18045>[]\n\n /**\n * Optional attack potential resistance of user authentication methods\n */\n userAuthentication?: StringWithAutoCompletion<Iso18045>[]\n\n /**\n * Optional url linking to the certification of the key storage component.\n */\n certification?: string\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n\n /**\n * Signer of the key attestation jwt\n */\n signer: JwtSigner\n\n /**\n * Callbacks used for creating the key attestation jwt\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n\n /**\n * Additional payload to include in the key attestation jwt payload. Will be applied after\n * any default claims that are included, so add claims with caution.\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport async function createKeyAttestationJwt(options: CreateKeyAttestationJwtOptions): Promise<string> {\n const header = parseWithErrorHandling(zKeyAttestationJwtHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: 'keyattestation+jwt',\n } satisfies KeyAttestationJwtHeader)\n\n const payload = parseWithErrorHandling(zKeyAttestationJwtPayloadForUse(options.use), {\n iat: dateToSeconds(options.issuedAt),\n exp: options.expiresAt ? dateToSeconds(options.expiresAt) : undefined,\n nonce: options.nonce,\n attested_keys: options.attestedKeys,\n user_authentication: options.userAuthentication,\n key_storage: options.keyStorage,\n certification: options.certification,\n ...options.additionalPayload,\n } satisfies KeyAttestationJwtPayload)\n\n const { jwt } = await options.callbacks.signJwt(options.signer, { header, payload })\n return jwt\n}\n\nexport interface ParseKeyAttestationJwtOptions {\n /**\n * The compact key attestation jwt\n */\n keyAttestationJwt: string\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n}\n\nexport function parseKeyAttestationJwt({ keyAttestationJwt, use }: ParseKeyAttestationJwtOptions) {\n return decodeJwt({\n jwt: keyAttestationJwt,\n headerSchema: zKeyAttestationJwtHeader,\n payloadSchema: zKeyAttestationJwtPayloadForUse(use),\n })\n}\n\nexport interface VerifyKeyAttestationJwtOptions {\n /**\n * The compact key attestation jwt\n */\n keyAttestationJwt: string\n\n /**\n * Expected nonce. If the key attestation is used directly as proof this should be provided.\n */\n expectedNonce?: string\n\n /**\n * Date at which the nonce will expire\n */\n nonceExpiresAt?: Date\n\n /**\n * The intended use of the key attestation. Based on this additional validation\n * is performed.\n *\n * - `proof_type.jwt` -> `exp` MUST be set\n * - `proof_type.attestation` -> `nonce` MUST be set\n */\n use?: KeyAttestationJwtUse\n\n /**\n * Current time, if not provided a new date instance will be created\n */\n now?: Date\n\n /**\n * Callbacks required for the key attestation jwt verification\n */\n callbacks: Pick<CallbackContext, 'verifyJwt'>\n}\n\nexport type VerifyKeyAttestationJwtReturn = Awaited<ReturnType<typeof verifyKeyAttestationJwt>>\nexport async function verifyKeyAttestationJwt(options: VerifyKeyAttestationJwtOptions) {\n const { header, payload } = parseKeyAttestationJwt({ keyAttestationJwt: options.keyAttestationJwt, use: options.use })\n\n // TODO: if you use stateless nonce, it doesn't make sense to verify the nonce here\n // We should just return the nonce after verification so it can be checked (or actually, it should be checked upfront)\n const now = options.now?.getTime() ?? Date.now()\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new Openid4vciError('Nonce used for key attestation jwt expired')\n }\n\n const { signer } = await verifyJwt({\n compact: options.keyAttestationJwt,\n header,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'Error verifiying key attestation jwt',\n expectedNonce: options.expectedNonce,\n now: options.now,\n })\n\n return {\n header,\n payload,\n signer,\n }\n}\n","import z from 'zod'\n\n// Used up to draft 14\nexport const zCredentialConfigurationSupportedClaimsDescriptionDraft14 = z\n .object({\n mandatory: z.boolean().optional(),\n value_type: z.string().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\n\nexport type CredentialConfigurationSupportedClaimsDraft14 = {\n [key: string]:\n | z.infer<typeof zCredentialConfigurationSupportedClaimsDescriptionDraft14>\n | CredentialConfigurationSupportedClaimsDraft14\n}\n\nexport const zCredentialConfigurationSupportedClaimsDraft14: z.ZodType<CredentialConfigurationSupportedClaimsDraft14> =\n z.record(\n z.string(),\n z.union([\n zCredentialConfigurationSupportedClaimsDescriptionDraft14,\n z.lazy(() => zCredentialConfigurationSupportedClaimsDraft14),\n ])\n )\n\nconst zClaimDescriptionPathValue = z.union([z.string(), z.number().int().nonnegative(), z.null()])\nconst zClaimsDescriptionPath = z.tuple([zClaimDescriptionPathValue], zClaimDescriptionPathValue)\nexport type ClaimsDescriptionPath = z.infer<typeof zClaimsDescriptionPath>\n\nconst zMsoMdocClaimsDescriptionPath = z.tuple([z.string(), z.string()], zClaimDescriptionPathValue, {\n message:\n 'mso_mdoc claims description path MUST be an array with at least two string elements, pointing to the namespace and element identifier within an mdoc credential',\n})\nexport type MsoMdocClaimsDescriptionPath = z.infer<typeof zMsoMdocClaimsDescriptionPath>\n\nexport const zIssuerMetadataClaimsDescription = z\n .object({\n path: zClaimsDescriptionPath,\n mandatory: z.boolean().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\nexport type IssuerMetadataClaimsDescription = z.infer<typeof zIssuerMetadataClaimsDescription>\n\nexport const zMsoMdocIssuerMetadataClaimsDescription = zIssuerMetadataClaimsDescription.extend({\n path: zMsoMdocClaimsDescriptionPath,\n})\nexport type MsoMdocIssuerMetadataClaimsDescription = z.infer<typeof zMsoMdocIssuerMetadataClaimsDescription>\n","import { zDataUrl, zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zIso18045OrStringArray } from '../../key-attestation/z-key-attestation'\n\nconst zCredentialConfigurationSupportedDisplayEntry = z\n .object({\n name: z.string(),\n locale: z.string().optional(),\n logo: z\n .object({\n // FIXME: make required again, but need to support draft 11 first\n uri: zHttpsUrl.or(zDataUrl).optional(),\n alt_text: z.string().optional(),\n })\n .loose()\n .optional(),\n description: z.string().optional(),\n background_color: z.string().optional(),\n background_image: z\n .object({\n // TODO: should be required, but paradym's metadata is wrong here.\n uri: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n text_color: z.string().optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommonCredentialMetadata = z\n .object({\n display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommon = z\n .object({\n format: z.string(),\n scope: z.string().optional(),\n cryptographic_binding_methods_supported: z.array(z.string()).optional(),\n credential_signing_alg_values_supported: z.array(z.string()).or(z.array(z.number())).optional(),\n proof_types_supported: z\n .record(\n z.union([z.literal('jwt'), z.literal('attestation'), z.string()]),\n z.object({\n proof_signing_alg_values_supported: z.array(z.string()),\n key_attestations_required: z\n .object({\n key_storage: zIso18045OrStringArray.optional(),\n user_authentication: zIso18045OrStringArray.optional(),\n })\n .loose()\n .optional(),\n })\n )\n .optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata.optional(),\n })\n .loose()\n\nexport const zCredentialConfigurationSupportedCommonDraft15 = z\n .object({\n format: z.string(),\n scope: z.string().optional(),\n cryptographic_binding_methods_supported: z.array(z.string()).optional(),\n // Up until draft 15 it was an array of strings\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n proof_types_supported: z\n .record(\n z.union([z.literal('jwt'), z.literal('attestation'), z.string()]),\n z.object({\n proof_signing_alg_values_supported: z.array(z.string()),\n key_attestations_required: z\n .object({\n key_storage: zIso18045OrStringArray.optional(),\n user_authentication: zIso18045OrStringArray.optional(),\n })\n .loose()\n .optional(),\n })\n )\n .optional(),\n display: z.array(zCredentialConfigurationSupportedDisplayEntry).optional(),\n\n // For typing purposes.\n credential_metadata: z.optional(z.never()),\n })\n .loose()\n","import z from 'zod'\nimport {\n zCredentialConfigurationSupportedClaimsDraft14,\n zMsoMdocIssuerMetadataClaimsDescription,\n} from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zMsoMdocFormatIdentifier = z.literal('mso_mdoc')\nexport type MsoMdocFormatIdentifier = z.infer<typeof zMsoMdocFormatIdentifier>\n\nexport const zMsoMdocCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n credential_signing_alg_values_supported: z.array(z.number()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zMsoMdocCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n claims: z.array(zMsoMdocIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zMsoMdocCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),\n order: z.optional(z.array(z.string())),\n})\n\nexport const zMsoMdocCredentialRequestFormatDraft14 = z.object({\n format: zMsoMdocFormatIdentifier,\n doctype: z.string(),\n // Format based request is removed in Draft 15, so only old claims syntax supported.\n claims: zCredentialConfigurationSupportedClaimsDraft14.optional(),\n})\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zSdJwtDcFormatIdentifier = z.literal('dc+sd-jwt')\nexport type SdJwtDcFormatIdentifier = z.infer<typeof zSdJwtDcFormatIdentifier>\n\nexport const zSdJwtDcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n vct: z.string(),\n format: zSdJwtDcFormatIdentifier,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zSdJwtDcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n vct: z.string(),\n format: zSdJwtDcFormatIdentifier,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n","import z from 'zod'\nimport {\n zCredentialConfigurationSupportedClaimsDraft14,\n zIssuerMetadataClaimsDescription,\n} from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcFormatIdentifier = z.literal('vc+sd-jwt')\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport type LegacySdJwtVcFormatIdentifier = z.infer<typeof zLegacySdJwtVcFormatIdentifier>\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialIssuerMetadataV1 = zCredentialConfigurationSupportedCommon.extend({\n vct: z.string(),\n format: zLegacySdJwtVcFormatIdentifier,\n order: z.optional(z.array(z.string())),\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n credential_definition: z.optional(z.never()),\n})\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n vct: z.string(),\n format: zLegacySdJwtVcFormatIdentifier,\n claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),\n order: z.optional(z.array(z.string())),\n credential_definition: z.optional(z.never()),\n})\n\n/**\n * @deprecated format has been deprecated in favor of \"dc+sd-jwt\" since Draft 23\n * of the OpenID for Verifiable Presentations specification. Please update your\n * implementations accordingly.\n */\nexport const zLegacySdJwtVcCredentialRequestFormatDraft14 = z.object({\n format: zLegacySdJwtVcFormatIdentifier,\n vct: z.string(),\n claims: z.optional(zCredentialConfigurationSupportedClaimsDraft14),\n credential_definition: z.optional(z.never()),\n})\n","import z from 'zod'\n\nconst zCredentialSubjectLeafTypeDraft14 = z\n .object({\n mandatory: z.boolean().optional(),\n value_type: z.string().optional(),\n display: z\n .array(\n z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n })\n .loose()\n )\n .optional(),\n })\n .loose()\n\nconst zClaimValueSchemaDraft14 = z.union([\n z.array(z.any()),\n z.record(z.string(), z.any()),\n zCredentialSubjectLeafTypeDraft14,\n])\n\nexport const zW3cVcCredentialSubjectDraft14 = z.record(z.string(), zClaimValueSchemaDraft14)\n\nexport const zW3cVcJsonLdCredentialDefinition = z\n .object({\n '@context': z.array(z.string()),\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nexport const zW3cVcJsonLdCredentialDefinitionDraft14 = zW3cVcJsonLdCredentialDefinition.extend({\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n})\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport { zW3cVcCredentialSubjectDraft14 } from './z-w3c-vc-common'\n\nexport const zJwtVcJsonFormatIdentifier = z.literal('jwt_vc_json')\nexport type JwtVcJsonFormatIdentifier = z.infer<typeof zJwtVcJsonFormatIdentifier>\n\nconst zJwtVcJsonCredentialDefinition = z\n .object({\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nconst zJwtVcJsonCredentialDefinitionDraft14 = zJwtVcJsonCredentialDefinition.extend({\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinitionDraft14,\n order: z.array(z.string()).optional(),\n})\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft11 = z\n .object({\n format: zJwtVcJsonFormatIdentifier,\n order: z.array(z.string()).optional(),\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft11To14 = zJwtVcJsonCredentialIssuerMetadataDraft11.transform(\n ({ types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zJwtVcJsonCredentialIssuerMetadataDraft14To11 = zJwtVcJsonCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n types: type,\n ...credentialDefinition,\n }))\n .pipe(zJwtVcJsonCredentialIssuerMetadataDraft11)\n\nexport const zJwtVcJsonCredentialRequestFormatDraft14 = z.object({\n format: zJwtVcJsonFormatIdentifier,\n credential_definition: zJwtVcJsonCredentialDefinition,\n})\n\nexport const zJwtVcJsonCredentialRequestDraft11 = z\n .object({\n format: zJwtVcJsonFormatIdentifier,\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n types: z.tuple([z.string()], z.string()),\n credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14),\n })\n .loose()\n\nexport const zJwtVcJsonCredentialRequestDraft11To14 = zJwtVcJsonCredentialRequestDraft11.transform(\n ({ types, credentialSubject, ...rest }) => {\n return {\n ...rest,\n credential_definition: {\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n }\n }\n)\n\nexport const zJwtVcJsonCredentialRequestDraft14To11 = zJwtVcJsonCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n types: type,\n ...credentialDefinition,\n }))\n .pipe(zJwtVcJsonCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport {\n zW3cVcCredentialSubjectDraft14,\n zW3cVcJsonLdCredentialDefinition,\n zW3cVcJsonLdCredentialDefinitionDraft14,\n} from './z-w3c-vc-common'\n\nexport const zJwtVcJsonLdFormatIdentifier = z.literal('jwt_vc_json-ld')\nexport type JwtVcJsonLdFormatIdentifier = z.infer<typeof zJwtVcJsonLdFormatIdentifier>\n\nexport const zJwtVcJsonLdCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n order: z.optional(z.array(z.string())),\n})\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft11 = z\n .object({\n order: z.array(z.string()).optional(),\n format: zJwtVcJsonLdFormatIdentifier,\n // Credential definition was spread on top level instead of a separate property in v11\n // As well as using types instead of type\n '@context': z.array(z.string()),\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft11To14 = zJwtVcJsonLdCredentialIssuerMetadataDraft11.transform(\n ({ '@context': context, types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n '@context': context,\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zJwtVcJsonLdCredentialIssuerMetadataDraft14To11 = zJwtVcJsonLdCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n ...credentialDefinition,\n types: type,\n }))\n .pipe(zJwtVcJsonLdCredentialIssuerMetadataDraft11)\n\nexport const zJwtVcJsonLdCredentialRequestFormatDraft14 = z.object({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n})\n\nexport const zJwtVcJsonLdCredentialRequestDraft11 = z\n .object({\n format: zJwtVcJsonLdFormatIdentifier,\n credential_definition: z\n .object({\n '@context': z.array(z.string()),\n // credential_definition was using types instead of type in v11\n types: z.tuple([z.string()], z.string()),\n credentialSubject: z.optional(zW3cVcCredentialSubjectDraft14),\n })\n .loose(),\n })\n .loose()\n\nexport const zJwtVcJsonLdCredentialRequestDraft11To14 = zJwtVcJsonLdCredentialRequestDraft11.transform(\n ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n type: types,\n },\n })\n)\n\nexport const zJwtVcJsonLdCredentialRequestDraft14To11 = zJwtVcJsonLdCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n types: type,\n },\n }))\n .pipe(zJwtVcJsonLdCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\nimport {\n zW3cVcCredentialSubjectDraft14,\n zW3cVcJsonLdCredentialDefinition,\n zW3cVcJsonLdCredentialDefinitionDraft14,\n} from './z-w3c-vc-common'\n\nexport const zLdpVcFormatIdentifier = z.literal('ldp_vc')\nexport type LdpVcFormatIdentifier = z.infer<typeof zLdpVcFormatIdentifier>\n\nexport const zLdpVcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft14 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n order: z.array(z.string()).optional(),\n})\n\nexport const zLdpVcCredentialIssuerMetadataDraft11 = z\n .object({\n order: z.array(z.string()).optional(),\n format: zLdpVcFormatIdentifier,\n // Credential definition was spread on top level instead of a separatey property in v11\n // As well as using types instead of type\n '@context': z.array(z.string()),\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n })\n .loose()\n\nexport const zLdpVcCredentialIssuerMetadataDraft11To14 = zLdpVcCredentialIssuerMetadataDraft11.transform(\n ({ '@context': context, types, credentialSubject, ...rest }) => ({\n ...rest,\n credential_definition: {\n '@context': context,\n type: types,\n // Prevent weird typing issue with optional vs undefined\n ...(credentialSubject ? { credentialSubject } : {}),\n },\n })\n)\n\nexport const zLdpVcCredentialIssuerMetadataDraft14To11 = zLdpVcCredentialIssuerMetadataDraft14\n .loose()\n .transform(({ credential_definition: { type, ...credentialDefinition }, ...rest }) => ({\n ...rest,\n ...credentialDefinition,\n types: type,\n }))\n .pipe(zLdpVcCredentialIssuerMetadataDraft11)\n\nexport const zLdpVcCredentialRequestFormatDraft14 = z.object({\n format: zLdpVcFormatIdentifier,\n credential_definition: zW3cVcJsonLdCredentialDefinitionDraft14,\n})\n\nconst zLdpVcCredentialRequestDraft11 = z\n .object({\n format: zLdpVcFormatIdentifier,\n credential_definition: z.object({\n '@context': z.array(z.string()),\n // credential_definition was using types instead of type in v11\n types: z.tuple([z.string()], z.string()),\n credentialSubject: zW3cVcCredentialSubjectDraft14.optional(),\n }),\n })\n .loose()\n\nexport const zLdpVcCredentialRequestDraft11To14 = zLdpVcCredentialRequestDraft11.transform(\n ({ credential_definition: { types, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n type: types,\n },\n })\n)\n\nexport const zLdpVcCredentialRequestDraft14To11 = zLdpVcCredentialRequestFormatDraft14\n .loose()\n .transform(({ credential_definition: { type, ...restCredentialDefinition }, ...rest }) => ({\n ...rest,\n credential_definition: {\n ...restCredentialDefinition,\n types: type,\n },\n }))\n .pipe(zLdpVcCredentialRequestDraft11)\n","import z from 'zod'\nimport { zIssuerMetadataClaimsDescription } from '../../../metadata/credential-issuer/z-claims-description'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonCredentialMetadata,\n zCredentialConfigurationSupportedCommonDraft15,\n} from '../../../metadata/credential-issuer/z-credential-configuration-supported-common'\n\nexport const zSdJwtW3VcFormatIdentifier = z.literal('vc+sd-jwt')\nexport type SdJwtW3VcFormatIdentifier = z.infer<typeof zSdJwtW3VcFormatIdentifier>\n\nconst zSdJwtW3VcCredentialDefinition = z\n .object({\n type: z.tuple([z.string()], z.string()),\n })\n .loose()\n\nexport const zSdJwtW3VcCredentialIssuerMetadata = zCredentialConfigurationSupportedCommon.extend({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n credential_signing_alg_values_supported: z.array(z.string()).optional(),\n credential_metadata: zCredentialConfigurationSupportedCommonCredentialMetadata\n .extend({\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n })\n .optional(),\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n\nexport const zSdJwtW3VcCredentialIssuerMetadataDraft15 = zCredentialConfigurationSupportedCommonDraft15.extend({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n claims: z.array(zIssuerMetadataClaimsDescription).optional(),\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n\nexport const zSdJwtW3VcCredentialRequestFormatDraft14 = z.object({\n format: zSdJwtW3VcFormatIdentifier,\n credential_definition: zSdJwtW3VcCredentialDefinition,\n\n // FIXME(vc+sd-jwt): remove when dropping support for legacy vc+sd-jwt. Allows type narrowing.\n vct: z.optional(z.never()),\n})\n","import {\n fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray,\n jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray,\n} from '@openid4vc/oauth2'\nimport { type InferOutputUnion, type Simplify, zDataUrl, zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n type CredentialFormatIdentifier,\n zJwtVcJsonCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadataDraft11To14,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n zJwtVcJsonCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonCredentialIssuerMetadataDraft15,\n zJwtVcJsonFormatIdentifier,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadataDraft11To14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonLdCredentialIssuerMetadataDraft15,\n zJwtVcJsonLdFormatIdentifier,\n zLdpVcCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadataDraft11To14,\n zLdpVcCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadataDraft14To11,\n zLdpVcCredentialIssuerMetadataDraft15,\n zLdpVcFormatIdentifier,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zMsoMdocCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zMsoMdocCredentialIssuerMetadataDraft15,\n zMsoMdocFormatIdentifier,\n zSdJwtDcCredentialIssuerMetadata,\n zSdJwtDcCredentialIssuerMetadataDraft15,\n zSdJwtDcFormatIdentifier,\n} from '../../formats/credential'\nimport { zLegacySdJwtVcCredentialIssuerMetadataV1 } from '../../formats/credential/sd-jwt-vc/z-sd-jwt-vc'\nimport {\n zSdJwtW3VcCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadataDraft15,\n} from '../../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { Openid4vciVersion } from '../../version'\nimport { claimsObjectToClaimsArray } from './credential-configurations'\nimport {\n zCredentialConfigurationSupportedCommon,\n zCredentialConfigurationSupportedCommonDraft15,\n} from './z-credential-configuration-supported-common'\n\nconst allCredentialIssuerMetadataFormats = [\n zSdJwtDcCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadata,\n zSdJwtW3VcCredentialIssuerMetadataDraft15,\n zLegacySdJwtVcCredentialIssuerMetadataV1,\n zSdJwtDcCredentialIssuerMetadataDraft15,\n zMsoMdocCredentialIssuerMetadataDraft15,\n zJwtVcJsonLdCredentialIssuerMetadataDraft15,\n zLdpVcCredentialIssuerMetadataDraft15,\n zJwtVcJsonCredentialIssuerMetadataDraft15,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadataDraft14,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n] as const\ntype CredentialIssuerMetadataFormatValidator = (typeof allCredentialIssuerMetadataFormats)[number]\nexport const allCredentialIssuerMetadataFormatIdentifiers = allCredentialIssuerMetadataFormats.map(\n (format) => format.shape.format.value\n)\n\nexport const zCredentialConfigurationSupportedWithFormats = z\n .union([zCredentialConfigurationSupportedCommon, zCredentialConfigurationSupportedCommonDraft15])\n .transform((data, ctx) => {\n // No additional validation for unknown formats\n if (!allCredentialIssuerMetadataFormatIdentifiers.includes(data.format as CredentialFormatIdentifier)) return data\n\n const validators = allCredentialIssuerMetadataFormats.filter(\n (formatValidator) => formatValidator.shape.format.value === data.format\n ) as CredentialIssuerMetadataFormatValidator[]\n\n const result = z\n // We use object and passthrough as otherwise the non-format specific properties will be stripped\n .object({})\n .loose()\n .and(\n validators.length > 1\n ? z.union(\n validators as [\n CredentialIssuerMetadataFormatValidator,\n CredentialIssuerMetadataFormatValidator,\n ...CredentialIssuerMetadataFormatValidator[],\n ]\n )\n : validators[0]\n )\n .safeParse(data)\n\n if (result.success) {\n return result.data as Simplify<typeof result.data & typeof data>\n }\n\n for (const issue of result.error.issues) {\n // FIXME: this worked with zod 3\n ctx.addIssue({\n ...issue,\n code: issue.code as 'custom',\n })\n }\n\n return z.NEVER\n })\n\ntype CredentialConfigurationSupportedCommon = z.infer<typeof zCredentialConfigurationSupportedCommon>\nexport type CredentialConfigurationSupportedFormatSpecific = InferOutputUnion<typeof allCredentialIssuerMetadataFormats>\nexport type CredentialConfigurationSupportedWithFormats = CredentialConfigurationSupportedFormatSpecific &\n CredentialConfigurationSupportedCommon\nexport type CredentialConfigurationsSupportedWithFormats = Record<string, CredentialConfigurationSupportedWithFormats>\n\nexport type CredentialConfigurationSupported = z.infer<typeof zCredentialConfigurationSupportedWithFormats>\nexport type CredentialConfigurationsSupported = Record<string, CredentialConfigurationSupported>\n\nconst zCredentialIssuerMetadataDisplayEntry = z\n .object({\n name: z.string().optional(),\n locale: z.string().optional(),\n logo: z\n .object({\n // FIXME: make required again, but need to support draft 11 first\n uri: zHttpsUrl.or(zDataUrl).optional(),\n alt_text: z.string().optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\nexport type CredentialIssuerMetadataDisplayEntry = z.infer<typeof zCredentialIssuerMetadataDisplayEntry>\n\nexport type CredentialIssuerMetadata = z.infer<typeof zCredentialIssuerMetadataDraft14Draft15V1>\nexport const zCredentialIssuerMetadataDraft14Draft15V1 = z\n .object({\n credential_issuer: zHttpsUrl,\n authorization_servers: z.array(zHttpsUrl).optional(),\n credential_endpoint: zHttpsUrl,\n deferred_credential_endpoint: zHttpsUrl.optional(),\n notification_endpoint: zHttpsUrl.optional(),\n\n // Added after draft 14, but needed for proper\n nonce_endpoint: zHttpsUrl.optional(),\n credential_response_encryption: z\n .object({\n alg_values_supported: z.array(z.string()),\n enc_values_supported: z.array(z.string()),\n encryption_required: z.boolean(),\n })\n .loose()\n .optional(),\n batch_credential_issuance: z\n .object({\n batch_size: z.number().positive(),\n })\n .loose()\n .optional(),\n display: z.array(zCredentialIssuerMetadataDisplayEntry).optional(),\n credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedCommon),\n })\n .loose()\n\n// Transforms credential supported to credential configuration supported format\n// Ignores unknown formats\nexport const zCredentialConfigurationSupportedDraft11ToV1 = z\n .object({\n id: z.string().optional(),\n format: z.string(),\n cryptographic_suites_supported: z.array(z.string()).optional(),\n display: z\n .array(\n z\n .object({\n logo: z\n .object({\n url: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n background_image: z\n .object({\n url: zHttpsUrl.or(zDataUrl).optional(),\n })\n .loose()\n .optional(),\n })\n .loose()\n )\n .optional(),\n claims: z\n .any()\n .transform((claims) => claimsObjectToClaimsArray(claims))\n .optional(),\n })\n .loose()\n .transform(({ cryptographic_suites_supported, display, claims, id, format, ...rest }) => ({\n ...rest,\n format: format === 'vc+sd-jwt' && rest.vct ? 'dc+sd-jwt' : format,\n ...(cryptographic_suites_supported\n ? {\n credential_signing_alg_values_supported:\n // For mso_mdoc, transform JWA signature algorithm strings to fully-specified COSE algorithm numbers\n format === zMsoMdocFormatIdentifier.value\n ? jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray(cryptographic_suites_supported)\n : cryptographic_suites_supported,\n }\n : {}),\n ...(claims || display\n ? {\n credential_metadata: {\n ...(claims ? { claims } : {}),\n ...(display\n ? {\n display: display.map(({ logo, background_image, ...displayRest }) => ({\n ...displayRest,\n // url became uri and also required\n // so if there's no url in the logo, we remove the whole logo object\n ...(logo?.url\n ? {\n // TODO: we should add the other params from logo as well\n logo: {\n uri: logo.url,\n },\n }\n : {}),\n\n // TODO: we should add the other params from background_image as well\n // url became uri and also required\n // so if there's no url in the background_image, we remove the whole logo object\n ...(background_image?.url\n ? {\n background_image: {\n uri: background_image.url,\n },\n }\n : {}),\n })),\n }\n : {}),\n },\n }\n : {}),\n }))\n .transform((data, ctx): unknown => {\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialIssuerMetadataDraft11To14,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialIssuerMetadataDraft11To14,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialIssuerMetadataDraft11To14,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n // FIXME: this worked with zod 3\n ctx.addIssue({\n ...issue,\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n .pipe(zCredentialConfigurationSupportedWithFormats)\n\n// Transforms credential configuration supported from draft 16 to draft 15\nconst zCredentialConfigurationSupportedV1ToDraft15 = zCredentialConfigurationSupportedWithFormats.transform(\n ({ credential_metadata, ...rest }) => ({\n ...credential_metadata,\n ...rest,\n })\n)\n\n// Transforms credential configuration supported to credentials_supported format\n// Ignores unknown formats\nconst zCredentialConfigurationSupportedV1ToDraft11 = zCredentialConfigurationSupportedV1ToDraft15\n .transform((configuration, ctx) => {\n if (!configuration.id || typeof configuration.id !== 'string') {\n ctx.addIssue({\n code: 'invalid_type',\n expected: 'string',\n input: configuration.id,\n path: ['id'],\n message: 'Missing required id field',\n })\n return z.NEVER\n }\n\n return {\n ...configuration,\n id: configuration.id,\n // We remove claims when downgrading to draft 11\n claims: undefined,\n }\n })\n .transform(\n ({\n id,\n credential_signing_alg_values_supported,\n display,\n proof_types_supported,\n scope,\n format,\n claims,\n ...rest\n }): unknown => ({\n ...rest,\n // vc+sd-jwt was changed to dc+sd-jwt in draft 15\n format: format === 'dc+sd-jwt' ? 'vc+sd-jwt' : format,\n ...(credential_signing_alg_values_supported\n ? {\n cryptographic_suites_supported:\n // For mso_mdoc, transform fully-specified COSE algorithm numbers to JWA signature algorithm strings\n format === zMsoMdocFormatIdentifier.value &&\n typeof credential_signing_alg_values_supported[0] === 'number'\n ? fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray(\n credential_signing_alg_values_supported as number[]\n )\n : credential_signing_alg_values_supported,\n }\n : {}),\n ...(display\n ? {\n display: display.map(({ logo, background_image, ...displayRest }) => {\n const { uri: logoUri, ...logoRest } = logo ?? {}\n const { uri: backgroundImageUri, ...backgroundImageRest } = background_image ?? {}\n return {\n ...displayRest,\n // draft 11 uses url, draft 13/14 uses uri\n ...(logoUri ? { logo: { url: logoUri, ...logoRest } } : {}),\n // draft 11 uses url, draft 13/14 uses uri\n ...(backgroundImageUri ? { logo: { url: backgroundImageUri, ...backgroundImageRest } } : {}),\n }\n }),\n }\n : {}),\n id,\n })\n )\n .pipe(\n z.union([\n zLdpVcCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonCredentialIssuerMetadataDraft14To11,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14To11,\n // To handle unrecognized formats and not error immediately we allow the common format as well\n // but they can't use any of the format identifiers that have a specific transformation. This way if a format is\n // has a transformation it NEEDS to use the format specific transformation, and otherwise we fall back to the common validation\n z\n .object({\n format: z\n .string()\n .refine(\n (input) =>\n !(\n [\n zLdpVcFormatIdentifier.value,\n zJwtVcJsonFormatIdentifier.value,\n zJwtVcJsonLdFormatIdentifier.value,\n ] as string[]\n ).includes(input)\n ),\n })\n .loose(),\n ])\n )\n\nexport const zCredentialIssuerMetadataDraft11ToV1 = z\n .object({\n authorization_server: z.string().optional(),\n credentials_supported: z.array(\n z\n .object({\n id: z.string().optional(),\n })\n .loose()\n ),\n })\n .loose()\n .transform(({ authorization_server, credentials_supported, ...rest }) => {\n return {\n ...rest,\n ...(authorization_server ? { authorization_servers: [authorization_server] } : {}),\n // Go from array to map but keep v11 structure\n credential_configurations_supported: Object.fromEntries(\n credentials_supported\n .map((supported) => (supported.id ? ([supported.id, supported] as const) : undefined))\n .filter((i): i is Exclude<typeof i, undefined> => i !== undefined)\n ),\n }\n })\n .pipe(\n z\n .object({\n // Update from v11 structure to v14 structure\n credential_configurations_supported: z.record(z.string(), zCredentialConfigurationSupportedDraft11ToV1),\n })\n .loose()\n )\n .pipe(zCredentialIssuerMetadataDraft14Draft15V1)\n\n/**\n * Typing is a bit off on this one\n */\nexport type CredentialIssuerMetadataDraft11 = Simplify<\n CredentialIssuerMetadata & {\n authorization_server?: string\n credentials_supported: z.infer<typeof zCredentialConfigurationSupportedV1ToDraft11>[]\n }\n>\n\nexport const zCredentialIssuerMetadataWithDraft11 = zCredentialIssuerMetadataDraft14Draft15V1\n .transform((issuerMetadata) => ({\n ...issuerMetadata,\n ...(issuerMetadata.authorization_servers ? { authorization_server: issuerMetadata.authorization_servers[0] } : {}),\n credentials_supported: Object.entries(issuerMetadata.credential_configurations_supported).map(\n ([id, value]) =>\n ({\n ...value,\n id,\n }) as (typeof issuerMetadata)['credential_configurations_supported'][typeof id]\n ),\n }))\n .pipe(\n zCredentialIssuerMetadataDraft14Draft15V1.extend({\n credentials_supported: z.array(zCredentialConfigurationSupportedV1ToDraft11),\n })\n )\n\nexport const zCredentialIssuerMetadata = z.union([\n // First prioritize draft 16/15/14 (and 13)\n zCredentialIssuerMetadataDraft14Draft15V1,\n // Then try parsing draft 11 and transform into draft 16\n zCredentialIssuerMetadataDraft11ToV1,\n])\n\nexport const zCredentialIssuerMetadataWithDraftVersion = z.union([\n zCredentialIssuerMetadataDraft14Draft15V1.transform((credentialIssuerMetadata) => {\n const credentialConfigurations = Object.values(credentialIssuerMetadata.credential_configurations_supported)\n\n const isDraft15 = credentialConfigurations.some((configuration) => {\n const knownConfiguration = configuration as CredentialConfigurationSupportedWithFormats\n\n // Added in draft 15, it's not possible to detect with 100% guarantee\n if (knownConfiguration.format === zSdJwtDcFormatIdentifier.value) return true\n if (Array.isArray(knownConfiguration.claims)) return true\n if (\n Object.values(knownConfiguration.proof_types_supported ?? {}).some(\n (proofType) => proofType.key_attestations_required !== undefined\n )\n )\n return true\n\n // For now we assume draft 14 if we don't have any evidence it's draft 15\n return false\n })\n\n // we assume V1 is used when we detect V1\n const isV1 = credentialConfigurations.some(\n (configuration) =>\n // Added in draft 16, but since there's no other breaking changes\n configuration.credential_metadata ||\n // Was changed to COSE algorithms in Draft 16 (which we detect as v1)\n (configuration.format === 'mso_mdoc' &&\n configuration.credential_signing_alg_values_supported?.some((supported) => typeof supported === 'number'))\n )\n\n return {\n credentialIssuerMetadata,\n originalDraftVersion: isV1\n ? Openid4vciVersion.V1\n : isDraft15\n ? Openid4vciVersion.Draft15\n : Openid4vciVersion.Draft14,\n }\n }),\n // Then try parsing draft 11 and transform into draft 16\n zCredentialIssuerMetadataDraft11ToV1.transform((credentialIssuerMetadata) => ({\n credentialIssuerMetadata,\n originalDraftVersion: Openid4vciVersion.Draft11,\n })),\n])\n","import { Oauth2Error } from '@openid4vc/oauth2'\nimport { ValidationError } from '@openid4vc/utils'\nimport type z from 'zod'\nimport { Openid4vciError } from '../../error/Openid4vciError'\nimport type { IssuerMetadataResult } from '../fetch-issuer-metadata'\nimport {\n type IssuerMetadataClaimsDescription,\n zCredentialConfigurationSupportedClaimsDraft14,\n} from './z-claims-description'\nimport {\n type CredentialConfigurationsSupported,\n zCredentialConfigurationSupportedDraft11ToV1,\n} from './z-credential-issuer-metadata'\n\nexport interface ExtractScopesForCredentialConfigurationIdsOptions {\n /**\n * The credential configuration ids to extract the scope from\n */\n credentialConfigurationIds: string[]\n\n /**\n * Whether to throw an error if the corresponding credential configuration\n * for a provided credential configuration id has no scope.\n *\n * @default false\n */\n throwOnConfigurationWithoutScope?: boolean\n\n /**\n * The issuer metadata\n */\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function extractScopesForCredentialConfigurationIds(\n options: ExtractScopesForCredentialConfigurationIdsOptions\n): string[] | undefined {\n const scopes = new Set<string>()\n\n for (const credentialConfigurationId of options.credentialConfigurationIds) {\n const credentialConfiguration =\n options.issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId]\n\n if (!credentialConfiguration) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' not found in metadata from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n }\n\n const scope = credentialConfiguration.scope\n if (scope) scopes.add(scope)\n else if (!scope && options.throwOnConfigurationWithoutScope) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' does not have a 'scope' configured, and 'throwOnConfigurationWithoutScope' was enabled.`\n )\n }\n }\n\n return scopes.size > 0 ? Array.from(scopes) : undefined\n}\n\n/**\n * Transforms draft 11 credentials supported syntax to credential configurations supported\n *\n * @throws if a credentials supported entry without id is passed\n * @throws if a credentials supported entry with invalid structure or format specific properties is passed\n */\nexport function credentialsSupportedToCredentialConfigurationsSupported(\n credentialsSupported: Array<z.input<typeof zCredentialConfigurationSupportedDraft11ToV1>>\n) {\n const credentialConfigurationsSupported: CredentialConfigurationsSupported = {}\n\n for (let index = 0; index < credentialsSupported.length; index++) {\n const credentialSupported = credentialsSupported[index]\n if (!credentialSupported.id) {\n throw new Openid4vciError(\n `Credential supported at index '${index}' does not have an 'id' property. Credential configuration requires the 'id' property as key`\n )\n }\n\n const parseResult = zCredentialConfigurationSupportedDraft11ToV1.safeParse(credentialSupported)\n if (!parseResult.success) {\n throw new ValidationError(\n `Error transforming credential supported with id '${credentialSupported.id}' to credential configuration supported format`,\n parseResult.error\n )\n }\n\n credentialConfigurationsSupported[credentialSupported.id] = parseResult.data\n }\n\n return credentialConfigurationsSupported\n}\n\n/**\n * Transforms draft 14 claims object syntax to the new array-based claims description syntax\n *\n * @param claims - The claims object in draft 14 format\n * @returns Array of claims descriptions or undefined if validation fails\n */\nexport function claimsObjectToClaimsArray(claims: unknown): Array<IssuerMetadataClaimsDescription> | undefined {\n // Validate input\n const parseResult = zCredentialConfigurationSupportedClaimsDraft14.safeParse(claims)\n if (!parseResult.success) {\n return undefined\n }\n\n const result: Array<IssuerMetadataClaimsDescription> = []\n\n /**\n * Recursively process claims object, building up the path from parent keys\n */\n function processClaimsObject(\n claimsObj: Record<string, unknown>,\n parentPath: Array<string | number | null> = []\n ): void {\n for (const [key, value] of Object.entries(claimsObj)) {\n const currentPath = [...parentPath, key]\n\n // Check if this is a leaf node (has claim properties like mandatory, value_type, display)\n if (\n value &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n ('mandatory' in value || 'value_type' in value || 'display' in value)\n ) {\n const claimValue = value as Record<string, unknown>\n\n // Create the claim description\n const claimDescription: IssuerMetadataClaimsDescription = {\n path: currentPath as [string | number | null, ...(string | number | null)[]],\n }\n\n // Add optional properties\n if (typeof claimValue.mandatory === 'boolean') {\n claimDescription.mandatory = claimValue.mandatory\n }\n\n if (Array.isArray(claimValue.display)) {\n claimDescription.display = claimValue.display as Array<{\n name?: string\n locale?: string\n }>\n }\n\n // Note: value_type is not included in the new syntax\n\n result.push(claimDescription)\n\n // Check if there are nested claims (excluding the known properties)\n const nestedClaims = Object.entries(claimValue).filter(\n ([k]) => k !== 'mandatory' && k !== 'value_type' && k !== 'display'\n )\n\n if (nestedClaims.length > 0) {\n const nestedObj = Object.fromEntries(nestedClaims)\n processClaimsObject(nestedObj, currentPath)\n }\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n // This is a nested object without claim properties, recurse\n processClaimsObject(value as Record<string, unknown>, currentPath)\n }\n }\n }\n\n processClaimsObject(parseResult.data)\n\n return result\n}\n","import { zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zCredentialIssuerMetadataDraft14Draft15V1 } from './z-credential-issuer-metadata'\n\nexport const zSignedCredentialIssuerMetadataHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z.literal('openidvci-issuer-metadata+jwt'),\n })\n .loose()\n\nexport type SignedCredentialIssuerMetadataHeader = z.infer<typeof zSignedCredentialIssuerMetadataHeader>\n\nexport const zSignedCredentialIssuerMetadataPayload = z\n .object({\n ...zJwtPayload.shape,\n iat: zNumericDate,\n sub: z.string(),\n\n // NOTE: we don't support older drafts below 14 for signed metadata\n ...zCredentialIssuerMetadataDraft14Draft15V1.shape,\n })\n .loose()\n\nexport type SignedCredentialIssuerMetadataPayload = z.infer<typeof zSignedCredentialIssuerMetadataPayload>\n","import {\n type CallbackContext,\n type DecodeJwtResult,\n decodeJwt,\n fetchWellKnownMetadata,\n type JwtSignerWithJwk,\n jwtSignerFromJwt,\n Oauth2Error,\n verifyJwt,\n zCompactJwt,\n} from '@openid4vc/oauth2'\nimport { ContentType, joinUriParts, OpenId4VcBaseError, parseWithErrorHandling, URL } from '@openid4vc/utils'\nimport type { CredentialFormatIdentifier } from '../../formats/credential'\nimport type { Openid4vciVersion } from '../../version'\nimport type { IssuerMetadataResult } from '../fetch-issuer-metadata'\nimport {\n allCredentialIssuerMetadataFormatIdentifiers,\n type CredentialConfigurationSupportedWithFormats,\n type CredentialConfigurationsSupported,\n type CredentialConfigurationsSupportedWithFormats,\n type CredentialIssuerMetadata,\n zCredentialConfigurationSupportedWithFormats,\n zCredentialIssuerMetadataWithDraftVersion,\n} from './z-credential-issuer-metadata'\nimport {\n zSignedCredentialIssuerMetadataHeader,\n zSignedCredentialIssuerMetadataPayload,\n} from './z-signed-credential-issuer-metadata'\n\nconst wellKnownCredentialIssuerSuffix = '.well-known/openid-credential-issuer'\n\nexport interface FetchCredentialIssuerMetadataOptions {\n /**\n * Callbacks for fetching the credential issur metadata.\n * If no `verifyJwt` callback is provided, the request\n * will not include the `application/jwt` Accept header\n * for signed metadata.\n */\n callbacks?: Partial<Pick<CallbackContext, 'fetch' | 'verifyJwt'>>\n\n /**\n * Only used for verifying signed issuer metadata. If not provided\n * current time will be used\n */\n now?: Date\n}\n\nexport interface CredentialIssuerMetadataSigned {\n jwt: DecodeJwtResult<typeof zSignedCredentialIssuerMetadataHeader, typeof zSignedCredentialIssuerMetadataPayload>\n signer: JwtSignerWithJwk\n}\n\nexport interface FetchCredentialIssuerMetadataReturn {\n /**\n * The credential issuer metadata, optionally transformed to Draft 14+ syntax\n */\n credentialIssuerMetadata: CredentialIssuerMetadata\n\n /**\n * The original draft version of the credential issuer metadata\n */\n originalDraftVersion: Openid4vciVersion\n\n /**\n * Metadata about the signed issuer metadata, if the metadata was signed.\n */\n signed?: CredentialIssuerMetadataSigned\n}\n\n/**\n * @inheritdoc {@link fetchWellKnownMetadata}\n */\nexport async function fetchCredentialIssuerMetadata(\n credentialIssuer: string,\n options?: FetchCredentialIssuerMetadataOptions\n): Promise<FetchCredentialIssuerMetadataReturn | null> {\n const parsedIssuerUrl = new URL(credentialIssuer)\n\n const legacyWellKnownMetadataUrl = joinUriParts(credentialIssuer, [wellKnownCredentialIssuerSuffix])\n const wellKnownMetadataUrl = joinUriParts(parsedIssuerUrl.origin, [\n wellKnownCredentialIssuerSuffix,\n parsedIssuerUrl.pathname,\n ])\n\n // If verify jwt callback is provided, we accept both signed and unsigned issuer metadata\n const acceptedContentType: [ContentType, ...ContentType[]] = options?.callbacks?.verifyJwt\n ? [ContentType.Jwt, ContentType.Json]\n : [ContentType.Json]\n\n // Either unsigned metadata or signed JWT\n const responseSchema = zCredentialIssuerMetadataWithDraftVersion.or(zCompactJwt)\n\n let result = null\n let firstError = null\n\n try {\n result = await fetchWellKnownMetadata(wellKnownMetadataUrl, responseSchema, {\n fetch: options?.callbacks?.fetch,\n acceptedContentType,\n })\n } catch (error) {\n if (error instanceof OpenId4VcBaseError) throw error\n\n // An exception occurs if a CORS-policy blocks the request, i.e. because the URL is invalid due to the legacy path being used\n // The legacy path should still be tried therefore we store the first error to rethrow it later if needed\n firstError = error\n }\n\n // If the metadata is not available at the new URL, fetch it at the legacy URL\n // The legacy url is the same if no subpath is used by the issuer\n if (!result && legacyWellKnownMetadataUrl !== wellKnownMetadataUrl) {\n try {\n result = await fetchWellKnownMetadata(legacyWellKnownMetadataUrl, responseSchema, {\n fetch: options?.callbacks?.fetch,\n acceptedContentType,\n })\n } catch (error) {\n // If the first attempt also errored, rethrow that original error; otherwise rethrow this one\n throw firstError ?? error\n }\n }\n\n if (!result && firstError) {\n throw firstError\n }\n\n let issuerMetadataWithVersion: FetchCredentialIssuerMetadataReturn | null = null\n\n if (typeof result === 'string') {\n // We won't reach this, as we already handle this with accepted content types.\n // Mainly to make TS happy\n if (!options?.callbacks?.verifyJwt) {\n throw new Oauth2Error(\n `Unable to verify signed credential issuer metadata, no 'verifyJwt' callback provided to fetch credential issuer metadata method.`\n )\n }\n const { header, payload, signature } = decodeJwt({\n jwt: result,\n headerSchema: zSignedCredentialIssuerMetadataHeader,\n payloadSchema: zSignedCredentialIssuerMetadataPayload,\n })\n\n if (payload.sub !== credentialIssuer) {\n throw new Oauth2Error(\n `The 'sub' parameter '${payload.sub}' in the signed well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`\n )\n }\n\n // Extract signer of the JWT\n const signer = jwtSignerFromJwt({ header, payload })\n\n const verifyResult = await verifyJwt({\n compact: result,\n header,\n payload,\n verifyJwtCallback: options.callbacks.verifyJwt,\n now: options.now,\n signer,\n errorMessage: 'signed credential issuer metadata jwt verification failed',\n })\n\n const issuerMetadata = parseWithErrorHandling(\n zCredentialIssuerMetadataWithDraftVersion,\n payload,\n 'Unable to determine version for signed issuer metadata'\n )\n\n issuerMetadataWithVersion = {\n ...issuerMetadata,\n signed: {\n signer: verifyResult.signer,\n jwt: {\n header,\n payload,\n signature,\n compact: result,\n },\n },\n }\n } else if (result) {\n issuerMetadataWithVersion = result\n }\n\n // credential issuer param MUST match\n if (\n issuerMetadataWithVersion &&\n issuerMetadataWithVersion.credentialIssuerMetadata.credential_issuer !== credentialIssuer\n ) {\n throw new Oauth2Error(\n `The 'credential_issuer' parameter '${issuerMetadataWithVersion.credentialIssuerMetadata.credential_issuer}' in the well known credential issuer metadata at '${wellKnownMetadataUrl}' does not match the provided credential issuer '${credentialIssuer}'.`\n )\n }\n\n return issuerMetadataWithVersion\n}\n\n/**\n * Extract credential configuration supported entries where the `format` is known to this\n * library and the configuration validates correctly. Should be ran only after verifying\n * the credential issuer metadata structure, so we can be certain that if the `format`\n * matches the other format specific requirements are also met.\n *\n * Validation is done when resolving issuer metadata, or when calling `createIssuerMetadata`.\n */\nexport function extractKnownCredentialConfigurationSupportedFormats(\n credentialConfigurationsSupported: CredentialConfigurationsSupported\n): CredentialConfigurationsSupportedWithFormats {\n return Object.fromEntries(\n Object.entries(credentialConfigurationsSupported).filter(\n (entry): entry is [string, CredentialConfigurationSupportedWithFormats] => {\n // Type guard to ensure that the returned entries have known formats\n const credentialConfiguration = zCredentialConfigurationSupportedWithFormats.safeParse(entry[1]) // Validate structure\n if (!credentialConfiguration.success) {\n return false\n }\n return allCredentialIssuerMetadataFormatIdentifiers.includes(\n credentialConfiguration.data.format as CredentialFormatIdentifier\n )\n }\n )\n )\n}\n\n/**\n * Get a known credential configuration supported by its id, it will throw an error if the configuration\n * is not found or if its found but the credential configuration is invalid.\n */\nexport function getKnownCredentialConfigurationSupportedById(\n issuerMetadata: IssuerMetadataResult,\n credentialConfigurationId: string\n) {\n const configuration = issuerMetadata.credentialIssuer.credential_configurations_supported[credentialConfigurationId]\n\n if (!configuration) {\n throw new Oauth2Error(\n `Credential configuration with id '${credentialConfigurationId}' not found in credential configurations supported.`\n )\n }\n\n if (!issuerMetadata.knownCredentialConfigurations[credentialConfigurationId]) {\n parseWithErrorHandling(\n zCredentialConfigurationSupportedWithFormats,\n configuration,\n `Credential configuration with id '${credentialConfigurationId}' is not valid`\n )\n }\n\n return issuerMetadata.knownCredentialConfigurations[credentialConfigurationId]\n}\n","import { zIs } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport {\n zJwtVcJsonCredentialIssuerMetadata,\n zJwtVcJsonCredentialIssuerMetadataDraft14,\n zJwtVcJsonLdCredentialIssuerMetadata,\n zJwtVcJsonLdCredentialIssuerMetadataDraft14,\n zLdpVcCredentialIssuerMetadata,\n zLdpVcCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcCredentialIssuerMetadataDraft14,\n zLegacySdJwtVcFormatIdentifier,\n zMsoMdocCredentialIssuerMetadata,\n zMsoMdocCredentialIssuerMetadataDraft14,\n zSdJwtDcCredentialIssuerMetadata,\n} from '../formats/credential'\nimport { zLegacySdJwtVcCredentialIssuerMetadataV1 } from '../formats/credential/sd-jwt-vc/z-sd-jwt-vc'\nimport { zSdJwtW3VcCredentialIssuerMetadata } from '../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport type { CredentialRequestWithFormats } from './z-credential-request'\n\nexport interface GetCredentialRequestFormatPayloadForCredentialConfigurationIdOptions {\n /**\n * The credential configuration id to get the format payload for\n */\n credentialConfigurationId: string\n\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n}\n\nexport function getCredentialRequestFormatPayloadForCredentialConfigurationId(\n options: GetCredentialRequestFormatPayloadForCredentialConfigurationIdOptions\n): CredentialRequestWithFormats {\n const credentialConfiguration = getKnownCredentialConfigurationSupportedById(\n options.issuerMetadata,\n options.credentialConfigurationId\n )\n\n if (\n zIs(zLegacySdJwtVcCredentialIssuerMetadataV1, credentialConfiguration) ||\n zIs(zLegacySdJwtVcCredentialIssuerMetadataDraft14, credentialConfiguration) ||\n (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration) &&\n (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11 ||\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft14))\n ) {\n return {\n format: 'vc+sd-jwt',\n vct: credentialConfiguration.vct,\n }\n }\n\n if (\n zIs(zMsoMdocCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zMsoMdocCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n doctype: credentialConfiguration.doctype,\n }\n }\n\n if (\n zIs(zLdpVcCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zLdpVcCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n '@context': credentialConfiguration.credential_definition['@context'],\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (\n zIs(zJwtVcJsonLdCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zJwtVcJsonLdCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n '@context': credentialConfiguration.credential_definition['@context'],\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (\n zIs(zJwtVcJsonCredentialIssuerMetadata, credentialConfiguration) ||\n zIs(zJwtVcJsonCredentialIssuerMetadataDraft14, credentialConfiguration)\n ) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n if (zIs(zSdJwtDcCredentialIssuerMetadata, credentialConfiguration)) {\n throw new Openid4vciError(\n `Credential configuration id '${options.credentialConfigurationId}' with format ${zLegacySdJwtVcFormatIdentifier.value} does not support credential request based on 'format'. Use 'credential_configuration_id' directly.`\n )\n }\n\n if (zIs(zSdJwtW3VcCredentialIssuerMetadata, credentialConfiguration)) {\n return {\n format: credentialConfiguration.format,\n credential_definition: {\n type: credentialConfiguration.credential_definition.type,\n },\n }\n }\n\n throw new Openid4vciError(\n `Unknown format '${credentialConfiguration.format}' in credential configuration with id '${options.credentialConfigurationId}' for credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n}\n","import { zCompactJwt } from '@openid4vc/oauth2'\nimport z from 'zod'\nimport {\n type KeyAttestationJwtHeader,\n zKeyAttestationJwtHeader,\n zKeyAttestationJwtPayloadForUse,\n} from '../../../key-attestation/z-key-attestation'\n\nexport const zAttestationProofTypeIdentifier = z.literal('attestation')\nexport const attestationProofTypeIdentifier = zAttestationProofTypeIdentifier.value\nexport type AttestationProofTypeIdentifier = z.infer<typeof zAttestationProofTypeIdentifier>\n\nexport const zCredentialRequestProofAttestation = z.object({\n proof_type: zAttestationProofTypeIdentifier,\n attestation: zCompactJwt,\n})\n\nexport const zCredentialRequestAttestationProofTypeHeader = zKeyAttestationJwtHeader\nexport type CredentialRequestAttestationProofTypeHeader = KeyAttestationJwtHeader\n\nexport const zCredentialRequestAttestationProofTypePayload = zKeyAttestationJwtPayloadForUse('proof_type.attestation')\nexport type CredentialRequestAttestationProofTypePayload = z.infer<typeof zCredentialRequestAttestationProofTypePayload>\n","import { zCompactJwt, zJwtHeader, zJwtPayload } from '@openid4vc/oauth2'\nimport { zHttpsUrl, zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport const zJwtProofTypeIdentifier = z.literal('jwt')\nexport const jwtProofTypeIdentifier = zJwtProofTypeIdentifier.value\nexport type JwtProofTypeIdentifier = z.infer<typeof zJwtProofTypeIdentifier>\n\nexport const zCredentialRequestProofJwt = z.object({\n proof_type: zJwtProofTypeIdentifier,\n jwt: zCompactJwt,\n})\n\nexport const zCredentialRequestJwtProofTypeHeader = zJwtHeader\n .extend({\n key_attestation: z.optional(zCompactJwt),\n typ: z.literal('openid4vci-proof+jwt'),\n })\n .loose()\n .refine(({ kid, jwk }) => jwk === undefined || kid === undefined, {\n message: `Both 'jwk' and 'kid' are defined. Only one is allowed`,\n })\n .refine(({ trust_chain, kid }) => !trust_chain || !kid, {\n message: `When 'trust_chain' is provided, 'kid' is required`,\n })\n\nexport type CredentialRequestJwtProofTypeHeader = z.infer<typeof zCredentialRequestJwtProofTypeHeader>\n\nexport const zCredentialRequestJwtProofTypePayload = z\n .object({\n ...zJwtPayload.shape,\n aud: z.union([zHttpsUrl, z.array(zHttpsUrl)]),\n iat: zNumericDate,\n })\n .loose()\n\nexport type CredentialRequestJwtProofTypePayload = z.infer<typeof zCredentialRequestJwtProofTypePayload>\n","import { zJwk } from '@openid4vc/oauth2'\nimport type { InferOutputUnion, Simplify } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n zAttestationProofTypeIdentifier,\n zCredentialRequestProofAttestation,\n zCredentialRequestProofJwt,\n zJwtProofTypeIdentifier,\n} from '../formats/proof-type'\n\nconst zCredentialRequestProofCommon = z\n .object({\n proof_type: z.string(),\n })\n .loose()\n\nexport const allCredentialRequestProofs = [zCredentialRequestProofJwt, zCredentialRequestProofAttestation] as const\n\nexport const zCredentialRequestProof = z.union([\n zCredentialRequestProofCommon,\n z.discriminatedUnion('proof_type', allCredentialRequestProofs),\n])\n\nconst zCredentialRequestProofsCommon = z.record(z.string(), z.array(z.unknown()))\nexport const zCredentialRequestProofs = z.object({\n [zJwtProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofJwt.shape.jwt)),\n [zAttestationProofTypeIdentifier.value]: z.optional(z.array(zCredentialRequestProofAttestation.shape.attestation)),\n})\n\ntype CredentialRequestProofCommon = z.infer<typeof zCredentialRequestProofCommon>\nexport type CredentialRequestProofFormatSpecific = InferOutputUnion<typeof allCredentialRequestProofs>\nexport type CredentialRequestProofWithFormats = Simplify<\n CredentialRequestProofCommon & CredentialRequestProofFormatSpecific\n>\nexport type CredentialRequestProof = z.infer<typeof zCredentialRequestProof>\n\nexport type CredentialRequestProofsCommon = z.infer<typeof zCredentialRequestProofsCommon>\nexport type CredentialRequestProofsFormatSpecific = z.infer<typeof zCredentialRequestProofs>\nexport type CredentialRequestProofsWithFormat = CredentialRequestProofsCommon & CredentialRequestProofsFormatSpecific\nexport type CredentialRequestProofs = z.infer<typeof zCredentialRequestProofs>\n\nexport const zCredentialRequestCommon = z\n .object({\n proof: zCredentialRequestProof.optional(),\n proofs: z.optional(\n z\n .intersection(zCredentialRequestProofsCommon, zCredentialRequestProofs)\n .refine((proofs) => Object.values(proofs).length === 1, {\n message: `The 'proofs' object in a credential request should contain exactly one attribute`,\n })\n ),\n\n credential_response_encryption: z\n .object({\n jwk: zJwk,\n alg: z.string(),\n enc: z.string(),\n })\n .loose()\n .optional(),\n })\n .loose()\n // It's not allowed to provide both proof and proofs\n .refine(({ proof, proofs }) => !(proof !== undefined && proofs !== undefined), {\n message: `Both 'proof' and 'proofs' are defined. Only one is allowed`,\n })\n","import { zJwk } from '@openid4vc/oauth2'\nimport type { InferOutputUnion, Simplify } from '@openid4vc/utils'\nimport z from 'zod'\nimport {\n zJwtVcJsonCredentialRequestFormatDraft14,\n zJwtVcJsonLdCredentialRequestFormatDraft14,\n zLdpVcCredentialRequestFormatDraft14,\n zLegacySdJwtVcCredentialRequestFormatDraft14,\n zMsoMdocCredentialRequestFormatDraft14,\n} from '../formats/credential'\nimport {\n zJwtVcJsonCredentialRequestDraft11To14,\n zJwtVcJsonCredentialRequestDraft14To11,\n zJwtVcJsonFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-jwt-vc-json'\nimport {\n zJwtVcJsonLdCredentialRequestDraft11To14,\n zJwtVcJsonLdCredentialRequestDraft14To11,\n zJwtVcJsonLdFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-jwt-vc-json-ld'\nimport {\n zLdpVcCredentialRequestDraft11To14,\n zLdpVcCredentialRequestDraft14To11,\n zLdpVcFormatIdentifier,\n} from '../formats/credential/w3c-vc/z-w3c-ldp-vc'\nimport { zSdJwtW3VcCredentialRequestFormatDraft14 } from '../formats/credential/w3c-vc/z-w3c-sd-jwt-vc'\nimport { zCredentialRequestCommon } from './z-credential-request-common'\n\nexport const allCredentialRequestFormats = [\n zSdJwtW3VcCredentialRequestFormatDraft14,\n zMsoMdocCredentialRequestFormatDraft14,\n zLdpVcCredentialRequestFormatDraft14,\n zJwtVcJsonLdCredentialRequestFormatDraft14,\n zJwtVcJsonCredentialRequestFormatDraft14,\n zLegacySdJwtVcCredentialRequestFormatDraft14,\n] as const\n\nexport const allCredentialRequestFormatIdentifiers = allCredentialRequestFormats.map(\n (format) => format.shape.format.value\n)\n\n// Credential configuration no format used\nconst zCredentialRequestCredentialConfigurationId = z.object({\n credential_configuration_id: z.string(),\n\n credential_identifier: z\n .never({ message: \"'credential_identifier' cannot be defined when 'credential_configuration_id' is set.\" })\n .optional(),\n})\n\n// Authorization details no format used\nconst zAuthorizationDetailsCredentialRequest = z.object({\n credential_identifier: z.string(),\n\n credential_configuration_id: z\n .never({ message: \"'credential_configuration_id' cannot be defined when 'credential_identifier' is set.\" })\n .optional(),\n})\n\nconst zCredentialRequestFormat = z\n .object({\n format: z.string(),\n\n // We add these nevers here so that if one of these is present, we will always use\n // the new properties rather than the deprecated format\n credential_identifier: z\n .never({ message: \"'credential_identifier' cannot be defined when 'format' is set.\" })\n .optional(),\n\n credential_configuration_id: z\n .never({ message: \"'credential_configuration_id' cannot be defined when 'format' is set.\" })\n .optional(),\n })\n .loose()\n\nexport const zCredentialRequestDraft14WithFormat = zCredentialRequestCommon\n .and(zCredentialRequestFormat)\n .transform((data, ctx) => {\n // No additional validation for unknown formats\n if (\n !allCredentialRequestFormatIdentifiers.includes(\n data.format as (typeof allCredentialRequestFormatIdentifiers)[number]\n )\n )\n return data\n\n const result = z\n // We use object and passthrough as otherwise the non-format specific properties will be stripped\n .object({})\n .loose()\n // FIXME(vc+sd-jwt): use discriminated union when dropping support for legacy vc+sd-jwt format.\n .and(z.union(allCredentialRequestFormats))\n .safeParse(data)\n if (result.success) {\n return result.data as Simplify<typeof result.data & typeof data>\n }\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n\nconst zCredentialRequestDraft15 = z.union([\n zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest),\n zCredentialRequestCommon.and(zCredentialRequestCredentialConfigurationId),\n])\n\nconst zCredentialRequestDraft14 = z.union([\n zCredentialRequestDraft14WithFormat,\n zCredentialRequestCommon.and(zAuthorizationDetailsCredentialRequest),\n])\n\nexport const zCredentialRequestDraft11To14 = zCredentialRequestCommon\n .and(zCredentialRequestFormat)\n .transform((data, ctx): unknown => {\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft11To14,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft11To14,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft11To14,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n })\n .pipe(zCredentialRequestDraft14)\n\nexport const zCredentialRequestDraft14To11 = zCredentialRequestDraft14.transform((data, ctx) => {\n if (data.credential_identifier !== undefined) {\n ctx.addIssue({\n code: 'custom',\n continue: false,\n message: `'credential_identifier' is not supported in OpenID4VCI draft 11`,\n path: ['credential_identifier'],\n })\n return z.NEVER\n }\n const formatSpecificTransformations = {\n [zLdpVcFormatIdentifier.value]: zLdpVcCredentialRequestDraft14To11,\n [zJwtVcJsonFormatIdentifier.value]: zJwtVcJsonCredentialRequestDraft14To11,\n [zJwtVcJsonLdFormatIdentifier.value]: zJwtVcJsonLdCredentialRequestDraft14To11,\n } as const\n\n if (!Object.keys(formatSpecificTransformations).includes(data.format)) return data\n\n const schema = formatSpecificTransformations[data.format as keyof typeof formatSpecificTransformations]\n const result = schema.safeParse(data)\n if (result.success) return result.data\n for (const issue of result.error.issues) {\n ctx.addIssue({\n ...issue,\n // FIXME: this used to work fine in zod 3\n code: issue.code as 'custom',\n })\n }\n return z.NEVER\n})\n\nexport const zCredentialRequest = z.union([\n zCredentialRequestDraft15,\n zCredentialRequestDraft14,\n zCredentialRequestDraft11To14,\n])\n\nexport const zDeferredCredentialRequest = z.object({\n transaction_id: z.string().nonempty(),\n credential_response_encryption: z\n .object({\n jwk: zJwk,\n alg: z.string(),\n enc: z.string(),\n })\n .loose()\n .optional(),\n})\n\ntype CredentialRequestCommon = z.infer<typeof zCredentialRequestCommon>\nexport type CredentialRequestFormatSpecific = InferOutputUnion<typeof allCredentialRequestFormats>\nexport type CredentialRequestWithFormats = CredentialRequestCommon & CredentialRequestFormatSpecific\n\nexport type CredentialRequestDraft14 = z.infer<typeof zCredentialRequestDraft14>\nexport type CredentialRequestDraft15 = z.infer<typeof zCredentialRequestDraft15>\nexport type CredentialRequest = CredentialRequestDraft14 | CredentialRequestDraft15\n\nexport type DeferredCredentialRequest = z.infer<typeof zDeferredCredentialRequest>\n","import z from 'zod'\n\nexport enum Oauth2ErrorCodes {\n ServerError = 'server_error',\n\n // Resource Indicators\n InvalidTarget = 'invalid_target',\n\n // Oauth2\n InvalidRequest = 'invalid_request',\n InvalidToken = 'invalid_token',\n InsufficientScope = 'insufficient_scope',\n InvalidGrant = 'invalid_grant',\n InvalidClient = 'invalid_client',\n UnauthorizedClient = 'unauthorized_client',\n UnsupportedGrantType = 'unsupported_grant_type',\n InvalidScope = 'invalid_scope',\n\n // DPoP\n InvalidDpopProof = 'invalid_dpop_proof',\n UseDpopNonce = 'use_dpop_nonce',\n\n // FiPA\n RedirectToWeb = 'redirect_to_web',\n InvalidSession = 'invalid_session',\n InsufficientAuthorization = 'insufficient_authorization',\n\n // OpenID4VCI\n InvalidCredentialRequest = 'invalid_credential_request',\n CredentialRequestDenied = 'credential_request_denied',\n InvalidProof = 'invalid_proof',\n InvalidNonce = 'invalid_nonce',\n InvalidEncryptionParameters = 'invalid_encryption_parameters',\n UnknownCredentialConfiguration = 'unknown_credential_configuration',\n UnknownCredentialIdentifier = 'unknown_credential_identifier',\n InvalidTransactionId = 'invalid_transaction_id',\n // Removed from Draft 16+\n UnsupportedCredentialType = 'unsupported_credential_type',\n UnsupportedCredentialFormat = 'unsupported_credential_format',\n\n // Jar\n InvalidRequestUri = 'invalid_request_uri',\n InvalidRequestObject = 'invalid_request_object',\n RequestNotSupported = 'request_not_supported',\n RequestUriNotSupported = 'request_uri_not_supported',\n\n // OpenID4VP\n VpFormatsNotSupported = 'vp_formats_not_supported',\n AccessDenied = 'access_denied',\n InvalidPresentationDefinitionUri = 'invalid_presentation_definition_uri',\n InvalidPresentationDefinitionReference = 'invalid_presentation_definition_reference',\n InvalidRequestUriMethod = 'invalid_request_uri_method',\n InvalidTransactionData = 'invalid_transaction_data',\n WalletUnavailable = 'wallet_unavailable',\n}\n\nexport const zOauth2ErrorResponse = z\n .object({\n error: z.union([z.enum(Oauth2ErrorCodes), z.string()]),\n error_description: z.string().optional(),\n error_uri: z.string().optional(),\n })\n .loose()\n\nexport type Oauth2ErrorResponse = z.infer<typeof zOauth2ErrorResponse>\n","import z from 'zod'\nimport { zOauth2ErrorResponse } from '../../../oauth2/src/common/z-oauth2-error'\n\nconst zCredentialEncoding = z.union([z.string(), z.record(z.string(), z.any())])\n\nconst zBaseCredentialResponse = z\n .object({\n credentials: z\n .union([\n // Draft >= 15\n z.array(z.object({ credential: zCredentialEncoding })),\n // Draft < 15\n z.array(zCredentialEncoding),\n ])\n .optional(),\n notification_id: z.string().optional(),\n\n transaction_id: z.string().optional(),\n interval: z.number().int().positive().optional(),\n })\n .loose()\n\nexport const zCredentialResponse = zBaseCredentialResponse\n .extend({\n credential: z.optional(zCredentialEncoding),\n\n c_nonce: z.string().optional(),\n c_nonce_expires_in: z.number().int().optional(),\n })\n .loose()\n .superRefine((value, ctx) => {\n const { credential, credentials, transaction_id, interval, notification_id } = value\n\n // NOTE: we allow both credential and credentials to be present, to better work with\n // issuers that return both for backwards compatibility\n if ([credential || credentials, transaction_id].filter((i) => i !== undefined).length !== 1) {\n ctx.addIssue({\n code: 'custom',\n message: `Exactly one of 'credential'/'credentials', or 'transaction_id' MUST be defined.`,\n })\n }\n\n if (transaction_id && !interval) {\n ctx.addIssue({\n code: 'custom',\n message: `'interval' MUST be defined when 'transaction_id' is defined.`,\n })\n }\n\n if (notification_id && !(credentials || credential)) {\n ctx.addIssue({\n code: 'custom',\n message: `'notification_id' MUST NOT be defined when 'credential' or 'credentials' are not defined.`,\n })\n }\n })\n\nexport type CredentialResponse = z.infer<typeof zCredentialResponse>\n\nexport const zCredentialErrorResponse = z\n .object({\n ...zOauth2ErrorResponse.shape,\n\n c_nonce: z.string().optional(),\n c_nonce_expires_in: z.number().int().optional(),\n })\n .loose()\n\nexport type CredentialErrorResponse = z.infer<typeof zCredentialErrorResponse>\n\nexport const zDeferredCredentialResponse = zBaseCredentialResponse.superRefine((value, ctx) => {\n const { credentials, transaction_id, interval, notification_id } = value\n\n if ([credentials, transaction_id].filter((i) => i !== undefined).length !== 1) {\n ctx.addIssue({\n code: 'custom',\n message: `Exactly one of 'credentials', or 'transaction_id' MUST be defined.`,\n })\n }\n\n if (transaction_id && !interval) {\n ctx.addIssue({\n code: 'custom',\n message: `'interval' MUST be defined when 'transaction_id' is defined.`,\n })\n }\n\n if (notification_id && credentials) {\n ctx.addIssue({\n code: 'custom',\n message: `'notification_id' MUST NOT be defined when 'credentials' is not defined.`,\n })\n }\n})\n\nexport type DeferredCredentialResponse = z.infer<typeof zDeferredCredentialResponse>\n","import {\n type CallbackContext,\n Oauth2Error,\n type RequestDpopOptions,\n type ResourceRequestResponseNotOk,\n type ResourceRequestResponseOk,\n resourceRequest,\n type zOauth2ErrorResponse,\n} from '@openid4vc/oauth2'\nimport { ContentType, isResponseContentType, parseWithErrorHandling } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { Openid4vciVersion } from '../version'\nimport {\n type CredentialRequest,\n type CredentialRequestWithFormats,\n zCredentialRequest,\n zCredentialRequestDraft14To11,\n zDeferredCredentialRequest,\n} from './z-credential-request'\nimport type { CredentialRequestProof, CredentialRequestProofs } from './z-credential-request-common'\nimport {\n type CredentialResponse,\n type DeferredCredentialResponse,\n zCredentialErrorResponse,\n zCredentialResponse,\n zDeferredCredentialResponse,\n} from './z-credential-response'\n\ninterface RetrieveCredentialsBaseOptions {\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Callback used in retrieve credentials endpoints\n */\n callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'hash' | 'signJwt'>\n\n /**\n * Access token authorized to retrieve the credential(s)\n */\n accessToken: string\n\n /**\n * DPoP options\n */\n dpop?: RequestDpopOptions\n}\n\nexport interface RetrieveCredentialsWithCredentialConfigurationIdOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The credential configuration id to request\n */\n credentialConfigurationId: string\n\n proof?: CredentialRequestProof\n proofs?: CredentialRequestProofs\n}\n\nexport async function retrieveCredentialsWithCredentialConfigurationId(\n options: RetrieveCredentialsWithCredentialConfigurationIdOptions\n) {\n if (\n options.issuerMetadata.originalDraftVersion !== Openid4vciVersion.Draft15 &&\n options.issuerMetadata.originalDraftVersion !== Openid4vciVersion.V1\n ) {\n throw new Openid4vciError(\n '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.'\n )\n }\n\n // This ensures the credential configuration exists\n getKnownCredentialConfigurationSupportedById(options.issuerMetadata, options.credentialConfigurationId)\n\n const credentialRequest: CredentialRequest = {\n ...options.additionalRequestPayload,\n\n credential_configuration_id: options.credentialConfigurationId,\n proof: options.proof,\n proofs: options.proofs,\n }\n\n return retrieveCredentials({\n callbacks: options.callbacks,\n credentialRequest,\n issuerMetadata: options.issuerMetadata,\n accessToken: options.accessToken,\n dpop: options.dpop,\n })\n}\n\nexport interface RetrieveCredentialsWithFormatOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The format specific payload. Needs to at least include the `format` and other params\n * are determined by the format itself\n */\n formatPayload: CredentialRequestWithFormats\n\n proof?: CredentialRequestProof\n proofs?: CredentialRequestProofs\n}\n\nexport async function retrieveCredentialsWithFormat(options: RetrieveCredentialsWithFormatOptions) {\n if (\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft15 ||\n options.issuerMetadata.originalDraftVersion === Openid4vciVersion.V1\n ) {\n throw new Openid4vciError(\n 'Requesting credentials based on format is not supported on OpenID4VCI above draft 15. Provide the credential configuration id directly in the request.'\n )\n }\n\n const credentialRequest: CredentialRequest = {\n ...options.formatPayload,\n ...options.additionalRequestPayload,\n\n proof: options.proof,\n proofs: options.proofs,\n }\n\n return retrieveCredentials({\n callbacks: options.callbacks,\n credentialRequest,\n issuerMetadata: options.issuerMetadata,\n accessToken: options.accessToken,\n dpop: options.dpop,\n })\n}\n\nexport interface RetrieveCredentialsOptions extends RetrieveCredentialsBaseOptions {\n /**\n * The credential request\n */\n credentialRequest: CredentialRequest\n}\n\nexport interface RetrieveCredentialsResponseOk extends ResourceRequestResponseOk {\n /**\n * The successful validated (in structure, not the actual contents are validated) credential response payload\n */\n credentialResponse: CredentialResponse\n}\n\nexport interface RetrieveCredentialsResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response itself was successful but the validation of the\n * credential response data structure failed\n */\n credentialResponseResult?: ReturnType<typeof zCredentialResponse.safeParse>\n\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a credential error response. It may be successful or it may not be.\n */\n credentialErrorResponseResult?: ReturnType<typeof zCredentialErrorResponse.safeParse>\n}\n\n/**\n * internal method\n */\nasync function retrieveCredentials(\n options: RetrieveCredentialsOptions\n): Promise<RetrieveCredentialsResponseNotOk | RetrieveCredentialsResponseOk> {\n const credentialEndpoint = options.issuerMetadata.credentialIssuer.credential_endpoint\n\n let credentialRequest = parseWithErrorHandling(\n zCredentialRequest,\n options.credentialRequest,\n 'Error validating credential request'\n )\n\n if (credentialRequest.proofs) {\n const { batch_credential_issuance } = options.issuerMetadata.credentialIssuer\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n throw new Oauth2Error(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support batch credential issuance using the 'proofs' request property. Only 'proof' is supported.`\n )\n }\n\n const proofs = Object.values(credentialRequest.proofs)[0]\n if (proofs.length > (batch_credential_issuance?.batch_size ?? 1)) {\n throw new Oauth2Error(\n `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.`\n )\n }\n }\n\n if (options.issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft11) {\n credentialRequest = parseWithErrorHandling(\n zCredentialRequestDraft14To11,\n credentialRequest,\n `Error transforming credential request from ${Openid4vciVersion.Draft14} to ${Openid4vciVersion.Draft11}`\n )\n }\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: credentialEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(credentialRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const credentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n credentialErrorResponseResult,\n }\n }\n\n // Try to parse the credential response\n const credentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n if (!credentialResponseResult?.success) {\n return {\n ...resourceResponse,\n ok: false,\n credentialResponseResult,\n }\n }\n\n return {\n ...resourceResponse,\n credentialResponse: credentialResponseResult.data,\n }\n}\n\nexport interface RetrieveDeferredCredentialsOptions extends RetrieveCredentialsBaseOptions {\n /**\n * Additional payload to include in the credential request.\n */\n additionalRequestPayload?: Record<string, unknown>\n\n /**\n * The transaction ID\n */\n transactionId: string\n}\n\nexport interface RetrieveDeferredCredentialsResponseOk extends ResourceRequestResponseOk {\n /**\n * The successful validated (in structure, not the actual contents are validated) deferred credential response payload\n */\n deferredCredentialResponse: DeferredCredentialResponse\n}\n\nexport interface RetrieveDeferredCredentialsResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response itself was successful but the validation of the\n * credential response data structure failed\n */\n deferredCredentialResponseResult?: ReturnType<typeof zDeferredCredentialResponse.safeParse>\n\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a credential error response. It may be successful or it may not be.\n */\n deferredCredentialErrorResponseResult?: ReturnType<typeof zOauth2ErrorResponse.safeParse>\n}\n\nexport async function retrieveDeferredCredentials(\n options: RetrieveDeferredCredentialsOptions\n): Promise<RetrieveDeferredCredentialsResponseNotOk | RetrieveDeferredCredentialsResponseOk> {\n const credentialEndpoint = options.issuerMetadata.credentialIssuer.deferred_credential_endpoint\n if (!credentialEndpoint) {\n throw new Openid4vciError(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not support deferred credential retrieval.`\n )\n }\n\n const deferredCredentialRequest = parseWithErrorHandling(\n zDeferredCredentialRequest,\n {\n transaction_id: options.transactionId,\n ...options.additionalRequestPayload,\n },\n 'Error validating deferred credential request'\n )\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: credentialEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(deferredCredentialRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const deferredCredentialErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zCredentialErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n deferredCredentialErrorResponseResult,\n }\n }\n\n // Try to parse the credential response\n const deferredCredentialResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zDeferredCredentialResponse\n .refine((response) => response.credentials || response.transaction_id === options.transactionId, {\n error: `Transaction id in deferred credential response does not match transaction id in deferred credential request '${options.transactionId}'`,\n })\n .safeParse(await resourceResponse.response.clone().json())\n : undefined\n if (!deferredCredentialResponseResult?.success) {\n return {\n ...resourceResponse,\n ok: false,\n deferredCredentialResponseResult,\n }\n }\n\n return {\n ...resourceResponse,\n deferredCredentialResponse: deferredCredentialResponseResult.data,\n }\n}\n","import {\n type CallbackContext,\n decodeJwt,\n isJwkInSet,\n type JwtSigner,\n jwtHeaderFromJwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling } from '@openid4vc/utils'\nimport { Openid4vciError } from '../../../error/Openid4vciError'\nimport { type VerifyKeyAttestationJwtReturn, verifyKeyAttestationJwt } from '../../../key-attestation/key-attestation'\nimport { zKeyAttestationJwtHeader, zKeyAttestationJwtPayload } from '../../../key-attestation/z-key-attestation'\nimport {\n type CredentialRequestJwtProofTypeHeader,\n type CredentialRequestJwtProofTypePayload,\n zCredentialRequestJwtProofTypeHeader,\n zCredentialRequestJwtProofTypePayload,\n} from './z-jwt-proof-type'\n\nexport interface CreateCredentialRequestJwtProofOptions {\n /**\n * Nonce to use in the jwt. Should be derived from the c_nonce\n */\n nonce?: string\n\n /**\n * The credential issuer identifier\n */\n credentialIssuer: string\n\n /**\n * The date when the token was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The client id of the wallet requesting the credential. Should not be included when using\n * the pre-authorized code flow\n */\n clientId?: string\n\n /**\n * Key attestation jwt that the proof should based on. In this case it is required that the `signer` uses\n * a key from the `attested_keys` in the key attestation jwt payload.\n */\n keyAttestationJwt?: string\n\n signer: JwtSigner\n callbacks: Pick<CallbackContext, 'signJwt' | 'hash'>\n}\n\nexport async function createCredentialRequestJwtProof(\n options: CreateCredentialRequestJwtProofOptions\n): Promise<string> {\n const header = parseWithErrorHandling(zCredentialRequestJwtProofTypeHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n key_attestation: options.keyAttestationJwt,\n typ: 'openid4vci-proof+jwt',\n } satisfies CredentialRequestJwtProofTypeHeader)\n\n const payload = parseWithErrorHandling(zCredentialRequestJwtProofTypePayload, {\n nonce: options.nonce,\n aud: options.credentialIssuer,\n iat: dateToSeconds(options.issuedAt),\n iss: options.clientId,\n } satisfies CredentialRequestJwtProofTypePayload)\n\n const { jwt, signerJwk } = await options.callbacks.signJwt(options.signer, { header, payload })\n\n // Check the jwt is signed with an key from attested_keys in the key_attestation jwt\n if (options.keyAttestationJwt) {\n const decodedKeyAttestation = decodeJwt({\n jwt: options.keyAttestationJwt,\n headerSchema: zKeyAttestationJwtHeader,\n payloadSchema: zKeyAttestationJwtPayload,\n })\n\n const isSigedWithAttestedKey = await isJwkInSet({\n jwk: signerJwk,\n jwks: decodedKeyAttestation.payload.attested_keys,\n callbacks: options.callbacks,\n })\n\n if (!isSigedWithAttestedKey) {\n throw new Openid4vciError(\n `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`\n )\n }\n }\n\n return jwt\n}\n\nexport interface VerifyCredentialRequestJwtProofOptions {\n /**\n * The proof jwt\n */\n jwt: string\n\n /**\n * Expected nonce. Should be a c_nonce previously shared with the wallet\n */\n expectedNonce?: string\n\n /**\n * Date at which the nonce will expire\n */\n nonceExpiresAt?: Date\n\n /**\n * The credential issuer identifier, will be matched against the `aud` claim.\n */\n credentialIssuer: string\n\n /**\n * The client id of the wallet requesting the credential, if available.\n */\n clientId?: string\n\n /**\n * Current time, if not provided a new date instance will be created\n */\n now?: Date\n\n /**\n * Callbacks required for the jwt verification.\n *\n * Will be used for the jwt proof, and optionally a `key_attestation` in the jwt proof header.\n */\n callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>\n}\n\nexport async function verifyCredentialRequestJwtProof(options: VerifyCredentialRequestJwtProofOptions) {\n const { header, payload } = decodeJwt({\n jwt: options.jwt,\n headerSchema: zCredentialRequestJwtProofTypeHeader,\n payloadSchema: zCredentialRequestJwtProofTypePayload,\n })\n\n const now = options.now?.getTime() ?? Date.now()\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new Openid4vciError('Nonce used for credential request proof expired')\n }\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n header,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'Error verifiying credential request proof jwt.',\n expectedNonce: options.expectedNonce,\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n now: options.now,\n })\n\n let keyAttestationResult: VerifyKeyAttestationJwtReturn | undefined\n // Check the jwt is signed with an key from attested_keys in the key_attestation jwt\n if (header.key_attestation) {\n keyAttestationResult = await verifyKeyAttestationJwt({\n callbacks: options.callbacks,\n keyAttestationJwt: header.key_attestation,\n use: 'proof_type.jwt',\n })\n\n const isSigedWithAttestedKey = await isJwkInSet({\n jwk: signer.publicJwk,\n jwks: keyAttestationResult.payload.attested_keys,\n callbacks: options.callbacks,\n })\n\n if (!isSigedWithAttestedKey) {\n throw new Openid4vciError(\n `Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'`\n )\n }\n }\n\n return {\n header,\n payload,\n signer,\n keyAttestation: keyAttestationResult,\n }\n}\n","import {\n type AuthorizationServerMetadata,\n type CallbackContext,\n fetchAuthorizationServerMetadata,\n Oauth2Error,\n zAuthorizationServerMetadata,\n} from '@openid4vc/oauth2'\n\nimport { parseWithErrorHandling } from '@openid4vc/utils'\nimport type { Openid4vciVersion } from '../version'\nimport {\n type CredentialIssuerMetadataSigned,\n extractKnownCredentialConfigurationSupportedFormats,\n fetchCredentialIssuerMetadata,\n} from './credential-issuer/credential-issuer-metadata'\nimport type {\n CredentialConfigurationsSupportedWithFormats,\n CredentialIssuerMetadata,\n} from './credential-issuer/z-credential-issuer-metadata'\n\nexport interface ResolveIssuerMetadataOptions {\n /**\n * Only fetch metadata for authorization servers that are part of this list. This can help if you know beforehand\n * which authorization servers will be used. The list is not validated to ensure all entries are also\n * in the issuer metadata.\n */\n restrictToAuthorizationServers?: string[]\n\n /**\n * Allow extracting authorization server metadata from the credential issuer metadata. This is added for backwards\n * compatibility with some implementations that did not host a separate authorization server metadata and will be removed\n * in a future version.\n *\n * @default true\n */\n allowAuthorizationMetadataFromCredentialIssuerMetadata?: boolean\n\n /**\n * Callbacks for fetching the credential issur metadata.\n * If no `verifyJwt` callback is provided, the request\n * will not include the `application/jwt` Accept header\n * for signed metadata.\n */\n callbacks: Partial<Pick<CallbackContext, 'fetch' | 'verifyJwt'>>\n\n /**\n * Only used for verifying signed issuer metadata. If not provided\n * current time will be used\n */\n now?: Date\n}\n\nexport interface IssuerMetadataResult {\n originalDraftVersion: Openid4vciVersion\n credentialIssuer: CredentialIssuerMetadata\n\n /**\n * Metadata about the signed credential issuer metadata,\n * if the issuer metadata was signed\n */\n signedCredentialIssuer?: CredentialIssuerMetadataSigned\n\n authorizationServers: AuthorizationServerMetadata[]\n\n /**\n * Known credential configurations includes all the credential configurations with a known credential format\n * that pass the validation requirements from the OpenID4VCI specification. Recognized formats that do not\n * adhere to the format specific metadata requirements are not included, but also won't result in an error, to\n * to still allow interacting with issuers using invalid metadata for specific configurations.\n */\n knownCredentialConfigurations: CredentialConfigurationsSupportedWithFormats\n}\n\nexport async function resolveIssuerMetadata(\n credentialIssuer: string,\n options?: ResolveIssuerMetadataOptions\n): Promise<IssuerMetadataResult> {\n const allowAuthorizationMetadataFromCredentialIssuerMetadata =\n options?.allowAuthorizationMetadataFromCredentialIssuerMetadata ?? true\n\n const credentialIssuerMetadataWithDraftVersion = await fetchCredentialIssuerMetadata(credentialIssuer, {\n callbacks: options?.callbacks,\n now: options?.now,\n })\n if (!credentialIssuerMetadataWithDraftVersion) {\n throw new Oauth2Error(`Well known credential issuer metadata for issuer '${credentialIssuer}' not found.`)\n }\n\n const { credentialIssuerMetadata, originalDraftVersion, signed } = credentialIssuerMetadataWithDraftVersion\n\n // If no authoriation servers are defined, use the credential issuer as the authorization server\n const authorizationServers = credentialIssuerMetadata.authorization_servers ?? [credentialIssuer]\n\n const authoriationServersMetadata: AuthorizationServerMetadata[] = []\n for (const authorizationServer of authorizationServers) {\n if (\n options?.restrictToAuthorizationServers &&\n !options.restrictToAuthorizationServers.includes(authorizationServer)\n ) {\n continue\n }\n\n let authorizationServerMetadata = await fetchAuthorizationServerMetadata(\n authorizationServer,\n options?.callbacks.fetch\n )\n if (\n !authorizationServerMetadata &&\n authorizationServer === credentialIssuer &&\n allowAuthorizationMetadataFromCredentialIssuerMetadata\n ) {\n authorizationServerMetadata = parseWithErrorHandling(\n zAuthorizationServerMetadata,\n {\n token_endpoint: credentialIssuerMetadata.token_endpoint,\n issuer: credentialIssuer,\n },\n `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.`\n )\n }\n\n if (!authorizationServerMetadata) {\n throw new Oauth2Error(\n `Well known openid configuration or authorization server metadata for authorization server '${authorizationServer}' not found.`\n )\n }\n\n authoriationServersMetadata.push(authorizationServerMetadata)\n }\n\n // Collect all known credential configurations with formats\n const knownCredentialConfigurations = extractKnownCredentialConfigurationSupportedFormats(\n credentialIssuerMetadata.credential_configurations_supported\n )\n\n return {\n originalDraftVersion,\n credentialIssuer: credentialIssuerMetadata,\n signedCredentialIssuer: signed,\n\n authorizationServers: authoriationServersMetadata,\n knownCredentialConfigurations,\n }\n}\n","import { zInteger } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport const zNonceResponse = z\n .object({\n c_nonce: z.string(),\n c_nonce_expires_in: z.optional(zInteger),\n })\n .loose()\nexport type NonceResponse = z.infer<typeof zNonceResponse>\n","import { InvalidFetchResponseError } from '@openid4vc/oauth2'\nimport { ContentType, createZodFetcher, type Fetch, parseWithErrorHandling, ValidationError } from '@openid4vc/utils'\nimport { Openid4vciError } from '../error/Openid4vciError'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport { type NonceResponse, zNonceResponse } from './z-nonce'\n\nexport interface RequestNonceOptions {\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Custom fetch implementation to use\n */\n fetch?: Fetch\n}\n\n/**\n * Request a nonce from the `nonce_endpoint`\n *\n * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata\n * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response\n * @throws ValidationError - if validating the nonce response failed\n */\nexport async function requestNonce(options: RequestNonceOptions): Promise<NonceResponse> {\n const fetchWithZod = createZodFetcher(options?.fetch)\n const nonceEndpoint = options.issuerMetadata.credentialIssuer.nonce_endpoint\n\n if (!nonceEndpoint) {\n throw new Openid4vciError(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a nonce endpoint.`\n )\n }\n\n const { response, result } = await fetchWithZod(zNonceResponse, ContentType.Json, nonceEndpoint, {\n method: 'POST',\n })\n\n if (!response.ok || !result) {\n throw new InvalidFetchResponseError(\n `Requesting nonce from '${nonceEndpoint}' resulted in an unsuccessful response with status '${response.status}'`,\n await response.clone().text(),\n response\n )\n }\n\n if (!result.success) {\n throw new ValidationError('Error parsing nonce response', result.error)\n }\n\n return result.data\n}\n\nexport interface CreateNonceResponseOptions {\n cNonce: string\n cNonceExpiresIn?: number\n\n /**\n * Additional payload to include in the nonce response.\n *\n * Will be applied after default params to allow extension so be cautious\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createNonceResponse(options: CreateNonceResponseOptions) {\n return parseWithErrorHandling(zNonceResponse, {\n c_nonce: options.cNonce,\n c_nonce_expires_in: options.cNonceExpiresIn,\n ...options.additionalPayload,\n } satisfies NonceResponse)\n}\n","import z from 'zod'\n\nconst zNotificationEvent = z.enum(['credential_accepted', 'credential_failure', 'credential_deleted'])\nexport type NotificationEvent = z.infer<typeof zNotificationEvent>\n\nexport const zNotificationRequest = z\n .object({\n notification_id: z.string(),\n event: zNotificationEvent,\n event_description: z.optional(z.string()),\n })\n .loose()\n\nexport type NotificationRequest = z.infer<typeof zNotificationRequest>\n\nexport const zNotificationErrorResponse = z\n .object({\n error: z.enum(['invalid_notification_id', 'invalid_notification_request']),\n })\n .loose()\nexport type NotificationErrorResponse = z.infer<typeof zNotificationErrorResponse>\n","import {\n type CallbackContext,\n Oauth2Error,\n type RequestDpopOptions,\n type ResourceRequestResponseNotOk,\n type ResourceRequestResponseOk,\n resourceRequest,\n} from '@openid4vc/oauth2'\nimport { ContentType, isResponseContentType, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport {\n type NotificationEvent,\n type NotificationRequest,\n zNotificationErrorResponse,\n zNotificationRequest,\n} from './z-notification'\n\nexport interface SendNotificationOptions {\n notification: {\n /**\n * Notification id, as returned in the credential response\n */\n notificationId: string\n\n /**\n * The notification\n */\n event: NotificationEvent\n\n /**\n * Human readable description of the event\n */\n eventDescription?: string\n }\n\n /**\n * Metadata of the credential issuer and authorization servers.\n */\n issuerMetadata: IssuerMetadataResult\n\n /**\n * Callback used in notification endpoint\n */\n callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'hash' | 'signJwt'>\n\n /**\n * Access token authorized to retrieve the credential(s)\n */\n accessToken: string\n\n /**\n * DPoP options\n */\n dpop?: RequestDpopOptions\n\n /**\n * Additional payload to include in the notification request.\n */\n additionalRequestPayload?: Record<string, unknown>\n}\n\nexport type SendNotificationResponseOk = ResourceRequestResponseOk\nexport interface SendNotificationResponseNotOk extends ResourceRequestResponseNotOk {\n /**\n * If this is defined it means the response was JSON and we tried to parse it as\n * a notification error response. It may be successful or it may not be.\n */\n notificationErrorResponseResult?: ReturnType<typeof zNotificationErrorResponse.safeParse>\n}\n\nexport async function sendNotification(\n options: SendNotificationOptions\n): Promise<SendNotificationResponseNotOk | SendNotificationResponseOk> {\n const notificationEndpoint = options.issuerMetadata.credentialIssuer.notification_endpoint\n\n if (!notificationEndpoint) {\n throw new Oauth2Error(\n `Credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}' does not have a notification endpiont configured.`\n )\n }\n\n const notificationRequest = parseWithErrorHandling(\n zNotificationRequest,\n {\n event: options.notification.event,\n notification_id: options.notification.notificationId,\n event_description: options.notification.eventDescription,\n } satisfies NotificationRequest,\n 'Error validating notification request'\n )\n\n const resourceResponse = await resourceRequest({\n dpop: options.dpop,\n accessToken: options.accessToken,\n callbacks: options.callbacks,\n url: notificationEndpoint,\n requestOptions: {\n method: 'POST',\n headers: {\n 'Content-Type': ContentType.Json,\n },\n body: JSON.stringify(notificationRequest),\n },\n })\n\n if (!resourceResponse.ok) {\n const notificationErrorResponseResult = isResponseContentType(ContentType.Json, resourceResponse.response)\n ? zNotificationErrorResponse.safeParse(await resourceResponse.response.clone().json())\n : undefined\n\n return {\n ...resourceResponse,\n notificationErrorResponseResult,\n }\n }\n\n return resourceResponse\n}\n","import {\n authorizationCodeGrantIdentifier,\n type CallbackContext,\n type CreateAuthorizationRequestUrlOptions,\n type CreatePkceReturn,\n getAuthorizationServerMetadataFromList,\n Oauth2Client,\n Oauth2ClientAuthorizationChallengeError,\n Oauth2Error,\n Oauth2ErrorCodes,\n type ParseAuthorizationResponseOptions,\n parseAuthorizationResponseRedirectUrl,\n preAuthorizedCodeGrantIdentifier,\n type RequestDpopOptions,\n type RetrieveAuthorizationCodeAccessTokenOptions,\n type RetrievePreAuthorizedCodeAccessTokenOptions,\n type VerifyAuthorizationResponseOptions,\n verifyAuthorizationResponse,\n} from '@openid4vc/oauth2'\n\nimport {\n determineAuthorizationServerForCredentialOffer,\n resolveCredentialOffer,\n} from './credential-offer/credential-offer'\nimport type { CredentialOfferObject } from './credential-offer/z-credential-offer'\nimport { getCredentialRequestFormatPayloadForCredentialConfigurationId } from './credential-request/format-payload'\nimport {\n type RetrieveCredentialsResponseNotOk,\n type RetrieveCredentialsResponseOk,\n type RetrieveCredentialsWithFormatOptions,\n type RetrieveDeferredCredentialsOptions,\n type RetrieveDeferredCredentialsResponseOk,\n retrieveCredentialsWithCredentialConfigurationId,\n retrieveCredentialsWithFormat,\n retrieveDeferredCredentials,\n} from './credential-request/retrieve-credentials'\nimport { Openid4vciError } from './error/Openid4vciError'\nimport { Openid4vciRetrieveCredentialsError } from './error/Openid4vciRetrieveCredentialsError'\nimport { Openid4vciSendNotificationError } from './error/Openid4vciSendNotificationError'\nimport {\n type CreateCredentialRequestJwtProofOptions,\n createCredentialRequestJwtProof,\n} from './formats/proof-type/jwt/jwt-proof-type'\nimport { type IssuerMetadataResult, resolveIssuerMetadata } from './metadata/fetch-issuer-metadata'\nimport { type RequestNonceOptions, requestNonce } from './nonce/nonce-request'\nimport { type SendNotificationOptions, sendNotification } from './notification/notification'\nimport { Openid4vciVersion } from './version'\n\nexport enum AuthorizationFlow {\n Oauth2Redirect = 'Oauth2Redirect',\n PresentationDuringIssuance = 'PresentationDuringIssuance',\n}\n\nexport interface Openid4vciClientOptions {\n /**\n * Callbacks required for the openid4vc client\n */\n callbacks: Omit<CallbackContext, 'verifyJwt' | 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Openid4vciClient {\n private oauth2Client: Oauth2Client\n\n public constructor(private options: Openid4vciClientOptions) {\n this.oauth2Client = new Oauth2Client({\n callbacks: this.options.callbacks,\n })\n }\n\n /**\n * Resolve a credential offer into a credential offer object, handling both\n * 'credential_offer' and 'credential_offer_uri' params.\n */\n public async resolveCredentialOffer(credentialOffer: string): Promise<CredentialOfferObject> {\n return resolveCredentialOffer(credentialOffer, {\n fetch: this.options.callbacks.fetch,\n })\n }\n\n public async resolveIssuerMetadata(credentialIssuer: string): Promise<IssuerMetadataResult> {\n return resolveIssuerMetadata(credentialIssuer, {\n callbacks: this.options.callbacks,\n })\n }\n\n /**\n * Retrieve an authorization code for a presentation during issuance session\n *\n * This can only be called if an authorization challenge was performed before and returned a\n * `presentation` parameter along with an `auth_session`. If the presentation response included\n * an `presentation_during_issuance_session` parameter it MUST be included in this request as well.\n */\n public async retrieveAuthorizationCodeUsingPresentation(options: {\n /**\n * Auth session as returned by `{@link Openid4vciClient.initiateAuthorization}\n */\n authSession: string\n\n /**\n * Presentation during issuance session, obtained from the RP after submitting\n * openid4vp authorization response\n */\n presentationDuringIssuanceSession?: string\n\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n\n dpop?: RequestDpopOptions\n }) {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks })\n const { authorizationChallengeResponse, dpop } = await oauth2Client.sendAuthorizationChallengeRequest({\n authorizationServerMetadata,\n authSession: options.authSession,\n presentationDuringIssuanceSession: options.presentationDuringIssuanceSession,\n dpop: options.dpop,\n })\n\n return { authorizationChallengeResponse, dpop }\n }\n\n /**\n * Initiates authorization for credential issuance. It handles the following cases:\n * - Authorization Challenge\n * - Pushed Authorization Request\n * - Regular Authorization url\n *\n * In case the authorization challenge request returns an error with `insufficient_authorization`\n * with a `presentation` field it means the authorization server expects presentation of credentials\n * before issuance of credentials. If this is the case, the value in `presentation` should be treated\n * as an openid4vp authorization request and submitted to the verifier. Once the presentation response\n * has been submitted, the RP will respond with a `presentation_during_issuance_session` parameter.\n * Together with the `auth_session` parameter returned in this call you can retrieve an `authorization_code`\n * using\n */\n public async initiateAuthorization(\n options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks' | 'authorizationServerMetadata'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }\n ): Promise<\n // TODO: cleanup these types\n | {\n authorizationFlow: AuthorizationFlow.PresentationDuringIssuance\n openid4vpRequestUrl: string\n authSession: string\n authorizationServer: string\n }\n | {\n authorizationFlow: AuthorizationFlow.Oauth2Redirect\n authorizationRequestUrl: string\n authorizationServer: string\n pkce?: CreatePkceReturn\n }\n > {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const oauth2Client = new Oauth2Client({ callbacks: this.options.callbacks })\n\n try {\n const result = await oauth2Client.initiateAuthorization({\n clientId: options.clientId,\n pkceCodeVerifier: options.pkceCodeVerifier,\n redirectUri: options.redirectUri,\n scope: options.scope,\n additionalRequestPayload: {\n ...options.additionalRequestPayload,\n issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state,\n },\n dpop: options.dpop,\n resource: options.issuerMetadata.credentialIssuer.credential_issuer,\n authorizationServerMetadata,\n })\n\n return {\n ...result,\n authorizationFlow: AuthorizationFlow.Oauth2Redirect,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n } catch (error) {\n // Authorization server asks us to complete openid4vp request before issuance\n if (\n error instanceof Oauth2ClientAuthorizationChallengeError &&\n error.errorResponse.error === Oauth2ErrorCodes.InsufficientAuthorization &&\n error.errorResponse.presentation\n ) {\n if (!error.errorResponse.auth_session) {\n throw new Openid4vciError(\n `Expected 'auth_session' to be defined with authorization challenge response error '${error.errorResponse.error}' and 'presentation' parameter`\n )\n }\n return {\n authorizationFlow: AuthorizationFlow.PresentationDuringIssuance,\n openid4vpRequestUrl: error.errorResponse.presentation,\n authSession: error.errorResponse.auth_session,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n }\n\n throw error\n }\n }\n\n /**\n * Convenience method around {@link Oauth2Client.createAuthorizationRequestUrl}\n * but specifically focused on a credential offer\n */\n public async createAuthorizationRequestUrlFromOffer(\n options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks' | 'authorizationServerMetadata'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n if (!options.credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`Provided credential offer does not include the 'authorization_code' grant.`)\n }\n\n const authorizationCodeGrant = options.credentialOffer.grants[authorizationCodeGrantIdentifier]\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n issuerMetadata: options.issuerMetadata,\n grantAuthorizationServer: authorizationCodeGrant.authorization_server,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n options.issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const { authorizationRequestUrl, pkce, dpop } = await this.oauth2Client.createAuthorizationRequestUrl({\n authorizationServerMetadata,\n clientId: options.clientId,\n additionalRequestPayload: {\n ...options.additionalRequestPayload,\n issuer_state: options.credentialOffer?.grants?.authorization_code?.issuer_state,\n },\n resource: options.issuerMetadata.credentialIssuer.credential_issuer,\n redirectUri: options.redirectUri,\n scope: options.scope,\n pkceCodeVerifier: options.pkceCodeVerifier,\n dpop: options.dpop,\n })\n\n return {\n authorizationRequestUrl,\n pkce,\n dpop,\n authorizationServer: authorizationServerMetadata.issuer,\n }\n }\n\n /**\n * Convenience method around {@link Oauth2Client.retrievePreAuthorizedCodeAccessToken}\n * but specifically focused on a credential offer\n */\n public async retrievePreAuthorizedCodeAccessTokenFromOffer({\n credentialOffer,\n issuerMetadata,\n additionalRequestPayload,\n txCode,\n dpop,\n }: Omit<\n RetrievePreAuthorizedCodeAccessTokenOptions,\n 'callbacks' | 'authorizationServerMetadata' | 'preAuthorizedCode' | 'resource'\n > & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }) {\n if (!credentialOffer.grants?.[preAuthorizedCodeGrantIdentifier]) {\n throw new Oauth2Error(`The credential offer does not contain the '${preAuthorizedCodeGrantIdentifier}' grant.`)\n }\n\n if (credentialOffer.grants[preAuthorizedCodeGrantIdentifier].tx_code && !txCode) {\n // TODO: we could further validate the tx_code, but not sure if that's needed?\n // the server will do that for us as well\n throw new Oauth2Error(\n `Retrieving access token requires a 'tx_code' in the request, but the 'txCode' parameter was not provided.`\n )\n }\n\n const preAuthorizedCode = credentialOffer.grants[preAuthorizedCodeGrantIdentifier]['pre-authorized_code']\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n grantAuthorizationServer: credentialOffer.grants[preAuthorizedCodeGrantIdentifier].authorization_server,\n issuerMetadata,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const result = await this.oauth2Client.retrievePreAuthorizedCodeAccessToken({\n authorizationServerMetadata,\n preAuthorizedCode,\n txCode,\n resource: issuerMetadata.credentialIssuer.credential_issuer,\n additionalRequestPayload,\n dpop,\n })\n\n return {\n ...result,\n authorizationServer,\n }\n }\n\n /**\n * Parses the authorization (error) response redirect url, and verifies the\n * 'iss' value based on the authorization server metadata.\n *\n * If you need values from the authorization response (e.g. state) to retrieve the\n * authorization server metadata, you can manually import and call `parseAuthorizationResponseRedirectUrl` and\n * `verifyAuthorizationResponse`.\n */\n public parseAndVerifyAuthorizationResponseRedirectUrl(\n options: ParseAuthorizationResponseOptions & Omit<VerifyAuthorizationResponseOptions, 'authorizationResponse'>\n ) {\n const authorizationResponse = parseAuthorizationResponseRedirectUrl(options)\n\n verifyAuthorizationResponse({\n ...options,\n authorizationResponse,\n })\n\n return authorizationResponse\n }\n\n /**\n * Convenience method around {@link Oauth2Client.retrieveAuthorizationCodeAccessToken}\n * but specifically focused on a credential offer\n */\n public async retrieveAuthorizationCodeAccessTokenFromOffer({\n issuerMetadata,\n additionalRequestPayload,\n credentialOffer,\n authorizationCode,\n pkceCodeVerifier,\n redirectUri,\n dpop,\n }: Omit<RetrieveAuthorizationCodeAccessTokenOptions, 'authorizationServerMetadata' | 'callbacks'> & {\n credentialOffer: CredentialOfferObject\n issuerMetadata: IssuerMetadataResult\n }) {\n if (!credentialOffer.grants?.[authorizationCodeGrantIdentifier]) {\n throw new Oauth2Error(`The credential offer does not contain the '${authorizationCodeGrantIdentifier}' grant.`)\n }\n\n const authorizationServer = determineAuthorizationServerForCredentialOffer({\n grantAuthorizationServer: credentialOffer.grants[authorizationCodeGrantIdentifier].authorization_server,\n issuerMetadata,\n })\n\n const authorizationServerMetadata = getAuthorizationServerMetadataFromList(\n issuerMetadata.authorizationServers,\n authorizationServer\n )\n\n const result = await this.oauth2Client.retrieveAuthorizationCodeAccessToken({\n authorizationServerMetadata,\n authorizationCode,\n pkceCodeVerifier,\n additionalRequestPayload,\n dpop,\n redirectUri,\n resource: issuerMetadata.credentialIssuer.credential_issuer,\n })\n\n return {\n ...result,\n authorizationServer,\n }\n }\n\n /**\n * Request a nonce to be used in credential request proofs from the `nonce_endpoint`\n *\n * @throws Openid4vciError - if no `nonce_endpoint` is configured in the issuer metadata\n * @throws InvalidFetchResponseError - if the nonce endpoint did not return a successful response\n * @throws ValidationError - if validating the nonce response failed\n */\n public async requestNonce(options: Pick<RequestNonceOptions, 'issuerMetadata'>) {\n return requestNonce({\n ...options,\n fetch: this.options.callbacks.fetch,\n })\n }\n\n /**\n * Creates the jwt proof payload and header to be included in a credential request.\n */\n public async createCredentialRequestJwtProof(\n options: Pick<\n CreateCredentialRequestJwtProofOptions,\n 'signer' | 'nonce' | 'issuedAt' | 'clientId' | 'keyAttestationJwt'\n > & {\n issuerMetadata: IssuerMetadataResult\n credentialConfigurationId: string\n }\n ) {\n const credentialConfiguration =\n options.issuerMetadata.credentialIssuer.credential_configurations_supported[options.credentialConfigurationId]\n if (!credentialConfiguration) {\n throw new Openid4vciError(\n `Credential configuration with '${options.credentialConfigurationId}' not found in 'credential_configurations_supported' from credential issuer '${options.issuerMetadata.credentialIssuer.credential_issuer}'`\n )\n }\n\n if (credentialConfiguration.proof_types_supported) {\n if (!credentialConfiguration.proof_types_supported.jwt) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' does not support the 'jwt' proof type.`\n )\n }\n\n if (\n !credentialConfiguration.proof_types_supported.jwt.proof_signing_alg_values_supported.includes(\n options.signer.alg\n )\n ) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' does not support the '${options.signer.alg}' alg for 'jwt' proof type.`\n )\n }\n\n // TODO: might be beneficial to also decode the key attestation and see if the required level is reached\n if (credentialConfiguration.proof_types_supported.jwt.key_attestations_required && !options.keyAttestationJwt) {\n throw new Openid4vciError(\n `Credential configuration with id '${options.credentialConfigurationId}' requires key attestations for 'jwt' proof type but no 'keyAttestationJwt' was provided`\n )\n }\n }\n\n const jwt = await createCredentialRequestJwtProof({\n credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n signer: options.signer,\n clientId: options.clientId,\n issuedAt: options.issuedAt,\n nonce: options.nonce,\n keyAttestationJwt: options.keyAttestationJwt,\n callbacks: this.options.callbacks,\n })\n\n return {\n jwt,\n }\n }\n\n /**\n * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response\n * @throws ValidationError - if validation of the credential request failed\n * @throws Openid4vciError - if the `credentialConfigurationId` couldn't be found, or if the the format specific request couldn't be constructed\n */\n public async retrieveCredentials({\n issuerMetadata,\n proof,\n proofs,\n credentialConfigurationId,\n additionalRequestPayload,\n accessToken,\n dpop,\n }: Pick<\n RetrieveCredentialsWithFormatOptions,\n 'accessToken' | 'additionalRequestPayload' | 'issuerMetadata' | 'proof' | 'proofs' | 'dpop'\n > & { credentialConfigurationId: string }) {\n let credentialResponse: RetrieveCredentialsResponseNotOk | RetrieveCredentialsResponseOk\n\n if (\n issuerMetadata.originalDraftVersion === Openid4vciVersion.Draft15 ||\n issuerMetadata.originalDraftVersion === Openid4vciVersion.V1\n ) {\n credentialResponse = await retrieveCredentialsWithCredentialConfigurationId({\n accessToken,\n credentialConfigurationId,\n issuerMetadata,\n additionalRequestPayload,\n proof,\n proofs,\n callbacks: this.options.callbacks,\n dpop,\n })\n } else {\n const formatPayload = getCredentialRequestFormatPayloadForCredentialConfigurationId({\n credentialConfigurationId,\n issuerMetadata,\n })\n\n credentialResponse = await retrieveCredentialsWithFormat({\n accessToken,\n formatPayload,\n issuerMetadata,\n additionalRequestPayload,\n proof,\n proofs,\n callbacks: this.options.callbacks,\n dpop,\n })\n }\n\n if (!credentialResponse.ok) {\n throw new Openid4vciRetrieveCredentialsError(\n `Error retrieving credentials from '${issuerMetadata.credentialIssuer.credential_issuer}'`,\n credentialResponse,\n await credentialResponse.response.clone().text()\n )\n }\n\n return credentialResponse\n }\n\n /**\n * @throws Openid4vciRetrieveCredentialsError - if an unsuccessful response or the response couldn't be parsed as credential response\n * @throws ValidationError - if validation of the credential request failed\n */\n public async retrieveDeferredCredentials(\n options: Pick<\n RetrieveDeferredCredentialsOptions,\n 'issuerMetadata' | 'accessToken' | 'transactionId' | 'dpop' | 'additionalRequestPayload'\n >\n ): Promise<RetrieveDeferredCredentialsResponseOk> {\n const credentialResponse = await retrieveDeferredCredentials({\n ...options,\n callbacks: this.options.callbacks,\n })\n\n if (!credentialResponse.ok) {\n throw new Openid4vciRetrieveCredentialsError(\n `Error retrieving deferred credentials from '${options.issuerMetadata.credentialIssuer.credential_issuer}'`,\n credentialResponse,\n await credentialResponse.response.clone().text()\n )\n }\n\n return credentialResponse\n }\n\n /**\n * @throws Openid4vciSendNotificationError - if an unsuccessful response\n * @throws ValidationError - if validation of the notification request failed\n */\n public async sendNotification({\n issuerMetadata,\n notification,\n additionalRequestPayload,\n accessToken,\n dpop,\n }: Pick<\n SendNotificationOptions,\n 'accessToken' | 'additionalRequestPayload' | 'issuerMetadata' | 'dpop' | 'notification'\n >) {\n const notificationResponse = await sendNotification({\n accessToken,\n issuerMetadata,\n additionalRequestPayload,\n callbacks: this.options.callbacks,\n dpop,\n notification,\n })\n\n if (!notificationResponse.ok) {\n throw new Openid4vciSendNotificationError(\n `Error sending notification to '${issuerMetadata.credentialIssuer.credential_issuer}'`,\n notificationResponse\n )\n }\n\n return notificationResponse\n }\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport type { ParseCredentialRequestReturn } from './parse-credential-request'\nimport {\n type CredentialResponse,\n type DeferredCredentialResponse,\n zCredentialResponse,\n zDeferredCredentialResponse,\n} from './z-credential-response'\n\nexport interface CreateCredentialResponseOptions {\n credentialRequest: ParseCredentialRequestReturn\n\n credential?: CredentialResponse['credential']\n credentials?: CredentialResponse['credentials']\n\n transactionId?: string\n interval?: number\n\n cNonce?: string\n cNonceExpiresInSeconds?: number\n\n notificationId?: string\n\n /**\n * Additional payload to include in the credential response\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createCredentialResponse(options: CreateCredentialResponseOptions) {\n return parseWithErrorHandling(zCredentialResponse, {\n c_nonce: options.cNonce,\n c_nonce_expires_in: options.cNonceExpiresInSeconds,\n credential: options.credential,\n credentials: options.credentials,\n notification_id: options.notificationId,\n\n transaction_id: options.transactionId,\n interval: options.interval,\n\n // NOTE `format` is removed in draft 13. For now if a format was requested\n // we just always return it in the response as well.\n format: options.credentialRequest.format?.format,\n ...options.additionalPayload,\n } satisfies CredentialResponse)\n}\n\nexport type CreateDeferredCredentialResponseOptions = (\n | {\n credentials: DeferredCredentialResponse['credentials']\n notificationId?: string\n\n transactionId?: never\n interval?: never\n }\n | {\n /**\n * The `transaction_id` used to identify the deferred issuance transaction.\n */\n transactionId: string\n interval: number\n\n credentials?: never\n notificationId?: never\n }\n) & {\n /**\n * Additional payload to include in the deferred credential response\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport function createDeferredCredentialResponse(options: CreateDeferredCredentialResponseOptions) {\n return parseWithErrorHandling(zDeferredCredentialResponse, {\n credentials: options.credentials,\n notification_id: options.notificationId,\n\n transaction_id: options.transactionId,\n interval: options.interval,\n\n ...options.additionalPayload,\n } satisfies DeferredCredentialResponse)\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport z from 'zod'\nimport { attestationProofTypeIdentifier } from '../formats/proof-type/attestation/z-attestation-proof-type'\nimport { jwtProofTypeIdentifier } from '../formats/proof-type/jwt/z-jwt-proof-type'\nimport { getKnownCredentialConfigurationSupportedById } from '../metadata/credential-issuer/credential-issuer-metadata'\nimport type { CredentialConfigurationSupportedWithFormats } from '../metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from '../metadata/fetch-issuer-metadata'\nimport {\n allCredentialRequestFormatIdentifiers,\n allCredentialRequestFormats,\n type CredentialRequest,\n type CredentialRequestFormatSpecific,\n zCredentialRequest,\n} from './z-credential-request'\nimport {\n allCredentialRequestProofs,\n type CredentialRequestProofsFormatSpecific,\n zCredentialRequestProofs,\n} from './z-credential-request-common'\n\nexport interface ParseCredentialRequestOptions {\n issuerMetadata: IssuerMetadataResult\n credentialRequest: Record<string, unknown>\n}\n\nexport interface ParseCredentialRequestReturn {\n /**\n * If the request was for a `format` that is known to this library it will have the\n * format specific data defined here. Will not be defined if the request is for an unknown format,\n * or if `credential_identifier` is used.\n */\n format?: CredentialRequestFormatSpecific\n\n /**\n * If the request contains `proof` or `proofs` with a `proof_type` that is known to this\n * library it will have the proof type specific data defined here. Will not be defined\n * if the `proof_type` is not known or no `proof` or `proofs` were included.\n *\n * The `proof` property is parsed to the new proofs structure and the entries will\n * always only have a single entry in this case.\n *\n * NOTE: this value being `undefined` does NOT mean there were no proofs.\n * It means that either there were no proofs, or that the proof format is not\n * known to this library\n */\n proofs?: CredentialRequestProofsFormatSpecific\n\n /**\n * If authorization details were used a `credential_identifier` will be included\n * in the request. Will not be defined if `format` is defined.\n */\n credentialIdentifier?: string\n\n /**\n * Starting from OID4VCI draft 15 the credential request can include a `credential_configuration_id`.\n * This will only be defined if the request included the credential configuration id.\n *\n * An error will be thrown if a credential configuration id was included in the request that is not\n * present in the credential configurations supported of the issuer metadata\n */\n credentialConfigurationId?: string\n\n /**\n * If the request included a `credential_configuration_id` with a known format, it will\n * be included here. It's still possible `credential_configuration_id` was defined, but\n * it's not a known format.\n */\n credentialConfiguration?: CredentialConfigurationSupportedWithFormats\n\n /**\n * The validated credential request. If both `format` and `credentialIdentifier` are\n * undefined you can still handle the request by using this object directly.\n */\n credentialRequest: CredentialRequest\n}\n\nexport function parseCredentialRequest(options: ParseCredentialRequestOptions): ParseCredentialRequestReturn {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequest,\n options.credentialRequest,\n 'Error validating credential request'\n )\n let proofs: CredentialRequestProofsFormatSpecific | undefined\n\n // Try to parse the known proofs from the `proofs` object\n const knownProofs = zCredentialRequestProofs.strict().safeParse(credentialRequest.proofs)\n if (knownProofs.success) {\n proofs = knownProofs.data\n }\n\n // Try to parse the known proof from the `proof`\n const knownProof = z.union(allCredentialRequestProofs).safeParse(credentialRequest.proof)\n if (knownProof.success && knownProof.data.proof_type === jwtProofTypeIdentifier) {\n proofs = { [jwtProofTypeIdentifier]: [knownProof.data.jwt] }\n } else if (knownProof.success && knownProof.data.proof_type === attestationProofTypeIdentifier) {\n proofs = { [attestationProofTypeIdentifier]: [knownProof.data.attestation] }\n }\n\n if (credentialRequest.credential_configuration_id) {\n // This will throw an error if the credential configuration does not exist or is not valid\n getKnownCredentialConfigurationSupportedById(options.issuerMetadata, credentialRequest.credential_configuration_id)\n\n const credentialConfigurations = options.issuerMetadata.knownCredentialConfigurations\n\n return {\n credentialConfiguration: credentialConfigurations[credentialRequest.credential_configuration_id],\n credentialConfigurationId: credentialRequest.credential_configuration_id,\n credentialRequest,\n proofs,\n }\n }\n\n if (credentialRequest.credential_identifier) {\n return {\n credentialIdentifier: credentialRequest.credential_identifier,\n credentialRequest,\n proofs,\n }\n }\n\n if (\n credentialRequest.format &&\n allCredentialRequestFormatIdentifiers.includes(\n credentialRequest.format as (typeof allCredentialRequestFormatIdentifiers)[number]\n )\n ) {\n return {\n // Removes all claims that are not specific to this format\n format: parseWithErrorHandling(\n z.union(allCredentialRequestFormats),\n credentialRequest,\n 'Unable to validate format specific properties from credential request'\n ),\n credentialRequest,\n proofs,\n }\n }\n\n return {\n credentialRequest,\n proofs,\n }\n}\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport { type DeferredCredentialRequest, zDeferredCredentialRequest } from './z-credential-request'\n\nexport interface ParseDeferredCredentialRequestOptions {\n deferredCredentialRequest: Record<string, unknown>\n}\n\nexport interface ParseDeferredCredentialRequestReturn {\n /**\n * The validated credential request. If both `format` and `credentialIdentifier` are\n * undefined you can still handle the request by using this object directly.\n */\n deferredCredentialRequest: DeferredCredentialRequest\n}\n\nexport function parseDeferredCredentialRequest(\n options: ParseDeferredCredentialRequestOptions\n): ParseDeferredCredentialRequestReturn {\n const deferredCredentialRequest = parseWithErrorHandling(\n zDeferredCredentialRequest,\n options.deferredCredentialRequest,\n 'Error validating credential request'\n )\n\n return {\n deferredCredentialRequest,\n }\n}\n","import {\n type CreateKeyAttestationJwtOptions,\n createKeyAttestationJwt,\n type VerifyKeyAttestationJwtOptions,\n verifyKeyAttestationJwt,\n} from '../../../key-attestation/key-attestation'\n\nexport interface CreateCredentialRequestAttestationProofOptions extends Omit<CreateKeyAttestationJwtOptions, 'use'> {\n /**\n * Nonce to use in the attestation. Should be derived from the c_nonce\n *\n * Required because the attestation is created for 'attestation' proof types\n */\n nonce: string\n\n /**\n * The date when the key attestation will expire.\n */\n expiresAt: Date\n}\n\nexport async function createCredentialRequestAttestationProof(\n options: CreateCredentialRequestAttestationProofOptions\n): Promise<string> {\n return createKeyAttestationJwt({\n ...options,\n use: 'proof_type.attestation',\n })\n}\n\nexport interface VerifyCredentialRequestAttestationProofOptions extends Omit<VerifyKeyAttestationJwtOptions, 'use'> {}\nexport async function verifyCredentialRequestAttestationProof(options: VerifyCredentialRequestAttestationProofOptions) {\n const verificationResult = await verifyKeyAttestationJwt({\n ...options,\n use: 'proof_type.attestation',\n })\n\n return verificationResult\n}\n","import { type CallbackContext, type JwtSigner, jwtHeaderFromJwtSigner } from '@openid4vc/oauth2'\nimport { dateToSeconds, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CredentialIssuerMetadata } from './z-credential-issuer-metadata'\nimport {\n type SignedCredentialIssuerMetadataHeader,\n type SignedCredentialIssuerMetadataPayload,\n zSignedCredentialIssuerMetadataHeader,\n zSignedCredentialIssuerMetadataPayload,\n} from './z-signed-credential-issuer-metadata'\n\nexport interface CreateSignedCredentialIssuerMetadataJwtOptions {\n /**\n * The credential issuer metadata to include in the jwt\n */\n credentialIssuerMetadata: CredentialIssuerMetadata\n\n /**\n * The date when the credential issuer metadata was issued. If not provided the current time will be used.\n */\n issuedAt?: Date\n\n /**\n * The date when the credential issuer metadata will expire.\n */\n expiresAt?: Date\n\n /**\n * Signer of the credential issuer metadata jwt\n */\n signer: JwtSigner\n\n /**\n * The issuer of the issuer metadata jwt. This field is optional\n */\n issuer?: string\n\n /**\n * Callbacks used for creating the credential issuer metadata jwt\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n\n /**\n * Additional payload to include in the credential issuer metadata jwt payload. Will be applied after\n * any default claims that are included, so add claims with caution.\n */\n additionalPayload?: Record<string, unknown>\n}\n\nexport async function createSignedCredentialIssuerMetadataJwt(\n options: CreateSignedCredentialIssuerMetadataJwtOptions\n): Promise<string> {\n const header = parseWithErrorHandling(zSignedCredentialIssuerMetadataHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: 'openidvci-issuer-metadata+jwt',\n } satisfies SignedCredentialIssuerMetadataHeader)\n\n const payload = parseWithErrorHandling(zSignedCredentialIssuerMetadataPayload, {\n ...options.credentialIssuerMetadata,\n sub: options.credentialIssuerMetadata.credential_issuer,\n iat: dateToSeconds(options.issuedAt),\n exp: options.expiresAt ? dateToSeconds(options.expiresAt) : undefined,\n iss: options.issuer,\n ...options.additionalPayload,\n } satisfies SignedCredentialIssuerMetadataPayload)\n\n const { jwt } = await options.callbacks.signJwt(options.signer, { header, payload })\n return jwt\n}\n","import {\n type CallbackContext,\n Oauth2AuthorizationServer,\n Oauth2ErrorCodes,\n Oauth2JwtVerificationError,\n Oauth2ServerErrorResponseError,\n} from '@openid4vc/oauth2'\nimport { parseWithErrorHandling, ValidationError } from '@openid4vc/utils'\nimport type { VerifyClientAttestationOptions } from '../../oauth2/src/client-attestation/client-attestation'\nimport { type CreateCredentialOfferOptions, createCredentialOffer } from './credential-offer/credential-offer'\nimport {\n type CreateCredentialResponseOptions,\n type CreateDeferredCredentialResponseOptions,\n createCredentialResponse,\n createDeferredCredentialResponse,\n} from './credential-request/credential-response'\nimport {\n type ParseCredentialRequestOptions,\n type ParseCredentialRequestReturn,\n parseCredentialRequest,\n} from './credential-request/parse-credential-request'\nimport {\n type ParseDeferredCredentialRequestOptions,\n type ParseDeferredCredentialRequestReturn,\n parseDeferredCredentialRequest,\n} from './credential-request/parse-deferred-credential-request'\nimport { Openid4vciError } from './error/Openid4vciError'\nimport {\n type VerifyCredentialRequestAttestationProofOptions,\n verifyCredentialRequestAttestationProof,\n} from './formats/proof-type/attestation/attestation-proof-type'\nimport {\n type VerifyCredentialRequestJwtProofOptions,\n verifyCredentialRequestJwtProof,\n} from './formats/proof-type/jwt/jwt-proof-type'\nimport { extractKnownCredentialConfigurationSupportedFormats } from './metadata/credential-issuer/credential-issuer-metadata'\nimport {\n type CreateSignedCredentialIssuerMetadataJwtOptions,\n createSignedCredentialIssuerMetadataJwt,\n} from './metadata/credential-issuer/signed-credential-issuer-metadata'\nimport {\n type CredentialIssuerMetadata,\n zCredentialIssuerMetadata,\n zCredentialIssuerMetadataWithDraft11,\n} from './metadata/credential-issuer/z-credential-issuer-metadata'\nimport type { IssuerMetadataResult } from './metadata/fetch-issuer-metadata'\nimport { type CreateNonceResponseOptions, createNonceResponse } from './nonce/nonce-request'\n\nexport interface Openid4vciIssuerOptions {\n /**\n * Callbacks required for the openid4vc issuer\n */\n callbacks: Omit<CallbackContext, 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Openid4vciIssuer {\n public constructor(private options: Openid4vciIssuerOptions) {}\n\n public getCredentialIssuerMetadataDraft11(credentialIssuerMetadata: CredentialIssuerMetadata) {\n return parseWithErrorHandling(zCredentialIssuerMetadataWithDraft11, credentialIssuerMetadata)\n }\n\n public getKnownCredentialConfigurationsSupported(credentialIssuerMetadata: CredentialIssuerMetadata) {\n return extractKnownCredentialConfigurationSupportedFormats(\n credentialIssuerMetadata.credential_configurations_supported\n )\n }\n\n /**\n * Create issuer metadata and validates the structure is correct\n */\n public createCredentialIssuerMetadata(credentialIssuerMetadata: CredentialIssuerMetadata): CredentialIssuerMetadata {\n return parseWithErrorHandling(\n zCredentialIssuerMetadata,\n credentialIssuerMetadata,\n 'Error validating credential issuer metadata'\n )\n }\n\n /**\n * Validates credential issuer metadata structure is correct and creates signed credential issuer metadata JWT\n */\n public createSignedCredentialIssuerMetadataJwt(\n options: Omit<CreateSignedCredentialIssuerMetadataJwtOptions, 'callbacks'>\n ): Promise<string> {\n return createSignedCredentialIssuerMetadataJwt({\n callbacks: this.options.callbacks,\n ...options,\n })\n }\n\n public async createCredentialOffer(\n options: Pick<\n CreateCredentialOfferOptions,\n | 'issuerMetadata'\n | 'additionalPayload'\n | 'grants'\n | 'credentialOfferUri'\n | 'credentialOfferScheme'\n | 'credentialConfigurationIds'\n >\n ) {\n return createCredentialOffer({\n callbacks: this.options.callbacks,\n credentialConfigurationIds: options.credentialConfigurationIds,\n grants: options.grants,\n issuerMetadata: options.issuerMetadata,\n additionalPayload: options.additionalPayload,\n credentialOfferScheme: options.credentialOfferScheme,\n credentialOfferUri: options.credentialOfferUri,\n })\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - if verification of the jwt failed. You can extract\n * the credential error response from this.\n */\n public async verifyCredentialRequestJwtProof(\n options: Pick<\n VerifyCredentialRequestJwtProofOptions,\n 'clientId' | 'jwt' | 'now' | 'expectedNonce' | 'nonceExpiresAt'\n > & {\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n try {\n return await verifyCredentialRequestJwtProof({\n callbacks: this.options.callbacks,\n credentialIssuer: options.issuerMetadata.credentialIssuer.credential_issuer,\n expectedNonce: options.expectedNonce,\n nonceExpiresAt: options.nonceExpiresAt,\n jwt: options.jwt,\n clientId: options.clientId,\n now: options.now,\n })\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidProof,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError\n ? error.message\n : 'Invalid proof',\n },\n\n {\n internalMessage: 'Error verifying credential request proof jwt',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - if verification of the key attestation failed. You can extract\n * the credential error response from this.\n */\n public async verifyCredentialRequestAttestationProof(\n options: Pick<\n VerifyCredentialRequestAttestationProofOptions,\n 'keyAttestationJwt' | 'expectedNonce' | 'nonceExpiresAt' | 'now'\n > & {\n issuerMetadata: IssuerMetadataResult\n }\n ) {\n try {\n return await verifyCredentialRequestAttestationProof({\n callbacks: this.options.callbacks,\n expectedNonce: options.expectedNonce,\n keyAttestationJwt: options.keyAttestationJwt,\n nonceExpiresAt: options.nonceExpiresAt,\n now: options.now,\n })\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidProof,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof Oauth2JwtVerificationError || error instanceof Openid4vciError\n ? error.message\n : 'Invalid proof',\n },\n\n {\n internalMessage: 'Error verifying credential request proof attestation',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - when validation of the credential request fails\n * You can extract the credential error response from this.\n */\n public parseCredentialRequest(options: ParseCredentialRequestOptions): ParseCredentialRequestReturn {\n try {\n // TODO: method should include reason for parsing - (e.g. unsupported format etc..)\n return parseCredentialRequest(options)\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidCredentialRequest,\n error_description:\n // TODO: error should have a internalErrorMessage and a publicErrorMessage\n error instanceof ValidationError ? error.message : 'Invalid request',\n },\n {\n internalMessage: 'Error verifying credential request proof jwt',\n cause: error,\n }\n )\n }\n\n // TODO: might be nice to add some extra validation params here so it's\n // easy for an issuer to verify whether the request matches with the configuration\n // e.g. alg of holder binding, key_attestations_required, proof_types_supported,\n // request matches offer, etc..\n }\n\n /**\n * @throws Oauth2ServerErrorResponseError - when validation of the deferred credential request fails\n */\n public parseDeferredCredentialRequest(\n options: ParseDeferredCredentialRequestOptions\n ): ParseDeferredCredentialRequestReturn {\n try {\n return parseDeferredCredentialRequest(options)\n } catch (error) {\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidCredentialRequest,\n error_description: error instanceof ValidationError ? error.message : 'Invalid request',\n },\n {\n internalMessage: 'Error parsing deferred credential request',\n cause: error,\n }\n )\n }\n }\n\n /**\n * @throws ValidationError - when validation of the credential response fails\n */\n public createCredentialResponse(options: CreateCredentialResponseOptions) {\n return createCredentialResponse(options)\n }\n\n /**\n * @throws ValidationError - when validation of the credential response fails\n */\n public createDeferredCredentialResponse(options: CreateDeferredCredentialResponseOptions) {\n return createDeferredCredentialResponse(options)\n }\n\n /**\n * @throws ValidationError - when validation of the nonce response fails\n */\n public createNonceResponse(options: CreateNonceResponseOptions) {\n return createNonceResponse(options)\n }\n\n public async verifyWalletAttestation(options: Omit<VerifyClientAttestationOptions, 'callbacks'>) {\n return new Oauth2AuthorizationServer({\n callbacks: this.options.callbacks,\n }).verifyClientAttestation(options)\n }\n}\n","import {\n type CallbackContext,\n type CreateClientAttestationJwtOptions,\n createClientAttestationJwt,\n} from '@openid4vc/oauth2'\nimport { type CreateKeyAttestationJwtOptions, createKeyAttestationJwt } from './key-attestation/key-attestation'\n\nexport interface Openid4vciWalletProviderOptions {\n /**\n * Callbacks required for the openid4vc issuer\n */\n callbacks: Pick<CallbackContext, 'signJwt'>\n}\n\nexport class Openid4vciWalletProvider {\n public constructor(private options: Openid4vciWalletProviderOptions) {}\n\n public async createWalletAttestationJwt(\n options: Omit<CreateClientAttestationJwtOptions, 'callbacks'> & { walletName?: string; walletLink?: string }\n ) {\n const additionalPayload = options.additionalPayload\n ? {\n wallet_name: options.walletName,\n wallet_link: options.walletLink,\n ...options.additionalPayload,\n }\n : {\n wallet_name: options.walletName,\n wallet_link: options.walletLink,\n }\n\n return await createClientAttestationJwt({\n ...options,\n callbacks: this.options.callbacks,\n additionalPayload,\n })\n }\n\n public async createKeyAttestationJwt(options: Omit<CreateKeyAttestationJwtOptions, 'callbacks'>) {\n return await createKeyAttestationJwt({\n callbacks: this.options.callbacks,\n ...options,\n })\n }\n}\n"],"mappings":";;;;;AAAA,IAAY,kEAAL;AACL;AACA;AACA;AACA;;;;;;AAMF,MAAa,yBAAyB;;;;ACFtC,MAAM,UAAU,EACb,OAAO;CACN,YAAY,EAAE,MAAM,CAAC,EAAE,QAAQ,UAAU,EAAE,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC,UAAU;CACzE,QAAQ,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;CACnC,aAAa,EAAE,QAAQ,CAAC,IAAI,IAAI,CAAC,UAAU;CAC5C,CAAC,CACD,OAAO;AAIV,MAAa,yBAAyB,EACnC,OAAO;CACN,oBAAoB,EACjB,OAAO;EACN,cAAc,EAAE,QAAQ,CAAC,UAAU;EACnC,sBAAsB,UAAU,UAAU;EAC3C,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