@pagopa/io-wallet-oid4vci 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +56 -26
- package/dist/index.d.ts +56 -26
- package/dist/index.js +194 -133
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +144 -79
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/authorization-response/complete-authorization.ts","../src/errors.ts","../src/authorization-response/verify-authorization-response.ts","../src/authorization-response/z-authorization-response.ts","../src/credential-offer/extract-grant-details.ts","../src/credential-offer/z-credential-offer.ts","../src/credential-offer/parse-credential-offer-uri.ts","../src/credential-offer/resolve-credential-offer.ts","../src/credential-offer/validate-credential-offer.ts","../src/credential-request/create-credential-request.ts","../src/credential-request/v1.0/create-credential-request.ts","../src/credential-request/v1.0/z-credential.ts","../src/credential-request/z-base-credential-request.ts","../src/credential-request/v1.3/create-credential-request.ts","../src/credential-request/v1.3/z-credential.ts","../src/credential-request/parse-credential-request.ts","../src/credential-request/z-proof-jwt.ts","../src/credential-request/verify-credential-request-jwt-proof.ts","../src/credential-request/verify-key-attestation-jwt.ts","../src/wallet-provider/z-key-attestation.ts","../src/credential-response/create-credential-response.ts","../src/credential-response/v1.0/create-credential-response.ts","../src/credential-response/v1.0/z-credential-response.ts","../src/credential-response/z-immediate-credential-response.ts","../src/credential-response/v1.3/create-credential-response.ts","../src/credential-response/v1.3/z-credential-response.ts","../src/credential-response/fetch-credential-response.ts","../src/credential-response/z-credential-response.ts","../src/metadata/fetch-metadata.ts","../src/metadata/z-metadata-response.ts","../src/wallet-provider/WalletProvider.ts"],"sourcesContent":["export * from \"./authorization-response\";\nexport * from \"./credential-offer\";\nexport * from \"./credential-request\";\nexport * from \"./credential-response\";\nexport * from \"./errors\";\nexport * from \"./metadata\";\nexport * from \"./wallet-provider\";\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { getJwtFromFormPost } from \"@pagopa/io-wallet-oauth2\";\nimport {\n FetchAuthorizationResponseOptions,\n fetchAuthorizationResponse,\n} from \"@pagopa/io-wallet-oid4vp\";\nimport {\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../errors\";\nimport {\n VerifyAuthorizationResponseFormPostJWTOptions,\n verifyAuthorizationResponseFormPostJWT,\n} from \"./verify-authorization-response\";\nimport {\n AuthorizationResponse,\n zAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface CompleteAuthorizationOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The response_uri returned by the server after a successful\n * OID4VP Authorization Response is sent\n */\n response_uri: string;\n}\n\n/**\n * Combination of {@link CompleteAuthorizationOptions},\n * {@link FetchAuthorizationResponseOptions} and\n * {@link VerifyAuthorizationResponseFormPostJWTOptions}\n */\nexport type SendAuthorizationResponseAndExtractCodeOptions =\n FetchAuthorizationResponseOptions &\n Omit<\n VerifyAuthorizationResponseFormPostJWTOptions,\n \"authorizationResponseCompact\" | \"authorizationResponseDecoded\"\n > &\n Omit<CompleteAuthorizationOptions, \"response_uri\">;\n\nexport type CompleteAuthorizationResult = Awaited<\n ReturnType<typeof getJwtFromFormPost<AuthorizationResponse>>\n>;\n\n/**\n * Method that completes the form_post.jwt based authorization\n * process for credentials issuance following the ITWallet\n * specification by retrieving the form from the provided uri,\n * extracting and parsing the contained JWT and verifying the\n * iss and state fields match the authorization session's expected\n * values.\n * See https://italia.github.io/eid-wallet-it-docs/versione-corrente/en/credential-issuance-low-level.html#\n * steps 6-7 for details.\n *\n * @param options {@link CompleteAuthorizationOptions}\n * @returns An object containing the fetched JWT and its decoding. The JWT contains the access code\n * necessary for access token issuance\n */\nexport async function completeAuthorization(\n options: CompleteAuthorizationOptions,\n): Promise<CompleteAuthorizationResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const authorizationResponseResult = await fetch(options.response_uri);\n\n await hasStatusOrThrow(\n 200,\n UnexpectedStatusCodeError,\n )(authorizationResponseResult);\n\n return await getJwtFromFormPost({\n formData: await authorizationResponseResult.text(),\n schema: zAuthorizationResponse,\n });\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error completing the authorization process: ${error instanceof Error ? `${error.name} : ${error.message}` : String(error)}`,\n );\n }\n}\n\n/**\n * Convenience method that combines {@link completeAuthorization},\n * oid4vp package's {@link fetchAuthorizationResponse} and {@link verifyAuthorizationResponseFormPostJWT} to retrieve the\n * access code starting from the authorization response and the response uri\n *\n * @param options {@link SendAuthorizationResponseAndExtractCodeOptions}\n * @returns An object containing the fetched JWT and its decoding. The JWT contains the access code\n * for necessary for access token issuance\n */\nexport async function sendAuthorizationResponseAndExtractCode(\n options: SendAuthorizationResponseAndExtractCodeOptions,\n): Promise<AuthorizationResponse> {\n try {\n const authorizationResult = await fetchAuthorizationResponse(options);\n\n if (!authorizationResult.redirect_uri) {\n throw new Oid4vciError(\n \"The authorization response did not contain a redirect_uri\",\n );\n }\n\n const jwtAndPayload = await completeAuthorization({\n ...options,\n response_uri: authorizationResult.redirect_uri,\n });\n\n return verifyAuthorizationResponseFormPostJWT({\n authorizationResponseCompact: jwtAndPayload.jwt,\n authorizationResponseDecoded: jwtAndPayload.decodedJwt,\n callbacks: {\n verifyJwt: options.callbacks.verifyJwt,\n },\n iss: options.iss,\n signer: options.signer,\n state: options.state,\n });\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error sending the authorization response and retrieving the acces code: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","/**\n * Generic error thrown on Oid4vci operations\n */\nexport class Oid4vciError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oid4vciError\";\n }\n}\n\n/**\n * Error thrown in case the DPoP key passed to the\n * {@link WalletProvider.createItWalletAttestationJwt} method\n * doesn't contain a kid\n */\nexport class WalletProviderError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"WalletProviderError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during nonce request.\n */\nexport class NonceRequestError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"NonceRequestError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential response fetching.\n */\nexport class FetchCredentialResponseError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"FetchCredentialResponseError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential request parsing.\n */\nexport class ParseCredentialRequestError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"ParseCredentialRequestError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when metadata fetching fails at all discovery endpoints.\n */\nexport class FetchMetadataError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.cause = cause;\n this.name = \"FetchMetadataError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential response creation.\n */\nexport class CreateCredentialResponseError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"CreateCredentialResponseError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential request JWT proof verification.\n */\nexport class VerifyCredentialRequestJwtProofError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"VerifyCredentialRequestJwtProofError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when an error occurs during key attestation JWT verification.\n */\nexport class VerifyKeyAttestationJwtError extends Oid4vciError {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"VerifyKeyAttestationJwtError\";\n this.cause = cause;\n }\n}\n\n/**\n * Error thrown when an error occurs during credential offer operations.\n * This includes parsing, resolving, validating, and extracting grant details from credential offers.\n */\nexport class CredentialOfferError extends Oid4vciError {\n constructor(message: string, statusCode?: number) {\n super(message, statusCode);\n this.name = \"CredentialOfferError\";\n }\n}\n\n/**\n * Error thrown when a credential request is missing the required DPoP proof header.\n */\nexport class MissingDpopProofError extends Oid4vciError {\n constructor(\n message = \"Credential request is missing required 'DPoP' proof header\",\n ) {\n super(message);\n this.name = \"MissingDpopProofError\";\n }\n}\n\n/**\n * Error thrown when a credential request has a missing or invalid Authorization header.\n */\nexport class CredentialAuthorizationHeaderError extends Oid4vciError {\n constructor(\n message = \"Credential request is missing required 'Authorization' header with DPoP scheme\",\n ) {\n super(message);\n this.name = \"CredentialAuthorizationHeaderError\";\n }\n}\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\n\nimport { Oid4vciError } from \"../errors\";\nimport {\n AuthorizationResponse,\n zAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface VerifyAuthorizationResponseOptions {\n /**\n * Authorization response object containing the authorization\n * code, the issuer and the session's state\n */\n authorizationResponse: AuthorizationResponse;\n\n /**\n * The issuer the Wallet Instance started the\n * authorization flow (either via PAR or directly) with\n */\n iss: string;\n\n /**\n * The state sent by the Wallet Instance at the start\n * of the authorization flow (either via PAR or directly)\n */\n state: string;\n}\n\nexport interface VerifyAuthorizationResponseFormPostJWTOptions {\n /**\n * Compact AuthorizaitonResponse JWT\n */\n authorizationResponseCompact: string;\n\n /**\n * Authorization Response object containing the authorization\n * code, the issuer and the session's state\n */\n authorizationResponseDecoded: ReturnType<\n typeof decodeJwt<undefined, typeof zAuthorizationResponse>\n >;\n\n /**\n * Callback for verifying the authorization jwt signature\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The issuer the Wallet Instance started the\n * authorization flow (either via PAR or directly) with\n */\n iss: string;\n\n /**\n * Optional custom signer for verifying the authorization response JWT.\n * If not provided, the library will attempt to verify using information from the JWT header.\n */\n signer?: JwtSigner;\n\n /**\n * The state sent by the Wallet Instance at the start\n * of the authorization flow (either via PAR or directly)\n */\n state: string;\n}\n\n/**\n * Utility that verifies if the returned Authorization Response's iss and state field match\n * the Authorization Session ones\n * @param options {@link VerifyAuthorizationResponseOptions}\n * @returns the {@link AuthorizationResponse} passed as an option\n * @throws {Oid4vciError} in case the iss or state field of the Authorization request don't\n * match the provided ones\n */\nexport async function verifyAuthorizationResponse(\n options: VerifyAuthorizationResponseOptions,\n): Promise<AuthorizationResponse> {\n if (options.authorizationResponse.iss !== options.iss)\n throw new Oid4vciError(\n `Response result iss doesn't match passed counterpart. Expected: ${options.iss}, Got: ${options.authorizationResponse.iss}`,\n );\n if (options.authorizationResponse.state !== options.state)\n throw new Oid4vciError(\n `Response result state doesn't match passed counterpart. Expected: ${options.state}, Got: ${options.authorizationResponse.state}`,\n );\n\n return options.authorizationResponse;\n}\n\n/**\n * Wrapper of {@link verifyAuthorizationResponse} that verifies the signature of the JWT containing\n * the authorization response and extracts the {@link AuthorizationResponse} payload\n * @param options {@link VerifyAuthorizationResponseFormPostJWTOptions}\n * @returns the {@link AuthorizationResponse} passed as an option\n * @throws {Oid4vciError} in case {@link verifyAuthorizationResponse} throws or in case\n * signature verification fails\n */\nexport async function verifyAuthorizationResponseFormPostJWT(\n options: VerifyAuthorizationResponseFormPostJWTOptions,\n): Promise<AuthorizationResponse> {\n try {\n const decodedJwt = options.authorizationResponseDecoded;\n\n await verifyJwt({\n compact: options.authorizationResponseCompact,\n errorMessage: \"Error verifying JWT signature\",\n header: decodedJwt.header,\n payload: decodedJwt.payload,\n\n signer:\n options.signer ??\n jwtSignerFromJwt({\n header: decodedJwt.header,\n payload: decodedJwt.payload,\n }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return verifyAuthorizationResponse({\n authorizationResponse: options.authorizationResponseDecoded.payload,\n iss: options.iss,\n state: options.state,\n });\n } catch (error) {\n if (error instanceof Oid4vciError) throw error;\n\n throw new Oid4vciError(\n `Unexpected error verifying form post jwt: ${error instanceof Error ? `${error.name} : ${error.message}` : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\nexport const zAuthorizationResponse = z.object({\n code: z.string(),\n iss: z.string(),\n state: z.string(),\n});\n\nexport type AuthorizationResponse = z.infer<typeof zAuthorizationResponse>;\n","import type { ExtractGrantDetailsResult } from \"./types\";\nimport type { CredentialOffer } from \"./z-credential-offer\";\n\nimport { CredentialOfferError } from \"../errors\";\n\n/**\n * Extracts grant details from a credential offer.\n *\n * IT-Wallet v1.3 only supports the `authorization_code` grant type.\n * Pre-authorized code grants are NOT supported.\n *\n * This function extracts:\n * - Grant type (always \"authorization_code\" for IT-Wallet)\n * - Scope (REQUIRED)\n * - Authorization server (OPTIONAL, but REQUIRED when CI uses multiple auth servers)\n * - Issuer state (OPTIONAL)\n *\n * @param credentialOffer - The credential offer to extract grant details from\n * @returns Grant details containing the grant type and authorization code grant information\n * @throws {CredentialOfferError} If grants or authorization_code grant is missing\n */\nexport function extractGrantDetails(\n credentialOffer: CredentialOffer,\n): ExtractGrantDetailsResult {\n if (!credentialOffer.grants) {\n throw new CredentialOfferError(\"No grants found in credential offer\");\n }\n\n const authCodeGrant = credentialOffer.grants.authorization_code;\n\n if (!authCodeGrant) {\n throw new CredentialOfferError(\"authorization_code grant not found\");\n }\n\n return {\n authorizationCodeGrant: {\n authorizationServer: authCodeGrant.authorization_server,\n issuerState: authCodeGrant.issuer_state,\n scope: authCodeGrant.scope,\n },\n grantType: \"authorization_code\",\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Authorization Code Grant schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * The authorization_code grant is REQUIRED for IT-Wallet v1.3.\n * Pre-authorized code grant is NOT supported.\n */\nexport const zAuthorizationCodeGrant = z.object({\n /**\n * CONDITIONALLY REQUIRED. HTTPS URL of the Authorization Server.\n * REQUIRED only when the Credential Issuer uses multiple Authorization Servers.\n * If present, MUST match one of the authorization_servers in the Credential Issuer metadata.\n */\n authorization_server: z.url().optional(),\n\n /**\n * OPTIONAL. String value representing the issuer state.\n * Used to correlate the authorization request with the credential offer.\n */\n issuer_state: z.string().optional(),\n\n /**\n * REQUIRED. OAuth 2.0 scope value.\n * Defines the scope of access requested by the credential offer.\n */\n scope: z.string(),\n});\n\n/**\n * Credential Offer Grants schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * The grants object is REQUIRED for IT-Wallet v1.3.\n * Only authorization_code grant is supported.\n */\nexport const zCredentialOfferGrants = z.object({\n /**\n * REQUIRED. Authorization Code grant details.\n * IT-Wallet v1.3 only supports authorization_code grant.\n */\n authorization_code: zAuthorizationCodeGrant,\n});\n\n/**\n * Credential Offer schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * Represents a credential offer from a Credential Issuer to a wallet.\n */\nexport const zCredentialOffer = z.object({\n /**\n * REQUIRED. Array of credential configuration identifiers.\n * References the types of credentials offered as defined in the Credential Issuer metadata.\n */\n credential_configuration_ids: z.array(z.string()).min(1),\n\n /**\n * REQUIRED. HTTPS URL of the Credential Issuer.\n * The Credential Issuer from which the wallet will request credentials.\n */\n credential_issuer: z.url(),\n\n /**\n * REQUIRED. Grant information for the credential offer.\n * IT-Wallet v1.3 requires authorization_code grant.\n */\n grants: zCredentialOfferGrants,\n});\n\n/**\n * Credential Offer URI schema\n * Represents a parsed credential offer URI with scheme and parameters.\n *\n * Supports three URL schemes:\n * - openid-credential-offer:// - Standard OpenID scheme (custom URL scheme)\n * - haip-vci:// - High Assurance Interoperability Profile scheme (custom URL scheme)\n * - https:// - HTTPS Universal Links (preferred method)\n *\n * Transmission methods:\n * - By value: credential_offer parameter contains the JSON directly\n * - By reference: credential_offer_uri parameter points to the JSON\n */\nexport const zCredentialOfferUri = z\n .object({\n /**\n * OPTIONAL. Inline credential offer JSON (by value).\n * URL-encoded JSON string containing the credential offer.\n */\n credential_offer: z.string().optional(),\n\n /**\n * OPTIONAL. URL pointing to the credential offer JSON (by reference).\n * HTTPS URL where the credential offer can be fetched.\n */\n credential_offer_uri: z.url().optional(),\n\n /**\n * URL scheme used for the credential offer.\n * Determines the invocation method.\n */\n scheme: z.enum([\"openid-credential-offer\", \"haip-vci\", \"https\"]),\n })\n .refine((data) => data.credential_offer || data.credential_offer_uri, {\n message: \"Either credential_offer or credential_offer_uri must be present\",\n });\n\n/**\n * TypeScript type for Authorization Code Grant\n */\nexport type AuthorizationCodeGrant = z.infer<typeof zAuthorizationCodeGrant>;\n\n/**\n * TypeScript type for Credential Offer Grants\n */\nexport type CredentialOfferGrants = z.infer<typeof zCredentialOfferGrants>;\n\n/**\n * TypeScript type for Credential Offer\n */\nexport type CredentialOffer = z.infer<typeof zCredentialOffer>;\n\n/**\n * TypeScript type for Credential Offer URI\n */\nexport type CredentialOfferUri = z.infer<typeof zCredentialOfferUri>;\n","import type { ParseCredentialOfferUriOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\nimport {\n type CredentialOfferUri,\n zCredentialOfferUri,\n} from \"./z-credential-offer\";\n\n/**\n * Parses a credential offer URI and extracts the scheme and parameters.\n *\n * This function supports three URL schemes for credential offers:\n * - `openid-credential-offer://` - Standard OpenID scheme (custom URL scheme)\n * - `haip-vci://` - High Assurance Interoperability Profile scheme (custom URL scheme)\n * - `https://` - HTTPS Universal Links (preferred method)\n *\n * Credential offers can be transmitted in two ways:\n * - **By value**: The `credential_offer` parameter contains the JSON directly (URL-encoded)\n * - **By reference**: The `credential_offer_uri` parameter points to a URL where the JSON can be fetched\n *\n * @param options - Parsing options containing the URI and allowed schemes\n * @returns Parsed credential offer URI components with scheme and parameters\n * @throws {CredentialOfferError} If the URI is invalid, uses an unsupported scheme, or is missing required parameters\n *\n * @example Parse by-value offer with custom scheme\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"openid-credential-offer://?credential_offer=%7B%22credential_issuer%22%3A...\"\n * });\n * console.log(parsed.scheme); // \"openid-credential-offer\"\n * console.log(parsed.credential_offer); // URL-decoded JSON string\n * ```\n *\n * @example Parse by-reference offer with HTTPS Universal Link\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"https://wallet.example.com/credential-offer?credential_offer_uri=https://issuer.example.com/offers/123\"\n * });\n * console.log(parsed.scheme); // \"https\"\n * console.log(parsed.credential_offer_uri); // \"https://issuer.example.com/offers/123\"\n * ```\n *\n * @example Restrict allowed schemes\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"openid-credential-offer://?credential_offer=...\",\n * allowedSchemes: [\"openid-credential-offer\"] // Only allow standard OpenID scheme\n * });\n * ```\n */\nexport async function parseCredentialOfferUri(\n options: ParseCredentialOfferUriOptions,\n): Promise<CredentialOfferUri> {\n const {\n allowedSchemes = [\"openid-credential-offer\", \"haip-vci\", \"https\"],\n uri,\n } = options;\n\n try {\n // Parse the URI using the URL API\n const url = new URL(uri);\n\n // Extract and validate the scheme (protocol without the trailing colon)\n const scheme = url.protocol.replace(\":\", \"\");\n\n if (!allowedSchemes.includes(scheme)) {\n throw new CredentialOfferError(\n `Unsupported URL scheme: ${scheme}. Allowed schemes: ${allowedSchemes.join(\", \")}`,\n );\n }\n\n // Extract query parameters\n const credentialOffer = url.searchParams.get(\"credential_offer\");\n const credentialOfferUri = url.searchParams.get(\"credential_offer_uri\");\n\n // Construct the parsed result\n const parsed = {\n credential_offer: credentialOffer || undefined,\n credential_offer_uri: credentialOfferUri || undefined,\n scheme: scheme as \"haip-vci\" | \"https\" | \"openid-credential-offer\",\n };\n\n // Validate the structure using Zod\n // This will ensure that at least one of credential_offer or credential_offer_uri is present\n return zCredentialOfferUri.parse(parsed);\n } catch (error) {\n // Re-throw CredentialOfferError as-is\n if (error instanceof CredentialOfferError) {\n throw error;\n }\n\n // Wrap other errors in CredentialOfferError\n throw new CredentialOfferError(\n `Failed to parse credential offer URI: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import {\n UnexpectedStatusCodeError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { ResolveCredentialOfferOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\nimport { parseCredentialOfferUri } from \"./parse-credential-offer-uri\";\nimport { type CredentialOffer, zCredentialOffer } from \"./z-credential-offer\";\n\n/**\n * Resolves a credential offer from a URI or inline JSON string.\n *\n * This function handles multiple input formats:\n * - **URI with inline offer** (by value): The credential offer JSON is embedded in the URI as a URL-encoded parameter\n * - **URI with reference** (by reference): The URI points to a remote endpoint where the credential offer can be fetched\n * - **Direct JSON string**: The credential offer is provided as a plain JSON string\n *\n * Supported URI schemes:\n * - `openid-credential-offer://` - Standard OpenID scheme\n * - `haip-vci://` - High Assurance Interoperability Profile scheme\n * - `https://` - HTTPS Universal Links (preferred)\n *\n * @param options - Resolution options containing the credential offer and fetch callback\n * @returns Resolved and validated credential offer object\n * @throws {CredentialOfferError} If parsing fails, HTTP request fails, or validation fails\n *\n * @example Resolve by-value offer (inline JSON in URI)\n * ```typescript\n * const offer = await resolveCredentialOffer({\n * credentialOffer: \"openid-credential-offer://?credential_offer=%7B%22credential_issuer%22%3A...\",\n * callbacks: { fetch }\n * });\n * console.log(offer.credential_issuer);\n * ```\n *\n * @example Resolve by-reference offer (fetch from remote URI)\n * ```typescript\n * const offer = await resolveCredentialOffer({\n * credentialOffer: \"openid-credential-offer://?credential_offer_uri=https://issuer.example.com/offers/123\",\n * callbacks: { fetch }\n * });\n * console.log(offer.grants.authorization_code.scope);\n * ```\n *\n * @example Resolve from direct JSON string\n * ```typescript\n * const offerJson = '{\"credential_issuer\":\"https://issuer.example.com\",\"credential_configuration_ids\":[\"UniversityDegree\"],\"grants\":{\"authorization_code\":{\"scope\":\"openid\"}}}';\n * const offer = await resolveCredentialOffer({\n * credentialOffer: offerJson,\n * callbacks: { fetch }\n * });\n * ```\n */\nexport async function resolveCredentialOffer(\n options: ResolveCredentialOfferOptions,\n): Promise<CredentialOffer> {\n const { callbacks, credentialOffer } = options;\n\n try {\n // Check if the input is a URI (starts with a known scheme)\n if (\n credentialOffer.startsWith(\"openid-credential-offer://\") ||\n credentialOffer.startsWith(\"haip-vci://\") ||\n credentialOffer.startsWith(\"https://\")\n ) {\n // Parse the URI to extract the scheme and parameters\n const parsed = await parseCredentialOfferUri({ uri: credentialOffer });\n\n // By value - inline credential offer\n if (parsed.credential_offer) {\n const decoded = decodeURIComponent(parsed.credential_offer);\n const offerJson = JSON.parse(decoded);\n return zCredentialOffer.parse(offerJson);\n }\n\n // By reference - fetch from remote URI\n if (parsed.credential_offer_uri) {\n const fetch = createFetcher(callbacks.fetch);\n\n const response = await fetch(parsed.credential_offer_uri, {\n headers: {\n Accept: \"application/json\",\n },\n method: \"GET\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(response);\n\n const offerJson = await response.json();\n return zCredentialOffer.parse(offerJson);\n }\n }\n\n // Assume it's a direct JSON string\n const offerJson = JSON.parse(credentialOffer);\n return zCredentialOffer.parse(offerJson);\n } catch (error) {\n // Re-throw CredentialOfferError and UnexpectedStatusCodeError as-is\n if (\n error instanceof CredentialOfferError ||\n error instanceof UnexpectedStatusCodeError\n ) {\n throw error;\n }\n\n // Wrap other errors in CredentialOfferError\n throw new CredentialOfferError(\n `Failed to resolve credential offer: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type { ValidateCredentialOfferOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\n\n/**\n * Validates a credential offer against IT-Wallet v1.3 specifications.\n *\n * This function performs comprehensive validation of a credential offer to ensure\n * compliance with the IT-Wallet v1.3 requirements (Section 5.1):\n *\n * **Required validations:**\n * - `credential_issuer` must be an HTTPS URL\n * - `credential_configuration_ids` must contain at least one identifier\n * - `grants` object is REQUIRED for IT-Wallet v1.3\n * - `authorization_code` grant is REQUIRED (pre-authorized code is NOT supported)\n * - `scope` is REQUIRED within the authorization_code grant\n *\n * **Conditional validations:**\n * - `authorization_server` is REQUIRED when the Credential Issuer uses multiple Authorization Servers\n * - If `authorization_server` is present, it MUST match one of the servers in the Credential Issuer metadata\n *\n * @param options - Validation options containing the credential offer, config, and optional metadata\n * @throws {CredentialOfferError} If any validation rule fails\n */\nexport async function validateCredentialOffer(\n options: ValidateCredentialOfferOptions,\n): Promise<void> {\n const { credentialIssuerMetadata, credentialOffer } = options;\n\n // Validate credential_issuer is HTTPS\n if (!credentialOffer.credential_issuer.startsWith(\"https://\")) {\n throw new CredentialOfferError(\"credential_issuer must be an HTTPS URL\");\n }\n\n // Validate credential_configuration_ids is not empty\n if (credentialOffer.credential_configuration_ids.length === 0) {\n throw new CredentialOfferError(\n \"credential_configuration_ids must contain at least one identifier\",\n );\n }\n\n // IT-Wallet v1.3: grants is REQUIRED\n if (!credentialOffer.grants) {\n throw new CredentialOfferError(\"grants is REQUIRED for IT-Wallet v1.3\");\n }\n\n const authCodeGrant = credentialOffer.grants.authorization_code;\n\n // IT-Wallet v1.3: authorization_code grant is REQUIRED\n if (!authCodeGrant) {\n throw new CredentialOfferError(\n \"authorization_code grant is REQUIRED for IT-Wallet v1.3\",\n );\n }\n\n // Validate scope is present (REQUIRED in authorization_code)\n if (!authCodeGrant.scope) {\n throw new CredentialOfferError(\"authorization_code.scope is REQUIRED\");\n }\n\n // Conditional validation for authorization_server\n // REQUIRED only when CI uses multiple authorization servers\n if (credentialIssuerMetadata?.authorization_servers) {\n const authServers = credentialIssuerMetadata.authorization_servers;\n\n // If multiple authorization servers exist, authorization_server must be present\n if (authServers.length > 1 && !authCodeGrant.authorization_server) {\n throw new CredentialOfferError(\n \"authorization_server is REQUIRED when Credential Issuer uses multiple Authorization Servers\",\n );\n }\n\n // If authorization_server is present, validate it matches metadata\n if (authCodeGrant.authorization_server) {\n if (!authServers.includes(authCodeGrant.authorization_server)) {\n throw new CredentialOfferError(\n `authorization_server '${authCodeGrant.authorization_server}' does not match Credential Issuer metadata. Valid servers: ${authServers.join(\", \")}`,\n );\n }\n }\n }\n}\n","import {\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { CredentialRequest, CredentialRequestOptions } from \"./types\";\nimport type { CredentialRequestV1_0 } from \"./v1.0/z-credential\";\nimport type { CredentialRequestV1_3 } from \"./v1.3/z-credential\";\n\nimport * as V1_0 from \"./v1.0/create-credential-request\";\nimport * as V1_3 from \"./v1.3/create-credential-request\";\n\nfunction isV1_0Options(\n options: CredentialRequestOptions,\n): options is V1_0.CredentialRequestOptionsV1_0 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0;\n}\n\nfunction isV1_3Options(\n options: CredentialRequestOptions,\n): options is V1_3.CredentialRequestOptionsV1_3 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3;\n}\n\n/**\n * Creates a credential request according to the configured Italian Wallet specification version.\n *\n * Version Differences:\n * - v1.0: Returns singular `proof` object with explicit `proof_type` field\n * - v1.3: Returns plural `proofs` object with JWT array (batch support) and requires key attestation\n *\n * @param options - Request options including version config\n * @returns Version-specific credential request object\n * @throws {ItWalletSpecsVersionError} When version is not supported or keyAttestation is used with wrong version\n *\n * @example v1.0 - Basic credential request\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const request = await createCredentialRequest({\n * config,\n * callbacks: { signJwt: mySignJwtCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * nonce: \"c_nonce_value\",\n * signer: myJwtSigner\n * });\n * // Returns: { credential_identifier: \"...\", proof: { jwt: \"...\", proof_type: \"jwt\" } }\n *\n * @example v1.3 - Credential request with key attestation\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const request = await createCredentialRequest({\n * config,\n * callbacks: { signJwt: mySignJwtCallback, hash: myHashCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"education_degree_unibo_2017_l31_informatica\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * keyAttestation: 'eyJ...', // Required for v1.3\n * nonce: \"c_nonce_value\",\n * signers: [myJwtSigner]\n * });\n * // Returns: { credential_identifier: \"...\", proofs: { jwt: [\"...\"] } }\n */\n\n// Function overload for v1.0\nexport function createCredentialRequest(\n options: V1_0.CredentialRequestOptionsV1_0,\n): Promise<CredentialRequestV1_0>;\n\n// Function overload for v1.3\nexport function createCredentialRequest(\n options: V1_3.CredentialRequestOptionsV1_3,\n): Promise<CredentialRequestV1_3>;\n\n// Implementation signature (not callable by users)\nexport async function createCredentialRequest(\n options: CredentialRequestOptions,\n): Promise<CredentialRequest> {\n const { config } = options;\n\n if (isV1_0Options(options)) {\n return V1_0.createCredentialRequest(options);\n }\n\n if (isV1_3Options(options)) {\n return V1_3.createCredentialRequest(options);\n }\n\n throw new ItWalletSpecsVersionError(\n \"createCredentialRequest\",\n (config as { itWalletSpecsVersion: string }).itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n}\n","import type { CallbackContext, JwtSignerJwk } from \"@openid4vc/oauth2\";\n\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n dateToSeconds,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../../errors\";\nimport { BaseCredentialRequestOptions } from \"../types\";\nimport { CredentialRequestV1_0, zCredentialRequestV1_0 } from \"./z-credential\";\n\n/**\n * Options for creating a credential request with v1.0\n * Does NOT include keyAttestation parameter\n */\nexport interface CredentialRequestOptionsV1_0\n extends BaseCredentialRequestOptions {\n callbacks: Pick<CallbackContext, \"signJwt\">;\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n signer: JwtSignerJwk;\n // keyAttestation is NOT accepted in v1.0\n}\n\n/**\n * Create a Credential Request for IT-Wallet v1.0\n *\n * Version 1.0 specifics:\n * - Returns singular `proof` object with explicit `proof_type` field\n * - JWT header does NOT include `key_attestation`\n * - Single credential per request (no batch support)\n *\n * @param options - Request options\n * @returns Credential request for v1.0\n * @throws {ValidationError} When credential request validation fails\n * @throws {Oid4vciError} For other unexpected errors\n *\n * @example\n * const request = await createCredentialRequest({\n * callbacks: { signJwt: mySignJwtCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * nonce: \"c_nonce_value\",\n * signer: myJwtSigner\n * });\n * // Returns: { credential_identifier: \"...\", proof: { jwt: \"...\", proof_type: \"jwt\" } }\n */\nexport const createCredentialRequest = async (\n options: CredentialRequestOptionsV1_0,\n): Promise<CredentialRequestV1_0> => {\n try {\n const { signJwt } = options.callbacks;\n\n const proofJwt = await signJwt(options.signer, {\n header: {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"openid4vci-proof+jwt\",\n },\n payload: {\n aud: options.issuerIdentifier,\n iat: dateToSeconds(new Date()),\n iss: options.clientId,\n nonce: options.nonce,\n },\n });\n\n return parseWithErrorHandling(zCredentialRequestV1_0, {\n credential_identifier: options.credential_identifier,\n proof: {\n jwt: proofJwt.jwt,\n proof_type: \"jwt\",\n },\n } satisfies CredentialRequestV1_0);\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error during create credential request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport {\n credentialRequestRefiner,\n zBaseCredentialRequest,\n} from \"../z-base-credential-request\";\n\n/**\n * Proof object schema for v1.0\n * Contains a JWT and explicit proof_type field\n */\nexport const zCredentialRequestProof = z.object({\n jwt: z.string().min(1, \"JWT must not be empty\"),\n proof_type: z.literal(\"jwt\"), // MUST be \"jwt\"\n});\n\nexport type CredentialRequestProof = z.infer<typeof zCredentialRequestProof>;\n\n/**\n * Credential request schema for IT-Wallet v1.0\n *\n * Key characteristics:\n * - Uses singular `proof` object\n * - Explicit `proof_type` field (always \"jwt\")\n * - Single credential per request (no batch support)\n */\nexport const zCredentialRequestV1_0 = zBaseCredentialRequest\n .extend({\n proof: zCredentialRequestProof.describe(\n \"REQUIRED. Proof of possession of key material (must contain proof_type=jwt and a jwt).\",\n ),\n })\n .superRefine((data, ctx) => {\n credentialRequestRefiner(data, ctx);\n });\n\nexport type CredentialRequestV1_0 = z.infer<typeof zCredentialRequestV1_0>;\n","import { z } from \"zod\";\n\nimport type { CredentialRequestV1_0 } from \"./v1.0\";\nimport type { CredentialRequestV1_3 } from \"./v1.3\";\n\n/**\n * Base Credential request schema for IT-Wallet v1.0 and v1.3.\n * @internal\n */\nexport const zBaseCredentialRequest = z.object({\n credential_configuration_id: z\n .string()\n .optional()\n .describe(\n \"REQUIRED if credential_identifier param is absent. MUST NOT be used otherwise.\",\n ),\n\n credential_identifier: z\n .string()\n .optional()\n .describe(\n \"REQUIRED when Authorization Details of type openid_credential was returned. MUST NOT be used if credential_configuration_id is present.\",\n ),\n\n transaction_id: z\n .string()\n .optional()\n .describe(\n \"REQUIRED only in case of deferred flow. MUST NOT be present in immediate flow.\",\n ),\n});\n\nexport function credentialRequestRefiner(\n data: CredentialRequestV1_0 | CredentialRequestV1_3,\n ctx: z.RefinementCtx,\n) {\n // Exclusive OR between credential_identifier and credential_configuration_id\n if (data.credential_identifier && data.credential_configuration_id) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"credential_identifier and credential_configuration_id MUST NOT be used together\",\n path: [\"credential_identifier\"],\n });\n }\n\n if (!data.credential_identifier && !data.credential_configuration_id) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"One of credential_identifier or credential_configuration_id MUST be present\",\n path: [\"credential_identifier\"],\n });\n }\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n type JwtSignerJwk,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n dateToSeconds,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../../errors\";\nimport { BaseCredentialRequestOptions } from \"../types\";\nimport { CredentialRequestV1_3, zCredentialRequestV1_3 } from \"./z-credential\";\n\n/**\n * Options for creating a credential request with v1.3\n * Requires keyAttestation parameter\n */\nexport interface CredentialRequestOptionsV1_3\n extends BaseCredentialRequestOptions {\n callbacks: Pick<CallbackContext, \"hash\" | \"signJwt\">;\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n keyAttestation: string; // Required in v1.3\n /**\n * The maximum size for a single credential batch issuance request.\n * It is extracted from the Issuer Metadata: `batch_credential_issuance.batch_size`.\n */\n maxBatchSize?: number;\n /**\n * The list of signers to generate JWT proofs.\n * Multiple unique signers must be used for batch issuance.\n */\n signers: JwtSignerJwk[];\n}\n\n/**\n * Create a Credential Request for IT-Wallet v1.3\n *\n * Version 1.3 specifics:\n * - Returns plural `proofs` object with JWT array (batch support)\n * - proof_type field removed (implicit from structure)\n * - JWT header includes `key_attestation` field (Wallet Unit Attestation)\n *\n * @param options - Request options including keyAttestation\n * @returns Credential request for v1.3\n * @throws {ValidationError} When credential request validation fails\n * @throws {Oid4vciError} For other unexpected errors\n *\n * @example\n * const request = await createCredentialRequest({\n * callbacks: { signJwt: mySignJwtCallback, hash: myHashCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * keyAttestation: \"eyJ...\", // Required in v1.3\n * nonce: \"c_nonce_value\",\n * signers: [myJwtSigner]\n * });\n * // Returns: { credential_identifier: \"...\", proofs: { jwt: [\"...\"] } }\n */\nexport const createCredentialRequest = async (\n options: CredentialRequestOptionsV1_3,\n): Promise<CredentialRequestV1_3> => {\n try {\n const { maxBatchSize, signers } = options;\n\n if (signers.length === 0) {\n throw new ValidationError(\"At least one signer is required\");\n }\n\n if (maxBatchSize !== undefined) {\n if (!Number.isInteger(maxBatchSize) || maxBatchSize <= 0) {\n throw new ValidationError(\n \"Invalid maxBatchSize: it must be a positive integer\",\n );\n }\n\n if (signers.length > maxBatchSize) {\n throw new ValidationError(\n \"The number of provided signers exceeds the maximum batch size allowed\",\n );\n }\n }\n\n const { hash, signJwt } = options.callbacks;\n\n // Ensure all keys are unique for batch issuance\n if (signers.length > 1) {\n const allThumbprints = await Promise.all(\n signers.map((signer) =>\n calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: hash,\n jwk: signer.publicJwk,\n }),\n ),\n );\n const uniqueThumbprints = new Set(allThumbprints);\n if (uniqueThumbprints.size !== allThumbprints.length) {\n throw new ValidationError(\n \"Found multiple signers with the same JWK: each JWT proof must be unique and linked to a different credential key pair\",\n );\n }\n }\n\n const proofJwts = await Promise.all(\n signers.map((signer) =>\n signJwt(signer, {\n header: {\n alg: signer.alg,\n jwk: signer.publicJwk,\n key_attestation: options.keyAttestation,\n typ: \"openid4vci-proof+jwt\",\n },\n payload: {\n aud: options.issuerIdentifier,\n iat: dateToSeconds(new Date()),\n iss: options.clientId,\n nonce: options.nonce,\n },\n }),\n ),\n );\n\n return parseWithErrorHandling(zCredentialRequestV1_3, {\n credential_identifier: options.credential_identifier,\n proofs: {\n jwt: proofJwts.map((proofJwt) => proofJwt.jwt), // Array for batch support\n },\n } satisfies CredentialRequestV1_3);\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n\n throw new Oid4vciError(\n `Unexpected error during create credential request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport {\n credentialRequestRefiner,\n zBaseCredentialRequest,\n} from \"../z-base-credential-request\";\n\n/**\n * Proofs object schema for v1.3\n * Contains an array of JWTs (supports batch issuance)\n * proof_type is implicit (determined by the property name)\n */\nexport const zCredentialRequestProofs = z.object({\n jwt: z\n .array(z.string().min(1, \"JWT must not be empty\"))\n .min(1, \"At least one JWT proof is required\"),\n});\n\nexport type CredentialRequestProofs = z.infer<typeof zCredentialRequestProofs>;\n\n/**\n * Credential request schema for IT-Wallet v1.3\n *\n * Key changes from v1.0:\n * - Uses plural `proofs` object (not `proof`)\n * - proof_type field removed (implicit from structure)\n * - JWT is an array (supports batch issuance)\n * - JWT header includes `key_attestation` field\n */\nexport const zCredentialRequestV1_3 = zBaseCredentialRequest\n .extend({\n proofs: zCredentialRequestProofs.describe(\n \"REQUIRED. Proof of possession of key material (contains array of JWTs for batch support).\",\n ),\n })\n .superRefine((data, ctx) => {\n credentialRequestRefiner(data, ctx);\n });\n\nexport type CredentialRequestV1_3 = z.infer<typeof zCredentialRequestV1_3>;\n","import {\n Oauth2JwtParseError,\n decodeJwt,\n extractDpopJwtFromHeaders,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n FetchHeaders,\n HEADERS,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n CredentialAuthorizationHeaderError,\n MissingDpopProofError as CredentialDpopProofError,\n ParseCredentialRequestError,\n} from \"../errors\";\nimport {\n CredentialRequestV1_0,\n zCredentialRequestV1_0,\n} from \"./v1.0/z-credential\";\nimport {\n CredentialRequestV1_3,\n zCredentialRequestV1_3,\n} from \"./v1.3/z-credential\";\nimport {\n ProofJwtHeader,\n ProofJwtPayload,\n zProofJwtHeaderV1_0,\n zProofJwtHeaderV1_3,\n zProofJwtPayload,\n} from \"./z-proof-jwt\";\n\ntype GrantType = \"authorization_code\" | \"pre-authorized_code\";\n\n/**\n * A normalized proof extracted from the credential request.\n * The proof JWT is decoded and validated, but its signature is not verified.\n */\nexport interface ParsedCredentialProof {\n /** Parsed proof JWT header. */\n header: ProofJwtHeader;\n /** Original compact JWT proof. */\n jwt: string;\n /** Parsed proof JWT payload. */\n payload: ProofJwtPayload;\n /** Normalized proof type. */\n proofType: \"jwt\";\n}\n\n/**\n * Optional expected values used for semantic validation during parsing.\n */\nexport interface ParseCredentialRequestExpectedValues {\n /** Expected `aud` claim inside the proof JWT payload. */\n audience?: string;\n /** Expected credential configuration identifier in the request body. */\n credential_configuration_id?: string;\n /** Expected credential identifier in the request body. */\n credential_identifier?: string;\n /** Expected `iss` claim inside the proof JWT payload. */\n issuer?: string;\n /** Expected `nonce` claim inside the proof JWT payload. */\n nonce?: string;\n}\n\n/**\n * Input options for parsing a credential request.\n */\nexport interface ParseCredentialRequestOptions {\n /** SDK config used to route parsing logic by IT-Wallet specification version. */\n config: IoWalletSdkConfig;\n /** Credential request payload to validate and parse. */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n /** Optional expected values for semantic checks. */\n expected?: ParseCredentialRequestExpectedValues;\n /** Grant type used to validate `iss` requirements in proof JWT payloads. */\n grantType?: GrantType;\n /** HTTP headers of the credential request, used to extract the DPoP proof. */\n headers: FetchHeaders;\n /** Whether the request is expected to be part of deferred issuance flow. */\n isDeferredFlow?: boolean;\n}\n\n/**\n * Parsed and normalized credential request.\n */\nexport interface ParsedCredentialRequest {\n /** Access token extracted from the Authorization header. */\n accessToken: string;\n /** Normalized credential selector values from the request body. */\n credential: {\n credential_configuration_id?: string;\n credential_identifier?: string;\n };\n /** Version-specific validated credential request. */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n /** DPoP proof JWT extracted from the request headers. */\n dpopProof: string;\n /** Normalized list of parsed proof JWTs. */\n proofs: ParsedCredentialProof[];\n /** Transaction metadata derived from flow context and request payload. */\n transaction: {\n isDeferredFlow: boolean;\n transaction_id?: string;\n };\n}\n\n/**\n * Validates request body identifiers against optionally provided expected values.\n */\nfunction validateExpectedValues(\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3,\n expected?: ParseCredentialRequestExpectedValues,\n): void {\n if (!expected) {\n return;\n }\n\n if (\n expected.credential_identifier &&\n credentialRequest.credential_identifier !== expected.credential_identifier\n ) {\n throw new ValidationError(\n \"credential_identifier does not match expected value\",\n );\n }\n\n if (\n expected.credential_configuration_id &&\n credentialRequest.credential_configuration_id !==\n expected.credential_configuration_id\n ) {\n throw new ValidationError(\n \"credential_configuration_id does not match expected value\",\n );\n }\n}\n\n/**\n * Validates that transaction_id presence matches deferred/immediate flow context.\n */\nfunction validateTransactionContext(options: {\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n isDeferredFlow: boolean;\n}): void {\n const { credentialRequest, isDeferredFlow } = options;\n\n if (isDeferredFlow && !credentialRequest.transaction_id) {\n throw new ValidationError(\n \"transaction_id is required for deferred credential issuance\",\n );\n }\n\n if (!isDeferredFlow && credentialRequest.transaction_id) {\n throw new ValidationError(\n \"transaction_id must not be present in immediate credential issuance flow\",\n );\n }\n}\n\n/**\n * Decodes and validates a single proof JWT, then applies semantic claim checks.\n */\nfunction parseProofJwt(options: {\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n jwt: string;\n}): ParsedCredentialProof {\n const decoded = decodeJwt({ jwt: options.jwt });\n const headerValidation =\n options.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3\n ? zProofJwtHeaderV1_3.safeParse(decoded.header)\n : zProofJwtHeaderV1_0.safeParse(decoded.header);\n\n if (!headerValidation.success) {\n throw new ValidationError(\n \"Credential proof JWT header is invalid or missing required claims\",\n );\n }\n\n const payloadValidation = zProofJwtPayload.safeParse(decoded.payload);\n if (!payloadValidation.success) {\n throw new ValidationError(\n \"Credential proof JWT payload is invalid or missing required claims\",\n );\n }\n\n const payload = payloadValidation.data;\n\n if (options.grantType === \"authorization_code\" && !payload.iss) {\n throw new ValidationError(\n \"Credential proof JWT payload must include iss for authorization_code grant\",\n );\n }\n\n if (options.expected?.audience && payload.aud !== options.expected.audience) {\n throw new ValidationError(\n \"Credential proof JWT aud does not match expected audience\",\n );\n }\n\n if (options.expected?.nonce && payload.nonce !== options.expected.nonce) {\n throw new ValidationError(\n \"Credential proof JWT nonce does not match expected nonce\",\n );\n }\n\n if (\n options.expected?.issuer &&\n payload.iss &&\n payload.iss !== options.expected.issuer\n ) {\n throw new ValidationError(\n \"Credential proof JWT iss does not match expected issuer\",\n );\n }\n\n if (\n options.grantType === \"authorization_code\" &&\n options.expected?.issuer &&\n !payload.iss\n ) {\n throw new ValidationError(\n \"Credential proof JWT payload is missing expected issuer (iss)\",\n );\n }\n\n return {\n header: headerValidation.data,\n jwt: options.jwt,\n payload,\n proofType: \"jwt\",\n };\n}\n\n/**\n * Converts version-specific proof containers (`proof` or `proofs.jwt[]`) into a normalized array.\n */\nfunction normalizeProofs(options: {\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n}): ParsedCredentialProof[] {\n if (\"proof\" in options.credentialRequest) {\n return [\n parseProofJwt({\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n jwt: options.credentialRequest.proof.jwt,\n }),\n ];\n }\n\n return options.credentialRequest.proofs.jwt.map((jwt) =>\n parseProofJwt({\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n jwt,\n }),\n );\n}\n\n/**\n * Builds the normalized parse result shared by v1.0 and v1.3 flows.\n */\nfunction toResult<\n TRequest extends CredentialRequestV1_0 | CredentialRequestV1_3,\n>(options: {\n accessToken: string;\n credentialRequest: TRequest;\n dpopProof: string;\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n isDeferredFlow: boolean;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n}): ParsedCredentialRequest {\n validateExpectedValues(options.credentialRequest, options.expected);\n validateTransactionContext({\n credentialRequest: options.credentialRequest,\n isDeferredFlow: options.isDeferredFlow,\n });\n\n const proofs = normalizeProofs({\n credentialRequest: options.credentialRequest,\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n });\n\n return {\n accessToken: options.accessToken,\n credential: {\n credential_configuration_id:\n options.credentialRequest.credential_configuration_id,\n credential_identifier: options.credentialRequest.credential_identifier,\n },\n credentialRequest: options.credentialRequest,\n dpopProof: options.dpopProof,\n proofs,\n transaction: {\n isDeferredFlow: options.isDeferredFlow,\n transaction_id: options.credentialRequest.transaction_id,\n },\n };\n}\n\n/**\n * Extracts and validates the DPoP-bound access token from the Authorization header.\n */\nfunction parseAuthorizationHeader(headers: FetchHeaders): string {\n const authorizationHeader = headers.get(HEADERS.AUTHORIZATION)?.trim();\n\n if (!authorizationHeader) {\n throw new CredentialAuthorizationHeaderError(\n \"Credential request is missing required 'Authorization' header with DPoP scheme\",\n );\n }\n\n const [scheme, token, ...rest] = authorizationHeader.split(/\\s+/);\n\n // Per RFC 9110 authentication schemes are case-insensitive\n if (rest.length > 0 || scheme?.toLowerCase() !== \"dpop\" || !token) {\n throw new CredentialAuthorizationHeaderError(\n \"Credential request contains an invalid 'Authorization' header. Expected format: 'Authorization: DPoP <access_token>'\",\n );\n }\n\n return token;\n}\n\n/**\n * Extracts and validates the DPoP proof JWT from the request headers.\n */\nfunction parseDpopProof(headers: FetchHeaders): string {\n const extracted = extractDpopJwtFromHeaders(headers);\n\n if (!extracted.valid) {\n throw new CredentialDpopProofError(\n \"Credential request contains a 'DPoP' header, but the value is not a valid JWT format\",\n );\n }\n\n if (!extracted.dpopJwt) {\n throw new CredentialDpopProofError(\n \"Credential request contains a 'DPoP' header, but the value is missing or empty\",\n );\n }\n\n return extracted.dpopJwt;\n}\n\n/**\n * Parses and validates a credential request for the configured IT-Wallet version.\n *\n * Performs the following validations in order:\n * 1. **Authorization header** — asserts the `Authorization` HTTP header is present\n * and uses the `DPoP` scheme with a non-empty access token. The extracted token\n * is returned as `accessToken` for subsequent verification by the caller.\n * 2. **DPoP proof header** — asserts the `DPoP` HTTP header is present and contains a\n * compact JWT. The extracted JWT is returned as `dpopProof` for subsequent\n * cryptographic verification by the caller (e.g. via `verifyTokenDPoP`).\n * 3. **Request body schema** — validates the body against the v1.0 or v1.3 schema.\n * 4. **Semantic checks** — verifies optional expected values (`audience`, `nonce`,\n * `issuer`, `credential_identifier`, `credential_configuration_id`).\n * 5. **Transaction context** — enforces `transaction_id` presence/absence rules\n * for deferred vs. immediate issuance flows.\n * 6. **Proof JWT structure** — decodes each proof JWT and validates its header and\n * payload claims, including `iss` requirements for the `authorization_code` grant.\n * For v1.3, asserts the `key_attestation` header claim is present and non-empty.\n *\n * This function does not perform cryptographic signature verification on proof JWTs\n * or the DPoP proof. Both must be verified separately after parsing.\n * For DPoP proofs, the caller can use the `verifyTokenDPoP` function exported by io-wallet-oauth2.\n *\n * @param options - Parsing options and validation context.\n * @returns Normalized parsed credential request including the extracted `accessToken` and `dpopProof`.\n * @throws {CredentialAuthorizationHeaderError} If the `Authorization` header is absent or invalid.\n * @throws {CredentialDpopProofError} If the `DPoP` header is absent or not a valid compact JWT.\n * @throws {ValidationError} If request body schema or semantic checks fail.\n * @throws {Oauth2JwtParseError} If a proof JWT cannot be decoded.\n * @throws {ItWalletSpecsVersionError} If the configured specification version is unsupported.\n * @throws {ParseCredentialRequestError} For unexpected parsing failures.\n */\nexport function parseCredentialRequest(\n options: ParseCredentialRequestOptions,\n): ParsedCredentialRequest {\n const grantType = options.grantType ?? \"authorization_code\";\n const isDeferredFlow = options.isDeferredFlow ?? false;\n const { config } = options;\n\n try {\n const accessToken = parseAuthorizationHeader(options.headers);\n const dpopProof = parseDpopProof(options.headers);\n\n if (options.config.isVersion(ItWalletSpecsVersion.V1_0)) {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequestV1_0,\n options.credentialRequest,\n \"Invalid credential request format for ItWalletSpecsVersion 1.0\",\n );\n\n return toResult({\n accessToken,\n credentialRequest,\n dpopProof,\n expected: options.expected,\n grantType,\n isDeferredFlow,\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n });\n }\n\n if (options.config.isVersion(ItWalletSpecsVersion.V1_3)) {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequestV1_3,\n options.credentialRequest,\n \"Invalid credential request format for ItWalletSpecsVersion 1.3\",\n );\n\n return toResult({\n accessToken,\n credentialRequest,\n dpopProof,\n expected: options.expected,\n grantType,\n isDeferredFlow,\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_3,\n });\n }\n\n throw new ItWalletSpecsVersionError(\n \"parseCredentialRequest\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof ItWalletSpecsVersionError ||\n error instanceof Oauth2JwtParseError ||\n error instanceof ValidationError ||\n error instanceof CredentialAuthorizationHeaderError ||\n error instanceof CredentialDpopProofError\n ) {\n throw error;\n }\n\n throw new ParseCredentialRequestError(\n `Unexpected error during credential request parsing: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error,\n );\n }\n}\n","import { zJwk } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nconst zBaseProofJwtHeader = z.object({\n alg: z.string().min(1),\n jwk: zJwk,\n typ: z.literal(\"openid4vci-proof+jwt\"),\n});\n\nexport const zProofJwtHeaderV1_0 = zBaseProofJwtHeader.loose();\n\nexport const zProofJwtHeaderV1_3 = zBaseProofJwtHeader\n .extend({\n key_attestation: z.string().min(1),\n })\n .loose();\n\nexport const zProofJwtPayload = z.looseObject({\n aud: z.string().min(1),\n iat: z.number(),\n iss: z.string().min(1).optional(),\n nonce: z.string().min(1),\n});\n\nexport type ProofJwtHeaderV1_0 = z.infer<typeof zProofJwtHeaderV1_0>;\nexport type ProofJwtHeaderV1_3 = z.infer<typeof zProofJwtHeaderV1_3>;\nexport type ProofJwtHeader = ProofJwtHeaderV1_0 | ProofJwtHeaderV1_3;\nexport type ProofJwtPayload = z.infer<typeof zProofJwtPayload>;\n","import { calculateJwkThumbprint, jwtSignerFromJwt } from \"@openid4vc/oauth2\";\nimport {\n CallbackContext,\n HashAlgorithm,\n Jwk,\n Oauth2JwtParseError,\n decodeJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n verifyJwtIatOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n VerifyCredentialRequestJwtProofError,\n VerifyKeyAttestationJwtError,\n} from \"../errors\";\nimport {\n FetchStatusListCallback,\n VerifyKeyAttestationJwtResult,\n verifyKeyAttestationJwt,\n} from \"./verify-key-attestation-jwt\";\nimport {\n ProofJwtHeaderV1_0,\n ProofJwtHeaderV1_3,\n ProofJwtPayload,\n zProofJwtHeaderV1_0,\n zProofJwtHeaderV1_3,\n zProofJwtPayload,\n} from \"./z-proof-jwt\";\n\nexport interface VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * Callbacks required for JWT signature verification and JWK thumbprint hashing.\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n /**\n * The client id of the wallet requesting the credential.\n * If provided, it will be matched against the `iss` claim.\n */\n clientId?: string;\n /**\n * The credential issuer identifier. Matched against the `aud` claim.\n */\n credentialIssuer: string;\n /**\n * Expected nonce value (`c_nonce`) previously shared with the wallet\n * via the Nonce Endpoint.\n */\n expectedNonce: string;\n /**\n * The compact JWT proof to verify.\n */\n jwt: string;\n /**\n * Date at which the nonce expires. If the current time exceeds this value,\n * verification fails before signature checking.\n */\n nonceExpiresAt?: Date;\n /**\n * Current time override. If not provided, `Date.now()` is used.\n */\n now?: Date;\n}\n\nexport interface VerifyCredentialRequestJwtProofOptionsV1_0\n extends VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * SDK configuration that determines the IT-Wallet specification version.\n * Controls which header schema is used and whether key attestation is verified.\n */\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport interface VerifyCredentialRequestJwtProofOptionsV1_3\n extends VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * SDK configuration that determines the IT-Wallet specification version.\n * Controls which header schema is used and whether key attestation is verified.\n */\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n /**\n * Optional callback used to fetch and evaluate key attestation revocation.\n *\n * When omitted and `itWalletSpecsVersion` is v1.3, key attestation revocation\n * is not checked by this function.\n */\n fetchStatusList?: FetchStatusListCallback;\n /**\n * Trusted key attestation issuers (wallet provider entity identifiers).\n * The key attestation `iss` claim must exactly match one of these values.\n */\n trustedWalletProviderIssuers: readonly string[];\n}\n\nexport type VerifyCredentialRequestJwtProofOptions =\n | VerifyCredentialRequestJwtProofOptionsV1_0\n | VerifyCredentialRequestJwtProofOptionsV1_3;\n\ninterface IsJwkInSetOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n jwk: Jwk;\n jwks: Jwk[];\n}\n\nasync function isJwkInSet(options: IsJwkInSetOptions): Promise<boolean> {\n const targetThumbprint = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.jwk,\n });\n\n const thumbprints = await Promise.all(\n options.jwks.map((jwk) =>\n calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk,\n }),\n ),\n );\n\n return thumbprints.includes(targetThumbprint);\n}\n\nfunction verifyProofJwtIatOrThrow(options: {\n now?: Date;\n payload: ProofJwtPayload;\n}) {\n try {\n verifyJwtIatOrThrow({\n iat: options.payload.iat,\n now: options.now,\n });\n } catch (error) {\n if (error instanceof Error) {\n throw new VerifyCredentialRequestJwtProofError(\n `Invalid iat claim in credential request proof JWT: ${error.message}`,\n error,\n );\n }\n }\n}\n\n/**\n * Verification result for IT-Wallet specification v1.0.\n * Does not include key attestation.\n */\nexport interface VerifyCredentialRequestJwtProofResultV1_0 {\n header: ProofJwtHeaderV1_0;\n payload: ProofJwtPayload;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\n/**\n * Verification result for IT-Wallet specification v1.3.\n * Includes the verified key attestation.\n */\nexport interface VerifyCredentialRequestJwtProofResultV1_3 {\n header: ProofJwtHeaderV1_3;\n keyAttestation: VerifyKeyAttestationJwtResult;\n payload: ProofJwtPayload;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\nexport type VerifyCredentialRequestJwtProofResult =\n | VerifyCredentialRequestJwtProofResultV1_0\n | VerifyCredentialRequestJwtProofResultV1_3;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptionsV1_0,\n): Promise<VerifyCredentialRequestJwtProofResultV1_0>;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptionsV1_3,\n): Promise<VerifyCredentialRequestJwtProofResultV1_3>;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptions,\n): Promise<VerifyCredentialRequestJwtProofResult>;\n\n/**\n * Verifies a credential request JWT proof according to the configured IT-Wallet specification version.\n *\n * Performs the following checks:\n * 1. Validates nonce expiry (if `nonceExpiresAt` is provided)\n * 2. Decodes and validates the JWT header and payload using version-specific schemas\n * 3. Validates proof `iat` freshness (max 5 minutes old, max 60 seconds in the future)\n * 4. Verifies the JWT signature via the `verifyJwt` callback\n * 5. (v1.3 only) Verifies the `key_attestation` JWT and checks that the proof signer key\n * is present in the key attestation's `attested_keys`\n * 6. (v1.3 only) Ensures key attestation `iss` belongs to `trustedWalletProviderIssuers`\n *\n * @param options - Verification options and callbacks.\n * @returns Decoded header, payload, signer, and (v1.3) key attestation result.\n * @throws {VerifyCredentialRequestJwtProofError} If nonce is expired, proof `iat` is outside\n * freshness bounds, signature is invalid, or the signer key is not in the attested keys.\n * @throws {ItWalletSpecsVersionError} If the configured specification version is unsupported.\n * @throws {ValidationError} If JWT header or payload schema validation fails.\n * @throws {Oauth2JwtParseError} If JWT decoding fails.\n */\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptions,\n): Promise<VerifyCredentialRequestJwtProofResult> {\n const configVersion = options.config.itWalletSpecsVersion;\n\n try {\n const now = options.now?.getTime() ?? Date.now();\n\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new VerifyCredentialRequestJwtProofError(\n \"Nonce used for credential request proof expired\",\n );\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n const { header, payload } = decodeJwt({\n headerSchema: zProofJwtHeaderV1_0,\n jwt: options.jwt,\n payloadSchema: zProofJwtPayload,\n });\n\n verifyProofJwtIatOrThrow({ now: options.now, payload });\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n errorMessage: \"Error verifying credential request proof jwt.\",\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n const { header, payload } = decodeJwt({\n headerSchema: zProofJwtHeaderV1_3,\n jwt: options.jwt,\n payloadSchema: zProofJwtPayload,\n });\n\n verifyProofJwtIatOrThrow({ now: options.now, payload });\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n errorMessage: \"Error verifying credential request proof jwt.\",\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n if (options.trustedWalletProviderIssuers.length === 0) {\n throw new VerifyCredentialRequestJwtProofError(\n \"trustedWalletProviderIssuers must include at least one trusted wallet provider issuer\",\n );\n }\n\n const keyAttestationResult = await verifyKeyAttestationJwt({\n callbacks: options.callbacks,\n fetchStatusList: options.fetchStatusList,\n keyAttestationJwt: header.key_attestation,\n now: options.now,\n });\n\n if (\n !options.trustedWalletProviderIssuers.includes(\n keyAttestationResult.payload.iss,\n )\n ) {\n throw new VerifyCredentialRequestJwtProofError(\n `Untrusted key attestation issuer: ${keyAttestationResult.payload.iss}`,\n );\n }\n\n const isSignedWithAttestedKey = await isJwkInSet({\n callbacks: options.callbacks,\n jwk: signer.publicJwk,\n jwks: keyAttestationResult.payload.attested_keys,\n });\n\n if (!isSignedWithAttestedKey) {\n throw new VerifyCredentialRequestJwtProofError(\n \"Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'\",\n );\n }\n\n return {\n header,\n keyAttestation: keyAttestationResult,\n payload,\n signer,\n };\n }\n\n throw new ItWalletSpecsVersionError(\n \"verifyCredentialRequestJwtProof\",\n configVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof VerifyCredentialRequestJwtProofError ||\n error instanceof VerifyKeyAttestationJwtError ||\n error instanceof ItWalletSpecsVersionError ||\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n ) {\n throw error;\n }\n\n throw new VerifyCredentialRequestJwtProofError(\n `Unexpected error during credential request proof verification: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error,\n );\n }\n}\n","import {\n CallbackContext,\n Oauth2JwtParseError,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport { ValidationError } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifyKeyAttestationJwtError } from \"../errors\";\nimport {\n KeyAttestationHeader,\n KeyAttestationPayload,\n zKeyAttestationHeader,\n zKeyAttestationPayload,\n} from \"../wallet-provider/z-key-attestation\";\n\nexport type FetchStatusListCallback = (statusList: {\n index: number;\n uri: string;\n}) => Promise<boolean>;\n\n/**\n * Options for verifying a key attestation JWT.\n */\nexport interface VerifyKeyAttestationJwtOptions {\n /**\n * Callback required for JWT signature verification.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n /**\n * Optional callback used to fetch and evaluate revocation status from the\n * status list referenced in `payload.status.status_list`.\n *\n * If omitted, revocation is not checked by this function.\n */\n fetchStatusList?: FetchStatusListCallback;\n /**\n * The compact key attestation JWT (`key-attestation+jwt`) to verify.\n */\n keyAttestationJwt: string;\n /**\n * Current time override. If not provided, the current time is used.\n */\n now?: Date;\n}\n\n/**\n * Result of a successful key attestation JWT verification.\n */\nexport interface VerifyKeyAttestationJwtResult {\n /** Parsed and validated key attestation JWT header. */\n header: KeyAttestationHeader;\n /** Parsed and validated key attestation JWT payload, including `attested_keys`. */\n payload: KeyAttestationPayload;\n /** The resolved signer that was used to verify the JWT. */\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\n/**\n * Decodes, validates, and verifies the signature of a key attestation JWT.\n *\n * The header and payload are validated against the `zKeyAttestationHeader` and\n * `zKeyAttestationPayload` schemas. The JWT signature is verified via the\n * `verifyJwt` callback.\n *\n * Revocation handling:\n * - If `fetchStatusList` is provided, this function checks whether the key\n * attestation is revoked using `payload.status.status_list`.\n * - If `fetchStatusList` is omitted, revocation checking is the caller's\n * responsibility.\n *\n * @param options - Verification options and callbacks.\n * @returns Decoded header, payload, and signer.\n * @throws {Oauth2JwtParseError} If JWT decoding fails.\n * @throws {ValidationError} If schema validation fails.\n */\nexport async function verifyKeyAttestationJwt(\n options: VerifyKeyAttestationJwtOptions,\n): Promise<VerifyKeyAttestationJwtResult> {\n try {\n const { header, payload } = decodeJwt({\n headerSchema: zKeyAttestationHeader,\n jwt: options.keyAttestationJwt,\n payloadSchema: zKeyAttestationPayload,\n });\n\n // Upstream verifyJwt/jwtSignerFromJwt still match IT-Wallet signature checks.\n const { signer } = await verifyJwt({\n compact: options.keyAttestationJwt,\n errorMessage: \"Key attestation JWT verification failed.\",\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n if (options.fetchStatusList) {\n const { idx, uri } = payload.status.status_list;\n const isRevoked = await options.fetchStatusList({\n index: idx,\n uri,\n });\n\n if (isRevoked) {\n throw new VerifyKeyAttestationJwtError(\n `Key attestation has been revoked (status list: ${uri}, index: ${idx})`,\n );\n }\n }\n\n return { header, payload, signer };\n } catch (error) {\n if (\n error instanceof VerifyKeyAttestationJwtError ||\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n ) {\n throw error;\n }\n\n throw new VerifyKeyAttestationJwtError(\n `Unexpected error during key attestation jwt verification: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error,\n );\n }\n}\n","import { zCertificateChain, zJwk, zTrustChain } from \"@pagopa/io-wallet-oauth2\";\nimport { zKeyStorageLevelV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport { z } from \"zod\";\n\nexport const zStatusList = z.object({\n idx: z.number(),\n uri: z.url(),\n});\n\nexport type StatusList = z.infer<typeof zStatusList>;\n\nexport const zKeyAttestationStatus = z.object({\n status_list: zStatusList,\n});\n\nexport type KeyAttestationStatus = z.infer<typeof zKeyAttestationStatus>;\n\n/**\n * For the moment, these are all the supported algorithms in both\n * {@link https://italia.github.io/eid-wallet-it-docs/releases/1.3.3/en/algorithms.html#cryptographic-algorithms|v1.3.3} and\n * {@link https://italia.github.io/eid-wallet-it-docs/releases/1.0.2/en/algorithms.html#cryptographic-algorithms|v1.0.2},\n * and in both specifications the `alg` field MUST be one of those values.\n */\nexport const zKeyAttestationAlg = z.enum([\n \"ES256\",\n \"ES384\",\n \"ES512\",\n \"PS256\",\n \"PS384\",\n \"PS512\",\n]);\n\nexport const zKeyAttestationHeader = z.object({\n alg: zKeyAttestationAlg,\n kid: z.string(),\n trust_chain: zTrustChain.optional(),\n typ: z.literal(\"key-attestation+jwt\"),\n x5c: zCertificateChain,\n});\n\nexport type KeyAttestationHeader = z.infer<typeof zKeyAttestationHeader>;\n\nexport const zKeyAttestationPayload = z.object({\n attested_keys: z.array(zJwk).nonempty(),\n certification: z.string().optional(),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n key_storage: z.array(zKeyStorageLevelV1_3).nonempty(),\n status: zKeyAttestationStatus,\n user_authentication: z.array(zKeyStorageLevelV1_3).nonempty(),\n});\n\nexport type KeyAttestationPayload = z.infer<typeof zKeyAttestationPayload>;\n\nexport const zKeyAttestationTypeHeader = z.literal(\"key-attestation+jwt\");\n\nexport const keyAttestationTypeHeader = zKeyAttestationTypeHeader.value;\n","import type {\n EncryptJweCallback,\n JweEncryptor,\n} from \"@pagopa/io-wallet-oauth2\";\n\nimport {\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type {\n CreateCredentialResponseOptions,\n CreateCredentialResponseOptionsV1_0,\n CreateCredentialResponseOptionsV1_3,\n CreateCredentialResponseResult,\n CreateCredentialResponseResultWithFlow,\n DeferredFlowOptionsV1_0,\n DeferredFlowOptionsV1_3,\n ImmediateFlowOptions,\n} from \"./types\";\nimport type {\n CredentialResponse,\n CredentialResponseEncryption,\n DeferredCredentialResponseV1_0,\n DeferredCredentialResponseV1_3,\n} from \"./z-credential-response\";\nimport type { ImmediateCredentialResponse } from \"./z-immediate-credential-response\";\n\nimport { CreateCredentialResponseError, Oid4vciError } from \"../errors\";\nimport * as V1_0 from \"./v1.0/create-credential-response\";\nimport * as V1_3 from \"./v1.3/create-credential-response\";\n\nexport type {\n CreateCredentialResponseOptions,\n CreateCredentialResponseOptionsV1_0,\n CreateCredentialResponseOptionsV1_3,\n CreateCredentialResponseResult,\n CreateCredentialResponseResultWithFlow,\n DeferredFlowOptionsV1_0,\n DeferredFlowOptionsV1_3,\n ImmediateFlowOptions,\n} from \"./types\";\n\n/**\n * Creates a credential response according to the configured Italian Wallet specification version.\n *\n * Supports both immediate and deferred issuance flows, with optional JWE encryption of the\n * generated response payload.\n *\n * Version Differences:\n * - v1.0 deferred flow uses `lead_time`\n * - v1.3 deferred flow uses `interval`\n * - immediate flow has the same shape in both versions (`credentials`, optional `notification_id`)\n *\n * @param options - Credential response creation options, including version config, flow data,\n * and optional encryption settings.\n * @returns An object containing:\n * - `credentialResponse`: plain version-specific credential response JSON\n * - `credentialResponseJwt`: encrypted JWE string when encryption is requested\n * @throws {ItWalletSpecsVersionError} When the configured specification version is not supported.\n * @throws {ValidationError} When the generated response does not satisfy the version schema.\n * @throws {Oid4vciError} When encryption is requested but `callbacks.encryptJwe` is not provided.\n * @throws {CreateCredentialResponseError} For unexpected errors during response creation.\n *\n * @example v1.0 - Immediate flow without encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const result = await createCredentialResponse({\n * config,\n * flow: {\n * credentials: [{ credential: \"eyJ...\" }],\n * notificationId: \"notif-123\",\n * },\n * });\n * // result.credentialResponse = { credentials: [{ credential: \"eyJ...\" }], notification_id: \"notif-123\" }\n * // result.credentialResponseJwt = undefined\n *\n * @example v1.3 - Immediate flow with encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const result = await createCredentialResponse({\n * callbacks: { encryptJwe: myEncryptJweCallback },\n * config,\n * credentialResponseEncryption: {\n * alg: \"ECDH-ES\",\n * enc: \"A256GCM\",\n * jwk: issuerEncryptionPublicJwk,\n * },\n * flow: {\n * credentials: [{ credential: \"eyJ...\" }],\n * },\n * });\n * // result.credentialResponse contains plain JSON\n * // result.credentialResponseJwt contains encrypted JWE\n *\n * @example v1.0 - Deferred flow without encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const result = await createCredentialResponse({\n * config,\n * flow: {\n * leadTime: 300,\n * transactionId: \"tx-v1-0\",\n * },\n * });\n * // result.credentialResponse = { lead_time: 300, transaction_id: \"tx-v1-0\" }\n *\n * @example v1.3 - Deferred flow with encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const result = await createCredentialResponse({\n * callbacks: { encryptJwe: myEncryptJweCallback },\n * config,\n * credentialResponseEncryption: {\n * alg: \"ECDH-ES\",\n * enc: \"A256GCM\",\n * jwk: issuerEncryptionPublicJwk,\n * },\n * flow: {\n * interval: 60,\n * transactionId: \"tx-v1-3\",\n * },\n * });\n * // result.credentialResponse = { interval: 60, transaction_id: \"tx-v1-3\" }\n * // result.credentialResponseJwt contains encrypted JWE\n */\n\nexport function createCredentialResponse(\n options:\n | ({\n flow: ImmediateFlowOptions;\n } & Omit<CreateCredentialResponseOptionsV1_0, \"flow\">)\n | ({\n flow: ImmediateFlowOptions;\n } & Omit<CreateCredentialResponseOptionsV1_3, \"flow\">),\n): Promise<CreateCredentialResponseResultWithFlow<ImmediateCredentialResponse>>;\n\nexport function createCredentialResponse(\n options: {\n flow: DeferredFlowOptionsV1_0;\n } & Omit<CreateCredentialResponseOptionsV1_0, \"flow\">,\n): Promise<\n CreateCredentialResponseResultWithFlow<DeferredCredentialResponseV1_0>\n>;\n\nexport function createCredentialResponse(\n options: {\n flow: DeferredFlowOptionsV1_3;\n } & Omit<CreateCredentialResponseOptionsV1_3, \"flow\">,\n): Promise<\n CreateCredentialResponseResultWithFlow<DeferredCredentialResponseV1_3>\n>;\n\nexport function createCredentialResponse(\n options: CreateCredentialResponseOptions,\n): Promise<CreateCredentialResponseResult>;\n\nexport async function createCredentialResponse(\n options: CreateCredentialResponseOptions,\n): Promise<CreateCredentialResponseResult> {\n try {\n const credentialResponse = buildVersionedResponse(options);\n let credentialResponseJwt: string | undefined;\n\n if (options.credentialResponseEncryption) {\n const encryptJwe = options.callbacks?.encryptJwe;\n\n if (!encryptJwe) {\n throw new Oid4vciError(\n \"'credentialResponseEncryption' was provided but 'callbacks.encryptJwe' is not defined...\",\n );\n }\n\n credentialResponseJwt = await encryptResponse(\n credentialResponse,\n options.credentialResponseEncryption,\n encryptJwe,\n );\n }\n\n return { credentialResponse, credentialResponseJwt };\n } catch (error) {\n if (\n error instanceof ItWalletSpecsVersionError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new CreateCredentialResponseError(\n `Unexpected error during create credential response: ${error instanceof Error ? error.message : String(error)}`,\n error,\n );\n }\n}\n\nfunction buildVersionedResponse(\n options: CreateCredentialResponseOptions,\n): CredentialResponse {\n const version = options.config.itWalletSpecsVersion;\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n return V1_0.createCredentialResponseV1_0(options.flow);\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n return V1_3.createCredentialResponseV1_3(options.flow);\n }\n\n throw new ItWalletSpecsVersionError(\"createCredentialResponse\", version, [\n ItWalletSpecsVersion.V1_0,\n ItWalletSpecsVersion.V1_3,\n ]);\n}\n\nasync function encryptResponse(\n credentialResponse: CredentialResponse,\n credentialResponseEncryption: CredentialResponseEncryption,\n encryptJwe: EncryptJweCallback,\n): Promise<string> {\n const jweEncryptor: JweEncryptor = {\n alg: credentialResponseEncryption.alg,\n enc: credentialResponseEncryption.enc,\n method: \"jwk\",\n publicJwk: credentialResponseEncryption.jwk,\n };\n\n const { jwe } = await encryptJwe(\n jweEncryptor,\n JSON.stringify(credentialResponse),\n );\n\n return jwe;\n}\n","import { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport type { DeferredFlowOptionsV1_0, ImmediateFlowOptions } from \"../types\";\n\nimport {\n type CredentialResponseV1_0,\n zCredentialResponseV1_0,\n} from \"./z-credential-response\";\n\nexport function createCredentialResponseV1_0(\n flow: DeferredFlowOptionsV1_0 | ImmediateFlowOptions,\n): CredentialResponseV1_0 {\n if (\"credentials\" in flow) {\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n {\n credentials: flow.credentials,\n ...(flow.notificationId !== undefined && {\n notification_id: flow.notificationId,\n }),\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.0\",\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n {\n lead_time: flow.leadTime,\n transaction_id: flow.transactionId,\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.0\",\n );\n}\n","import { z } from \"zod\";\n\nimport { zImmediateCredentialResponse } from \"../z-immediate-credential-response\";\n\nexport const zDeferredCredentialResponseV1_0 = z.strictObject({\n lead_time: z\n .number()\n .int()\n .positive()\n .describe(\n \"REQUIRED if credentials is not present, otherwise it MUST NOT be present. The amount of time (in seconds) required before making a Deferred Credential Request.\",\n ),\n transaction_id: z.string().nonempty(),\n});\n\nexport type DeferredCredentialResponseV1_0 = z.infer<\n typeof zDeferredCredentialResponseV1_0\n>;\n\nexport const zCredentialResponseV1_0 = z.union([\n zImmediateCredentialResponse,\n zDeferredCredentialResponseV1_0,\n]);\n\nexport type CredentialResponseV1_0 = z.infer<typeof zCredentialResponseV1_0>;\n","import { z } from \"zod\";\n\nexport const zCredentialObject = z.object({\n credential: z.string(),\n});\n\nexport type CredentialObject = z.infer<typeof zCredentialObject>;\n\nexport const zImmediateCredentialResponse = z.strictObject({\n credentials: z\n .array(zCredentialObject)\n .nonempty()\n .describe(\n \"Conditional. Array of issued Digital Credentials as JSON objects with `credential` member containing encoded credential string. Present for immediate issuance (HTTP 200).\",\n ),\n notification_id: z\n .string()\n .optional()\n .describe(\n \"OPTIONAL. Identifier for notification requests. Only present with credentials parameter.\",\n ),\n});\n\nexport type ImmediateCredentialResponse = z.infer<\n typeof zImmediateCredentialResponse\n>;\n","import { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport type { DeferredFlowOptionsV1_3, ImmediateFlowOptions } from \"../types\";\n\nimport {\n type CredentialResponseV1_3,\n zCredentialResponseV1_3,\n} from \"./z-credential-response\";\n\nexport function createCredentialResponseV1_3(\n flow: DeferredFlowOptionsV1_3 | ImmediateFlowOptions,\n): CredentialResponseV1_3 {\n if (\"credentials\" in flow) {\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n {\n credentials: flow.credentials,\n ...(flow.notificationId !== undefined && {\n notification_id: flow.notificationId,\n }),\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.3\",\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n {\n interval: flow.interval,\n transaction_id: flow.transactionId,\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.3\",\n );\n}\n","import { z } from \"zod\";\n\nimport { zImmediateCredentialResponse } from \"../z-immediate-credential-response\";\n\nexport const zDeferredCredentialResponseV1_3 = z.strictObject({\n interval: z\n .number()\n .int()\n .positive()\n .describe(\n \"REQUIRED if transaction_id is present, otherwise it MUST NOT be present. The amount of time (in seconds) required before making a Deferred Credential Request\",\n ),\n transaction_id: z.string().nonempty(),\n});\n\nexport type DeferredCredentialResponseV1_3 = z.infer<\n typeof zDeferredCredentialResponseV1_3\n>;\n\nexport const zCredentialResponseV1_3 = z.union([\n zImmediateCredentialResponse,\n zDeferredCredentialResponseV1_3,\n]);\n\nexport type CredentialResponseV1_3 = z.infer<typeof zCredentialResponseV1_3>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { CredentialRequestV1_0 } from \"../credential-request/v1.0\";\nimport type { CredentialRequestV1_3 } from \"../credential-request/v1.3\";\n\nimport { FetchCredentialResponseError } from \"../errors\";\nimport {\n CredentialResponse,\n zCredentialResponseV1_0,\n zCredentialResponseV1_3,\n} from \"./z-credential-response\";\n\n/**\n * Options for fetching credential response\n * Accepts credential requests from any supported version\n */\nexport interface FetchCredentialResponseOptions {\n accessToken: string;\n callbacks: Pick<CallbackContext, \"fetch\">;\n credentialEndpoint: string;\n /**\n * Credential request object (supports both v1.0 and v1.3 formats)\n */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n dPoP: string;\n}\n\n/**\n * Fetch a credential response from the credential endpoint\n *\n * Supports both v1.0 and v1.3 credential request formats.\n * The response format is version-agnostic.\n *\n * @param options - Configuration for credential fetch\n * @returns Parsed credential response\n * @throws {UnexpectedStatusCodeError} If HTTP status is not 200 or 202 for deferred issuance\n * @throws {ValidationError} If response validation fails\n * @throws {FetchCredentialResponseError} For unexpected errors\n */\nexport async function fetchCredentialResponse(\n options: FetchCredentialResponseOptions,\n): Promise<CredentialResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const credentialResponse = await fetch(options.credentialEndpoint, {\n body: JSON.stringify(options.credentialRequest),\n headers: {\n [HEADERS.AUTHORIZATION]: `DPoP ${options.accessToken}`,\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.DPOP]: options.dPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(\n [200, 202],\n UnexpectedStatusCodeError,\n )(credentialResponse);\n\n const credentialResponseJson = await credentialResponse.json();\n\n if (\"proof\" in options.credentialRequest) {\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n credentialResponseJson,\n `Failed to parse credential response (v1.0)`,\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n credentialResponseJson,\n `Failed to parse credential response (v1.3)`,\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchCredentialResponseError(\n `Unexpected error during credential response: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n","import { zAlgValueNotNone, zJwk } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nimport type { CredentialResponseV1_0 } from \"./v1.0/z-credential-response\";\nimport type { CredentialResponseV1_3 } from \"./v1.3/z-credential-response\";\n\nexport {\n zCredentialResponseV1_0,\n zDeferredCredentialResponseV1_0,\n} from \"./v1.0/z-credential-response\";\n\nexport type {\n CredentialResponseV1_0,\n DeferredCredentialResponseV1_0,\n} from \"./v1.0/z-credential-response\";\n\nexport {\n zCredentialResponseV1_3,\n zDeferredCredentialResponseV1_3,\n} from \"./v1.3/z-credential-response\";\n\nexport type {\n CredentialResponseV1_3,\n DeferredCredentialResponseV1_3,\n} from \"./v1.3/z-credential-response\";\n\nexport {\n zCredentialObject,\n zImmediateCredentialResponse,\n} from \"./z-immediate-credential-response\";\n\nexport type {\n CredentialObject,\n ImmediateCredentialResponse,\n} from \"./z-immediate-credential-response\";\n\nexport type CredentialResponse =\n | CredentialResponseV1_0\n | CredentialResponseV1_3;\n\nexport const zCredentialResponseEncryption = z.looseObject({\n alg: zAlgValueNotNone,\n enc: z.string(),\n jwk: zJwk,\n});\n\nexport type CredentialResponseEncryption = z.infer<\n typeof zCredentialResponseEncryption\n>;\n","import { CallbackContext, VerifyJwtCallback } from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport { itWalletEntityStatementClaimsSchema } from \"@pagopa/io-wallet-oid-federation\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { FetchMetadataError } from \"../errors\";\nimport {\n MetadataResponse,\n zMetadataResponseV1_0,\n zMetadataResponseV1_3,\n zPartialIssuerMetadata,\n} from \"./z-metadata-response\";\n\ninterface RawFederationResult {\n discoveredVia: \"federation\";\n metadata: z.infer<typeof itWalletEntityStatementClaimsSchema>[\"metadata\"];\n openid_federation_claims: z.infer<typeof itWalletEntityStatementClaimsSchema>;\n}\n\ninterface RawOid4vciResult {\n discoveredVia: \"oid4vci\";\n metadata: {\n oauth_authorization_server: Record<string, unknown>;\n openid_credential_issuer: z.infer<typeof zPartialIssuerMetadata>;\n };\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.endsWith(\"/\") ? url : `${url}/`;\n}\n\nexport interface FetchMetadataOptions {\n /** Callback providing the fetch implementation */\n callbacks: {\n /**\n * Optional JWT signature verification callback.\n * When provided, the entity statement signature retrieved via federation\n * discovery is verified using this callback.\n * When omitted, trust is derived solely from TLS (the default behaviour).\n */\n verifyJwt?: VerifyJwtCallback;\n } & Pick<CallbackContext, \"fetch\">;\n\n /**\n * SDK configuration used to route discovery logic by IT-Wallet specification version.\n */\n config: IoWalletSdkConfig;\n\n /**\n * Base URL of the Credential Issuer (e.g. \"https://issuer.example.it\").\n * The well-known paths are appended automatically.\n */\n credentialIssuerUrl: string;\n}\n\n/**\n * Attempts the federation discovery path.\n * Returns the normalised metadata object if successful or undefined.\n * In case of ValidationError, the error is re-thrown, as it indicates a non-compliant implementation that should be surfaced instead of falling back to the OID4VCI discovery.\n * For any other error (e.g. network issues, non-200 status code), undefined is returned to trigger the fallback mechanism.\n */\nasync function tryFederationDiscovery(\n fetch: ReturnType<typeof createFetcher>,\n baseUrl: string,\n verifyJwt?: VerifyJwtCallback,\n): Promise<RawFederationResult | undefined> {\n try {\n const federationUrl = new URL(\n \".well-known/openid-federation\",\n ensureTrailingSlash(baseUrl),\n ).toString();\n const response = await fetch(federationUrl);\n\n if (response.status !== 200) {\n return undefined;\n }\n\n const entityStatement = await response.text();\n const { header, payload } = decodeJwt({\n jwt: entityStatement,\n payloadSchema: itWalletEntityStatementClaimsSchema,\n });\n\n if (verifyJwt) {\n const jwtSigner = {\n alg: header.alg as string,\n kid: header.kid as string,\n method: \"federation\" as const,\n };\n const result = await verifyJwt(jwtSigner, {\n compact: entityStatement,\n header,\n payload,\n });\n if (!result.verified) {\n throw new ValidationError(\n \"Entity statement signature verification failed\",\n );\n }\n }\n\n return {\n discoveredVia: \"federation\",\n metadata: payload.metadata,\n openid_federation_claims: payload,\n };\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n return undefined;\n }\n}\n\n/**\n * Executes the fallback OID4VCI discovery path:\n * 1. GET {baseUrl}/.well-known/openid-credential-issuer\n * 2a. If authorization_servers[] is present → GET {authServerUrl}/.well-known/oauth-authorization-server\n * 2b. If absent → the issuer JSON already contains the auth-server claims inline\n *\n * Well-known paths are appended relative to the full base URL, preserving any\n * path segment (e.g. \"https://issuer.example.it/v1\" → \"https://issuer.example.it/v1/.well-known/...\").\n */\nasync function fallbackDiscovery(\n fetch: ReturnType<typeof createFetcher>,\n baseUrl: string,\n): Promise<RawOid4vciResult> {\n const issuerUrl = new URL(\n \".well-known/openid-credential-issuer\",\n ensureTrailingSlash(baseUrl),\n ).toString();\n const issuerResponse = await fetch(issuerUrl);\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(issuerResponse);\n\n const issuerJson = parseWithErrorHandling(\n zPartialIssuerMetadata,\n await issuerResponse.json(),\n \"Failed to parse credential issuer metadata\",\n );\n const authorizationServers = issuerJson.authorization_servers;\n\n let oauthAuthorizationServer: Record<string, unknown>;\n\n if (authorizationServers && authorizationServers.length > 0) {\n const parsedUrl = z.url().safeParse(authorizationServers[0]);\n if (!parsedUrl.success || !parsedUrl.data.startsWith(\"https://\")) {\n throw new ValidationError(\n \"authorization_servers[0] is not a valid HTTPS URL\",\n );\n }\n\n const authServerUrl = new URL(\n \".well-known/oauth-authorization-server\",\n ensureTrailingSlash(parsedUrl.data),\n ).toString();\n\n const authServerResponse = await fetch(authServerUrl);\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(authServerResponse);\n\n oauthAuthorizationServer = (await authServerResponse.json()) as Record<\n string,\n unknown\n >;\n } else {\n oauthAuthorizationServer = issuerJson;\n }\n\n return {\n discoveredVia: \"oid4vci\",\n metadata: {\n oauth_authorization_server: oauthAuthorizationServer,\n openid_credential_issuer: issuerJson,\n },\n };\n}\n\n/**\n * Performs the OID4VCI discovery flow for a Credential Issuer, routing discovery\n * strategy and metadata schema validation based on the IT-Wallet specification version\n * provided in `config`.\n *\n * **v1.0**: Only `.well-known/openid-federation` is attempted. If federation discovery\n * fails, a `FetchMetadataError` is thrown — there is no OID4VCI fallback in v1.0.\n * Returns `MetadataResponseV1_0` with `discoveredVia: \"federation\"`.\n *\n * **v1.3**: Federation discovery is attempted first (`.well-known/openid-federation`).\n * On failure, falls back to `.well-known/openid-credential-issuer` + optional\n * `.well-known/oauth-authorization-server`. Returns `MetadataResponseV1_3`.\n *\n * Well-known paths are appended relative to the full `credentialIssuerUrl`, preserving\n * any path segment (e.g. `\"https://issuer.example.it/v1\"` →\n * `\"https://issuer.example.it/v1/.well-known/...\"`).\n *\n * When federation discovery succeeds, the full entity statement claims are\n * preserved in `openid_federation_claims`.\n * Signature verification of the entity statement is optional: supply\n * `callbacks.verifyJwt` to enable it. When omitted, trust is derived from TLS\n * alone (successful retrieval from the well-known endpoint).\n *\n * @param options - Configuration for metadata fetching, including `config` for version routing\n * @returns Normalised metadata with `discoveredVia` indicating the discovery path used\n * @throws {UnexpectedStatusCodeError} If a fallback endpoint returns a non-200 status (v1.3 only)\n * @throws {ValidationError} If the response does not match the expected schema\n * @throws {ItWalletSpecsVersionError} If `config.itWalletSpecsVersion` is not V1_0 or V1_3\n * @throws {FetchMetadataError} If federation discovery fails for v1.0, or for any other unexpected error\n */\nexport async function fetchMetadata(\n options: FetchMetadataOptions,\n): Promise<MetadataResponse> {\n const { config } = options;\n try {\n const urlValidation = z.url().safeParse(options.credentialIssuerUrl);\n if (!urlValidation.success || !urlValidation.data.startsWith(\"https://\")) {\n throw new ValidationError(\n \"credentialIssuerUrl must be a valid HTTPS URL\",\n );\n }\n\n const fetch = createFetcher(options.callbacks.fetch);\n\n if (config.isVersion(ItWalletSpecsVersion.V1_0)) {\n // v1.0: federation ONLY — no OID4VCI fallback\n const federationResult = await tryFederationDiscovery(\n fetch,\n options.credentialIssuerUrl,\n options.callbacks.verifyJwt,\n );\n if (!federationResult) {\n throw new FetchMetadataError(\n `Federation discovery failed for IT Wallet v1.0; no fallback available for credentialIssuerUrl ${options.credentialIssuerUrl}`,\n );\n }\n return parseWithErrorHandling(\n zMetadataResponseV1_0,\n federationResult,\n \"Failed to parse v1.0 metadata response\",\n );\n }\n\n if (config.isVersion(ItWalletSpecsVersion.V1_3)) {\n // v1.3: federation-first, OID4VCI fallback\n const federationResult = await tryFederationDiscovery(\n fetch,\n options.credentialIssuerUrl,\n options.callbacks.verifyJwt,\n );\n const raw =\n federationResult ??\n (await fallbackDiscovery(fetch, options.credentialIssuerUrl));\n return parseWithErrorHandling(\n zMetadataResponseV1_3,\n raw,\n \"Failed to parse v1.3 metadata response\",\n );\n }\n\n throw new ItWalletSpecsVersionError(\n \"fetchMetadata\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof ItWalletSpecsVersionError ||\n error instanceof FetchMetadataError\n ) {\n throw error;\n }\n throw new FetchMetadataError(\n \"Unexpected error during metadata fetch\",\n error,\n );\n }\n}\n","import {\n itWalletEntityStatementClaimsSchema,\n itWalletMetadataV1_0,\n itWalletMetadataV1_3,\n} from \"@pagopa/io-wallet-oid-federation\";\nimport { z } from \"zod\";\n\nexport const zMetadataResponseV1_0 = z.object({\n discoveredVia: z.enum([\"federation\"]),\n metadata: itWalletMetadataV1_0,\n openid_federation_claims: itWalletEntityStatementClaimsSchema,\n});\n\nexport const zMetadataResponseV1_3 = z.object({\n discoveredVia: z.enum([\"federation\", \"oid4vci\"]),\n metadata: itWalletMetadataV1_3,\n openid_federation_claims: itWalletEntityStatementClaimsSchema.optional(),\n});\n\nexport const zMetadataResponse = z.union([\n zMetadataResponseV1_0,\n zMetadataResponseV1_3,\n]);\n\nexport type MetadataResponseV1_0 = z.infer<typeof zMetadataResponseV1_0>;\nexport type MetadataResponseV1_3 = z.infer<typeof zMetadataResponseV1_3>;\nexport type MetadataResponse = MetadataResponseV1_0 | MetadataResponseV1_3;\n\n// For intermediate parsing in fallbackDiscovery:\nexport const zPartialIssuerMetadata = z.looseObject({\n authorization_servers: z.array(z.string()).optional(),\n});\n","import { CallbackContext, JwtSignerX5c } from \"@openid4vc/oauth2\";\nimport { Jwk, V1_0, V1_3 } from \"@pagopa/io-wallet-oauth2\";\nimport { KeyStorageLevelV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { WalletProviderError } from \"../errors\";\nimport { WalletAttestationOptions } from \"./types\";\nimport {\n KeyAttestationStatus,\n keyAttestationTypeHeader,\n} from \"./z-key-attestation\";\n\nfunction assertV1_0Options(\n options: WalletAttestationOptions,\n): asserts options is V1_0.WalletAttestationOptionsV1_0 {\n if (options.signer.method !== \"federation\") {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.0 (federation) but received options with signer method \"${options.signer.method}\"`,\n );\n }\n}\n\nfunction assertV1_3Options(\n options: WalletAttestationOptions,\n): asserts options is V1_3.WalletAttestationOptionsV1_3 {\n if (options.signer.method !== \"x5c\") {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.3 (x5c) but received options with signer method \"${options.signer.method}\"`,\n );\n }\n}\n\n/**\n * @interface KeyAttestationOptions\n * @description Defines the options required to create a key attestation JWT.\n * This attestation conveys information about the cryptographic keys managed by the wallet,\n * their storage characteristics, user authentication level, and revocation status.\n */\nexport interface KeyAttestationOptions {\n /**\n * The array of JWKs representing the attested keys.\n */\n attestedKeys: [Jwk, ...Jwk[]];\n\n callbacks: Pick<CallbackContext, \"signJwt\">;\n\n /**\n * Optional URL to the key storage component certification.\n */\n certification?: string;\n\n /**\n * The optional expiration date for the attestation JWT. If not provided, a default lifetime will be used.\n * @type {Date}\n */\n expiresAt?: Date;\n\n /**\n * The issuance date of the key attestation. Defaults to the current date and time if not provided.\n * @type {Date}\n */\n issuedAt?: Date;\n\n issuer: string;\n\n /**\n * The levels of security for key storage as per ISO 18045 standards.\n * @type {[KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]]}\n */\n keyStorage: [KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]];\n\n /**\n * The signer information containing the Key ID and the X.509 certificate chain.\n */\n signer: JwtSignerX5c;\n\n /**\n * The status information related to the key attestation.\n */\n status: KeyAttestationStatus;\n\n /**\n * An array of JWTs representing the chain of trust from the federation's trust anchor\n * @type {[string, ...string[]]}\n */\n trustChain?: [string, ...string[]];\n\n /**\n * The levels of user authentication as per ISO 18045 standards.\n * @type {[KeyStorageLevel, ...KeyStorageLevel[]]}\n */\n userAuthentication: [KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]];\n}\n\n/**\n * @class WalletProvider\n * @description An implementation of a wallet provider for the OpenID4VCI protocol, tailored for the Italian ecosystem.\n * It handles the creation of wallet attestations required during the credential issuance flow.\n */\nexport class WalletProvider {\n private specVersion: ItWalletSpecsVersion;\n\n constructor(options: IoWalletSdkConfig) {\n this.specVersion = options.itWalletSpecsVersion;\n }\n\n /**\n * Creates a wallet unit attestation.\n *\n * The key attestation is a signed token that describes the attested keys, their storage characteristics,\n * user authentication level, and status, and can include certification and a trust chain as needed.\n *\n * @public\n * @async\n * @param {KeyAttestationOptions} options - The options used to construct and sign the key attestation JWT.\n * @returns {Promise<string>} A promise that resolves to the signed key attestation JWT.\n * @throws {WalletProviderError} Thrown when the JWT cannot be created or signed.\n */\n public async createItKeyAttestationJwt(\n options: KeyAttestationOptions,\n ): Promise<string> {\n const { signJwt } = options.callbacks;\n\n const now = new Date();\n const issuedAt = options.issuedAt ?? now;\n const expiresAt =\n options.expiresAt ?? addSecondsToDate(now, 3600 * 24 * 360);\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n typ: keyAttestationTypeHeader,\n x5c: options.signer.x5c,\n ...(options.trustChain && { trust_chain: options.trustChain }),\n };\n\n const payload = {\n attested_keys: options.attestedKeys,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: options.issuer,\n key_storage: options.keyStorage,\n status: options.status,\n user_authentication: options.userAuthentication,\n ...(options.certification && { certification: options.certification }),\n };\n\n try {\n const { jwt } = await signJwt(options.signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n throw new WalletProviderError(\n `Failed to create key attestation JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Creates a wallet attestation JWT according to the configured Italian Wallet specification version.\n *\n * Version Differences:\n * - v1.0: Uses only `trust_chain` in header (federation method)\n * - v1.3: Requires `x5c` in header, optional `trust_chain`, supports `nbf` and `status` claims\n *\n * @public\n * @async\n * @param {WalletAttestationOptions} options - The necessary parameters to build the attestation.\n * @returns {Promise<string>} A promise that resolves to the signed wallet attestation JWT as a string.\n * @throws {WalletProviderError} When dpopJwkPublic.kid is missing\n * @throws {ItWalletSpecsVersionError} When version is not supported\n *\n * @example v1.0 - Basic wallet attestation with trust chain\n * const jwt = await provider.createItWalletAttestationJwt({\n * callbacks: { signJwt: mySignJwtCallback },\n * dpopJwkPublic: myJwk,\n * issuer: \"https://wallet-provider.example.com\",\n * signer: {\n * alg: \"ES256\",\n * kid: \"provider-key-id\",\n * trustChain: [\"trust-anchor-jwt\", \"intermediate-jwt\"]\n * }\n * });\n *\n * @example v1.3 - Wallet attestation with x5c and optional fields\n * const jwt = await provider.createItWalletAttestationJwt({\n * callbacks: { signJwt: mySignJwtCallback },\n * dpopJwkPublic: myJwk,\n * issuer: \"https://wallet-provider.example.com\",\n * signer: {\n * alg: \"ES256\",\n * kid: \"provider-key-id\",\n * x5c: [\"cert1-base64\", \"cert2-base64\"],\n * trustChain: [\"trust-anchor-jwt\"] // Optional in v1.3\n * },\n * nbf: new Date('2025-01-01'), // Optional\n * status: { status_list: { idx: 2, uri: \"https://status.example.com\" } } // Optional\n * });\n */\n\n public async createItWalletAttestationJwt(\n options: WalletAttestationOptions,\n ): Promise<string> {\n // Validate that dpopJwkPublic has a kid property\n // This validation is common across all versions\n if (!options.dpopJwkPublic.kid) {\n throw new WalletProviderError(\"The DPoP JWK must have a 'kid' property\");\n }\n\n if (this.specVersion === ItWalletSpecsVersion.V1_0) {\n assertV1_0Options(options);\n return V1_0.createWalletAttestationJwt({\n authenticatorAssuranceLevel: options.authenticatorAssuranceLevel,\n callbacks: options.callbacks,\n dpopJwkPublic: options.dpopJwkPublic,\n expiresAt: options.expiresAt,\n issuer: options.issuer,\n signer: options.signer,\n walletLink: options.walletLink,\n walletName: options.walletName,\n });\n }\n\n if (this.specVersion === ItWalletSpecsVersion.V1_3) {\n assertV1_3Options(options);\n return V1_3.createWalletAttestationJwt({\n callbacks: options.callbacks,\n dpopJwkPublic: options.dpopJwkPublic,\n expiresAt: options.expiresAt,\n issuer: options.issuer,\n nbf: options.nbf,\n signer: options.signer,\n status: options.status,\n walletLink: options.walletLink,\n walletName: options.walletName,\n });\n }\n\n throw new ItWalletSpecsVersionError(\n \"createItWalletAttestationJwt\",\n this.specVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,8BAAmC;AACnC,8BAGO;AACP,6BAKO;;;ACRA,IAAM,eA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,KAAK,QAAQ;AAAA,QACb,QAAQ,QAAQ;AAAA,QAChB,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,MACtB,CAAC;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,MACA,KAAK;AAAA,MACL,CAAC,8CAAqB,MAAM,8CAAqB,IAAI;AAAA,IACvD;AAAA,EACF;AACF;","names":["createCredentialRequest","z","import_zod","import_io_wallet_utils","offerJson","import_io_wallet_utils","import_io_wallet_utils","import_zod","import_zod","import_oauth2","import_io_wallet_utils","import_zod","createCredentialRequest","createCredentialRequest","import_io_wallet_oauth2","import_io_wallet_utils","import_io_wallet_oauth2","import_zod","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_io_wallet_oauth2","import_zod","import_io_wallet_utils","import_io_wallet_utils","import_zod","import_zod","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_io_wallet_oauth2","import_zod","import_io_wallet_oauth2","import_io_wallet_oid_federation","import_io_wallet_utils","import_zod","import_io_wallet_oid_federation","import_zod","verifyJwt","z","import_io_wallet_oauth2","import_io_wallet_utils"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/authorization-response/complete-authorization.ts","../src/errors.ts","../src/authorization-response/verify-authorization-response.ts","../src/authorization-response/z-authorization-response.ts","../src/credential-offer/extract-grant-details.ts","../src/credential-offer/z-credential-offer.ts","../src/credential-offer/parse-credential-offer-uri.ts","../src/credential-offer/resolve-credential-offer.ts","../src/credential-offer/validate-credential-offer.ts","../src/credential-request/create-credential-request.ts","../src/credential-request/v1.0/create-credential-request.ts","../src/credential-request/v1.0/z-credential.ts","../src/credential-request/z-base-credential-request.ts","../src/credential-request/v1.3/create-credential-request.ts","../src/credential-request/v1.3/z-credential.ts","../src/credential-request/parse-credential-request.ts","../src/credential-request/z-proof-jwt.ts","../src/credential-request/verify-credential-request-jwt-proof.ts","../src/credential-request/verify-key-attestation-jwt.ts","../src/wallet-provider/z-key-attestation.ts","../src/credential-response/create-credential-response.ts","../src/credential-response/v1.0/create-credential-response.ts","../src/credential-response/v1.0/z-credential-response.ts","../src/credential-response/z-immediate-credential-response.ts","../src/credential-response/v1.3/create-credential-response.ts","../src/credential-response/v1.3/z-credential-response.ts","../src/credential-response/fetch-credential-response.ts","../src/credential-response/z-credential-response.ts","../src/metadata/fetch-metadata.ts","../src/metadata/z-metadata-response.ts","../src/wallet-provider/WalletProvider.ts"],"sourcesContent":["export * from \"./authorization-response/complete-authorization\";\nexport * from \"./authorization-response/verify-authorization-response\";\nexport * from \"./authorization-response/z-authorization-response\";\nexport { extractGrantDetails } from \"./credential-offer/extract-grant-details\";\nexport { parseCredentialOfferUri } from \"./credential-offer/parse-credential-offer-uri\";\nexport { resolveCredentialOffer } from \"./credential-offer/resolve-credential-offer\";\nexport type {\n ExtractGrantDetailsResult,\n ParseCredentialOfferUriOptions,\n ResolveCredentialOfferOptions,\n ValidateCredentialOfferOptions,\n} from \"./credential-offer/types\";\nexport { validateCredentialOffer } from \"./credential-offer/validate-credential-offer\";\nexport type {\n AuthorizationCodeGrant,\n CredentialOffer,\n CredentialOfferGrants,\n CredentialOfferUri,\n} from \"./credential-offer/z-credential-offer\";\nexport * from \"./credential-request/create-credential-request\";\nexport * from \"./credential-request/parse-credential-request\";\nexport type * from \"./credential-request/types\";\nexport type { CredentialRequestV1_0 } from \"./credential-request/v1.0/z-credential\";\nexport { zCredentialRequestV1_0 } from \"./credential-request/v1.0/z-credential\";\nexport type { CredentialRequestV1_3 } from \"./credential-request/v1.3/z-credential\";\nexport { zCredentialRequestV1_3 } from \"./credential-request/v1.3/z-credential\";\nexport * from \"./credential-request/verify-credential-request-jwt-proof\";\nexport * from \"./credential-request/verify-key-attestation-jwt\";\nexport * from \"./credential-request/z-proof-jwt\";\nexport * from \"./credential-response/create-credential-response\";\nexport * from \"./credential-response/fetch-credential-response\";\nexport * from \"./credential-response/z-credential-response\";\nexport * from \"./errors\";\nexport {\n type FetchMetadataOptions,\n fetchMetadata,\n} from \"./metadata/fetch-metadata\";\nexport {\n type MetadataResponse,\n type MetadataResponseV1_0,\n type MetadataResponseV1_3,\n zMetadataResponse,\n zMetadataResponseV1_0,\n zMetadataResponseV1_3,\n} from \"./metadata/z-metadata-response\";\nexport * from \"./wallet-provider/WalletProvider\";\nexport type * from \"./wallet-provider/types\";\nexport * from \"./wallet-provider/z-key-attestation\";\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport { getJwtFromFormPost } from \"@pagopa/io-wallet-oauth2\";\nimport {\n FetchAuthorizationResponseOptions,\n fetchAuthorizationResponse,\n} from \"@pagopa/io-wallet-oid4vp\";\nimport {\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../errors\";\nimport {\n VerifyAuthorizationResponseFormPostJWTOptions,\n verifyAuthorizationResponseFormPostJWT,\n} from \"./verify-authorization-response\";\nimport {\n AuthorizationResponse,\n zAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface CompleteAuthorizationOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The response_uri returned by the server after a successful\n * OID4VP Authorization Response is sent\n */\n response_uri: string;\n}\n\n/**\n * Combination of {@link CompleteAuthorizationOptions},\n * {@link FetchAuthorizationResponseOptions} and\n * {@link VerifyAuthorizationResponseFormPostJWTOptions}\n */\nexport type SendAuthorizationResponseAndExtractCodeOptions =\n FetchAuthorizationResponseOptions &\n Omit<\n VerifyAuthorizationResponseFormPostJWTOptions,\n \"authorizationResponseCompact\" | \"authorizationResponseDecoded\"\n > &\n Omit<CompleteAuthorizationOptions, \"response_uri\">;\n\nexport type CompleteAuthorizationResult = Awaited<\n ReturnType<typeof getJwtFromFormPost<AuthorizationResponse>>\n>;\n\n/**\n * Method that completes the form_post.jwt based authorization\n * process for credentials issuance following the ITWallet\n * specification by retrieving the form from the provided uri,\n * extracting and parsing the contained JWT and verifying the\n * iss and state fields match the authorization session's expected\n * values.\n * See https://italia.github.io/eid-wallet-it-docs/versione-corrente/en/credential-issuance-low-level.html#\n * steps 6-7 for details.\n *\n * @param options {@link CompleteAuthorizationOptions}\n * @returns An object containing the fetched JWT and its decoding. The JWT contains the access code\n * necessary for access token issuance\n */\nexport async function completeAuthorization(\n options: CompleteAuthorizationOptions,\n): Promise<CompleteAuthorizationResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const authorizationResponseResult = await fetch(options.response_uri);\n\n await hasStatusOrThrow(\n 200,\n UnexpectedStatusCodeError,\n )(authorizationResponseResult);\n\n return await getJwtFromFormPost({\n formData: await authorizationResponseResult.text(),\n schema: zAuthorizationResponse,\n });\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error completing the authorization process: ${error instanceof Error ? `${error.name} : ${error.message}` : String(error)}`,\n );\n }\n}\n\n/**\n * Convenience method that combines {@link completeAuthorization},\n * oid4vp package's {@link fetchAuthorizationResponse} and {@link verifyAuthorizationResponseFormPostJWT} to retrieve the\n * access code starting from the authorization response and the response uri\n *\n * @param options {@link SendAuthorizationResponseAndExtractCodeOptions}\n * @returns An object containing the fetched JWT and its decoding. The JWT contains the access code\n * for necessary for access token issuance\n */\nexport async function sendAuthorizationResponseAndExtractCode(\n options: SendAuthorizationResponseAndExtractCodeOptions,\n): Promise<AuthorizationResponse> {\n try {\n const authorizationResult = await fetchAuthorizationResponse(options);\n\n if (!authorizationResult.redirect_uri) {\n throw new Oid4vciError(\n \"The authorization response did not contain a redirect_uri\",\n );\n }\n\n const jwtAndPayload = await completeAuthorization({\n ...options,\n response_uri: authorizationResult.redirect_uri,\n });\n\n return verifyAuthorizationResponseFormPostJWT({\n authorizationResponseCompact: jwtAndPayload.jwt,\n authorizationResponseDecoded: jwtAndPayload.decodedJwt,\n callbacks: {\n verifyJwt: options.callbacks.verifyJwt,\n },\n iss: options.iss,\n signer: options.signer,\n state: options.state,\n });\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error sending the authorization response and retrieving the acces code: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","/**\n * Generic error thrown on Oid4vci operations\n */\nexport class Oid4vciError extends Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"Oid4vciError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown in case the DPoP key passed to the\n * {@link WalletProvider.createItWalletAttestationJwt} method\n * doesn't contain a kid\n */\nexport class WalletProviderError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"WalletProviderError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during nonce request.\n */\nexport class NonceRequestError extends Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"NonceRequestError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential response fetching.\n */\nexport class FetchCredentialResponseError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FetchCredentialResponseError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential request parsing.\n */\nexport class ParseCredentialRequestError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ParseCredentialRequestError\";\n }\n}\n\n/**\n * Error thrown when metadata fetching fails at all discovery endpoints.\n */\nexport class FetchMetadataError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FetchMetadataError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential response creation.\n */\nexport class CreateCredentialResponseError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CreateCredentialResponseError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during credential request JWT proof verification.\n */\nexport class VerifyCredentialRequestJwtProofError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"VerifyCredentialRequestJwtProofError\";\n }\n}\n\n/**\n * Error thrown when an error occurs during key attestation JWT verification.\n */\nexport class VerifyKeyAttestationJwtError extends Oid4vciError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"VerifyKeyAttestationJwtError\";\n }\n}\n\n/**\n * Error thrown when an error occurs during credential offer operations.\n * This includes parsing, resolving, validating, and extracting grant details from credential offers.\n */\nexport class CredentialOfferError extends Oid4vciError {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"CredentialOfferError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown when a credential request is missing the required DPoP proof header.\n */\nexport class MissingDpopProofError extends Oid4vciError {\n constructor(\n message = \"Credential request is missing required 'DPoP' proof header\",\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"MissingDpopProofError\";\n }\n}\n\n/**\n * Error thrown when a credential request has a missing or invalid Authorization header.\n */\nexport class CredentialAuthorizationHeaderError extends Oid4vciError {\n constructor(\n message = \"Credential request is missing required 'Authorization' header with DPoP scheme\",\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"CredentialAuthorizationHeaderError\";\n }\n}\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\n\nimport { Oid4vciError } from \"../errors\";\nimport {\n AuthorizationResponse,\n zAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface VerifyAuthorizationResponseOptions {\n /**\n * Authorization response object containing the authorization\n * code, the issuer and the session's state\n */\n authorizationResponse: AuthorizationResponse;\n\n /**\n * The issuer the Wallet Instance started the\n * authorization flow (either via PAR or directly) with\n */\n iss: string;\n\n /**\n * The state sent by the Wallet Instance at the start\n * of the authorization flow (either via PAR or directly)\n */\n state: string;\n}\n\nexport interface VerifyAuthorizationResponseFormPostJWTOptions {\n /**\n * Compact AuthorizaitonResponse JWT\n */\n authorizationResponseCompact: string;\n\n /**\n * Authorization Response object containing the authorization\n * code, the issuer and the session's state\n */\n authorizationResponseDecoded: ReturnType<\n typeof decodeJwt<undefined, typeof zAuthorizationResponse>\n >;\n\n /**\n * Callback for verifying the authorization jwt signature\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The issuer the Wallet Instance started the\n * authorization flow (either via PAR or directly) with\n */\n iss: string;\n\n /**\n * Optional custom signer for verifying the authorization response JWT.\n * If not provided, the library will attempt to verify using information from the JWT header.\n */\n signer?: JwtSigner;\n\n /**\n * The state sent by the Wallet Instance at the start\n * of the authorization flow (either via PAR or directly)\n */\n state: string;\n}\n\n/**\n * Utility that verifies if the returned Authorization Response's iss and state field match\n * the Authorization Session ones\n * @param options {@link VerifyAuthorizationResponseOptions}\n * @returns the {@link AuthorizationResponse} passed as an option\n * @throws {Oid4vciError} in case the iss or state field of the Authorization request don't\n * match the provided ones\n */\nexport async function verifyAuthorizationResponse(\n options: VerifyAuthorizationResponseOptions,\n): Promise<AuthorizationResponse> {\n if (options.authorizationResponse.iss !== options.iss)\n throw new Oid4vciError(\n `Response result iss doesn't match passed counterpart. Expected: ${options.iss}, Got: ${options.authorizationResponse.iss}`,\n );\n if (options.authorizationResponse.state !== options.state)\n throw new Oid4vciError(\n `Response result state doesn't match passed counterpart. Expected: ${options.state}, Got: ${options.authorizationResponse.state}`,\n );\n\n return options.authorizationResponse;\n}\n\n/**\n * Wrapper of {@link verifyAuthorizationResponse} that verifies the signature of the JWT containing\n * the authorization response and extracts the {@link AuthorizationResponse} payload\n * @param options {@link VerifyAuthorizationResponseFormPostJWTOptions}\n * @returns the {@link AuthorizationResponse} passed as an option\n * @throws {Oid4vciError} in case {@link verifyAuthorizationResponse} throws or in case\n * signature verification fails\n */\nexport async function verifyAuthorizationResponseFormPostJWT(\n options: VerifyAuthorizationResponseFormPostJWTOptions,\n): Promise<AuthorizationResponse> {\n try {\n const decodedJwt = options.authorizationResponseDecoded;\n\n await verifyJwt({\n compact: options.authorizationResponseCompact,\n errorMessage: \"Error verifying JWT signature\",\n header: decodedJwt.header,\n payload: decodedJwt.payload,\n\n signer:\n options.signer ??\n jwtSignerFromJwt({\n header: decodedJwt.header,\n payload: decodedJwt.payload,\n }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return verifyAuthorizationResponse({\n authorizationResponse: options.authorizationResponseDecoded.payload,\n iss: options.iss,\n state: options.state,\n });\n } catch (error) {\n if (error instanceof Oid4vciError) throw error;\n\n throw new Oid4vciError(\n `Unexpected error verifying form post jwt: ${error instanceof Error ? `${error.name} : ${error.message}` : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\nexport const zAuthorizationResponse = z.object({\n code: z.string(),\n iss: z.string(),\n state: z.string(),\n});\n\nexport type AuthorizationResponse = z.infer<typeof zAuthorizationResponse>;\n","import type { ExtractGrantDetailsResult } from \"./types\";\nimport type { CredentialOffer } from \"./z-credential-offer\";\n\nimport { CredentialOfferError } from \"../errors\";\n\n/**\n * Extracts grant details from a credential offer.\n *\n * IT-Wallet v1.3 only supports the `authorization_code` grant type.\n * Pre-authorized code grants are NOT supported.\n *\n * This function extracts:\n * - Grant type (always \"authorization_code\" for IT-Wallet)\n * - Scope (REQUIRED)\n * - Authorization server (OPTIONAL, but REQUIRED when CI uses multiple auth servers)\n * - Issuer state (OPTIONAL)\n *\n * @param credentialOffer - The credential offer to extract grant details from\n * @returns Grant details containing the grant type and authorization code grant information\n * @throws {CredentialOfferError} If grants or authorization_code grant is missing\n */\nexport function extractGrantDetails(\n credentialOffer: CredentialOffer,\n): ExtractGrantDetailsResult {\n if (!credentialOffer.grants) {\n throw new CredentialOfferError(\"No grants found in credential offer\");\n }\n\n const authCodeGrant = credentialOffer.grants.authorization_code;\n\n if (!authCodeGrant) {\n throw new CredentialOfferError(\"authorization_code grant not found\");\n }\n\n return {\n authorizationCodeGrant: {\n authorizationServer: authCodeGrant.authorization_server,\n issuerState: authCodeGrant.issuer_state,\n scope: authCodeGrant.scope,\n },\n grantType: \"authorization_code\",\n };\n}\n","import { z } from \"zod\";\n\n/**\n * Authorization Code Grant schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * The authorization_code grant is REQUIRED for IT-Wallet v1.3.\n * Pre-authorized code grant is NOT supported.\n */\nexport const zAuthorizationCodeGrant = z.object({\n /**\n * CONDITIONALLY REQUIRED. HTTPS URL of the Authorization Server.\n * REQUIRED only when the Credential Issuer uses multiple Authorization Servers.\n * If present, MUST match one of the authorization_servers in the Credential Issuer metadata.\n */\n authorization_server: z.url().optional(),\n\n /**\n * OPTIONAL. String value representing the issuer state.\n * Used to correlate the authorization request with the credential offer.\n */\n issuer_state: z.string().optional(),\n\n /**\n * REQUIRED. OAuth 2.0 scope value.\n * Defines the scope of access requested by the credential offer.\n */\n scope: z.string(),\n});\n\n/**\n * Credential Offer Grants schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * The grants object is REQUIRED for IT-Wallet v1.3.\n * Only authorization_code grant is supported.\n */\nexport const zCredentialOfferGrants = z.object({\n /**\n * REQUIRED. Authorization Code grant details.\n * IT-Wallet v1.3 only supports authorization_code grant.\n */\n authorization_code: zAuthorizationCodeGrant,\n});\n\n/**\n * Credential Offer schema\n * IT-Wallet v1.3 specification: Section 5.1\n *\n * Represents a credential offer from a Credential Issuer to a wallet.\n */\nexport const zCredentialOffer = z.object({\n /**\n * REQUIRED. Array of credential configuration identifiers.\n * References the types of credentials offered as defined in the Credential Issuer metadata.\n */\n credential_configuration_ids: z.array(z.string()).min(1),\n\n /**\n * REQUIRED. HTTPS URL of the Credential Issuer.\n * The Credential Issuer from which the wallet will request credentials.\n */\n credential_issuer: z.url(),\n\n /**\n * REQUIRED. Grant information for the credential offer.\n * IT-Wallet v1.3 requires authorization_code grant.\n */\n grants: zCredentialOfferGrants,\n});\n\n/**\n * Credential Offer URI schema\n * Represents a parsed credential offer URI with scheme and parameters.\n *\n * Supports three URL schemes:\n * - openid-credential-offer:// - Standard OpenID scheme (custom URL scheme)\n * - haip-vci:// - High Assurance Interoperability Profile scheme (custom URL scheme)\n * - https:// - HTTPS Universal Links (preferred method)\n *\n * Transmission methods:\n * - By value: credential_offer parameter contains the JSON directly\n * - By reference: credential_offer_uri parameter points to the JSON\n */\nexport const zCredentialOfferUri = z\n .object({\n /**\n * OPTIONAL. Inline credential offer JSON (by value).\n * URL-encoded JSON string containing the credential offer.\n */\n credential_offer: z.string().optional(),\n\n /**\n * OPTIONAL. URL pointing to the credential offer JSON (by reference).\n * HTTPS URL where the credential offer can be fetched.\n */\n credential_offer_uri: z.url().optional(),\n\n /**\n * URL scheme used for the credential offer.\n * Determines the invocation method.\n */\n scheme: z.enum([\"openid-credential-offer\", \"haip-vci\", \"https\"]),\n })\n .refine((data) => data.credential_offer || data.credential_offer_uri, {\n message: \"Either credential_offer or credential_offer_uri must be present\",\n });\n\n/**\n * TypeScript type for Authorization Code Grant\n */\nexport type AuthorizationCodeGrant = z.infer<typeof zAuthorizationCodeGrant>;\n\n/**\n * TypeScript type for Credential Offer Grants\n */\nexport type CredentialOfferGrants = z.infer<typeof zCredentialOfferGrants>;\n\n/**\n * TypeScript type for Credential Offer\n */\nexport type CredentialOffer = z.infer<typeof zCredentialOffer>;\n\n/**\n * TypeScript type for Credential Offer URI\n */\nexport type CredentialOfferUri = z.infer<typeof zCredentialOfferUri>;\n","import type { ParseCredentialOfferUriOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\nimport {\n type CredentialOfferUri,\n zCredentialOfferUri,\n} from \"./z-credential-offer\";\n\n/**\n * Parses a credential offer URI and extracts the scheme and parameters.\n *\n * This function supports three URL schemes for credential offers:\n * - `openid-credential-offer://` - Standard OpenID scheme (custom URL scheme)\n * - `haip-vci://` - High Assurance Interoperability Profile scheme (custom URL scheme)\n * - `https://` - HTTPS Universal Links (preferred method)\n *\n * Credential offers can be transmitted in two ways:\n * - **By value**: The `credential_offer` parameter contains the JSON directly (URL-encoded)\n * - **By reference**: The `credential_offer_uri` parameter points to a URL where the JSON can be fetched\n *\n * @param options - Parsing options containing the URI and allowed schemes\n * @returns Parsed credential offer URI components with scheme and parameters\n * @throws {CredentialOfferError} If the URI is invalid, uses an unsupported scheme, or is missing required parameters\n *\n * @example Parse by-value offer with custom scheme\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"openid-credential-offer://?credential_offer=%7B%22credential_issuer%22%3A...\"\n * });\n * console.log(parsed.scheme); // \"openid-credential-offer\"\n * console.log(parsed.credential_offer); // URL-decoded JSON string\n * ```\n *\n * @example Parse by-reference offer with HTTPS Universal Link\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"https://wallet.example.com/credential-offer?credential_offer_uri=https://issuer.example.com/offers/123\"\n * });\n * console.log(parsed.scheme); // \"https\"\n * console.log(parsed.credential_offer_uri); // \"https://issuer.example.com/offers/123\"\n * ```\n *\n * @example Restrict allowed schemes\n * ```typescript\n * const parsed = await parseCredentialOfferUri({\n * uri: \"openid-credential-offer://?credential_offer=...\",\n * allowedSchemes: [\"openid-credential-offer\"] // Only allow standard OpenID scheme\n * });\n * ```\n */\nexport async function parseCredentialOfferUri(\n options: ParseCredentialOfferUriOptions,\n): Promise<CredentialOfferUri> {\n const {\n allowedSchemes = [\"openid-credential-offer\", \"haip-vci\", \"https\"],\n uri,\n } = options;\n\n try {\n // Parse the URI using the URL API\n const url = new URL(uri);\n\n // Extract and validate the scheme (protocol without the trailing colon)\n const scheme = url.protocol.replace(\":\", \"\");\n\n if (!allowedSchemes.includes(scheme)) {\n throw new CredentialOfferError(\n `Unsupported URL scheme: ${scheme}. Allowed schemes: ${allowedSchemes.join(\", \")}`,\n );\n }\n\n // Extract query parameters\n const credentialOffer = url.searchParams.get(\"credential_offer\");\n const credentialOfferUri = url.searchParams.get(\"credential_offer_uri\");\n\n // Construct the parsed result\n const parsed = {\n credential_offer: credentialOffer || undefined,\n credential_offer_uri: credentialOfferUri || undefined,\n scheme: scheme as \"haip-vci\" | \"https\" | \"openid-credential-offer\",\n };\n\n // Validate the structure using Zod\n // This will ensure that at least one of credential_offer or credential_offer_uri is present\n return zCredentialOfferUri.parse(parsed);\n } catch (error) {\n // Re-throw CredentialOfferError as-is\n if (error instanceof CredentialOfferError) {\n throw error;\n }\n\n // Wrap other errors in CredentialOfferError\n throw new CredentialOfferError(\n `Failed to parse credential offer URI: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import {\n UnexpectedStatusCodeError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { ResolveCredentialOfferOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\nimport { parseCredentialOfferUri } from \"./parse-credential-offer-uri\";\nimport { type CredentialOffer, zCredentialOffer } from \"./z-credential-offer\";\n\n/**\n * Resolves a credential offer from a URI or inline JSON string.\n *\n * This function handles multiple input formats:\n * - **URI with inline offer** (by value): The credential offer JSON is embedded in the URI as a URL-encoded parameter\n * - **URI with reference** (by reference): The URI points to a remote endpoint where the credential offer can be fetched\n * - **Direct JSON string**: The credential offer is provided as a plain JSON string\n *\n * Supported URI schemes:\n * - `openid-credential-offer://` - Standard OpenID scheme\n * - `haip-vci://` - High Assurance Interoperability Profile scheme\n * - `https://` - HTTPS Universal Links (preferred)\n *\n * @param options - Resolution options containing the credential offer and fetch callback\n * @returns Resolved and validated credential offer object\n * @throws {CredentialOfferError} If parsing fails, HTTP request fails, or validation fails\n *\n * @example Resolve by-value offer (inline JSON in URI)\n * ```typescript\n * const offer = await resolveCredentialOffer({\n * credentialOffer: \"openid-credential-offer://?credential_offer=%7B%22credential_issuer%22%3A...\",\n * callbacks: { fetch }\n * });\n * console.log(offer.credential_issuer);\n * ```\n *\n * @example Resolve by-reference offer (fetch from remote URI)\n * ```typescript\n * const offer = await resolveCredentialOffer({\n * credentialOffer: \"openid-credential-offer://?credential_offer_uri=https://issuer.example.com/offers/123\",\n * callbacks: { fetch }\n * });\n * console.log(offer.grants.authorization_code.scope);\n * ```\n *\n * @example Resolve from direct JSON string\n * ```typescript\n * const offerJson = '{\"credential_issuer\":\"https://issuer.example.com\",\"credential_configuration_ids\":[\"UniversityDegree\"],\"grants\":{\"authorization_code\":{\"scope\":\"openid\"}}}';\n * const offer = await resolveCredentialOffer({\n * credentialOffer: offerJson,\n * callbacks: { fetch }\n * });\n * ```\n */\nexport async function resolveCredentialOffer(\n options: ResolveCredentialOfferOptions,\n): Promise<CredentialOffer> {\n const { callbacks, credentialOffer } = options;\n\n try {\n // Check if the input is a URI (starts with a known scheme)\n if (\n credentialOffer.startsWith(\"openid-credential-offer://\") ||\n credentialOffer.startsWith(\"haip-vci://\") ||\n credentialOffer.startsWith(\"https://\")\n ) {\n // Parse the URI to extract the scheme and parameters\n const parsed = await parseCredentialOfferUri({ uri: credentialOffer });\n\n // By value - inline credential offer\n if (parsed.credential_offer) {\n const decoded = decodeURIComponent(parsed.credential_offer);\n const offerJson = JSON.parse(decoded);\n return zCredentialOffer.parse(offerJson);\n }\n\n // By reference - fetch from remote URI\n if (parsed.credential_offer_uri) {\n const fetch = createFetcher(callbacks.fetch);\n\n const response = await fetch(parsed.credential_offer_uri, {\n headers: {\n Accept: \"application/json\",\n },\n method: \"GET\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(response);\n\n const offerJson = await response.json();\n return zCredentialOffer.parse(offerJson);\n }\n }\n\n // Assume it's a direct JSON string\n const offerJson = JSON.parse(credentialOffer);\n return zCredentialOffer.parse(offerJson);\n } catch (error) {\n // Re-throw CredentialOfferError and UnexpectedStatusCodeError as-is\n if (\n error instanceof CredentialOfferError ||\n error instanceof UnexpectedStatusCodeError\n ) {\n throw error;\n }\n\n // Wrap other errors in CredentialOfferError\n throw new CredentialOfferError(\n `Failed to resolve credential offer: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type { ValidateCredentialOfferOptions } from \"./types\";\n\nimport { CredentialOfferError } from \"../errors\";\n\n/**\n * Validates a credential offer against IT-Wallet v1.3 specifications.\n *\n * This function performs comprehensive validation of a credential offer to ensure\n * compliance with the IT-Wallet v1.3 requirements (Section 5.1):\n *\n * **Required validations:**\n * - `credential_issuer` must be an HTTPS URL\n * - `credential_configuration_ids` must contain at least one identifier\n * - `grants` object is REQUIRED for IT-Wallet v1.3\n * - `authorization_code` grant is REQUIRED (pre-authorized code is NOT supported)\n * - `scope` is REQUIRED within the authorization_code grant\n *\n * **Conditional validations:**\n * - `authorization_server` is REQUIRED when the Credential Issuer uses multiple Authorization Servers\n * - If `authorization_server` is present, it MUST match one of the servers in the Credential Issuer metadata\n *\n * @param options - Validation options containing the credential offer, config, and optional metadata\n * @throws {CredentialOfferError} If any validation rule fails\n */\nexport async function validateCredentialOffer(\n options: ValidateCredentialOfferOptions,\n): Promise<void> {\n const { credentialIssuerMetadata, credentialOffer } = options;\n\n // Validate credential_issuer is HTTPS\n if (!credentialOffer.credential_issuer.startsWith(\"https://\")) {\n throw new CredentialOfferError(\"credential_issuer must be an HTTPS URL\");\n }\n\n // Validate credential_configuration_ids is not empty\n if (credentialOffer.credential_configuration_ids.length === 0) {\n throw new CredentialOfferError(\n \"credential_configuration_ids must contain at least one identifier\",\n );\n }\n\n // IT-Wallet v1.3: grants is REQUIRED\n if (!credentialOffer.grants) {\n throw new CredentialOfferError(\"grants is REQUIRED for IT-Wallet v1.3\");\n }\n\n const authCodeGrant = credentialOffer.grants.authorization_code;\n\n // IT-Wallet v1.3: authorization_code grant is REQUIRED\n if (!authCodeGrant) {\n throw new CredentialOfferError(\n \"authorization_code grant is REQUIRED for IT-Wallet v1.3\",\n );\n }\n\n // Validate scope is present (REQUIRED in authorization_code)\n if (!authCodeGrant.scope) {\n throw new CredentialOfferError(\"authorization_code.scope is REQUIRED\");\n }\n\n // Conditional validation for authorization_server\n // REQUIRED only when CI uses multiple authorization servers\n if (credentialIssuerMetadata?.authorization_servers) {\n const authServers = credentialIssuerMetadata.authorization_servers;\n\n // If multiple authorization servers exist, authorization_server must be present\n if (authServers.length > 1 && !authCodeGrant.authorization_server) {\n throw new CredentialOfferError(\n \"authorization_server is REQUIRED when Credential Issuer uses multiple Authorization Servers\",\n );\n }\n\n // If authorization_server is present, validate it matches metadata\n if (authCodeGrant.authorization_server) {\n if (!authServers.includes(authCodeGrant.authorization_server)) {\n throw new CredentialOfferError(\n `authorization_server '${authCodeGrant.authorization_server}' does not match Credential Issuer metadata. Valid servers: ${authServers.join(\", \")}`,\n );\n }\n }\n }\n}\n","import {\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { CredentialRequest, CredentialRequestOptions } from \"./types\";\nimport type { CredentialRequestV1_0 } from \"./v1.0/z-credential\";\nimport type { CredentialRequestV1_3 } from \"./v1.3/z-credential\";\n\nimport * as V1_0 from \"./v1.0/create-credential-request\";\nimport * as V1_3 from \"./v1.3/create-credential-request\";\n\nfunction isV1_0Options(\n options: CredentialRequestOptions,\n): options is V1_0.CredentialRequestOptionsV1_0 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0;\n}\n\nfunction isV1_3Options(\n options: CredentialRequestOptions,\n): options is V1_3.CredentialRequestOptionsV1_3 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3;\n}\n\n/**\n * Creates a credential request according to the configured Italian Wallet specification version.\n *\n * Version Differences:\n * - v1.0: Returns singular `proof` object with explicit `proof_type` field\n * - v1.3: Returns plural `proofs` object with JWT array (batch support) and requires key attestation\n *\n * @param options - Request options including version config\n * @returns Version-specific credential request object\n * @throws {ItWalletSpecsVersionError} When version is not supported or keyAttestation is used with wrong version\n *\n * @example v1.0 - Basic credential request\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const request = await createCredentialRequest({\n * config,\n * callbacks: { signJwt: mySignJwtCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * nonce: \"c_nonce_value\",\n * signer: myJwtSigner\n * });\n * // Returns: { credential_identifier: \"...\", proof: { jwt: \"...\", proof_type: \"jwt\" } }\n *\n * @example v1.3 - Credential request with key attestation\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const request = await createCredentialRequest({\n * config,\n * callbacks: { signJwt: mySignJwtCallback, hash: myHashCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"education_degree_unibo_2017_l31_informatica\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * keyAttestation: 'eyJ...', // Required for v1.3\n * nonce: \"c_nonce_value\",\n * signers: [myJwtSigner]\n * });\n * // Returns: { credential_identifier: \"...\", proofs: { jwt: [\"...\"] } }\n */\n\n// Function overload for v1.0\nexport function createCredentialRequest(\n options: V1_0.CredentialRequestOptionsV1_0,\n): Promise<CredentialRequestV1_0>;\n\n// Function overload for v1.3\nexport function createCredentialRequest(\n options: V1_3.CredentialRequestOptionsV1_3,\n): Promise<CredentialRequestV1_3>;\n\n// Implementation signature (not callable by users)\nexport async function createCredentialRequest(\n options: CredentialRequestOptions,\n): Promise<CredentialRequest> {\n const { config } = options;\n\n if (isV1_0Options(options)) {\n return V1_0.createCredentialRequest(options);\n }\n\n if (isV1_3Options(options)) {\n return V1_3.createCredentialRequest(options);\n }\n\n throw new ItWalletSpecsVersionError(\n \"createCredentialRequest\",\n (config as { itWalletSpecsVersion: string }).itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n}\n","import type { CallbackContext, JwtSignerJwk } from \"@openid4vc/oauth2\";\n\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n dateToSeconds,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../../errors\";\nimport { BaseCredentialRequestOptions } from \"../types\";\nimport { CredentialRequestV1_0, zCredentialRequestV1_0 } from \"./z-credential\";\n\n/**\n * Options for creating a credential request with v1.0\n * Does NOT include keyAttestation parameter\n */\nexport interface CredentialRequestOptionsV1_0\n extends BaseCredentialRequestOptions {\n callbacks: Pick<CallbackContext, \"signJwt\">;\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n signer: JwtSignerJwk;\n // keyAttestation is NOT accepted in v1.0\n}\n\n/**\n * Create a Credential Request for IT-Wallet v1.0\n *\n * Version 1.0 specifics:\n * - Returns singular `proof` object with explicit `proof_type` field\n * - JWT header does NOT include `key_attestation`\n * - Single credential per request (no batch support)\n *\n * @param options - Request options\n * @returns Credential request for v1.0\n * @throws {ValidationError} When credential request validation fails\n * @throws {Oid4vciError} For other unexpected errors\n *\n * @example\n * const request = await createCredentialRequest({\n * callbacks: { signJwt: mySignJwtCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * nonce: \"c_nonce_value\",\n * signer: myJwtSigner\n * });\n * // Returns: { credential_identifier: \"...\", proof: { jwt: \"...\", proof_type: \"jwt\" } }\n */\nexport const createCredentialRequest = async (\n options: CredentialRequestOptionsV1_0,\n): Promise<CredentialRequestV1_0> => {\n try {\n const { signJwt } = options.callbacks;\n\n const proofJwt = await signJwt(options.signer, {\n header: {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"openid4vci-proof+jwt\",\n },\n payload: {\n aud: options.issuerIdentifier,\n iat: dateToSeconds(new Date()),\n iss: options.clientId,\n nonce: options.nonce,\n },\n });\n\n return parseWithErrorHandling(zCredentialRequestV1_0, {\n credential_identifier: options.credential_identifier,\n proof: {\n jwt: proofJwt.jwt,\n proof_type: \"jwt\",\n },\n } satisfies CredentialRequestV1_0);\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new Oid4vciError(\n `Unexpected error during create credential request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport {\n credentialRequestRefiner,\n zBaseCredentialRequest,\n} from \"../z-base-credential-request\";\n\n/**\n * Proof object schema for v1.0\n * Contains a JWT and explicit proof_type field\n */\nexport const zCredentialRequestProof = z.object({\n jwt: z.string().min(1, \"JWT must not be empty\"),\n proof_type: z.literal(\"jwt\"), // MUST be \"jwt\"\n});\n\nexport type CredentialRequestProof = z.infer<typeof zCredentialRequestProof>;\n\n/**\n * Credential request schema for IT-Wallet v1.0\n *\n * Key characteristics:\n * - Uses singular `proof` object\n * - Explicit `proof_type` field (always \"jwt\")\n * - Single credential per request (no batch support)\n */\nexport const zCredentialRequestV1_0 = zBaseCredentialRequest\n .extend({\n proof: zCredentialRequestProof.describe(\n \"REQUIRED. Proof of possession of key material (must contain proof_type=jwt and a jwt).\",\n ),\n })\n .superRefine((data, ctx) => {\n credentialRequestRefiner(data, ctx);\n });\n\nexport type CredentialRequestV1_0 = z.infer<typeof zCredentialRequestV1_0>;\n","import { z } from \"zod\";\n\nimport type { CredentialRequestV1_0 } from \"./v1.0/z-credential\";\nimport type { CredentialRequestV1_3 } from \"./v1.3/z-credential\";\n\n/**\n * Base Credential request schema for IT-Wallet v1.0 and v1.3.\n * @internal\n */\nexport const zBaseCredentialRequest = z.object({\n credential_configuration_id: z\n .string()\n .optional()\n .describe(\n \"REQUIRED if credential_identifier param is absent. MUST NOT be used otherwise.\",\n ),\n\n credential_identifier: z\n .string()\n .optional()\n .describe(\n \"REQUIRED when Authorization Details of type openid_credential was returned. MUST NOT be used if credential_configuration_id is present.\",\n ),\n\n transaction_id: z\n .string()\n .optional()\n .describe(\n \"REQUIRED only in case of deferred flow. MUST NOT be present in immediate flow.\",\n ),\n});\n\nexport function credentialRequestRefiner(\n data: CredentialRequestV1_0 | CredentialRequestV1_3,\n ctx: z.RefinementCtx,\n) {\n // Exclusive OR between credential_identifier and credential_configuration_id\n if (data.credential_identifier && data.credential_configuration_id) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"credential_identifier and credential_configuration_id MUST NOT be used together\",\n path: [\"credential_identifier\"],\n });\n }\n\n if (!data.credential_identifier && !data.credential_configuration_id) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"One of credential_identifier or credential_configuration_id MUST be present\",\n path: [\"credential_identifier\"],\n });\n }\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n type JwtSignerJwk,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n dateToSeconds,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vciError } from \"../../errors\";\nimport { BaseCredentialRequestOptions } from \"../types\";\nimport { CredentialRequestV1_3, zCredentialRequestV1_3 } from \"./z-credential\";\n\n/**\n * Options for creating a credential request with v1.3\n * Requires keyAttestation parameter\n */\nexport interface CredentialRequestOptionsV1_3\n extends BaseCredentialRequestOptions {\n callbacks: Pick<CallbackContext, \"hash\" | \"signJwt\">;\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n keyAttestation: string; // Required in v1.3\n /**\n * The maximum size for a single credential batch issuance request.\n * It is extracted from the Issuer Metadata: `batch_credential_issuance.batch_size`.\n */\n maxBatchSize?: number;\n /**\n * The list of signers to generate JWT proofs.\n * Multiple unique signers must be used for batch issuance.\n */\n signers: JwtSignerJwk[];\n}\n\n/**\n * Create a Credential Request for IT-Wallet v1.3\n *\n * Version 1.3 specifics:\n * - Returns plural `proofs` object with JWT array (batch support)\n * - proof_type field removed (implicit from structure)\n * - JWT header includes `key_attestation` field (Wallet Unit Attestation)\n *\n * @param options - Request options including keyAttestation\n * @returns Credential request for v1.3\n * @throws {ValidationError} When credential request validation fails\n * @throws {Oid4vciError} For other unexpected errors\n *\n * @example\n * const request = await createCredentialRequest({\n * callbacks: { signJwt: mySignJwtCallback, hash: myHashCallback },\n * clientId: \"my-client-id\",\n * credential_identifier: \"UniversityDegree\",\n * issuerIdentifier: \"https://issuer.example.com\",\n * keyAttestation: \"eyJ...\", // Required in v1.3\n * nonce: \"c_nonce_value\",\n * signers: [myJwtSigner]\n * });\n * // Returns: { credential_identifier: \"...\", proofs: { jwt: [\"...\"] } }\n */\nexport const createCredentialRequest = async (\n options: CredentialRequestOptionsV1_3,\n): Promise<CredentialRequestV1_3> => {\n try {\n const { maxBatchSize, signers } = options;\n\n const [firstSigner, ...otherSigners] = signers;\n\n if (!firstSigner) {\n throw new ValidationError(\"At least one signer is required\");\n }\n\n if (maxBatchSize !== undefined) {\n if (!Number.isInteger(maxBatchSize) || maxBatchSize <= 0) {\n throw new ValidationError(\n \"Invalid maxBatchSize: it must be a positive integer\",\n );\n }\n\n if (signers.length > maxBatchSize) {\n throw new ValidationError(\n \"The number of provided signers exceeds the maximum batch size allowed\",\n );\n }\n }\n\n const { hash, signJwt } = options.callbacks;\n\n // Ensure all keys are unique for batch issuance\n if (signers.length > 1) {\n const allThumbprints = await Promise.all(\n signers.map((signer) =>\n calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: hash,\n jwk: signer.publicJwk,\n }),\n ),\n );\n const uniqueThumbprints = new Set(allThumbprints);\n if (uniqueThumbprints.size !== allThumbprints.length) {\n throw new ValidationError(\n \"Found multiple signers with the same JWK: each JWT proof must be unique and linked to a different credential key pair\",\n );\n }\n }\n\n const createProofJwt = async (signer: JwtSignerJwk): Promise<string> =>\n (\n await signJwt(signer, {\n header: {\n alg: signer.alg,\n jwk: signer.publicJwk,\n key_attestation: options.keyAttestation,\n typ: \"openid4vci-proof+jwt\",\n },\n payload: {\n aud: options.issuerIdentifier,\n iat: dateToSeconds(new Date()),\n iss: options.clientId,\n nonce: options.nonce,\n },\n })\n ).jwt;\n\n const proofJwts: [string, ...string[]] = await Promise.all([\n createProofJwt(firstSigner),\n ...otherSigners.map(createProofJwt),\n ]);\n\n return parseWithErrorHandling(zCredentialRequestV1_3, {\n credential_identifier: options.credential_identifier,\n proofs: {\n jwt: proofJwts,\n },\n } satisfies CredentialRequestV1_3);\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n\n throw new Oid4vciError(\n `Unexpected error during create credential request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport {\n credentialRequestRefiner,\n zBaseCredentialRequest,\n} from \"../z-base-credential-request\";\n\nconst zCredentialRequestProofJwt = z\n .string()\n .min(1, \"JWT must not be empty in credential request proofs array\");\n\n/**\n * Proofs object schema for v1.3\n * Contains an array of JWTs (supports batch issuance)\n * proof_type is implicit (determined by the property name)\n */\nexport const zCredentialRequestProofs = z.object({\n jwt: z.tuple([zCredentialRequestProofJwt], zCredentialRequestProofJwt),\n});\n\nexport type CredentialRequestProofs = z.infer<typeof zCredentialRequestProofs>;\n\n/**\n * Credential request schema for IT-Wallet v1.3\n *\n * Key changes from v1.0:\n * - Uses plural `proofs` object (not `proof`)\n * - proof_type field removed (implicit from structure)\n * - JWT is an array (supports batch issuance)\n * - JWT header includes `key_attestation` field\n */\nexport const zCredentialRequestV1_3 = zBaseCredentialRequest\n .extend({\n proofs: zCredentialRequestProofs.describe(\n \"REQUIRED. Proof of possession of key material (contains array of JWTs for batch support).\",\n ),\n })\n .superRefine((data, ctx) => {\n credentialRequestRefiner(data, ctx);\n });\n\nexport type CredentialRequestV1_3 = z.infer<typeof zCredentialRequestV1_3>;\n","import {\n Oauth2JwtParseError,\n decodeJwt,\n extractDpopJwtFromHeaders,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n FetchHeaders,\n HEADERS,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n CredentialAuthorizationHeaderError,\n MissingDpopProofError as CredentialDpopProofError,\n ParseCredentialRequestError,\n} from \"../errors\";\nimport {\n CredentialRequestV1_0,\n zCredentialRequestV1_0,\n} from \"./v1.0/z-credential\";\nimport {\n CredentialRequestV1_3,\n zCredentialRequestV1_3,\n} from \"./v1.3/z-credential\";\nimport {\n ProofJwtHeader,\n ProofJwtPayload,\n zProofJwtHeaderV1_0,\n zProofJwtHeaderV1_3,\n zProofJwtPayload,\n} from \"./z-proof-jwt\";\n\ntype GrantType = \"authorization_code\" | \"pre-authorized_code\";\n\n/**\n * A normalized proof extracted from the credential request.\n * The proof JWT is decoded and validated, but its signature is not verified.\n */\nexport interface ParsedCredentialProof {\n /** Parsed proof JWT header. */\n header: ProofJwtHeader;\n /** Original compact JWT proof. */\n jwt: string;\n /** Parsed proof JWT payload. */\n payload: ProofJwtPayload;\n /** Normalized proof type. */\n proofType: \"jwt\";\n}\n\n/**\n * Optional expected values used for semantic validation during parsing.\n */\nexport interface ParseCredentialRequestExpectedValues {\n /** Expected `aud` claim inside the proof JWT payload. */\n audience?: string;\n /** Expected credential configuration identifier in the request body. */\n credential_configuration_id?: string;\n /** Expected credential identifier in the request body. */\n credential_identifier?: string;\n /** Expected `iss` claim inside the proof JWT payload. */\n issuer?: string;\n /** Expected `nonce` claim inside the proof JWT payload. */\n nonce?: string;\n}\n\n/**\n * Input options for parsing a credential request.\n */\nexport interface ParseCredentialRequestOptions {\n /** SDK config used to route parsing logic by IT-Wallet specification version. */\n config: IoWalletSdkConfig;\n /** Credential request payload to validate and parse. */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n /** Optional expected values for semantic checks. */\n expected?: ParseCredentialRequestExpectedValues;\n /** Grant type used to validate `iss` requirements in proof JWT payloads. */\n grantType?: GrantType;\n /** HTTP headers of the credential request, used to extract the DPoP proof. */\n headers: FetchHeaders;\n /** Whether the request is expected to be part of deferred issuance flow. */\n isDeferredFlow?: boolean;\n}\n\n/**\n * Parsed and normalized credential request.\n */\nexport interface ParsedCredentialRequest {\n /** Access token extracted from the Authorization header. */\n accessToken: string;\n /** Normalized credential selector values from the request body. */\n credential: {\n credential_configuration_id?: string;\n credential_identifier?: string;\n };\n /** Version-specific validated credential request. */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n /** DPoP proof JWT extracted from the request headers. */\n dpopProof: string;\n /** Normalized list of parsed proof JWTs. */\n proofs: ParsedCredentialProof[];\n /** Transaction metadata derived from flow context and request payload. */\n transaction: {\n isDeferredFlow: boolean;\n transaction_id?: string;\n };\n}\n\n/**\n * Validates request body identifiers against optionally provided expected values.\n */\nfunction validateExpectedValues(\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3,\n expected?: ParseCredentialRequestExpectedValues,\n): void {\n if (!expected) {\n return;\n }\n\n if (\n expected.credential_identifier &&\n credentialRequest.credential_identifier !== expected.credential_identifier\n ) {\n throw new ValidationError(\n \"credential_identifier does not match expected value\",\n );\n }\n\n if (\n expected.credential_configuration_id &&\n credentialRequest.credential_configuration_id !==\n expected.credential_configuration_id\n ) {\n throw new ValidationError(\n \"credential_configuration_id does not match expected value\",\n );\n }\n}\n\n/**\n * Validates that transaction_id presence matches deferred/immediate flow context.\n */\nfunction validateTransactionContext(options: {\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n isDeferredFlow: boolean;\n}): void {\n const { credentialRequest, isDeferredFlow } = options;\n\n if (isDeferredFlow && !credentialRequest.transaction_id) {\n throw new ValidationError(\n \"transaction_id is required for deferred credential issuance\",\n );\n }\n\n if (!isDeferredFlow && credentialRequest.transaction_id) {\n throw new ValidationError(\n \"transaction_id must not be present in immediate credential issuance flow\",\n );\n }\n}\n\n/**\n * Decodes and validates a single proof JWT, then applies semantic claim checks.\n */\nfunction parseProofJwt(options: {\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n jwt: string;\n}): ParsedCredentialProof {\n const decoded = decodeJwt({\n errorMessagePrefix: \"Error decoding credential request proof JWT:\",\n jwt: options.jwt,\n });\n const headerValidation =\n options.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3\n ? zProofJwtHeaderV1_3.safeParse(decoded.header)\n : zProofJwtHeaderV1_0.safeParse(decoded.header);\n\n if (!headerValidation.success) {\n throw new ValidationError(\n \"Credential proof JWT header is invalid or missing required claims\",\n );\n }\n\n const payloadValidation = zProofJwtPayload.safeParse(decoded.payload);\n if (!payloadValidation.success) {\n throw new ValidationError(\n \"Credential proof JWT payload is invalid or missing required claims\",\n );\n }\n\n const payload = payloadValidation.data;\n\n if (options.grantType === \"authorization_code\" && !payload.iss) {\n throw new ValidationError(\n \"Credential proof JWT payload must include iss for authorization_code grant\",\n );\n }\n\n if (options.expected?.audience && payload.aud !== options.expected.audience) {\n throw new ValidationError(\n \"Credential proof JWT aud does not match expected audience\",\n );\n }\n\n if (options.expected?.nonce && payload.nonce !== options.expected.nonce) {\n throw new ValidationError(\n \"Credential proof JWT nonce does not match expected nonce\",\n );\n }\n\n if (\n options.expected?.issuer &&\n payload.iss &&\n payload.iss !== options.expected.issuer\n ) {\n throw new ValidationError(\n \"Credential proof JWT iss does not match expected issuer\",\n );\n }\n\n if (\n options.grantType === \"authorization_code\" &&\n options.expected?.issuer &&\n !payload.iss\n ) {\n throw new ValidationError(\n \"Credential proof JWT payload is missing expected issuer (iss)\",\n );\n }\n\n return {\n header: headerValidation.data,\n jwt: options.jwt,\n payload,\n proofType: \"jwt\",\n };\n}\n\n/**\n * Converts version-specific proof containers (`proof` or `proofs.jwt[]`) into a normalized array.\n */\nfunction normalizeProofs(options: {\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n}): ParsedCredentialProof[] {\n if (\"proof\" in options.credentialRequest) {\n return [\n parseProofJwt({\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n jwt: options.credentialRequest.proof.jwt,\n }),\n ];\n }\n\n return options.credentialRequest.proofs.jwt.map((jwt) =>\n parseProofJwt({\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n jwt,\n }),\n );\n}\n\n/**\n * Builds the normalized parse result shared by v1.0 and v1.3 flows.\n */\nfunction toResult<\n TRequest extends CredentialRequestV1_0 | CredentialRequestV1_3,\n>(options: {\n accessToken: string;\n credentialRequest: TRequest;\n dpopProof: string;\n expected?: ParseCredentialRequestExpectedValues;\n grantType: GrantType;\n isDeferredFlow: boolean;\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 | ItWalletSpecsVersion.V1_3;\n}): ParsedCredentialRequest {\n validateExpectedValues(options.credentialRequest, options.expected);\n validateTransactionContext({\n credentialRequest: options.credentialRequest,\n isDeferredFlow: options.isDeferredFlow,\n });\n\n const proofs = normalizeProofs({\n credentialRequest: options.credentialRequest,\n expected: options.expected,\n grantType: options.grantType,\n itWalletSpecsVersion: options.itWalletSpecsVersion,\n });\n\n return {\n accessToken: options.accessToken,\n credential: {\n credential_configuration_id:\n options.credentialRequest.credential_configuration_id,\n credential_identifier: options.credentialRequest.credential_identifier,\n },\n credentialRequest: options.credentialRequest,\n dpopProof: options.dpopProof,\n proofs,\n transaction: {\n isDeferredFlow: options.isDeferredFlow,\n transaction_id: options.credentialRequest.transaction_id,\n },\n };\n}\n\n/**\n * Extracts and validates the DPoP-bound access token from the Authorization header.\n */\nfunction parseAuthorizationHeader(headers: FetchHeaders): string {\n const authorizationHeader = headers.get(HEADERS.AUTHORIZATION)?.trim();\n\n if (!authorizationHeader) {\n throw new CredentialAuthorizationHeaderError(\n \"Credential request is missing required 'Authorization' header with DPoP scheme\",\n );\n }\n\n const [scheme, token, ...rest] = authorizationHeader.split(/\\s+/);\n\n // Per RFC 9110 authentication schemes are case-insensitive\n if (rest.length > 0 || scheme?.toLowerCase() !== \"dpop\" || !token) {\n throw new CredentialAuthorizationHeaderError(\n \"Credential request contains an invalid 'Authorization' header. Expected format: 'Authorization: DPoP <access_token>'\",\n );\n }\n\n return token;\n}\n\n/**\n * Extracts and validates the DPoP proof JWT from the request headers.\n */\nfunction parseDpopProof(headers: FetchHeaders): string {\n const extracted = extractDpopJwtFromHeaders(headers);\n\n if (!extracted.valid) {\n throw new CredentialDpopProofError(\n \"Credential request contains a 'DPoP' header, but the value is not a valid JWT format\",\n );\n }\n\n if (!extracted.dpopJwt) {\n throw new CredentialDpopProofError(\n \"Credential request contains a 'DPoP' header, but the value is missing or empty\",\n );\n }\n\n return extracted.dpopJwt;\n}\n\n/**\n * Parses and validates a credential request for the configured IT-Wallet version.\n *\n * Performs the following validations in order:\n * 1. **Authorization header** — asserts the `Authorization` HTTP header is present\n * and uses the `DPoP` scheme with a non-empty access token. The extracted token\n * is returned as `accessToken` for subsequent verification by the caller.\n * 2. **DPoP proof header** — asserts the `DPoP` HTTP header is present and contains a\n * compact JWT. The extracted JWT is returned as `dpopProof` for subsequent\n * cryptographic verification by the caller (e.g. via `verifyTokenDPoP`).\n * 3. **Request body schema** — validates the body against the v1.0 or v1.3 schema.\n * 4. **Semantic checks** — verifies optional expected values (`audience`, `nonce`,\n * `issuer`, `credential_identifier`, `credential_configuration_id`).\n * 5. **Transaction context** — enforces `transaction_id` presence/absence rules\n * for deferred vs. immediate issuance flows.\n * 6. **Proof JWT structure** — decodes each proof JWT and validates its header and\n * payload claims, including `iss` requirements for the `authorization_code` grant.\n * For v1.3, asserts the `key_attestation` header claim is present and non-empty.\n *\n * This function does not perform cryptographic signature verification on proof JWTs\n * or the DPoP proof. Both must be verified separately after parsing.\n * For DPoP proofs, the caller can use the `verifyTokenDPoP` function exported by io-wallet-oauth2.\n *\n * @param options - Parsing options and validation context.\n * @returns Normalized parsed credential request including the extracted `accessToken` and `dpopProof`.\n * @throws {CredentialAuthorizationHeaderError} If the `Authorization` header is absent or invalid.\n * @throws {CredentialDpopProofError} If the `DPoP` header is absent or not a valid compact JWT.\n * @throws {ValidationError} If request body schema or semantic checks fail.\n * @throws {Oauth2JwtParseError} If a proof JWT cannot be decoded.\n * @throws {ItWalletSpecsVersionError} If the configured specification version is unsupported.\n * @throws {ParseCredentialRequestError} For unexpected parsing failures.\n */\nexport function parseCredentialRequest(\n options: ParseCredentialRequestOptions,\n): ParsedCredentialRequest {\n const grantType = options.grantType ?? \"authorization_code\";\n const isDeferredFlow = options.isDeferredFlow ?? false;\n const { config } = options;\n\n try {\n const accessToken = parseAuthorizationHeader(options.headers);\n const dpopProof = parseDpopProof(options.headers);\n\n if (options.config.isVersion(ItWalletSpecsVersion.V1_0)) {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequestV1_0,\n options.credentialRequest,\n \"Invalid credential request format for ItWalletSpecsVersion 1.0\",\n );\n\n return toResult({\n accessToken,\n credentialRequest,\n dpopProof,\n expected: options.expected,\n grantType,\n isDeferredFlow,\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n });\n }\n\n if (options.config.isVersion(ItWalletSpecsVersion.V1_3)) {\n const credentialRequest = parseWithErrorHandling(\n zCredentialRequestV1_3,\n options.credentialRequest,\n \"Invalid credential request format for ItWalletSpecsVersion 1.3\",\n );\n\n return toResult({\n accessToken,\n credentialRequest,\n dpopProof,\n expected: options.expected,\n grantType,\n isDeferredFlow,\n itWalletSpecsVersion: ItWalletSpecsVersion.V1_3,\n });\n }\n\n throw new ItWalletSpecsVersionError(\n \"parseCredentialRequest\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof ItWalletSpecsVersionError ||\n error instanceof Oauth2JwtParseError ||\n error instanceof ValidationError ||\n error instanceof CredentialAuthorizationHeaderError ||\n error instanceof CredentialDpopProofError\n ) {\n throw error;\n }\n\n throw new ParseCredentialRequestError(\n `Unexpected error during credential request parsing: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n}\n","import { zJwk } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nconst zBaseProofJwtHeader = z.object({\n alg: z.string().min(1),\n jwk: zJwk,\n typ: z.literal(\"openid4vci-proof+jwt\"),\n});\n\nexport const zProofJwtHeaderV1_0 = zBaseProofJwtHeader.loose();\n\nexport const zProofJwtHeaderV1_3 = zBaseProofJwtHeader\n .extend({\n key_attestation: z.string().min(1),\n })\n .loose();\n\nexport const zProofJwtPayload = z.looseObject({\n aud: z.string().min(1),\n iat: z.number(),\n iss: z.string().min(1).optional(),\n nonce: z.string().min(1),\n});\n\nexport type ProofJwtHeaderV1_0 = z.infer<typeof zProofJwtHeaderV1_0>;\nexport type ProofJwtHeaderV1_3 = z.infer<typeof zProofJwtHeaderV1_3>;\nexport type ProofJwtHeader = ProofJwtHeaderV1_0 | ProofJwtHeaderV1_3;\nexport type ProofJwtPayload = z.infer<typeof zProofJwtPayload>;\n","import { calculateJwkThumbprint, jwtSignerFromJwt } from \"@openid4vc/oauth2\";\nimport {\n CallbackContext,\n HashAlgorithm,\n Jwk,\n Oauth2JwtParseError,\n decodeJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n verifyJwtIatOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n VerifyCredentialRequestJwtProofError,\n VerifyKeyAttestationJwtError,\n} from \"../errors\";\nimport {\n FetchStatusListCallback,\n VerifyKeyAttestationJwtResult,\n verifyKeyAttestationJwt,\n} from \"./verify-key-attestation-jwt\";\nimport {\n ProofJwtHeaderV1_0,\n ProofJwtHeaderV1_3,\n ProofJwtPayload,\n zProofJwtHeaderV1_0,\n zProofJwtHeaderV1_3,\n zProofJwtPayload,\n} from \"./z-proof-jwt\";\n\nexport interface VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * Callbacks required for JWT signature verification and JWK thumbprint hashing.\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n /**\n * The client id of the wallet requesting the credential.\n * If provided, it will be matched against the `iss` claim.\n */\n clientId?: string;\n /**\n * The credential issuer identifier. Matched against the `aud` claim.\n */\n credentialIssuer: string;\n /**\n * Expected nonce value (`c_nonce`) previously shared with the wallet\n * via the Nonce Endpoint.\n */\n expectedNonce: string;\n /**\n * The compact JWT proof to verify.\n */\n jwt: string;\n /**\n * Date at which the nonce expires. If the current time exceeds this value,\n * verification fails before signature checking.\n */\n nonceExpiresAt?: Date;\n /**\n * Current time override. If not provided, `Date.now()` is used.\n */\n now?: Date;\n}\n\nexport interface VerifyCredentialRequestJwtProofOptionsV1_0\n extends VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * SDK configuration that determines the IT-Wallet specification version.\n * Controls which header schema is used and whether key attestation is verified.\n */\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport interface VerifyCredentialRequestJwtProofOptionsV1_3\n extends VerifyCredentialRequestJwtProofBaseOptions {\n /**\n * SDK configuration that determines the IT-Wallet specification version.\n * Controls which header schema is used and whether key attestation is verified.\n */\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n /**\n * Optional callback used to fetch and evaluate key attestation revocation.\n *\n * When omitted and `itWalletSpecsVersion` is v1.3, key attestation revocation\n * is not checked by this function.\n */\n fetchStatusList?: FetchStatusListCallback;\n /**\n * Trusted key attestation issuers (wallet provider entity identifiers).\n * The key attestation `iss` claim must exactly match one of these values.\n */\n trustedWalletProviderIssuers: readonly string[];\n}\n\nexport type VerifyCredentialRequestJwtProofOptions =\n | VerifyCredentialRequestJwtProofOptionsV1_0\n | VerifyCredentialRequestJwtProofOptionsV1_3;\n\ninterface IsJwkInSetOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n jwk: Jwk;\n jwks: Jwk[];\n}\n\nasync function isJwkInSet(options: IsJwkInSetOptions): Promise<boolean> {\n const targetThumbprint = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.jwk,\n });\n\n const thumbprints = await Promise.all(\n options.jwks.map((jwk) =>\n calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk,\n }),\n ),\n );\n\n return thumbprints.includes(targetThumbprint);\n}\n\nfunction verifyProofJwtIatOrThrow(options: {\n now?: Date;\n payload: ProofJwtPayload;\n}) {\n try {\n verifyJwtIatOrThrow({\n iat: options.payload.iat,\n now: options.now,\n });\n } catch (error) {\n if (error instanceof Error) {\n throw new VerifyCredentialRequestJwtProofError(\n `Invalid iat claim in credential request proof JWT: ${error.message}`,\n { cause: error },\n );\n }\n }\n}\n\n/**\n * Verification result for IT-Wallet specification v1.0.\n * Does not include key attestation.\n */\nexport interface VerifyCredentialRequestJwtProofResultV1_0 {\n header: ProofJwtHeaderV1_0;\n payload: ProofJwtPayload;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\n/**\n * Verification result for IT-Wallet specification v1.3.\n * Includes the verified key attestation.\n */\nexport interface VerifyCredentialRequestJwtProofResultV1_3 {\n header: ProofJwtHeaderV1_3;\n keyAttestation: VerifyKeyAttestationJwtResult;\n payload: ProofJwtPayload;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\nexport type VerifyCredentialRequestJwtProofResult =\n | VerifyCredentialRequestJwtProofResultV1_0\n | VerifyCredentialRequestJwtProofResultV1_3;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptionsV1_0,\n): Promise<VerifyCredentialRequestJwtProofResultV1_0>;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptionsV1_3,\n): Promise<VerifyCredentialRequestJwtProofResultV1_3>;\n\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptions,\n): Promise<VerifyCredentialRequestJwtProofResult>;\n\n/**\n * Verifies a credential request JWT proof according to the configured IT-Wallet specification version.\n *\n * Performs the following checks:\n * 1. Validates nonce expiry (if `nonceExpiresAt` is provided)\n * 2. Decodes and validates the JWT header and payload using version-specific schemas\n * 3. Validates proof `iat` freshness (max 5 minutes old, max 60 seconds in the future)\n * 4. Verifies the JWT signature via the `verifyJwt` callback\n * 5. (v1.3 only) Verifies the `key_attestation` JWT and checks that the proof signer key\n * is present in the key attestation's `attested_keys`\n * 6. (v1.3 only) Ensures key attestation `iss` belongs to `trustedWalletProviderIssuers`\n *\n * @param options - Verification options and callbacks.\n * @returns Decoded header, payload, signer, and (v1.3) key attestation result.\n * @throws {VerifyCredentialRequestJwtProofError} If nonce is expired, proof `iat` is outside\n * freshness bounds, signature is invalid, or the signer key is not in the attested keys.\n * @throws {ItWalletSpecsVersionError} If the configured specification version is unsupported.\n * @throws {ValidationError} If JWT header or payload schema validation fails.\n * @throws {Oauth2JwtParseError} If JWT decoding fails.\n */\nexport async function verifyCredentialRequestJwtProof(\n options: VerifyCredentialRequestJwtProofOptions,\n): Promise<VerifyCredentialRequestJwtProofResult> {\n const configVersion = options.config.itWalletSpecsVersion;\n\n try {\n const now = options.now?.getTime() ?? Date.now();\n\n if (options.nonceExpiresAt && now > options.nonceExpiresAt.getTime()) {\n throw new VerifyCredentialRequestJwtProofError(\n \"Nonce used for credential request proof expired\",\n );\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding credential request proof JWT:\",\n headerSchema: zProofJwtHeaderV1_0,\n jwt: options.jwt,\n payloadSchema: zProofJwtPayload,\n });\n\n verifyProofJwtIatOrThrow({ now: options.now, payload });\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n errorMessage: \"Error verifying credential request proof jwt.\",\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding credential request proof JWT:\",\n headerSchema: zProofJwtHeaderV1_3,\n jwt: options.jwt,\n payloadSchema: zProofJwtPayload,\n });\n\n verifyProofJwtIatOrThrow({ now: options.now, payload });\n\n const { signer } = await verifyJwt({\n compact: options.jwt,\n errorMessage: \"Error verifying credential request proof jwt.\",\n expectedAudience: options.credentialIssuer,\n expectedIssuer: options.clientId,\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n if (options.trustedWalletProviderIssuers.length === 0) {\n throw new VerifyCredentialRequestJwtProofError(\n \"trustedWalletProviderIssuers must include at least one trusted wallet provider issuer\",\n );\n }\n\n const keyAttestationResult = await verifyKeyAttestationJwt({\n callbacks: options.callbacks,\n fetchStatusList: options.fetchStatusList,\n keyAttestationJwt: header.key_attestation,\n now: options.now,\n });\n\n if (\n !options.trustedWalletProviderIssuers.includes(\n keyAttestationResult.payload.iss,\n )\n ) {\n throw new VerifyCredentialRequestJwtProofError(\n `Untrusted key attestation issuer: ${keyAttestationResult.payload.iss}`,\n );\n }\n\n const isSignedWithAttestedKey = await isJwkInSet({\n callbacks: options.callbacks,\n jwk: signer.publicJwk,\n jwks: keyAttestationResult.payload.attested_keys,\n });\n\n if (!isSignedWithAttestedKey) {\n throw new VerifyCredentialRequestJwtProofError(\n \"Credential request jwt proof is not signed with a key in the 'key_attestation' jwt payload 'attested_keys'\",\n );\n }\n\n return {\n header,\n keyAttestation: keyAttestationResult,\n payload,\n signer,\n };\n }\n\n throw new ItWalletSpecsVersionError(\n \"verifyCredentialRequestJwtProof\",\n configVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof VerifyCredentialRequestJwtProofError ||\n error instanceof VerifyKeyAttestationJwtError ||\n error instanceof ItWalletSpecsVersionError ||\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n ) {\n throw error;\n }\n\n throw new VerifyCredentialRequestJwtProofError(\n `Unexpected error during credential request proof verification: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n}\n","import {\n CallbackContext,\n Oauth2JwtParseError,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport { ValidationError } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifyKeyAttestationJwtError } from \"../errors\";\nimport {\n KeyAttestationHeader,\n KeyAttestationPayload,\n zKeyAttestationHeader,\n zKeyAttestationPayload,\n} from \"../wallet-provider/z-key-attestation\";\n\nexport type FetchStatusListCallback = (statusList: {\n index: number;\n uri: string;\n}) => Promise<boolean>;\n\n/**\n * Options for verifying a key attestation JWT.\n */\nexport interface VerifyKeyAttestationJwtOptions {\n /**\n * Callback required for JWT signature verification.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n /**\n * Optional callback used to fetch and evaluate revocation status from the\n * status list referenced in `payload.status.status_list`.\n *\n * If omitted, revocation is not checked by this function.\n */\n fetchStatusList?: FetchStatusListCallback;\n /**\n * The compact key attestation JWT (`key-attestation+jwt`) to verify.\n */\n keyAttestationJwt: string;\n /**\n * Current time override. If not provided, the current time is used.\n */\n now?: Date;\n}\n\n/**\n * Result of a successful key attestation JWT verification.\n */\nexport interface VerifyKeyAttestationJwtResult {\n /** Parsed and validated key attestation JWT header. */\n header: KeyAttestationHeader;\n /** Parsed and validated key attestation JWT payload, including `attested_keys`. */\n payload: KeyAttestationPayload;\n /** The resolved signer that was used to verify the JWT. */\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}\n\n/**\n * Decodes, validates, and verifies the signature of a key attestation JWT.\n *\n * The header and payload are validated against the `zKeyAttestationHeader` and\n * `zKeyAttestationPayload` schemas. The JWT signature is verified via the\n * `verifyJwt` callback.\n *\n * Revocation handling:\n * - If `fetchStatusList` is provided, this function checks whether the key\n * attestation is revoked using `payload.status.status_list`.\n * - If `fetchStatusList` is omitted, revocation checking is the caller's\n * responsibility.\n *\n * @param options - Verification options and callbacks.\n * @returns Decoded header, payload, and signer.\n * @throws {Oauth2JwtParseError} If JWT decoding fails.\n * @throws {ValidationError} If schema validation fails.\n */\nexport async function verifyKeyAttestationJwt(\n options: VerifyKeyAttestationJwtOptions,\n): Promise<VerifyKeyAttestationJwtResult> {\n try {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding key attestation JWT:\",\n headerSchema: zKeyAttestationHeader,\n jwt: options.keyAttestationJwt,\n payloadSchema: zKeyAttestationPayload,\n });\n\n // Upstream verifyJwt/jwtSignerFromJwt still match IT-Wallet signature checks.\n const { signer } = await verifyJwt({\n compact: options.keyAttestationJwt,\n errorMessage: \"Key attestation JWT verification failed.\",\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n if (options.fetchStatusList) {\n const { idx, uri } = payload.status.status_list;\n const isRevoked = await options.fetchStatusList({\n index: idx,\n uri,\n });\n\n if (isRevoked) {\n throw new VerifyKeyAttestationJwtError(\n `Key attestation has been revoked (status list: ${uri}, index: ${idx})`,\n );\n }\n }\n\n return { header, payload, signer };\n } catch (error) {\n if (\n error instanceof VerifyKeyAttestationJwtError ||\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n ) {\n throw error;\n }\n\n throw new VerifyKeyAttestationJwtError(\n `Unexpected error during key attestation jwt verification: ${\n error instanceof Error ? error.message : String(error)\n }`,\n { cause: error },\n );\n }\n}\n","import { zCertificateChain, zJwk, zTrustChain } from \"@pagopa/io-wallet-oauth2\";\nimport { zKeyStorageLevelV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport { zItwSupportedSignatureAlg } from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nexport const zStatusList = z.object({\n idx: z.number(),\n uri: z.url(),\n});\n\nexport type StatusList = z.infer<typeof zStatusList>;\n\nexport const zKeyAttestationStatus = z.object({\n status_list: zStatusList,\n});\n\nexport type KeyAttestationStatus = z.infer<typeof zKeyAttestationStatus>;\n\n/**\n * For the moment, the specification doesn't restrict the key attestation signature algorithm\n * to a subset of those that must/should be allowed\n */\nexport const zKeyAttestationAlg = zItwSupportedSignatureAlg;\n\nexport const zKeyAttestationHeader = z.object({\n alg: zKeyAttestationAlg,\n kid: z.string(),\n trust_chain: zTrustChain.optional(),\n typ: z.literal(\"key-attestation+jwt\"),\n x5c: zCertificateChain,\n});\n\nexport type KeyAttestationHeader = z.infer<typeof zKeyAttestationHeader>;\n\nexport const zKeyAttestationPayload = z.object({\n attested_keys: z.array(zJwk).nonempty(),\n certification: z.string().optional(),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n key_storage: z.array(zKeyStorageLevelV1_3).nonempty(),\n status: zKeyAttestationStatus,\n user_authentication: z.array(zKeyStorageLevelV1_3).nonempty(),\n});\n\nexport type KeyAttestationPayload = z.infer<typeof zKeyAttestationPayload>;\n\nexport const zKeyAttestationTypeHeader = z.literal(\"key-attestation+jwt\");\n\nexport const keyAttestationTypeHeader = zKeyAttestationTypeHeader.value;\n","import type {\n EncryptJweCallback,\n JweEncryptor,\n} from \"@pagopa/io-wallet-oauth2\";\n\nimport {\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type {\n CreateCredentialResponseOptions,\n CreateCredentialResponseOptionsV1_0,\n CreateCredentialResponseOptionsV1_3,\n CreateCredentialResponseResult,\n CreateCredentialResponseResultWithFlow,\n DeferredFlowOptionsV1_0,\n DeferredFlowOptionsV1_3,\n ImmediateFlowOptions,\n} from \"./types\";\nimport type {\n CredentialResponse,\n CredentialResponseEncryption,\n DeferredCredentialResponseV1_0,\n DeferredCredentialResponseV1_3,\n} from \"./z-credential-response\";\nimport type { ImmediateCredentialResponse } from \"./z-immediate-credential-response\";\n\nimport { CreateCredentialResponseError, Oid4vciError } from \"../errors\";\nimport * as V1_0 from \"./v1.0/create-credential-response\";\nimport * as V1_3 from \"./v1.3/create-credential-response\";\n\nexport type {\n CreateCredentialResponseOptions,\n CreateCredentialResponseOptionsV1_0,\n CreateCredentialResponseOptionsV1_3,\n CreateCredentialResponseResult,\n CreateCredentialResponseResultWithFlow,\n DeferredFlowOptionsV1_0,\n DeferredFlowOptionsV1_3,\n ImmediateFlowOptions,\n} from \"./types\";\n\n/**\n * Creates a credential response according to the configured Italian Wallet specification version.\n *\n * Supports both immediate and deferred issuance flows, with optional JWE encryption of the\n * generated response payload.\n *\n * Version Differences:\n * - v1.0 deferred flow uses `lead_time`\n * - v1.3 deferred flow uses `interval`\n * - immediate flow has the same shape in both versions (`credentials`, optional `notification_id`)\n *\n * @param options - Credential response creation options, including version config, flow data,\n * and optional encryption settings.\n * @returns An object containing:\n * - `credentialResponse`: plain version-specific credential response JSON\n * - `credentialResponseJwt`: encrypted JWE string when encryption is requested\n * @throws {ItWalletSpecsVersionError} When the configured specification version is not supported.\n * @throws {ValidationError} When the generated response does not satisfy the version schema.\n * @throws {Oid4vciError} When encryption is requested but `callbacks.encryptJwe` is not provided.\n * @throws {CreateCredentialResponseError} For unexpected errors during response creation.\n *\n * @example v1.0 - Immediate flow without encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const result = await createCredentialResponse({\n * config,\n * flow: {\n * credentials: [{ credential: \"eyJ...\" }],\n * notificationId: \"notif-123\",\n * },\n * });\n * // result.credentialResponse = { credentials: [{ credential: \"eyJ...\" }], notification_id: \"notif-123\" }\n * // result.credentialResponseJwt = undefined\n *\n * @example v1.3 - Immediate flow with encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const result = await createCredentialResponse({\n * callbacks: { encryptJwe: myEncryptJweCallback },\n * config,\n * credentialResponseEncryption: {\n * alg: \"ECDH-ES\",\n * enc: \"A256GCM\",\n * jwk: issuerEncryptionPublicJwk,\n * },\n * flow: {\n * credentials: [{ credential: \"eyJ...\" }],\n * },\n * });\n * // result.credentialResponse contains plain JSON\n * // result.credentialResponseJwt contains encrypted JWE\n *\n * @example v1.0 - Deferred flow without encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_0 });\n * const result = await createCredentialResponse({\n * config,\n * flow: {\n * leadTime: 300,\n * transactionId: \"tx-v1-0\",\n * },\n * });\n * // result.credentialResponse = { lead_time: 300, transaction_id: \"tx-v1-0\" }\n *\n * @example v1.3 - Deferred flow with encryption\n * const config = new IoWalletSdkConfig({ itWalletSpecsVersion: ItWalletSpecsVersion.V1_3 });\n * const result = await createCredentialResponse({\n * callbacks: { encryptJwe: myEncryptJweCallback },\n * config,\n * credentialResponseEncryption: {\n * alg: \"ECDH-ES\",\n * enc: \"A256GCM\",\n * jwk: issuerEncryptionPublicJwk,\n * },\n * flow: {\n * interval: 60,\n * transactionId: \"tx-v1-3\",\n * },\n * });\n * // result.credentialResponse = { interval: 60, transaction_id: \"tx-v1-3\" }\n * // result.credentialResponseJwt contains encrypted JWE\n */\n\nexport function createCredentialResponse(\n options:\n | ({\n flow: ImmediateFlowOptions;\n } & Omit<CreateCredentialResponseOptionsV1_0, \"flow\">)\n | ({\n flow: ImmediateFlowOptions;\n } & Omit<CreateCredentialResponseOptionsV1_3, \"flow\">),\n): Promise<CreateCredentialResponseResultWithFlow<ImmediateCredentialResponse>>;\n\nexport function createCredentialResponse(\n options: {\n flow: DeferredFlowOptionsV1_0;\n } & Omit<CreateCredentialResponseOptionsV1_0, \"flow\">,\n): Promise<\n CreateCredentialResponseResultWithFlow<DeferredCredentialResponseV1_0>\n>;\n\nexport function createCredentialResponse(\n options: {\n flow: DeferredFlowOptionsV1_3;\n } & Omit<CreateCredentialResponseOptionsV1_3, \"flow\">,\n): Promise<\n CreateCredentialResponseResultWithFlow<DeferredCredentialResponseV1_3>\n>;\n\nexport function createCredentialResponse(\n options: CreateCredentialResponseOptions,\n): Promise<CreateCredentialResponseResult>;\n\nexport async function createCredentialResponse(\n options: CreateCredentialResponseOptions,\n): Promise<CreateCredentialResponseResult> {\n try {\n const credentialResponse = buildVersionedResponse(options);\n let credentialResponseJwt: string | undefined;\n\n if (options.credentialResponseEncryption) {\n const encryptJwe = options.callbacks?.encryptJwe;\n\n if (!encryptJwe) {\n throw new Oid4vciError(\n \"'credentialResponseEncryption' was provided but 'callbacks.encryptJwe' is not defined...\",\n );\n }\n\n credentialResponseJwt = await encryptResponse(\n credentialResponse,\n options.credentialResponseEncryption,\n encryptJwe,\n );\n }\n\n return { credentialResponse, credentialResponseJwt };\n } catch (error) {\n if (\n error instanceof ItWalletSpecsVersionError ||\n error instanceof ValidationError ||\n error instanceof Oid4vciError\n ) {\n throw error;\n }\n throw new CreateCredentialResponseError(\n `Unexpected error during create credential response: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nfunction buildVersionedResponse(\n options: CreateCredentialResponseOptions,\n): CredentialResponse {\n const version = options.config.itWalletSpecsVersion;\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n return V1_0.createCredentialResponseV1_0(options.flow);\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n return V1_3.createCredentialResponseV1_3(options.flow);\n }\n\n throw new ItWalletSpecsVersionError(\"createCredentialResponse\", version, [\n ItWalletSpecsVersion.V1_0,\n ItWalletSpecsVersion.V1_3,\n ]);\n}\n\nasync function encryptResponse(\n credentialResponse: CredentialResponse,\n credentialResponseEncryption: CredentialResponseEncryption,\n encryptJwe: EncryptJweCallback,\n): Promise<string> {\n const jweEncryptor: JweEncryptor = {\n alg: credentialResponseEncryption.alg,\n enc: credentialResponseEncryption.enc,\n method: \"jwk\",\n publicJwk: credentialResponseEncryption.jwk,\n };\n\n const { jwe } = await encryptJwe(\n jweEncryptor,\n JSON.stringify(credentialResponse),\n );\n\n return jwe;\n}\n","import { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport type { DeferredFlowOptionsV1_0, ImmediateFlowOptions } from \"../types\";\n\nimport {\n type CredentialResponseV1_0,\n zCredentialResponseV1_0,\n} from \"./z-credential-response\";\n\nexport function createCredentialResponseV1_0(\n flow: DeferredFlowOptionsV1_0 | ImmediateFlowOptions,\n): CredentialResponseV1_0 {\n if (\"credentials\" in flow) {\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n {\n credentials: flow.credentials,\n ...(flow.notificationId !== undefined && {\n notification_id: flow.notificationId,\n }),\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.0\",\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n {\n lead_time: flow.leadTime,\n transaction_id: flow.transactionId,\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.0\",\n );\n}\n","import { z } from \"zod\";\n\nimport { zImmediateCredentialResponse } from \"../z-immediate-credential-response\";\n\nexport const zDeferredCredentialResponseV1_0 = z.strictObject({\n lead_time: z\n .number()\n .int()\n .positive()\n .describe(\n \"REQUIRED if credentials is not present, otherwise it MUST NOT be present. The amount of time (in seconds) required before making a Deferred Credential Request.\",\n ),\n transaction_id: z.string().nonempty(),\n});\n\nexport type DeferredCredentialResponseV1_0 = z.infer<\n typeof zDeferredCredentialResponseV1_0\n>;\n\nexport const zCredentialResponseV1_0 = z.union([\n zImmediateCredentialResponse,\n zDeferredCredentialResponseV1_0,\n]);\n\nexport type CredentialResponseV1_0 = z.infer<typeof zCredentialResponseV1_0>;\n","import { z } from \"zod\";\n\nexport const zCredentialObject = z.object({\n credential: z.string(),\n});\n\nexport type CredentialObject = z.infer<typeof zCredentialObject>;\n\nexport const zImmediateCredentialResponse = z.strictObject({\n credentials: z\n .array(zCredentialObject)\n .nonempty()\n .describe(\n \"Conditional. Array of issued Digital Credentials as JSON objects with `credential` member containing encoded credential string. Present for immediate issuance (HTTP 200).\",\n ),\n notification_id: z\n .string()\n .optional()\n .describe(\n \"OPTIONAL. Identifier for notification requests. Only present with credentials parameter.\",\n ),\n});\n\nexport type ImmediateCredentialResponse = z.infer<\n typeof zImmediateCredentialResponse\n>;\n","import { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport type { DeferredFlowOptionsV1_3, ImmediateFlowOptions } from \"../types\";\n\nimport {\n type CredentialResponseV1_3,\n zCredentialResponseV1_3,\n} from \"./z-credential-response\";\n\nexport function createCredentialResponseV1_3(\n flow: DeferredFlowOptionsV1_3 | ImmediateFlowOptions,\n): CredentialResponseV1_3 {\n if (\"credentials\" in flow) {\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n {\n credentials: flow.credentials,\n ...(flow.notificationId !== undefined && {\n notification_id: flow.notificationId,\n }),\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.3\",\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n {\n interval: flow.interval,\n transaction_id: flow.transactionId,\n },\n \"Invalid credential response for ItWalletSpecsVersion 1.3\",\n );\n}\n","import { z } from \"zod\";\n\nimport { zImmediateCredentialResponse } from \"../z-immediate-credential-response\";\n\nexport const zDeferredCredentialResponseV1_3 = z.strictObject({\n interval: z\n .number()\n .int()\n .positive()\n .describe(\n \"REQUIRED if transaction_id is present, otherwise it MUST NOT be present. The amount of time (in seconds) required before making a Deferred Credential Request\",\n ),\n transaction_id: z.string().nonempty(),\n});\n\nexport type DeferredCredentialResponseV1_3 = z.infer<\n typeof zDeferredCredentialResponseV1_3\n>;\n\nexport const zCredentialResponseV1_3 = z.union([\n zImmediateCredentialResponse,\n zDeferredCredentialResponseV1_3,\n]);\n\nexport type CredentialResponseV1_3 = z.infer<typeof zCredentialResponseV1_3>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { CredentialRequestV1_0 } from \"../credential-request/v1.0/z-credential\";\nimport type { CredentialRequestV1_3 } from \"../credential-request/v1.3/z-credential\";\n\nimport { FetchCredentialResponseError } from \"../errors\";\nimport {\n CredentialResponse,\n zCredentialResponseV1_0,\n zCredentialResponseV1_3,\n} from \"./z-credential-response\";\n\n/**\n * Options for fetching credential response\n * Accepts credential requests from any supported version\n */\nexport interface FetchCredentialResponseOptions {\n accessToken: string;\n callbacks: Pick<CallbackContext, \"fetch\">;\n credentialEndpoint: string;\n /**\n * Credential request object (supports both v1.0 and v1.3 formats)\n */\n credentialRequest: CredentialRequestV1_0 | CredentialRequestV1_3;\n dPoP: string;\n}\n\n/**\n * Fetch a credential response from the credential endpoint\n *\n * Supports both v1.0 and v1.3 credential request formats.\n * The response format is version-agnostic.\n *\n * @param options - Configuration for credential fetch\n * @returns Parsed credential response\n * @throws {UnexpectedStatusCodeError} If HTTP status is not 200 or 202 for deferred issuance\n * @throws {ValidationError} If response validation fails\n * @throws {FetchCredentialResponseError} For unexpected errors\n */\nexport async function fetchCredentialResponse(\n options: FetchCredentialResponseOptions,\n): Promise<CredentialResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const credentialResponse = await fetch(options.credentialEndpoint, {\n body: JSON.stringify(options.credentialRequest),\n headers: {\n [HEADERS.AUTHORIZATION]: `DPoP ${options.accessToken}`,\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.DPOP]: options.dPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(\n [200, 202],\n UnexpectedStatusCodeError,\n )(credentialResponse);\n\n const credentialResponseJson = await credentialResponse.json();\n\n if (\"proof\" in options.credentialRequest) {\n return parseWithErrorHandling(\n zCredentialResponseV1_0,\n credentialResponseJson,\n `Failed to parse credential response (v1.0)`,\n );\n }\n\n return parseWithErrorHandling(\n zCredentialResponseV1_3,\n credentialResponseJson,\n `Failed to parse credential response (v1.3)`,\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchCredentialResponseError(\n `Unexpected error during credential response: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n","import { zAlgValueNotNone, zJwk } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nimport type { CredentialResponseV1_0 } from \"./v1.0/z-credential-response\";\nimport type { CredentialResponseV1_3 } from \"./v1.3/z-credential-response\";\n\nexport {\n zCredentialResponseV1_0,\n zDeferredCredentialResponseV1_0,\n} from \"./v1.0/z-credential-response\";\n\nexport type {\n CredentialResponseV1_0,\n DeferredCredentialResponseV1_0,\n} from \"./v1.0/z-credential-response\";\n\nexport {\n zCredentialResponseV1_3,\n zDeferredCredentialResponseV1_3,\n} from \"./v1.3/z-credential-response\";\n\nexport type {\n CredentialResponseV1_3,\n DeferredCredentialResponseV1_3,\n} from \"./v1.3/z-credential-response\";\n\nexport {\n zCredentialObject,\n zImmediateCredentialResponse,\n} from \"./z-immediate-credential-response\";\n\nexport type {\n CredentialObject,\n ImmediateCredentialResponse,\n} from \"./z-immediate-credential-response\";\n\nexport type CredentialResponse =\n | CredentialResponseV1_0\n | CredentialResponseV1_3;\n\nexport const zCredentialResponseEncryption = z.looseObject({\n alg: zAlgValueNotNone,\n enc: z.string(),\n jwk: zJwk,\n});\n\nexport type CredentialResponseEncryption = z.infer<\n typeof zCredentialResponseEncryption\n>;\n","import { CallbackContext, VerifyJwtCallback } from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport { itWalletEntityStatementClaimsSchema } from \"@pagopa/io-wallet-oid-federation\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { FetchMetadataError } from \"../errors\";\nimport {\n MetadataResponse,\n zMetadataResponseV1_0,\n zMetadataResponseV1_3,\n zPartialIssuerMetadata,\n} from \"./z-metadata-response\";\n\ninterface RawFederationResult {\n discoveredVia: \"federation\";\n metadata: z.infer<typeof itWalletEntityStatementClaimsSchema>[\"metadata\"];\n openid_federation_claims: z.infer<typeof itWalletEntityStatementClaimsSchema>;\n}\n\ninterface RawOid4vciResult {\n discoveredVia: \"oid4vci\";\n metadata: {\n oauth_authorization_server: Record<string, unknown>;\n openid_credential_issuer: z.infer<typeof zPartialIssuerMetadata>;\n };\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.endsWith(\"/\") ? url : `${url}/`;\n}\n\nexport interface FetchMetadataOptions {\n /** Callback providing the fetch implementation */\n callbacks: {\n /**\n * Optional JWT signature verification callback.\n * When provided, the entity statement signature retrieved via federation\n * discovery is verified using this callback.\n * When omitted, trust is derived solely from TLS (the default behaviour).\n */\n verifyJwt?: VerifyJwtCallback;\n } & Pick<CallbackContext, \"fetch\">;\n\n /**\n * SDK configuration used to route discovery logic by IT-Wallet specification version.\n */\n config: IoWalletSdkConfig;\n\n /**\n * Base URL of the Credential Issuer (e.g. \"https://issuer.example.it\").\n * The well-known paths are appended automatically.\n */\n credentialIssuerUrl: string;\n}\n\n/**\n * Attempts the federation discovery path.\n * Returns the normalised metadata object if successful or undefined.\n * In case of ValidationError, the error is re-thrown, as it indicates a non-compliant implementation that should be surfaced instead of falling back to the OID4VCI discovery.\n * For any other error (e.g. network issues, non-200 status code), undefined is returned to trigger the fallback mechanism.\n */\nasync function tryFederationDiscovery(\n fetch: ReturnType<typeof createFetcher>,\n baseUrl: string,\n verifyJwt?: VerifyJwtCallback,\n): Promise<RawFederationResult | undefined> {\n try {\n const federationUrl = new URL(\n \".well-known/openid-federation\",\n ensureTrailingSlash(baseUrl),\n ).toString();\n const response = await fetch(federationUrl);\n\n if (response.status !== 200) {\n return undefined;\n }\n\n const entityStatement = await response.text();\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding entity statement JWT:\",\n jwt: entityStatement,\n payloadSchema: itWalletEntityStatementClaimsSchema,\n });\n\n if (verifyJwt) {\n const jwtSigner = {\n alg: header.alg as string,\n kid: header.kid as string,\n method: \"federation\" as const,\n };\n const result = await verifyJwt(jwtSigner, {\n compact: entityStatement,\n header,\n payload,\n });\n if (!result.verified) {\n throw new ValidationError(\n \"Entity statement signature verification failed\",\n );\n }\n }\n\n return {\n discoveredVia: \"federation\",\n metadata: payload.metadata,\n openid_federation_claims: payload,\n };\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n return undefined;\n }\n}\n\n/**\n * Executes the fallback OID4VCI discovery path:\n * 1. GET {baseUrl}/.well-known/openid-credential-issuer\n * 2a. If authorization_servers[] is present → GET {authServerUrl}/.well-known/oauth-authorization-server\n * 2b. If absent → the issuer JSON already contains the auth-server claims inline\n *\n * Well-known paths are appended relative to the full base URL, preserving any\n * path segment (e.g. \"https://issuer.example.it/v1\" → \"https://issuer.example.it/v1/.well-known/...\").\n */\nasync function fallbackDiscovery(\n fetch: ReturnType<typeof createFetcher>,\n baseUrl: string,\n): Promise<RawOid4vciResult> {\n const issuerUrl = new URL(\n \".well-known/openid-credential-issuer\",\n ensureTrailingSlash(baseUrl),\n ).toString();\n const issuerResponse = await fetch(issuerUrl);\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(issuerResponse);\n\n const issuerJson = parseWithErrorHandling(\n zPartialIssuerMetadata,\n await issuerResponse.json(),\n \"Failed to parse credential issuer metadata\",\n );\n const authorizationServers = issuerJson.authorization_servers;\n\n let oauthAuthorizationServer: Record<string, unknown>;\n\n if (authorizationServers && authorizationServers.length > 0) {\n const parsedUrl = z.url().safeParse(authorizationServers[0]);\n if (!parsedUrl.success || !parsedUrl.data.startsWith(\"https://\")) {\n throw new ValidationError(\n \"authorization_servers[0] is not a valid HTTPS URL\",\n );\n }\n\n const authServerUrl = new URL(\n \".well-known/oauth-authorization-server\",\n ensureTrailingSlash(parsedUrl.data),\n ).toString();\n\n const authServerResponse = await fetch(authServerUrl);\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(authServerResponse);\n\n oauthAuthorizationServer = (await authServerResponse.json()) as Record<\n string,\n unknown\n >;\n } else {\n oauthAuthorizationServer = issuerJson;\n }\n\n return {\n discoveredVia: \"oid4vci\",\n metadata: {\n oauth_authorization_server: oauthAuthorizationServer,\n openid_credential_issuer: issuerJson,\n },\n };\n}\n\n/**\n * Performs the OID4VCI discovery flow for a Credential Issuer, routing discovery\n * strategy and metadata schema validation based on the IT-Wallet specification version\n * provided in `config`.\n *\n * **v1.0**: Only `.well-known/openid-federation` is attempted. If federation discovery\n * fails, a `FetchMetadataError` is thrown — there is no OID4VCI fallback in v1.0.\n * Returns `MetadataResponseV1_0` with `discoveredVia: \"federation\"`.\n *\n * **v1.3**: Federation discovery is attempted first (`.well-known/openid-federation`).\n * On failure, falls back to `.well-known/openid-credential-issuer` + optional\n * `.well-known/oauth-authorization-server`. Returns `MetadataResponseV1_3`.\n *\n * Well-known paths are appended relative to the full `credentialIssuerUrl`, preserving\n * any path segment (e.g. `\"https://issuer.example.it/v1\"` →\n * `\"https://issuer.example.it/v1/.well-known/...\"`).\n *\n * When federation discovery succeeds, the full entity statement claims are\n * preserved in `openid_federation_claims`.\n * Signature verification of the entity statement is optional: supply\n * `callbacks.verifyJwt` to enable it. When omitted, trust is derived from TLS\n * alone (successful retrieval from the well-known endpoint).\n *\n * @param options - Configuration for metadata fetching, including `config` for version routing\n * @returns Normalised metadata with `discoveredVia` indicating the discovery path used\n * @throws {UnexpectedStatusCodeError} If a fallback endpoint returns a non-200 status (v1.3 only)\n * @throws {ValidationError} If the response does not match the expected schema\n * @throws {ItWalletSpecsVersionError} If `config.itWalletSpecsVersion` is not V1_0 or V1_3\n * @throws {FetchMetadataError} If federation discovery fails for v1.0, or for any other unexpected error\n */\nexport async function fetchMetadata(\n options: FetchMetadataOptions,\n): Promise<MetadataResponse> {\n const { config } = options;\n try {\n const urlValidation = z.url().safeParse(options.credentialIssuerUrl);\n if (!urlValidation.success || !urlValidation.data.startsWith(\"https://\")) {\n throw new ValidationError(\n \"credentialIssuerUrl must be a valid HTTPS URL\",\n );\n }\n\n const fetch = createFetcher(options.callbacks.fetch);\n\n if (config.isVersion(ItWalletSpecsVersion.V1_0)) {\n // v1.0: federation ONLY — no OID4VCI fallback\n const federationResult = await tryFederationDiscovery(\n fetch,\n options.credentialIssuerUrl,\n options.callbacks.verifyJwt,\n );\n if (!federationResult) {\n throw new FetchMetadataError(\n `Federation discovery failed for IT Wallet v1.0; no fallback available for credentialIssuerUrl ${options.credentialIssuerUrl}`,\n );\n }\n return parseWithErrorHandling(\n zMetadataResponseV1_0,\n federationResult,\n \"Failed to parse v1.0 metadata response\",\n );\n }\n\n if (config.isVersion(ItWalletSpecsVersion.V1_3)) {\n // v1.3: federation-first, OID4VCI fallback\n const federationResult = await tryFederationDiscovery(\n fetch,\n options.credentialIssuerUrl,\n options.callbacks.verifyJwt,\n );\n const raw =\n federationResult ??\n (await fallbackDiscovery(fetch, options.credentialIssuerUrl));\n return parseWithErrorHandling(\n zMetadataResponseV1_3,\n raw,\n \"Failed to parse v1.3 metadata response\",\n );\n }\n\n throw new ItWalletSpecsVersionError(\n \"fetchMetadata\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError ||\n error instanceof ItWalletSpecsVersionError ||\n error instanceof FetchMetadataError\n ) {\n throw error;\n }\n throw new FetchMetadataError(\"Unexpected error during metadata fetch\", {\n cause: error,\n });\n }\n}\n","import {\n itWalletEntityStatementClaimsSchema,\n itWalletMetadataV1_0,\n itWalletMetadataV1_3,\n} from \"@pagopa/io-wallet-oid-federation\";\nimport { z } from \"zod\";\n\nexport const zMetadataResponseV1_0 = z.object({\n discoveredVia: z.enum([\"federation\"]),\n metadata: itWalletMetadataV1_0,\n openid_federation_claims: itWalletEntityStatementClaimsSchema,\n});\n\nexport const zMetadataResponseV1_3 = z.object({\n discoveredVia: z.enum([\"federation\", \"oid4vci\"]),\n metadata: itWalletMetadataV1_3,\n openid_federation_claims: itWalletEntityStatementClaimsSchema.optional(),\n});\n\nexport const zMetadataResponse = z.union([\n zMetadataResponseV1_0,\n zMetadataResponseV1_3,\n]);\n\nexport type MetadataResponseV1_0 = z.infer<typeof zMetadataResponseV1_0>;\nexport type MetadataResponseV1_3 = z.infer<typeof zMetadataResponseV1_3>;\nexport type MetadataResponse = MetadataResponseV1_0 | MetadataResponseV1_3;\n\n// For intermediate parsing in fallbackDiscovery:\nexport const zPartialIssuerMetadata = z.looseObject({\n authorization_servers: z.array(z.string()).optional(),\n});\n","import { CallbackContext, JwtSignerX5c } from \"@openid4vc/oauth2\";\nimport {\n Jwk,\n type WalletAttestationOptionsV1_0,\n type WalletAttestationOptionsV1_3,\n type WalletAttestationOptionsV1_4,\n createWalletAttestationJwtV1_0,\n createWalletAttestationJwtV1_3,\n createWalletAttestationJwtV1_4,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { KeyStorageLevelV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { WalletProviderError } from \"../errors\";\nimport { WalletAttestationOptions } from \"./types\";\nimport {\n KeyAttestationStatus,\n keyAttestationTypeHeader,\n} from \"./z-key-attestation\";\n\nfunction assertV1_0Options(\n options: WalletAttestationOptions,\n): asserts options is WalletAttestationOptionsV1_0 {\n if (options.signer.method !== \"federation\") {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.0 (federation) but received options with signer method \"${options.signer.method}\"`,\n );\n }\n}\n\nfunction assertV1_3Options(\n options: WalletAttestationOptions,\n): asserts options is WalletAttestationOptionsV1_3 {\n if (options.signer.method !== \"x5c\") {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.3 (x5c) but received options with signer method \"${options.signer.method}\"`,\n );\n }\n}\n\nfunction assertV1_4Options(\n options: WalletAttestationOptions,\n): asserts options is WalletAttestationOptionsV1_4 {\n if (options.signer.method !== \"x5c\") {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.4 (x5c) but received options with signer method \"${options.signer.method}\"`,\n );\n }\n if (!options.walletLink) {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.4 but 'walletLink' is required and missing`,\n );\n }\n if (!options.walletName) {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.4 but 'walletName' is required and missing`,\n );\n }\n if (!(\"status\" in options) || !options.status) {\n throw new WalletProviderError(\n `Version mismatch: provider is configured for v1.4 but 'status' is required and missing`,\n );\n }\n}\n\n/**\n * @interface KeyAttestationOptions\n * @description Defines the options required to create a key attestation JWT.\n * This attestation conveys information about the cryptographic keys managed by the wallet,\n * their storage characteristics, user authentication level, and revocation status.\n */\nexport interface KeyAttestationOptions {\n /**\n * The array of JWKs representing the attested keys.\n */\n attestedKeys: [Jwk, ...Jwk[]];\n\n callbacks: Pick<CallbackContext, \"signJwt\">;\n\n /**\n * Optional URL to the key storage component certification.\n */\n certification?: string;\n\n /**\n * The optional expiration date for the attestation JWT. If not provided, a default lifetime will be used.\n * @type {Date}\n */\n expiresAt?: Date;\n\n /**\n * The issuance date of the key attestation. Defaults to the current date and time if not provided.\n * @type {Date}\n */\n issuedAt?: Date;\n\n issuer: string;\n\n /**\n * The levels of security for key storage as per ISO 18045 standards.\n * @type {[KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]]}\n */\n keyStorage: [KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]];\n\n /**\n * The signer information containing the Key ID and the X.509 certificate chain.\n */\n signer: JwtSignerX5c;\n\n /**\n * The status information related to the key attestation.\n */\n status: KeyAttestationStatus;\n\n /**\n * An array of JWTs representing the chain of trust from the federation's trust anchor\n * @type {[string, ...string[]]}\n */\n trustChain?: [string, ...string[]];\n\n /**\n * The levels of user authentication as per ISO 18045 standards.\n * @type {[KeyStorageLevel, ...KeyStorageLevel[]]}\n */\n userAuthentication: [KeyStorageLevelV1_3, ...KeyStorageLevelV1_3[]];\n}\n\n/**\n * @class WalletProvider\n * @description An implementation of a wallet provider for the OpenID4VCI protocol, tailored for the Italian ecosystem.\n * It handles the creation of wallet attestations required during the credential issuance flow.\n */\nexport class WalletProvider {\n private specVersion: ItWalletSpecsVersion;\n\n constructor(options: IoWalletSdkConfig) {\n this.specVersion = options.itWalletSpecsVersion;\n }\n\n /**\n * Creates a wallet unit attestation.\n *\n * The key attestation is a signed token that describes the attested keys, their storage characteristics,\n * user authentication level, and status, and can include certification and a trust chain as needed.\n *\n * @public\n * @async\n * @param {KeyAttestationOptions} options - The options used to construct and sign the key attestation JWT.\n * @returns {Promise<string>} A promise that resolves to the signed key attestation JWT.\n * @throws {WalletProviderError} Thrown when the JWT cannot be created or signed.\n */\n public async createItKeyAttestationJwt(\n options: KeyAttestationOptions,\n ): Promise<string> {\n const { signJwt } = options.callbacks;\n\n const now = new Date();\n const issuedAt = options.issuedAt ?? now;\n const expiresAt =\n options.expiresAt ?? addSecondsToDate(now, 3600 * 24 * 360);\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n typ: keyAttestationTypeHeader,\n x5c: options.signer.x5c,\n ...(options.trustChain && { trust_chain: options.trustChain }),\n };\n\n const payload = {\n attested_keys: options.attestedKeys,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: options.issuer,\n key_storage: options.keyStorage,\n status: options.status,\n user_authentication: options.userAuthentication,\n ...(options.certification && { certification: options.certification }),\n };\n\n try {\n const { jwt } = await signJwt(options.signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n throw new WalletProviderError(\n `Failed to create key attestation JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n /**\n * Creates a wallet attestation JWT according to the configured Italian Wallet specification version.\n *\n * Version Differences:\n * - v1.0: Uses only `trust_chain` in header (federation method); no `status` claim\n * - v1.3: Requires `x5c` in header, optional `trust_chain`; supports optional `nbf` and `status` claims\n * - v1.4: Requires `x5c` in header, optional `trust_chain`; `status`, `wallet_link`, and `wallet_name`\n * are all **required**; optional `eudi_wallet_info` claim; sets `sub` to `dpopJwkPublic.kid`\n *\n * @public\n * @async\n * @param {WalletAttestationOptions} options - The necessary parameters to build the attestation.\n * @returns {Promise<string>} A promise that resolves to the signed wallet attestation JWT as a string.\n * @throws {WalletProviderError} When dpopJwkPublic.kid is missing\n * @throws {ItWalletSpecsVersionError} When version is not supported\n *\n * @example v1.0 - Basic wallet attestation with trust chain\n * const jwt = await provider.createItWalletAttestationJwt({\n * callbacks: { signJwt: mySignJwtCallback },\n * dpopJwkPublic: myJwk,\n * issuer: \"https://wallet-provider.example.com\",\n * signer: {\n * alg: \"ES256\",\n * kid: \"provider-key-id\",\n * trustChain: [\"trust-anchor-jwt\", \"intermediate-jwt\"]\n * }\n * });\n *\n * @example v1.3 - Wallet attestation with x5c and optional fields\n * const jwt = await provider.createItWalletAttestationJwt({\n * callbacks: { signJwt: mySignJwtCallback },\n * dpopJwkPublic: myJwk,\n * issuer: \"https://wallet-provider.example.com\",\n * signer: {\n * alg: \"ES256\",\n * kid: \"provider-key-id\",\n * x5c: [\"cert1-base64\", \"cert2-base64\"],\n * trustChain: [\"trust-anchor-jwt\"] // Optional in v1.3\n * },\n * nbf: new Date('2025-01-01'), // Optional\n * status: { status_list: { idx: 2, uri: \"https://status.example.com\" } } // Optional\n * });\n *\n * @example v1.4 - Wallet attestation with required status and optional eudi_wallet_info\n * const jwt = await provider.createItWalletAttestationJwt({\n * callbacks: { signJwt: mySignJwtCallback },\n * dpopJwkPublic: myJwk,\n * issuer: \"https://wallet-provider.example.com\",\n * signer: {\n * alg: \"ES256\",\n * kid: \"provider-key-id\",\n * method: \"x5c\",\n * x5c: [\"cert1-base64\", \"cert2-base64\"],\n * trustChain: [\"trust-anchor-jwt\"] // Optional\n * },\n * status: { status_list: { idx: 2, uri: \"https://status.example.com\" } }, // Required\n * walletLink: \"https://wallet.example.com\", // Required\n * walletName: \"My Wallet\", // Required\n * eudiWalletInfo: { // Optional\n * general_info: {\n * wallet_provider_name: \"PagoPA\",\n * wallet_solution_certification_information: \"certification-ref\",\n * wallet_solution_id: \"wallet-solution-id\",\n * wallet_solution_version: \"1.0.0\"\n * }\n * }\n * });\n */\n\n public async createItWalletAttestationJwt(\n options: WalletAttestationOptions,\n ): Promise<string> {\n // Validate that dpopJwkPublic has a kid property\n // This validation is common across all versions\n if (!options.dpopJwkPublic.kid) {\n throw new WalletProviderError(\"The DPoP JWK must have a 'kid' property\");\n }\n\n if (this.specVersion === ItWalletSpecsVersion.V1_0) {\n assertV1_0Options(options);\n return createWalletAttestationJwtV1_0({\n authenticatorAssuranceLevel: options.authenticatorAssuranceLevel,\n callbacks: options.callbacks,\n dpopJwkPublic: options.dpopJwkPublic,\n expiresAt: options.expiresAt,\n issuer: options.issuer,\n signer: options.signer,\n walletLink: options.walletLink,\n walletName: options.walletName,\n });\n }\n\n if (this.specVersion === ItWalletSpecsVersion.V1_3) {\n assertV1_3Options(options);\n return createWalletAttestationJwtV1_3({\n callbacks: options.callbacks,\n dpopJwkPublic: options.dpopJwkPublic,\n expiresAt: options.expiresAt,\n issuer: options.issuer,\n nbf: options.nbf,\n signer: options.signer,\n status: options.status,\n walletLink: options.walletLink,\n walletName: options.walletName,\n });\n }\n\n if (this.specVersion === ItWalletSpecsVersion.V1_4) {\n assertV1_4Options(options);\n return createWalletAttestationJwtV1_4({\n callbacks: options.callbacks,\n dpopJwkPublic: options.dpopJwkPublic,\n eudiWalletInfo: options.eudiWalletInfo,\n expiresAt: options.expiresAt,\n issuer: options.issuer,\n signer: options.signer,\n status: options.status,\n walletLink: options.walletLink,\n walletName: options.walletName,\n });\n }\n\n throw new ItWalletSpecsVersionError(\n \"createItWalletAttestationJwt\",\n this.specVersion,\n Object.values(ItWalletSpecsVersion),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,8BAAmC;AACnC,8BAGO;AACP,6BAKO;;;ACRA,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B;AAAA,EACT,YACE,SACA,SACA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,aAAa,SAAS;AAAA,EAC7B;AACF;AAOO,IAAM,sBAAN,cAAkC,aAAa;AAAA,EACpD,YAAY,SAAiB,SAAwB;AACnD,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAClC;AAAA,EACT,YACE,SACA,SACA;AACA,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,aAAa,SAAS;AAAA,EAC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C,6BAA6B,QAAQ;AAAA,QACrC,WAAW,QAAQ;AAAA,QACnB,eAAe,QAAQ;AAAA,QACvB,WAAW,QAAQ;AAAA,QACnB,QAAQ,QAAQ;AAAA,QAChB,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,MACtB,CAAC;AAAA,IACH;AAEA,QAAI,KAAK,gBAAgB,8CAAqB,MAAM;AAClD,wBAAkB,OAAO;AACzB,iBAAO,yDAA+B;AAAA,QACpC,WAAW,QAAQ;AAAA,QACnB,eAAe,QAAQ;AAAA,QACvB,WAAW,QAAQ;AAAA,QACnB,QAAQ,QAAQ;AAAA,QAChB,KAAK,QAAQ;AAAA,QACb,QAAQ,QAAQ;AAAA,QAChB,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,MACtB,CAAC;AAAA,IACH;AAEA,QAAI,KAAK,gBAAgB,8CAAqB,MAAM;AAClD,wBAAkB,OAAO;AACzB,iBAAO,yDAA+B;AAAA,QACpC,WAAW,QAAQ;AAAA,QACnB,eAAe,QAAQ;AAAA,QACvB,gBAAgB,QAAQ;AAAA,QACxB,WAAW,QAAQ;AAAA,QACnB,QAAQ,QAAQ;AAAA,QAChB,QAAQ,QAAQ;AAAA,QAChB,QAAQ,QAAQ;AAAA,QAChB,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,MACtB,CAAC;AAAA,IACH;AAEA,UAAM,IAAI;AAAA,MACR;AAAA,MACA,KAAK;AAAA,MACL,OAAO,OAAO,6CAAoB;AAAA,IACpC;AAAA,EACF;AACF;","names":["createCredentialRequest","z","import_zod","import_io_wallet_utils","offerJson","import_io_wallet_utils","import_io_wallet_utils","import_zod","import_zod","import_oauth2","import_io_wallet_utils","import_zod","createCredentialRequest","createCredentialRequest","import_io_wallet_oauth2","import_io_wallet_utils","import_io_wallet_oauth2","import_zod","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_io_wallet_oauth2","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_io_wallet_utils","import_zod","import_zod","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_io_wallet_oauth2","import_zod","import_io_wallet_oauth2","import_io_wallet_oid_federation","import_io_wallet_utils","import_zod","import_io_wallet_oid_federation","import_zod","verifyJwt","z","import_io_wallet_oauth2","import_io_wallet_utils"]}
|