@pagopa/io-wallet-oid4vp 1.2.0 → 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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/authorization-request/create-authorization-request.ts","../src/errors.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-request.ts","../src/authorization-request/validate-authorization-request.ts","../src/authorization-request/z-authorization-request-url.ts","../src/authorization-request/parse-authorization-request.ts","../src/authorization-response/create-authorization-response.ts","../src/jarm/jarm-extract-jwks.ts","../src/jarm/parse-jarm-authorization-response.ts","../src/vp-token/parse-vp-token.ts","../src/vp-token/z-vp-token.ts","../src/authorization-response/validate-authorization-response.ts","../src/authorization-response/z-authorization-response.ts","../src/jarm/verify-jarm-authorization-response.ts","../src/jarm/z-jarm.ts","../src/authorization-response/fetch-authorization-response.ts","../src/authorization-response/parse-authorization-response.ts"],"sourcesContent":["export * from \"./authorization-request\";\nexport * from \"./authorization-response\";\nexport * from \"./errors\";\nexport * from \"./jarm\";\nexport * from \"./vp-token\";\n\nexport {\n type CreateOpenid4vpAuthorizationResponseOptions,\n type CreateOpenid4vpAuthorizationResponseResult,\n type VpToken,\n createOpenid4vpAuthorizationResponse,\n} from \"@openid4vc/openid4vp\";\n","import {\n type CallbackContext,\n type CreateJarRequestOptions,\n CreateJarRequestResult,\n JarAuthorizationRequest,\n JwtSignerFederation,\n JwtSignerX5c,\n createJarRequest,\n jwtHeaderFromJwtSigner,\n signedAuthorizationRequestJwtHeaderTyp,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n objectToQueryParams,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vpError } from \"../errors\";\nimport {\n Openid4vpAuthorizationRequestPayload,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n zOpenid4vpAuthorizationRequestPayload,\n} from \"./z-authorization-request\";\n\ntype BaseJarOptions<TSigner extends JwtSignerFederation | JwtSignerX5c> = {\n jwtSigner: TSigner;\n} & Pick<\n CreateJarRequestOptions,\n \"additionalJwtPayload\" | \"expiresInSeconds\" | \"now\" | \"requestUri\"\n>;\n\nexport type JarOptionsV1_0 = BaseJarOptions<JwtSignerFederation>;\n\nexport type JarOptionsV1_3 = BaseJarOptions<JwtSignerX5c>;\n\ntype JarOptions = JarOptionsV1_0 | JarOptionsV1_3;\n\ninterface BaseCreateAuthorizationRequestOptions<\n V extends ItWalletSpecsVersion,\n TJar extends JarOptions,\n> {\n /**\n * Authorization request payload to be validated and serialized.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n\n /**\n * Required callbacks used to create a signed/encrypted Request Object.\n */\n callbacks: Partial<Pick<CallbackContext, \"encryptJwe\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n config: IoWalletSdkConfig<V>;\n\n /**\n * The request is generated as a JAR authorization request.\n * When `additionalJwtPayload.aud` is missing, it is set to `requestUri`.\n */\n jar: TJar;\n\n /**\n * Authorization request URL scheme.\n * @default \"openid4vp://\"\n */\n scheme?: string;\n}\n\n/**\n * Options for creating an OpenID4VP authorization request URL.\n */\nexport type CreateAuthorizationRequestOptionsV1_0 =\n BaseCreateAuthorizationRequestOptions<\n ItWalletSpecsVersion.V1_0,\n JarOptionsV1_0\n >;\n\nexport type CreateAuthorizationRequestOptionsV1_3 =\n BaseCreateAuthorizationRequestOptions<\n ItWalletSpecsVersion.V1_3,\n JarOptionsV1_3\n >;\n\nexport type CreateAuthorizationRequestOptions =\n | CreateAuthorizationRequestOptionsV1_0\n | CreateAuthorizationRequestOptionsV1_3;\n\ninterface BaseCreateAuthorizationRequestResult<TJar extends JarOptions> {\n authorizationRequest: string;\n authorizationRequestObject: JarAuthorizationRequest;\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n jar: CreateJarRequestResult & TJar;\n}\n\nexport type CreateAuthorizationRequestResultV1_0 =\n BaseCreateAuthorizationRequestResult<JarOptionsV1_0>;\n\nexport type CreateAuthorizationRequestResultV1_3 =\n BaseCreateAuthorizationRequestResult<JarOptionsV1_3>;\n\nexport type CreateAuthorizationRequestResult =\n | CreateAuthorizationRequestResultV1_0\n | CreateAuthorizationRequestResultV1_3;\n\n/**\n * Creates an OpenID4VP authorization request URL.\n *\n * This function creates a JAR request object through\n * `createJarRequest` and serializes it into the URL query parameters.\n *\n * @param options {@link CreateAuthorizationRequestOptions}\n * @returns Authorization request URL plus request object details used to build it\n * @throws When authorization request payload validation fails\n * @throws When JAR creation fails\n */\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptionsV1_0,\n): Promise<CreateAuthorizationRequestResultV1_0>;\n\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptionsV1_3,\n): Promise<CreateAuthorizationRequestResultV1_3>;\n\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptions,\n): Promise<CreateAuthorizationRequestResult> {\n try {\n const { config } = options;\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n return await createAuthorizationRequestWithHeader(\n options,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n );\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n return await createAuthorizationRequestWithHeader(\n options,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n );\n }\n\n throw new ItWalletSpecsVersionError(\n \"createAuthorizationRequest\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (error instanceof ValidationError) {\n throw new Oid4vpError(`Invalid authorization request: ${error.message}`);\n }\n throw error;\n }\n}\n\nasync function createAuthorizationRequestWithHeader<TJar extends JarOptions>(\n options: BaseCreateAuthorizationRequestOptions<ItWalletSpecsVersion, TJar>,\n headerSchema:\n | typeof zOpenid4vpAuthorizationRequestHeaderV1_0\n | typeof zOpenid4vpAuthorizationRequestHeaderV1_3,\n): Promise<BaseCreateAuthorizationRequestResult<TJar>> {\n const { callbacks, jar, scheme = \"openid4vp://\" } = options;\n\n const authorizationRequestHeader = parseWithErrorHandling(headerSchema, {\n ...jwtHeaderFromJwtSigner(jar.jwtSigner),\n typ: signedAuthorizationRequestJwtHeaderTyp,\n });\n\n const authorizationRequestPayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationRequestPayload,\n options.authorizationRequestPayload,\n );\n\n const additionalJwtPayload = !jar.additionalJwtPayload?.aud\n ? { ...jar.additionalJwtPayload, aud: jar.requestUri }\n : jar.additionalJwtPayload;\n\n const jarResult = await createJarRequest({\n ...jar,\n additionalJwtPayload,\n authorizationRequestHeader,\n authorizationRequestPayload,\n callbacks,\n });\n\n return {\n authorizationRequest: createAuthorizationRequestUrl(\n scheme,\n jarResult.jarAuthorizationRequest,\n ),\n authorizationRequestObject: jarResult.jarAuthorizationRequest,\n authorizationRequestPayload,\n jar: { ...jar, ...jarResult },\n };\n}\n\nfunction createAuthorizationRequestUrl(\n scheme: string,\n request: JarAuthorizationRequest,\n) {\n const url = new URL(scheme);\n\n const searchParams = new URLSearchParams([\n ...url.searchParams.entries(),\n ...objectToQueryParams(request).entries(),\n ]);\n\n url.search = searchParams.toString();\n\n return url.toString();\n}\n","/**\n * Generic error thrown during Oid4vp operations\n */\nexport class Oid4vpError extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oid4vpError\";\n }\n}\n\n/**\n * Error thrown by {@link parseAuthorizeRequest} when the passed\n * request object has an invalid signature or unexpected errors\n * are thrown\n */\nexport class ParseAuthorizeRequestError extends Oid4vpError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"ParseAuthorizeRequestError\";\n }\n}\n\n/**\n * Error thrown by {@link fetchAuthorizationResponse}\n */\nexport class FetchAuthorizationResponseError extends Oid4vpError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"FetchAuthorizationResponseError\";\n }\n}\n\n/**\n * Error thrown by {@link createAuthorizationResponse} in case there\n * are unexpected errors.\n */\nexport class CreateAuthorizationResponseError extends Oid4vpError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"CreateAuthorizationResponseError\";\n }\n}\n\n/**\n * Error thrown when request_uri_method parameter has an invalid value.\n * Valid values are \"get\" or \"post\" (case-insensitive).\n */\nexport class InvalidRequestUriMethodError extends Oid4vpError {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidRequestUriMethodError\";\n }\n}\n","import {\n zAlgValueNotNone,\n zCertificateChain,\n zJwtPayload,\n zSignedAuthorizationRequestJwtHeaderTyp,\n zTrustChain,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { itWalletCredentialVerifierMetadataV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport { z } from \"zod\";\n\n/**\n * Zod parser that describes a JWT payload\n * containing an OID4VP Request Object\n */\nexport const zOpenid4vpAuthorizationRequestPayload = z\n .looseObject({\n client_id: z.string(),\n client_metadata: itWalletCredentialVerifierMetadataV1_3.optional(),\n dcql_query: z.record(z.string(), z.any()),\n nonce: z.string(),\n request_uri: z.url().optional(),\n request_uri_method: z.optional(z.string()),\n response_mode: z.literal(\"direct_post.jwt\"),\n response_type: z.literal(\"vp_token\"),\n response_uri: z.url(),\n scope: z.string().optional(),\n state: z.string(),\n transaction_data: z.array(z.string()).nonempty().optional(),\n transaction_data_hashes_alg: z.array(z.string()).optional(),\n wallet_nonce: z.string().optional(),\n })\n .and(\n z.object({\n ...zJwtPayload.shape,\n iss: z.string(),\n }),\n );\n\nexport type Openid4vpAuthorizationRequestPayload = z.infer<\n typeof zOpenid4vpAuthorizationRequestPayload\n>;\n\nconst zOpenid4vpAuthorizationRequestHeaderBase = z.object({\n alg: zAlgValueNotNone,\n kid: z.string(),\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n});\n\nexport const zOpenid4vpAuthorizationRequestHeaderV1_0 =\n zOpenid4vpAuthorizationRequestHeaderBase\n .extend({\n trust_chain: zTrustChain,\n })\n .loose();\n\nexport type Openid4vpAuthorizationRequestHeaderV1_0 = z.infer<\n typeof zOpenid4vpAuthorizationRequestHeaderV1_0\n>;\n\nexport const zOpenid4vpAuthorizationRequestHeaderV1_3 =\n zOpenid4vpAuthorizationRequestHeaderBase\n .extend({\n trust_chain: zTrustChain.optional(),\n x5c: zCertificateChain,\n })\n .loose();\n\nexport type Openid4vpAuthorizationRequestHeaderV1_3 = z.infer<\n typeof zOpenid4vpAuthorizationRequestHeaderV1_3\n>;\n\nexport type Openid4vpAuthorizationRequestHeader =\n | Openid4vpAuthorizationRequestHeaderV1_0\n | Openid4vpAuthorizationRequestHeaderV1_3;\n","import { type CallbackContext, Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vpError } from \"../errors\";\nimport { validateAuthorizationRequestParams } from \"./validate-authorization-request\";\nimport { zAuthorizationRequestUrlParams } from \"./z-authorization-request-url\";\n\nexport interface FetchAuthorizationRequestOptions {\n /**\n * The authorization URL from the QR code\n * Should contain `client_id` and either `request` or `request_uri` query parameters\n */\n authorizeRequestUrl: string;\n\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementation\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * Optional wallet metadata to send when request_uri_method=post.\n * If not provided and POST is required, sends an empty body (basic implementation).\n *\n * Specification: IT-Wallet v1.3.3 recommends (SHOULD) sending wallet capabilities\n * in application/x-www-form-urlencoded format when using POST.\n */\n walletMetadata?: {\n authorization_endpoint?: string;\n client_id_prefixes_supported?: string[];\n request_object_signing_alg_values_supported?: string[];\n response_modes_supported?: string[];\n response_types_supported?: string[];\n vp_formats_supported?: Record<string, unknown>;\n };\n\n /**\n * Optional wallet nonce for replay attack prevention (RECOMMENDED per spec)\n */\n walletNonce?: string;\n}\n\nexport interface ParsedQrCode {\n /**\n * The `client_id` from the authorization URL\n */\n clientId: string;\n /**\n * The `request_uri` from the authorization URL\n */\n requestUri?: string;\n /**\n * The `request_uri_method` from the authorization URL (get or post)\n */\n requestUriMethod?: \"get\" | \"post\";\n}\n\nexport interface FetchAuthorizationRequestResult {\n /**\n * The parsed QR code data\n * Includes `clientId`, `requestUri` and `requestUriMethod`\n */\n parsedQrCode: ParsedQrCode;\n\n /**\n * The original Request Object JWT, either fetched from `request_uri` or extracted from `request` parameter.\n */\n requestObjectJwt: string;\n\n /**\n * Transmission mode indicator\n * - \"value\": Request Object JWT passed inline via `request` parameter\n * - \"reference\": Request Object JWT fetched from `request_uri`\n */\n sendBy: \"reference\" | \"value\";\n}\n\n/**\n * Helper function to fetch Request Object JWT from request_uri.\n * Supports GET and POST methods, with optional wallet metadata for POST.\n *\n * @param requestUri - URI to fetch Request Object from\n * @param options - Fetch options including method and wallet metadata\n * @returns The Request Object JWT as a string\n * @throws {UnexpectedStatusCodeError} If the server returns a non-200 status code\n * @throws {Error} If the underlying fetch/createFetcher call fails (for example, due to network errors)\n */\nexport async function fetchRequestObjectJwt(\n requestUri: string,\n options: {\n fetch: CallbackContext[\"fetch\"];\n method: \"get\" | \"post\";\n walletMetadata?: FetchAuthorizationRequestOptions[\"walletMetadata\"];\n walletNonce?: string;\n },\n): Promise<string> {\n const fetch = createFetcher(options.fetch);\n\n // Prepare request configuration\n const requestInit: RequestInit = {\n method: options.method.toUpperCase(),\n };\n\n // Add body for POST requests per IT-Wallet spec (SHOULD include metadata)\n if (options.method === \"post\") {\n const formData = new URLSearchParams();\n\n // Add wallet_metadata if provided (spec: OPTIONAL)\n if (options.walletMetadata) {\n formData.append(\n \"wallet_metadata\",\n JSON.stringify(options.walletMetadata),\n );\n }\n\n // Add wallet_nonce if provided (spec: RECOMMENDED)\n if (options.walletNonce) {\n formData.append(\"wallet_nonce\", options.walletNonce);\n }\n\n requestInit.headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n requestInit.body = formData.toString();\n }\n\n const response = await fetch(requestUri, requestInit);\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(response);\n\n return await response.text();\n}\n\n/**\n * Fetches an OpenID4VP authorization request JWT from a QR code URL.\n *\n * Supports two transmission modes:\n * - **By Value**: Request Object JWT passed inline via `request` parameter\n * - **By Reference**: Request Object JWT fetched from `request_uri`\n *\n * The function:\n * 1. Parses the authorization URL to extract parameters\n * 2. Validates that exactly one of `request` or `request_uri` is present\n * 3. Either uses inline JWT or fetches from URI (GET/POST based on request_uri_method)\n * 4. Returns the Request Object JWT along with transmission mode metadata\n *\n * Note: This function does NOT parse or verify the JWT. Use {@link parseAuthorizeRequest}\n * separately to decode and optionally verify the signature.\n *\n * @param options {@link FetchAuthorizationRequestOptions}\n * @returns Promise that resolves to {@link FetchAuthorizationRequestResult}\n * @throws {Oid4vpError} When required query parameters are missing, the URL is invalid, or an unexpected error occurs during fetch or parsing\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code during fetch\n * @throws {ValidationError} When URL parameters fail schema validation\n *\n * @example By Value mode\n * ```typescript\n * const url = \"https://wallet.example.org/authorize?\" +\n * \"client_id=openid_federation%23https%3A%2F%2Frp.example.org\" +\n * \"&request=eyJhbGciOiJFUzI1NiIs...\";\n *\n * const result = await fetchAuthorizationRequest({\n * authorizeRequestUrl: url,\n * callbacks: { fetch },\n * });\n * // result.sendBy === \"value\"\n * // result.requestObjectJwt === \"eyJhbGciOiJFUzI1NiIs...\"\n * ```\n *\n * @example By Reference mode with POST\n * ```typescript\n * const url = \"https://wallet.example.org/authorize?\" +\n * \"client_id=openid_federation%23https%3A%2F%2Frp.example.org\" +\n * \"&request_uri=https%3A%2F%2Frp.example.org%2Frequest\" +\n * \"&request_uri_method=post\";\n *\n * const result = await fetchAuthorizationRequest({\n * authorizeRequestUrl: url,\n * callbacks: { fetch },\n * walletMetadata: {\n * authorization_endpoint: \"https://wallet.example.org/authorize\",\n * response_types_supported: [\"vp_token\"],\n * },\n * walletNonce: \"random-nonce\",\n * });\n * // result.sendBy === \"reference\"\n * // result.requestObjectJwt === fetched JWT from request_uri\n * ```\n */\nexport async function fetchAuthorizationRequest(\n options: FetchAuthorizationRequestOptions,\n): Promise<FetchAuthorizationRequestResult> {\n try {\n const url = new URL(options.authorizeRequestUrl);\n\n // Extract and validate URL parameters using Zod schema\n const rawParams = {\n client_id: url.searchParams.get(\"client_id\") ?? undefined,\n request: url.searchParams.get(\"request\") ?? undefined,\n request_uri: url.searchParams.get(\"request_uri\") ?? undefined,\n request_uri_method:\n url.searchParams.get(\"request_uri_method\") ?? undefined,\n state: url.searchParams.get(\"state\") ?? undefined,\n };\n\n // Parse and validate URL parameters with Zod schema\n const parsedParams = zAuthorizationRequestUrlParams.parse(rawParams);\n\n // Validate business logic (mutual exclusivity, etc.)\n const validatedParams = validateAuthorizationRequestParams(parsedParams);\n\n // Determine transmission mode\n const sendBy = validatedParams.request ? \"value\" : \"reference\";\n\n // Get JWT: either inline or fetch from URI\n let requestObjectJwt: string;\n if (validatedParams.request) {\n requestObjectJwt = validatedParams.request;\n } else {\n // Type system guarantees request_uri is defined here due to validation\n requestObjectJwt = await fetchRequestObjectJwt(\n validatedParams.request_uri as string,\n {\n fetch: options.callbacks.fetch,\n method: validatedParams.request_uri_method ?? \"get\",\n walletMetadata: options.walletMetadata,\n walletNonce: options.walletNonce,\n },\n );\n }\n\n return {\n parsedQrCode: {\n clientId: validatedParams.client_id,\n requestUri: validatedParams.request_uri,\n requestUriMethod:\n sendBy === \"reference\"\n ? (validatedParams.request_uri_method ?? \"get\")\n : undefined,\n },\n requestObjectJwt,\n sendBy,\n };\n } catch (error) {\n if (\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError ||\n error instanceof Oid4vpError ||\n error instanceof UnexpectedStatusCodeError\n ) {\n throw error;\n }\n\n throw new Oid4vpError(\n `Unexpected error during fetch authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { InvalidRequestUriMethodError, Oid4vpError } from \"../errors\";\nimport { AuthorizationRequestUrlParams } from \"./z-authorization-request-url\";\n\n/**\n * Validates authorization request URL parameters according to IT-Wallet and OpenID4VP specifications.\n *\n * Validation rules:\n * 1. Exactly one of `request` or `request_uri` must be present (mutual exclusivity)\n * 2. `request_uri_method` must be \"get\" or \"post\" (case-insensitive) if present\n * 3. `request_uri_method` can only be used with `request_uri` parameter\n *\n * @param params - Parsed authorization request URL parameters\n * @returns Type-narrowed params ensuring mutual exclusivity\n * @throws {Oid4vpError} When both or neither request/request_uri are present\n * @throws {InvalidRequestUriMethodError} When request_uri_method is not \"get\" or \"post\"\n * @throws {Oid4vpError} When request_uri_method is used without request_uri\n */\nexport function validateAuthorizationRequestParams(\n params: AuthorizationRequestUrlParams,\n) {\n // Mutual exclusivity check\n if (params.request && params.request_uri) {\n throw new Oid4vpError(\n \"request and request_uri cannot both be present in an authorization request\",\n );\n }\n\n // At least one must be present\n if (!params.request && !params.request_uri) {\n throw new Oid4vpError(\n \"Either request or request_uri parameter must be present\",\n );\n }\n\n // Validate request_uri_method if present\n if (params.request_uri_method) {\n const normalizedMethod = params.request_uri_method.toLowerCase();\n if (normalizedMethod !== \"get\" && normalizedMethod !== \"post\") {\n throw new InvalidRequestUriMethodError(\n `Invalid request_uri_method: '${params.request_uri_method}'. Must be 'get' or 'post'`,\n );\n }\n }\n\n // request_uri_method only allowed with request_uri\n if (params.request_uri_method && !params.request_uri) {\n throw new Oid4vpError(\n \"request_uri_method can only be used with request_uri parameter\",\n );\n }\n\n // Normalize request_uri_method to lowercase if present\n const normalizedMethod = params.request_uri_method\n ? (params.request_uri_method.toLowerCase() as \"get\" | \"post\")\n : undefined;\n\n return {\n ...params,\n request_uri_method: normalizedMethod,\n } as (\n | {\n request?: never;\n request_uri: string;\n request_uri_method?: \"get\" | \"post\";\n }\n | { request: string; request_uri?: never; request_uri_method?: never }\n ) &\n typeof params;\n}\n","import z from \"zod\";\n\n/**\n * Schema for authorization request URL query parameters.\n * Note: `request` contains the signed Request Object JWT, it is NOT a claim inside the Request Object.\n */\nexport const zAuthorizationRequestUrlParams = z.looseObject({\n client_id: z.string(),\n request: z.string().optional(), // JWT containing Request Object (by value)\n request_uri: z.url().optional(), // URI to fetch Request Object (by reference)\n request_uri_method: z.string().optional(), // HTTP method for request_uri (validated in business logic)\n state: z.string().optional(), // Optional state parameter\n});\n\nexport type AuthorizationRequestUrlParams = z.infer<\n typeof zAuthorizationRequestUrlParams\n>;\n","import {\n CallbackContext,\n JwtSigner,\n Oauth2JwtParseError,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { ParseAuthorizeRequestError } from \"../errors\";\nimport {\n Openid4vpAuthorizationRequestHeader,\n Openid4vpAuthorizationRequestPayload,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n zOpenid4vpAuthorizationRequestPayload,\n} from \"./z-authorization-request\";\n\n/**\n * Enum representing the client_id prefix types according to IT Wallet specifications\n */\nexport enum ClientIdPrefix {\n NONE = \"none\",\n OPENID_FEDERATION = \"openid_federation\",\n X509_HASH = \"x509_hash\",\n}\n\n/**\n * Extracts the prefix from a client_id string\n * @param clientId - The client_id from the request object\n * @returns The prefix type (x509_hash, openid_federation, or none)\n */\nexport function extractClientIdPrefix(clientId: string): ClientIdPrefix {\n if (clientId.startsWith(\"x509_hash:\")) {\n return ClientIdPrefix.X509_HASH;\n }\n if (clientId.startsWith(\"openid_federation:\")) {\n return ClientIdPrefix.OPENID_FEDERATION;\n }\n return ClientIdPrefix.NONE;\n}\n\n/**\n * Retrieves the public key for verifying the Request Object JWT signature\n * according to IT Wallet specifications.\n *\n * Priority order:\n * 1. If client_id has x509_hash prefix: use x5c certificate chain from header\n * 2. If client_id has openid_federation prefix or no prefix: return a federation signer; if trust_chain\n * is present it is forwarded, otherwise the verifyJwt callback is responsible for reconstructing\n * the chain from client_id\n *\n * @param options - Parse options containing decoded JWT\n * @returns The JWK to use for signature verification\n * @throws {ParseAuthorizeRequestError} When no valid public key can be found\n */\nfunction getPublicKeyForVerification(options: {\n header: Openid4vpAuthorizationRequestHeader;\n payload: Openid4vpAuthorizationRequestPayload;\n}): JwtSigner {\n const { header, payload } = options;\n\n const clientIdPrefix = extractClientIdPrefix(payload.client_id);\n\n // Priority 1: x509_hash prefix - use x5c certificate chain from header\n if (clientIdPrefix === ClientIdPrefix.X509_HASH) {\n if (!Array.isArray(header.x5c) || header.x5c.length === 0) {\n throw new ParseAuthorizeRequestError(\n \"x5c is required in JWT header for x509_hash client_id\",\n );\n }\n\n return {\n alg: header.alg,\n kid: header.kid,\n method: \"x5c\" as const,\n x5c: header.x5c,\n };\n }\n\n // Priority 2: openid_federation prefix or no prefix - use trust_chain if present,\n // otherwise delegate chain reconstruction to the verifyJwt callback\n if (\n clientIdPrefix === ClientIdPrefix.OPENID_FEDERATION ||\n clientIdPrefix === ClientIdPrefix.NONE\n ) {\n if (!header.kid) {\n throw new ParseAuthorizeRequestError(\n \"kid is required in JWT header for openid_federation client_id or no prefix\",\n );\n }\n\n return {\n alg: header.alg,\n kid: header.kid,\n method: \"federation\" as const,\n ...(header.trust_chain && { trustChain: header.trust_chain }),\n };\n }\n\n throw new ParseAuthorizeRequestError(\n \"Unable to determine public key for Request Object verification\",\n );\n}\n\nexport interface ParseAuthorizeRequestOptions {\n /**\n * Optional callback context for JWT signature verification.\n * If not provided, signature verification is skipped.\n */\n callbacks?: Pick<CallbackContext, \"verifyJwt\">;\n\n config: IoWalletSdkConfig;\n\n /**\n * The Authorization Request Object JWT.\n */\n requestObjectJwt: string;\n}\n\nexport interface ParsedAuthorizeRequestResult {\n /**\n * The JWT header of the authorization request object.\n */\n header: Openid4vpAuthorizationRequestHeader;\n /**\n * The parsed authorization request object.\n */\n payload: Openid4vpAuthorizationRequestPayload;\n}\n\n/**\n * Parses and optionally verifies a JWT containing an OpenID4VP Request Object.\n *\n * This method decodes the Request Object JWT and validates its structure. If the `verifyJwt`\n * callback is provided, it also verifies the JWT signature using the public key obtained\n * according to IT Wallet specifications:\n * 1. If client_id has x509_hash prefix: use x5c certificate chain from header\n * 2. If client_id has openid_federation prefix or no prefix: pass a federation signer to the callback;\n * trust_chain is forwarded when present, otherwise the callback must reconstruct the chain from client_id\n *\n * @param options {@link ParseAuthorizeRequestOptions}\n * @returns A {@link ParsedAuthorizeRequestResult} containing the RP required credentials payload and the {@link Openid4vpAuthorizationRequestHeader} JWT header\n * @throws {@link ValidationError} in case there are errors validating the Request Object structure\n * @throws {@link Oauth2JwtParseError} in case the request object jwt is malformed (e.g missing header, bad encoding)\n * @throws {@link ParseAuthorizeRequestError} in case the JWT signature is invalid (when verifyJwt is provided) or there are unexpected errors\n *\n * @security If `verifyJwt` callback is not provided in options, JWT signature verification is skipped.\n */\nexport async function parseAuthorizeRequest(\n options: ParseAuthorizeRequestOptions,\n): Promise<ParsedAuthorizeRequestResult> {\n try {\n const headerSchema = options.config.isVersion(ItWalletSpecsVersion.V1_0)\n ? zOpenid4vpAuthorizationRequestHeaderV1_0\n : zOpenid4vpAuthorizationRequestHeaderV1_3;\n\n const decoded = decodeJwt({\n headerSchema,\n jwt: options.requestObjectJwt,\n payloadSchema: zOpenid4vpAuthorizationRequestPayload,\n });\n\n if (options.callbacks?.verifyJwt) {\n const signer = getPublicKeyForVerification({\n header: decoded.header,\n payload: decoded.payload,\n });\n\n await verifyJwt({\n compact: options.requestObjectJwt,\n errorMessage: \"Error verifying Request Object signature\",\n header: decoded.header,\n payload: decoded.payload,\n signer,\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n }\n\n return {\n header: decoded.header,\n payload: decoded.payload,\n };\n } catch (error) {\n if (\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n )\n throw error;\n throw new ParseAuthorizeRequestError(\n `Unexpected error during Request Object parsing: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type {\n ItWalletCredentialVerifierMetadata,\n ItWalletCredentialVerifierMetadataV1_3,\n} from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext, JweEncryptor } from \"@pagopa/io-wallet-oauth2\";\nimport { Jwk } from \"@pagopa/io-wallet-oauth2\";\nimport { encodeToBase64Url } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientIdPrefix,\n Openid4vpAuthorizationRequestPayload,\n extractClientIdPrefix,\n} from \"../authorization-request\";\nimport { CreateAuthorizationResponseError } from \"../errors\";\nimport { extractEncryptionJwkFromJwks } from \"../jarm\";\nimport { VpToken } from \"../vp-token\";\nimport { Openid4vpAuthorizationResponse } from \"./z-authorization-response\";\n\nexport interface CreateAuthorizationResponseOptions {\n /**\n * JARM encryption algorithm (JWE alg), should be one of the values supported by the verifier's metadata.\n * falls back to \"ECDH-ES\" if not provided.\n */\n authorization_encrypted_response_alg?: string;\n\n /**\n * JARM encryption encoding (JWE enc), should be one of the values supported by the verifier's metadata.\n * falls back to \"A256GCM\" if not provided.\n */\n authorization_encrypted_response_enc?: string;\n\n /**\n * Callbacks for authorization response generation\n */\n callbacks: Pick<CallbackContext, \"encryptJwe\" | \"generateRandom\">;\n\n /**\n * Presentation's Request Object\n */\n requestObject: Pick<\n Openid4vpAuthorizationRequestPayload,\n \"client_id\" | \"client_metadata\" | \"nonce\" | \"state\"\n >;\n\n /**\n * Relying Party metadata JWKS\n */\n rpJwks: {\n encrypted_response_enc_values_supported?: string[];\n } & Pick<\n ItWalletCredentialVerifierMetadata | ItWalletCredentialVerifierMetadataV1_3,\n \"jwks\"\n >;\n\n /**\n * Array containing the vp_tokens of the credentials\n * to present\n */\n vp_token: VpToken;\n}\n\n/**\n * Result of createAuthorizationResponse function\n * Contains the generated JARM payload and the encrypted response to send to the verifier\n */\nexport interface CreateAuthorizationResponseResult {\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n jarm: {\n encryptionJwk: Jwk;\n responseJwe: string;\n };\n}\n\n/**\n * Creates an encrypted JARM authorization response for OpenID4VP presentation.\n *\n * This function generates a JARM (JWT Secured Authorization Response Mode) response\n * containing the VP tokens from the wallet to the verifier.\n *\n * **Version Compatibility:**\n * - v1.0 metadata: JARM algorithms are read from rpJwks if not explicitly provided\n * - v1.3 metadata: JARM algorithms may be provided explicitly; when omitted, values are\n * resolved from rpJwks or fall back to implementation defaults (e.g. ECDH-ES / A256GCM)\n *\n * @param options - Configuration for creating the authorization response\n * @param options.authorization_encrypted_response_alg - Optional JARM encryption algorithm (JWE alg). If omitted, falls back to \"ECDH-ES\".\n * @param options.authorization_encrypted_response_enc - Optional JARM encryption encoding (JWE enc). If omitted, the first value from metadata's encrypted_response_enc_values_supported is used, or falls back to \"A256GCM\".\n * @param options.callbacks - Cryptographic callbacks for JWE encryption\n * @param options.requestObject - The authorization request object to respond to\n * @param options.rpJwks - Relying Party JWKS with optional enc values (v1.0 or v1.3)\n * @param options.vp_token - Array of VP tokens to include in the response\n *\n * @returns An encrypted JARM authorization response (JWE compact serialization)\n *\n * @throws {CreateAuthorizationResponseError} If response generation or encryption fails\n */\nexport async function createAuthorizationResponse(\n options: CreateAuthorizationResponseOptions,\n): Promise<CreateAuthorizationResponseResult> {\n try {\n const encryptionAlg: string =\n options.authorization_encrypted_response_alg ?? \"ECDH-ES\";\n\n const encryptionEnc: string =\n options.authorization_encrypted_response_enc ?? \"A256GCM\";\n\n // Determine which metadata to use based on client_id prefix\n const { requestObject } = options;\n const clientMetadata = requestObject.client_metadata;\n const clientIdPrefix = extractClientIdPrefix(requestObject.client_id);\n\n if (clientIdPrefix === ClientIdPrefix.X509_HASH && !clientMetadata) {\n throw new CreateAuthorizationResponseError(\n \"clientMetadata is required when client_id uses x509_hash prefix\",\n );\n }\n\n // When using OpenID Federation, client_metadata may be present in the request\n // but per the Italian specification most of its content should be ignored —\n // use rpJwks for encryption parameters instead.\n const effectiveClientMetadata =\n clientIdPrefix === ClientIdPrefix.OPENID_FEDERATION\n ? undefined\n : clientMetadata;\n\n const authorizationResponsePayload: Openid4vpAuthorizationResponse = {\n state: requestObject.state,\n vp_token: options.vp_token,\n };\n\n // Extract encryption JWK from effective metadata\n const encryptionJwks = effectiveClientMetadata\n ? effectiveClientMetadata.jwks\n : options.rpJwks.jwks;\n const encryptionJwk = extractEncryptionJwkFromJwks(encryptionJwks, {\n supportedAlgValues: [encryptionAlg],\n });\n if (!encryptionJwk) {\n throw new CreateAuthorizationResponseError(\n \"No encryption JWK found in metadata\",\n );\n }\n\n const encValuesSupported =\n effectiveClientMetadata?.encrypted_response_enc_values_supported ??\n options.rpJwks.encrypted_response_enc_values_supported;\n\n let enc: string;\n if (encValuesSupported) {\n if (options.authorization_encrypted_response_enc !== undefined) {\n // Explicit value provided: use it if supported, otherwise take the first supported value\n enc =\n encValuesSupported.find(\n (e) => e === options.authorization_encrypted_response_enc,\n ) ??\n encValuesSupported[0] ??\n options.authorization_encrypted_response_enc;\n } else {\n // No explicit value: take the first (most preferred) value from the metadata\n enc = encValuesSupported[0] ?? encryptionEnc;\n }\n } else {\n enc = encryptionEnc;\n }\n\n const alg = encryptionJwk.alg ?? encryptionAlg;\n\n const nonceBytes = await options.callbacks.generateRandom(32);\n\n const jweEncryptor: JweEncryptor = {\n alg,\n apu: encodeToBase64Url(nonceBytes),\n apv: encodeToBase64Url(requestObject.nonce),\n enc,\n method: \"jwk\",\n publicJwk: encryptionJwk,\n };\n\n const plaintext = JSON.stringify(authorizationResponsePayload);\n\n const { encryptionJwk: usedJwk, jwe } = await options.callbacks.encryptJwe(\n jweEncryptor,\n plaintext,\n );\n\n return {\n authorizationResponsePayload,\n jarm: {\n encryptionJwk: usedJwk,\n responseJwe: jwe,\n },\n };\n } catch (error) {\n if (error instanceof CreateAuthorizationResponseError) {\n throw error;\n }\n throw new CreateAuthorizationResponseError(\n `Unexpected error during authorization response creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type { JwkSet } from \"@pagopa/io-wallet-oauth2\";\n\nexport function extractEncryptionJwkFromJwks(\n jwks: JwkSet,\n {\n kid,\n supportedAlgValues,\n }: {\n kid?: string;\n supportedAlgValues?: string[];\n },\n) {\n if (kid) {\n return jwks.keys.find((jwk) => jwk.kid === kid);\n }\n\n let algFiltered = jwks.keys.filter(\n (key) => key.alg && supportedAlgValues?.includes(key.alg),\n );\n if (algFiltered.length === 0) algFiltered = jwks.keys;\n\n let encFiltered = algFiltered.filter((key) => key.use === \"enc\");\n if (encFiltered.length === 0) {\n encFiltered = algFiltered.filter((key) => key.use !== \"sig\");\n }\n\n return encFiltered.length > 0 ? encFiltered[0] : jwks.keys[0];\n}\n","import {\n type CallbackContext,\n decodeJwtHeader,\n zCompactJwe,\n zCompactJwt,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request\";\nimport { ParseAuthorizationResponseResult } from \"../authorization-response/parse-authorization-response\";\nimport { validateOpenid4vpAuthorizationResponsePayload } from \"../authorization-response/validate-authorization-response\";\nimport { zOpenid4vpAuthorizationResponse } from \"../authorization-response/z-authorization-response\";\nimport { verifyJarmAuthorizationResponse } from \"./verify-jarm-authorization-response\";\nimport { zJarmHeader } from \"./z-jarm\";\n\nexport interface ParseJarmAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to validate JARM claims.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Callbacks used to decrypt and verify JARM JWT/JWE responses.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n /**\n * Compact JARM authorization response (`response` parameter value).\n */\n jarmResponseJwt: string;\n /**\n * Current time used for temporal claim validation (`exp`, `nbf`).\n * Defaults to current date-time when omitted.\n */\n now?: Date;\n}\n\n/**\n * Parses and validates a JARM authorization response for OpenID4VP.\n *\n * This function validates compact format, decrypts and/or verifies the JARM token,\n * parses the resulting OpenID4VP authorization response, and validates it against\n * the originating authorization request.\n *\n * @param options {@link ParseJarmAuthorizationResponseOptions}\n * @returns Parsed authorization response enriched with JARM metadata.\n */\nexport async function parseJarmAuthorizationResponse(\n options: ParseJarmAuthorizationResponseOptions,\n): Promise<ParseAuthorizationResponseResult> {\n const { authorizationRequestPayload, callbacks, jarmResponseJwt, now } =\n options;\n\n const jarmAuthorizationResponseJwt = parseWithErrorHandling(\n z.union([zCompactJwt, zCompactJwe]),\n jarmResponseJwt,\n \"Invalid jarm authorization response jwt.\",\n );\n\n const verifiedJarmResponse = await verifyJarmAuthorizationResponse({\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n now,\n });\n\n const { header: jarmHeader } = decodeJwtHeader({\n headerSchema: zJarmHeader,\n jwt: jarmAuthorizationResponseJwt,\n });\n\n const authorizationResponsePayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationResponse,\n verifiedJarmResponse.jarmAuthorizationResponse,\n \"Failed to parse openid4vp authorization response.\",\n );\n\n const validateOpenId4vpResponse =\n validateOpenid4vpAuthorizationResponsePayload({\n authorizationRequestPayload: authorizationRequestPayload,\n authorizationResponsePayload: authorizationResponsePayload,\n });\n\n return {\n ...validateOpenId4vpResponse,\n authorizationResponsePayload,\n expectedNonce: authorizationRequestPayload.nonce,\n jarm: { ...verifiedJarmResponse, jarmHeader },\n };\n}\n","import { parseIfJson, parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { zVpToken } from \"./z-vp-token\";\n\nexport function parseVpToken(vpToken: unknown) {\n return parseWithErrorHandling(\n zVpToken,\n parseIfJson(vpToken),\n \"Could not parse dcql vp_token. Expected an object where the values are encoded presentations\",\n );\n}\n","import { z } from \"zod\";\n\nexport const zVpToken = z.record(\n z.string(),\n z.string().or(z.array(z.string()).nonempty()),\n {\n message:\n \"vp_token must be an object where each key is a string and each value is a non-empty array of strings (v1.3) or a string (v1.0)\",\n },\n);\n\nexport type VpToken = z.infer<typeof zVpToken>;\n","import { Openid4vpAuthorizationRequestPayload } from \"../authorization-request\";\nimport { Oid4vpError } from \"../errors\";\nimport { parseVpToken } from \"../vp-token\";\nimport { Openid4vpAuthorizationResponse } from \"./z-authorization-response\";\n\nexport interface ValidateOpenid4vpAuthorizationResponseOptions {\n /**\n * Parsed request payload used as validation source.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Parsed authorization response payload to validate.\n */\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n}\n\n/**\n * Result of authorization response validation.\n */\nexport interface ValidateOpenid4vpAuthorizationResponseResult {\n presentations: ReturnType<typeof parseVpToken>;\n query: Openid4vpAuthorizationRequestPayload[\"dcql_query\"];\n}\n\n/**\n * Validates the OpenID4VP authorization response payload against the request payload.\n *\n * @param options {@link ValidateOpenid4vpAuthorizationResponseOptions}\n * @returns Presentations and query extracted from the validated flow.\n * @throws {Oid4vpError} If `state` is present in the request and does not match the response.\n */\nexport function validateOpenid4vpAuthorizationResponsePayload(\n options: ValidateOpenid4vpAuthorizationResponseOptions,\n): ValidateOpenid4vpAuthorizationResponseResult {\n const { authorizationRequestPayload, authorizationResponsePayload } = options;\n\n if (\n authorizationRequestPayload.state !== authorizationResponsePayload.state\n ) {\n throw new Oid4vpError(\"OpenId4Vp Authorization Response state mismatch.\");\n }\n\n const presentations = parseVpToken(authorizationResponsePayload.vp_token);\n\n return {\n presentations,\n query: authorizationRequestPayload.dcql_query,\n };\n}\n","import z from \"zod\";\n\nimport { zVpToken } from \"../vp-token\";\n\nexport const zOpenid4vpAuthorizationResponse = z.object({\n state: z.string(),\n vp_token: zVpToken,\n});\n\nexport type Openid4vpAuthorizationResponse = z.infer<\n typeof zOpenid4vpAuthorizationResponse\n>;\n\nexport const zOpenid4vpAuthorizationResponseResult = z.object({\n redirect_uri: z.url().optional(),\n});\n\nexport type Openid4vpAuthorizationResponseResult = z.infer<\n typeof zOpenid4vpAuthorizationResponseResult\n>;\n","import { jwtSignerFromJwt } from \"@openid4vc/oauth2\";\nimport {\n type CallbackContext,\n type Jwk,\n Oauth2Error,\n decodeJwt,\n decodeJwtHeader,\n zCompactJwe,\n zCompactJwt,\n zJwtHeader,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { stringToJsonWithErrorHandling } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request\";\nimport { extractEncryptionJwkFromJwks } from \"./jarm-extract-jwks\";\nimport {\n JarmAuthorizationResponse,\n JarmAuthorizationResponseEncryptedOnly,\n zEncryptedJarmHeader,\n zJarmAuthorizationResponse,\n zJarmAuthorizationResponseEncryptedOnly,\n} from \"./z-jarm\";\n\n/**\n * Supported JARM serialization/processing modes.\n */\nexport enum JarmMode {\n Encrypted = \"Encrypted\",\n Signed = \"Signed\",\n SignedEncrypted = \"SignedEncrypted\",\n}\n\nconst decryptJarmAuthorizationResponseJwt = async (options: {\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n callbacks: Pick<CallbackContext, \"decryptJwe\">;\n jarmAuthorizationResponseJwt: string;\n}) => {\n const {\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n } = options;\n\n let encryptionJwk: Jwk | undefined;\n const { header } = decodeJwtHeader({\n headerSchema: zEncryptedJarmHeader,\n jwt: jarmAuthorizationResponseJwt,\n });\n\n const jwks = authorizationRequestPayload.client_metadata?.jwks;\n\n if (jwks) {\n encryptionJwk = extractEncryptionJwkFromJwks(jwks, { kid: header.kid });\n }\n\n const result = await callbacks.decryptJwe(jarmAuthorizationResponseJwt, {\n jwk: encryptionJwk,\n });\n\n if (!result.decrypted) {\n throw new Oauth2Error(\"Failed to decrypt jarm auth response.\");\n }\n\n return {\n decryptionJwk: result.decryptionJwk,\n payload: result.payload,\n };\n};\n\nexport interface VerifyJarmAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to resolve metadata and key material.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Callbacks required for JWE decryption and JWT signature verification.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n /**\n * Compact serialized JARM response received from the verifier.\n */\n jarmAuthorizationResponseJwt: string;\n /**\n * Current time used for temporal claim validation (`exp`, `nbf`).\n * Defaults to current date-time when omitted.\n */\n now?: Date;\n}\n\n/**\n * Verified JARM authorization response data returned by {@link verifyJarmAuthorizationResponse}.\n */\nexport interface VerifyJarmAuthorizationResponseResult {\n /**\n * JWK used for decryption when the response is encrypted, or `undefined` if the response was not encrypted.\n */\n decryptionJwk: Jwk | undefined;\n /**\n * The `iss` claim from the JARM response, representing the issuer of the response.\n */\n issuer: string | undefined;\n /**\n * The parsed JARM authorization response body, containing claims like `iss`, `aud`, `exp`, etc.\n */\n jarmAuthorizationResponse:\n | JarmAuthorizationResponse\n | JarmAuthorizationResponseEncryptedOnly;\n /**\n * Detected JARM processing mode indicating whether the response was signed, encrypted, or both.\n */\n type: JarmMode;\n}\n\n/**\n * Verifies a JARM authorization response in signed, encrypted, or signed+encrypted mode.\n *\n * The function detects the response mode, performs decryption when needed, verifies\n * JWS signatures for signed payloads, and returns the parsed JARM body with metadata.\n *\n * @param options {@link VerifyJarmAuthorizationResponseOptions}\n * @returns Decryption and verification artifacts with parsed JARM payload.\n * @throws {Oauth2Error} If the response mode is invalid, decryption fails, or signature verification fails.\n */\nexport async function verifyJarmAuthorizationResponse(\n options: VerifyJarmAuthorizationResponseOptions,\n) {\n const {\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n } = options;\n\n const requestDataIsEncrypted = zCompactJwe.safeParse(\n jarmAuthorizationResponseJwt,\n ).success;\n const decryptedRequestData = requestDataIsEncrypted\n ? await decryptJarmAuthorizationResponseJwt({\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n })\n : { decryptionJwk: undefined, payload: jarmAuthorizationResponseJwt };\n\n const responseIsSigned = zCompactJwt.safeParse(\n decryptedRequestData.payload,\n ).success;\n\n if (!requestDataIsEncrypted && !responseIsSigned) {\n throw new Oauth2Error(\n \"Jarm Auth Response must be either encrypted, signed, or signed and encrypted.\",\n );\n }\n\n let jarmAuthorizationResponse:\n | JarmAuthorizationResponse\n | JarmAuthorizationResponseEncryptedOnly;\n\n if (responseIsSigned) {\n const { header: jwsProtectedHeader, payload: jwsPayload } = decodeJwt({\n headerSchema: z.object({ ...zJwtHeader.shape, kid: z.string() }),\n jwt: decryptedRequestData.payload,\n });\n\n const response = zJarmAuthorizationResponse.parse(jwsPayload);\n const jwtSigner = jwtSignerFromJwt({\n header: jwsProtectedHeader,\n payload: jwsPayload,\n });\n\n const verificationResult = await options.callbacks.verifyJwt(jwtSigner, {\n compact: decryptedRequestData.payload,\n header: jwsProtectedHeader,\n payload: jwsPayload,\n });\n\n if (!verificationResult.verified) {\n throw new Oauth2Error(\"Jarm Auth Response is not valid.\");\n }\n\n const expectedAudience = authorizationRequestPayload.client_id;\n const expectedIssuer = authorizationRequestPayload.iss;\n if (response.aud !== expectedAudience) {\n throw new Oauth2Error(\n `Jarm Auth Response contains 'aud' value '${response.aud}', but expected '${expectedAudience}'.`,\n );\n }\n\n if (response.iss !== expectedIssuer) {\n throw new Oauth2Error(\n `Jarm Auth Response contains 'iss' value '${response.iss}', but expected '${expectedIssuer}'.`,\n );\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (response.exp < nowSeconds) {\n throw new Oauth2Error(\"Jarm Auth Response has expired.\");\n }\n\n if (response.nbf !== undefined && response.nbf > nowSeconds) {\n throw new Oauth2Error(\"Jarm Auth Response is not active yet.\");\n }\n\n jarmAuthorizationResponse = response;\n } else {\n const jsonRequestData = stringToJsonWithErrorHandling(\n decryptedRequestData.payload,\n \"Unable to parse decrypted JARM JWE body to JSON\",\n );\n jarmAuthorizationResponse =\n zJarmAuthorizationResponseEncryptedOnly.parse(jsonRequestData);\n }\n\n const type: JarmMode =\n requestDataIsEncrypted && responseIsSigned\n ? JarmMode.SignedEncrypted\n : requestDataIsEncrypted\n ? JarmMode.Encrypted\n : JarmMode.Signed;\n\n const issuer = jarmAuthorizationResponse.iss;\n\n return {\n decryptionJwk: decryptedRequestData.decryptionJwk,\n issuer,\n jarmAuthorizationResponse,\n type,\n };\n}\n","import { zJwtHeader, zJwtPayload } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nexport const zJarmHeader = z.object({\n ...zJwtHeader.shape,\n apu: z.string().optional(),\n apv: z.string().optional(),\n kid: z.string(),\n});\n\nexport type JarmHeader = z.infer<typeof zJarmHeader>;\n\nexport const zEncryptedJarmHeader = z.object({\n ...zJwtHeader.shape,\n apu: z.string().optional(),\n apv: z.string().optional(),\n enc: z.string().optional(),\n kid: z.string(),\n});\n\nexport type EncryptedJarmHeader = z.infer<typeof zEncryptedJarmHeader>;\n\nexport const zJarmAuthorizationResponse = z.looseObject({\n /**\n * iss: The issuer URL of the authorization server that created the response\n * aud: The client_id of the client the response is intended for\n * exp: The expiration time of the JWT. A maximum JWT lifetime of 10 minutes is RECOMMENDED.\n */\n ...zJwtPayload.shape,\n ...zJwtPayload.pick({ aud: true, exp: true, iss: true }).required().shape,\n state: z.optional(z.string()),\n});\n\nexport type JarmAuthorizationResponse = z.infer<\n typeof zJarmAuthorizationResponse\n>;\n\nexport const zJarmAuthorizationResponseEncryptedOnly = z.looseObject({\n ...zJwtPayload.shape,\n state: z.optional(z.string()),\n});\n\nexport type JarmAuthorizationResponseEncryptedOnly = z.infer<\n typeof zJarmAuthorizationResponseEncryptedOnly\n>;\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 { FetchAuthorizationResponseError } from \"../errors\";\nimport {\n Openid4vpAuthorizationResponseResult,\n zOpenid4vpAuthorizationResponseResult,\n} from \"./z-authorization-response\";\n\n/**\n * Configuration options for fetching OID4VP Presentation Result\n */\nexport interface FetchAuthorizationResponseOptions {\n /**\n * The signed and encrypted {@link Openid4vpAuthorizationResponse} in base64 format\n */\n authorizationResponseJarm: string;\n\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The response_uri field contained in the {@link Openid4vpAuthorizationRequestPayload}\n */\n presentationResponseUri: string;\n}\n\n/**\n * Sends the {@link Openid4vpAuthorizationResponse} to the response uri provided by the session's\n * {@link Openid4vpAuthorizationRequestPayload} and returns the {@link Openid4vpAuthorizationResponseResult} object\n * containing the redirect_uri at which to continue the presentation\n *\n * @param options {@link FetchAuthorizationResponseOptions}\n * @returns Promise that resolves to the parsed {@link Openid4vpAuthorizationResponseResult}\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchAuthorizationResponse(\n options: FetchAuthorizationResponseOptions,\n): Promise<Openid4vpAuthorizationResponseResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const authorizationResponseResult = await fetch(\n options.presentationResponseUri,\n {\n body: new URLSearchParams({\n response: options.authorizationResponseJarm,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(\n 200,\n UnexpectedStatusCodeError,\n )(authorizationResponseResult);\n\n const authorizationResponseResultJson =\n await authorizationResponseResult.json();\n\n //Response could be anything, so it's returned as is for further processing\n return parseWithErrorHandling(\n zOpenid4vpAuthorizationResponseResult,\n authorizationResponseResultJson,\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchAuthorizationResponseError(\n `Unexpected error sending authorization response: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { CallbackContext } from \"@pagopa/io-wallet-oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request\";\nimport { Oid4vpError } from \"../errors\";\nimport {\n JarmHeader,\n VerifyJarmAuthorizationResponseResult,\n parseJarmAuthorizationResponse,\n} from \"../jarm\";\nimport {\n ValidateOpenid4vpAuthorizationResponseResult,\n validateOpenid4vpAuthorizationResponsePayload,\n} from \"./validate-authorization-response\";\nimport {\n Openid4vpAuthorizationResponse,\n zOpenid4vpAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface ParseAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to validate response parameters.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Authorization response received from the verifier endpoint or redirect URI.\n */\n authorizationResponse: Record<string, unknown>;\n /**\n * Callbacks required when the response is returned in JARM format.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n}\n\n/**\n * Parsed and validated authorization response.\n */\nexport type ParseAuthorizationResponseResult = {\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n expectedNonce: string;\n jarm?: {\n jarmHeader: JarmHeader;\n } & VerifyJarmAuthorizationResponseResult;\n} & ValidateOpenid4vpAuthorizationResponseResult;\n\n/**\n * Parses an OpenID4VP authorization response and validates it against the request.\n *\n * If the response includes a `response` parameter, the JARM flow is used.\n * Otherwise, the plain authorization response payload is parsed and validated.\n *\n * @param options {@link ParseAuthorizationResponseOptions}\n * @returns A parsed and validated authorization response.\n */\nexport async function parseAuthorizationResponse(\n options: ParseAuthorizationResponseOptions,\n): Promise<ParseAuthorizationResponseResult> {\n const { authorizationRequestPayload, authorizationResponse, callbacks } =\n options;\n\n if (authorizationResponse.response) {\n if (typeof authorizationResponse.response !== \"string\") {\n throw new Oid4vpError(\n \"Invalid jarm authorization response: 'response' parameter must be a jwt string.\",\n );\n }\n\n return parseJarmAuthorizationResponse({\n authorizationRequestPayload,\n callbacks,\n jarmResponseJwt: authorizationResponse.response,\n });\n }\n\n const authorizationResponsePayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationResponse,\n authorizationResponse,\n \"Failed to parse openid4vp authorization response.\",\n );\n\n const validatedOpenId4vpResponse =\n validateOpenid4vpAuthorizationResponsePayload({\n authorizationRequestPayload: authorizationRequestPayload,\n authorizationResponsePayload: authorizationResponsePayload,\n });\n\n return {\n ...validatedOpenId4vpResponse,\n authorizationResponsePayload,\n expectedNonce: authorizationRequestPayload.nonce,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;ACAA,IAAAA,2BAUO;AACP,6BAQO;;;AChBA,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,6BAAN,cAAyC,YAAY;AAAA,EAC1D,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,kCAAN,cAA8C,YAAY;AAAA,EAC/D,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,mCAAN,cAA+C,YAAY;AAAA,EAChE,YACE,SACgB,YAChB;AACA,UA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A,UACP,CAAC,gCAAQ,YAAY,GAAG,sCAAc;AAAA,QACxC;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACF;AAEA,cAAM;AAAA,MACJ;AAAA,MACA;AAAA,IACF,EAAE,2BAA2B;AAE7B,UAAM,kCACJ,MAAM,4BAA4B,KAAK;AAGzC,eAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,QACE,iBAAiB,qDACjB,iBAAiB,yCACjB;AACA,YAAM;AAAA,IACR;AACA,UAAM,IAAI;AAAA,MACR,oDAAoD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAC5G;AAAA,EACF;AACF;;;ACzFA,IAAAC,0BAAuC;AAqDvC,eAAsB,2BACpB,SAC2C;AAC3C,QAAM,EAAE,6BAA6B,uBAAuB,UAAU,IACpE;AAEF,MAAI,sBAAsB,UAAU;AAClC,QAAI,OAAO,sBAAsB,aAAa,UAAU;AACtD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO,+BAA+B;AAAA,MACpC;AAAA,MACA;AAAA,MACA,iBAAiB,sBAAsB;AAAA,IACzC,CAAC;AAAA,EACH;AAEA,QAAM,mCAA+B;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,6BACJ,8CAA8C;AAAA,IAC5C;AAAA,IACA;AAAA,EACF,CAAC;AAEH,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,eAAe,4BAA4B;AAAA,EAC7C;AACF;;;AlBrFA,uBAKO;","names":["import_io_wallet_oauth2","import_io_wallet_utils","normalizedMethod","import_zod","z","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","ClientIdPrefix","import_io_wallet_utils","import_io_wallet_oauth2","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_zod","import_zod","z","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_zod","import_io_wallet_oauth2","import_zod","JarmMode","z","z","import_io_wallet_utils","import_io_wallet_utils"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/authorization-request/create-authorization-request.ts","../src/errors.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-request.ts","../src/authorization-request/validate-authorization-request.ts","../src/authorization-request/z-authorization-request-url.ts","../src/authorization-request/parse-authorization-request.ts","../src/authorization-response/create-authorization-response.ts","../src/jarm/jarm-extract-jwks.ts","../src/authorization-response/fetch-authorization-response.ts","../src/authorization-response/z-authorization-response.ts","../src/vp-token/z-vp-token.ts","../src/authorization-response/parse-authorization-response.ts","../src/jarm/parse-jarm-authorization-response.ts","../src/vp-token/parse-vp-token.ts","../src/authorization-response/validate-authorization-response.ts","../src/jarm/verify-jarm-authorization-response.ts","../src/jarm/z-jarm.ts"],"sourcesContent":["export * from \"./authorization-request/create-authorization-request\";\nexport * from \"./authorization-request/fetch-authorization-request\";\nexport * from \"./authorization-request/parse-authorization-request\";\nexport * from \"./authorization-request/validate-authorization-request\";\nexport * from \"./authorization-request/z-authorization-request\";\nexport * from \"./authorization-request/z-authorization-request-url\";\nexport * from \"./authorization-response/create-authorization-response\";\nexport * from \"./authorization-response/fetch-authorization-response\";\nexport * from \"./authorization-response/parse-authorization-response\";\nexport * from \"./authorization-response/validate-authorization-response\";\nexport * from \"./authorization-response/z-authorization-response\";\nexport * from \"./errors\";\nexport * from \"./jarm/jarm-extract-jwks\";\nexport * from \"./jarm/parse-jarm-authorization-response\";\nexport * from \"./jarm/verify-jarm-authorization-response\";\nexport * from \"./jarm/z-jarm\";\nexport * from \"./vp-token/parse-vp-token\";\nexport * from \"./vp-token/z-vp-token\";\n\nexport {\n type CreateOpenid4vpAuthorizationResponseOptions,\n type CreateOpenid4vpAuthorizationResponseResult,\n type VpToken,\n createOpenid4vpAuthorizationResponse,\n} from \"@openid4vc/openid4vp\";\n","import {\n type CallbackContext,\n type CreateJarRequestOptions,\n CreateJarRequestResult,\n JarAuthorizationRequest,\n JwtSignerFederation,\n JwtSignerX5c,\n createJarRequest,\n jwtHeaderFromJwtSigner,\n signedAuthorizationRequestJwtHeaderTyp,\n} from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n ValidationError,\n hasConfigVersion,\n objectToQueryParams,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vpError } from \"../errors\";\nimport {\n Openid4vpAuthorizationRequestPayload,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n zOpenid4vpAuthorizationRequestPayload,\n} from \"./z-authorization-request\";\n\ntype BaseJarOptions<TSigner extends JwtSignerFederation | JwtSignerX5c> = {\n jwtSigner: TSigner;\n} & Pick<\n CreateJarRequestOptions,\n \"additionalJwtPayload\" | \"expiresInSeconds\" | \"now\" | \"requestUri\"\n>;\n\nexport type JarOptionsV1_0 = BaseJarOptions<JwtSignerFederation>;\n\nexport type JarOptionsV1_3 = BaseJarOptions<JwtSignerX5c>;\n\ntype JarOptions = JarOptionsV1_0 | JarOptionsV1_3;\n\ninterface BaseCreateAuthorizationRequestOptions<\n V extends ItWalletSpecsVersion,\n TJar extends JarOptions,\n> {\n /**\n * Authorization request payload to be validated and serialized.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n\n /**\n * Required callbacks used to create a signed/encrypted Request Object.\n */\n callbacks: Partial<Pick<CallbackContext, \"encryptJwe\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n config: IoWalletSdkConfig<V>;\n\n /**\n * The request is generated as a JAR authorization request.\n * When `additionalJwtPayload.aud` is missing, it is set to `requestUri`.\n */\n jar: TJar;\n\n /**\n * Authorization request URL scheme.\n * @default \"openid4vp://\"\n */\n scheme?: string;\n}\n\n/**\n * Options for creating an OpenID4VP authorization request URL.\n */\nexport type CreateAuthorizationRequestOptionsV1_0 =\n BaseCreateAuthorizationRequestOptions<\n ItWalletSpecsVersion.V1_0,\n JarOptionsV1_0\n >;\n\nexport type CreateAuthorizationRequestOptionsV1_3 =\n BaseCreateAuthorizationRequestOptions<\n ItWalletSpecsVersion.V1_3,\n JarOptionsV1_3\n >;\n\nexport type CreateAuthorizationRequestOptions =\n | CreateAuthorizationRequestOptionsV1_0\n | CreateAuthorizationRequestOptionsV1_3;\n\ninterface BaseCreateAuthorizationRequestResult<TJar extends JarOptions> {\n authorizationRequest: string;\n authorizationRequestObject: JarAuthorizationRequest;\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n jar: CreateJarRequestResult & TJar;\n}\n\nexport type CreateAuthorizationRequestResultV1_0 =\n BaseCreateAuthorizationRequestResult<JarOptionsV1_0>;\n\nexport type CreateAuthorizationRequestResultV1_3 =\n BaseCreateAuthorizationRequestResult<JarOptionsV1_3>;\n\nexport type CreateAuthorizationRequestResult =\n | CreateAuthorizationRequestResultV1_0\n | CreateAuthorizationRequestResultV1_3;\n\n/**\n * Creates an OpenID4VP authorization request URL.\n *\n * This function creates a JAR request object through\n * `createJarRequest` and serializes it into the URL query parameters.\n *\n * @param options {@link CreateAuthorizationRequestOptions}\n * @returns Authorization request URL plus request object details used to build it\n * @throws When authorization request payload validation fails\n * @throws When JAR creation fails\n */\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptionsV1_0,\n): Promise<CreateAuthorizationRequestResultV1_0>;\n\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptionsV1_3,\n): Promise<CreateAuthorizationRequestResultV1_3>;\n\nexport async function createAuthorizationRequest(\n options: CreateAuthorizationRequestOptions,\n): Promise<CreateAuthorizationRequestResult> {\n try {\n const { config } = options;\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_0)) {\n return await createAuthorizationRequestWithHeader(\n options,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n );\n }\n\n if (hasConfigVersion(options, ItWalletSpecsVersion.V1_3)) {\n return await createAuthorizationRequestWithHeader(\n options,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n );\n }\n\n throw new ItWalletSpecsVersionError(\n \"createAuthorizationRequest\",\n config.itWalletSpecsVersion,\n [ItWalletSpecsVersion.V1_0, ItWalletSpecsVersion.V1_3],\n );\n } catch (error) {\n if (error instanceof ValidationError) {\n throw new Oid4vpError(`Invalid authorization request: ${error.message}`);\n }\n throw error;\n }\n}\n\nasync function createAuthorizationRequestWithHeader<TJar extends JarOptions>(\n options: BaseCreateAuthorizationRequestOptions<ItWalletSpecsVersion, TJar>,\n headerSchema:\n | typeof zOpenid4vpAuthorizationRequestHeaderV1_0\n | typeof zOpenid4vpAuthorizationRequestHeaderV1_3,\n): Promise<BaseCreateAuthorizationRequestResult<TJar>> {\n const { callbacks, jar, scheme = \"openid4vp://\" } = options;\n\n const authorizationRequestHeader = parseWithErrorHandling(headerSchema, {\n ...jwtHeaderFromJwtSigner(jar.jwtSigner),\n typ: signedAuthorizationRequestJwtHeaderTyp,\n });\n\n const authorizationRequestPayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationRequestPayload,\n options.authorizationRequestPayload,\n );\n\n const additionalJwtPayload = !jar.additionalJwtPayload?.aud\n ? { ...jar.additionalJwtPayload, aud: jar.requestUri }\n : jar.additionalJwtPayload;\n\n const jarResult = await createJarRequest({\n ...jar,\n additionalJwtPayload,\n authorizationRequestHeader,\n authorizationRequestPayload,\n callbacks,\n });\n\n return {\n authorizationRequest: createAuthorizationRequestUrl(\n scheme,\n jarResult.jarAuthorizationRequest,\n ),\n authorizationRequestObject: jarResult.jarAuthorizationRequest,\n authorizationRequestPayload,\n jar: { ...jar, ...jarResult },\n };\n}\n\nfunction createAuthorizationRequestUrl(\n scheme: string,\n request: JarAuthorizationRequest,\n) {\n const url = new URL(scheme);\n\n const searchParams = new URLSearchParams([\n ...url.searchParams.entries(),\n ...objectToQueryParams(request).entries(),\n ]);\n\n url.search = searchParams.toString();\n\n return url.toString();\n}\n","/**\n * Generic error thrown during Oid4vp operations\n */\nexport class Oid4vpError extends Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"Oid4vpError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown by {@link parseAuthorizeRequest} when the passed\n * request object has an invalid signature or unexpected errors\n * are thrown\n */\nexport class ParseAuthorizeRequestError extends Oid4vpError {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"ParseAuthorizeRequestError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown by {@link fetchAuthorizationResponse}\n */\nexport class FetchAuthorizationResponseError extends Oid4vpError {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"FetchAuthorizationResponseError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown by {@link createAuthorizationResponse} in case there\n * are unexpected errors.\n */\nexport class CreateAuthorizationResponseError extends Oid4vpError {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"CreateAuthorizationResponseError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown when request_uri_method parameter has an invalid value.\n * Valid values are \"get\" or \"post\" (case-insensitive).\n */\nexport class InvalidRequestUriMethodError extends Oid4vpError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"InvalidRequestUriMethodError\";\n }\n}\n","import {\n zAlgValueNotNone,\n zCertificateChain,\n zJwtPayload,\n zSignedAuthorizationRequestJwtHeaderTyp,\n zTrustChain,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { itWalletCredentialVerifierMetadataV1_3 } from \"@pagopa/io-wallet-oid-federation\";\nimport { z } from \"zod\";\n\n/**\n * Zod parser that describes a JWT payload\n * containing an OID4VP Request Object\n */\nexport const zOpenid4vpAuthorizationRequestPayload = z\n .looseObject({\n client_id: z.string(),\n client_metadata: itWalletCredentialVerifierMetadataV1_3.optional(),\n dcql_query: z.record(z.string(), z.any()),\n nonce: z.string(),\n request_uri: z.url().optional(),\n request_uri_method: z.optional(z.string()),\n response_mode: z.literal(\"direct_post.jwt\"),\n response_type: z.literal(\"vp_token\"),\n response_uri: z.url(),\n scope: z.string().optional(),\n state: z.string(),\n transaction_data: z.array(z.string()).nonempty().optional(),\n transaction_data_hashes_alg: z.array(z.string()).optional(),\n wallet_nonce: z.string().optional(),\n })\n .and(\n z.object({\n ...zJwtPayload.shape,\n iss: z.string(),\n }),\n );\n\nexport type Openid4vpAuthorizationRequestPayload = z.infer<\n typeof zOpenid4vpAuthorizationRequestPayload\n>;\n\nconst zOpenid4vpAuthorizationRequestHeaderBase = z.object({\n alg: zAlgValueNotNone,\n kid: z.string(),\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n});\n\nexport const zOpenid4vpAuthorizationRequestHeaderV1_0 =\n zOpenid4vpAuthorizationRequestHeaderBase\n .extend({\n trust_chain: zTrustChain,\n })\n .loose();\n\nexport type Openid4vpAuthorizationRequestHeaderV1_0 = z.infer<\n typeof zOpenid4vpAuthorizationRequestHeaderV1_0\n>;\n\nexport const zOpenid4vpAuthorizationRequestHeaderV1_3 =\n zOpenid4vpAuthorizationRequestHeaderBase\n .extend({\n trust_chain: zTrustChain.optional(),\n x5c: zCertificateChain,\n })\n .loose();\n\nexport type Openid4vpAuthorizationRequestHeaderV1_3 = z.infer<\n typeof zOpenid4vpAuthorizationRequestHeaderV1_3\n>;\n\nexport type Openid4vpAuthorizationRequestHeader =\n | Openid4vpAuthorizationRequestHeaderV1_0\n | Openid4vpAuthorizationRequestHeaderV1_3;\n","import { type CallbackContext, Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oid4vpError } from \"../errors\";\nimport { validateAuthorizationRequestParams } from \"./validate-authorization-request\";\nimport { zAuthorizationRequestUrlParams } from \"./z-authorization-request-url\";\n\nexport interface FetchAuthorizationRequestOptions {\n /**\n * The authorization URL from the QR code\n * Should contain `client_id` and either `request` or `request_uri` query parameters\n */\n authorizeRequestUrl: string;\n\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementation\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * Optional wallet metadata to send when request_uri_method=post.\n * If not provided and POST is required, sends an empty body (basic implementation).\n *\n * Specification: IT-Wallet v1.3.3 recommends (SHOULD) sending wallet capabilities\n * in application/x-www-form-urlencoded format when using POST.\n */\n walletMetadata?: {\n authorization_endpoint?: string;\n client_id_prefixes_supported?: string[];\n request_object_signing_alg_values_supported?: string[];\n response_modes_supported?: string[];\n response_types_supported?: string[];\n vp_formats_supported?: Record<string, unknown>;\n };\n\n /**\n * Optional wallet nonce for replay attack prevention (RECOMMENDED per spec)\n */\n walletNonce?: string;\n}\n\nexport interface ParsedQrCode {\n /**\n * The `client_id` from the authorization URL\n */\n clientId: string;\n /**\n * The `request_uri` from the authorization URL\n */\n requestUri?: string;\n /**\n * The `request_uri_method` from the authorization URL (get or post)\n */\n requestUriMethod?: \"get\" | \"post\";\n}\n\nexport interface FetchAuthorizationRequestResult {\n /**\n * The parsed QR code data\n * Includes `clientId`, `requestUri` and `requestUriMethod`\n */\n parsedQrCode: ParsedQrCode;\n\n /**\n * The original Request Object JWT, either fetched from `request_uri` or extracted from `request` parameter.\n */\n requestObjectJwt: string;\n\n /**\n * Transmission mode indicator\n * - \"value\": Request Object JWT passed inline via `request` parameter\n * - \"reference\": Request Object JWT fetched from `request_uri`\n */\n sendBy: \"reference\" | \"value\";\n}\n\n/**\n * Helper function to fetch Request Object JWT from request_uri.\n * Supports GET and POST methods, with optional wallet metadata for POST.\n *\n * @param requestUri - URI to fetch Request Object from\n * @param options - Fetch options including method and wallet metadata\n * @returns The Request Object JWT as a string\n * @throws {UnexpectedStatusCodeError} If the server returns a non-200 status code\n * @throws {Error} If the underlying fetch/createFetcher call fails (for example, due to network errors)\n */\nexport async function fetchRequestObjectJwt(\n requestUri: string,\n options: {\n fetch: CallbackContext[\"fetch\"];\n method: \"get\" | \"post\";\n walletMetadata?: FetchAuthorizationRequestOptions[\"walletMetadata\"];\n walletNonce?: string;\n },\n): Promise<string> {\n const fetch = createFetcher(options.fetch);\n\n // Prepare request configuration\n const requestInit: RequestInit = {\n method: options.method.toUpperCase(),\n };\n\n // Add body for POST requests per IT-Wallet spec (SHOULD include metadata)\n if (options.method === \"post\") {\n const formData = new URLSearchParams();\n\n // Add wallet_metadata if provided (spec: OPTIONAL)\n if (options.walletMetadata) {\n formData.append(\n \"wallet_metadata\",\n JSON.stringify(options.walletMetadata),\n );\n }\n\n // Add wallet_nonce if provided (spec: RECOMMENDED)\n if (options.walletNonce) {\n formData.append(\"wallet_nonce\", options.walletNonce);\n }\n\n requestInit.headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n };\n requestInit.body = formData.toString();\n }\n\n const response = await fetch(requestUri, requestInit);\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(response);\n\n return await response.text();\n}\n\n/**\n * Fetches an OpenID4VP authorization request JWT from a QR code URL.\n *\n * Supports two transmission modes:\n * - **By Value**: Request Object JWT passed inline via `request` parameter\n * - **By Reference**: Request Object JWT fetched from `request_uri`\n *\n * The function:\n * 1. Parses the authorization URL to extract parameters\n * 2. Validates that exactly one of `request` or `request_uri` is present\n * 3. Either uses inline JWT or fetches from URI (GET/POST based on request_uri_method)\n * 4. Returns the Request Object JWT along with transmission mode metadata\n *\n * Note: This function does NOT parse or verify the JWT. Use {@link parseAuthorizeRequest}\n * separately to decode and optionally verify the signature.\n *\n * @param options {@link FetchAuthorizationRequestOptions}\n * @returns Promise that resolves to {@link FetchAuthorizationRequestResult}\n * @throws {Oid4vpError} When required query parameters are missing, the URL is invalid, or an unexpected error occurs during fetch or parsing\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code during fetch\n * @throws {ValidationError} When URL parameters fail schema validation\n *\n * @example By Value mode\n * ```typescript\n * const url = \"https://wallet.example.org/authorize?\" +\n * \"client_id=openid_federation%23https%3A%2F%2Frp.example.org\" +\n * \"&request=eyJhbGciOiJFUzI1NiIs...\";\n *\n * const result = await fetchAuthorizationRequest({\n * authorizeRequestUrl: url,\n * callbacks: { fetch },\n * });\n * // result.sendBy === \"value\"\n * // result.requestObjectJwt === \"eyJhbGciOiJFUzI1NiIs...\"\n * ```\n *\n * @example By Reference mode with POST\n * ```typescript\n * const url = \"https://wallet.example.org/authorize?\" +\n * \"client_id=openid_federation%23https%3A%2F%2Frp.example.org\" +\n * \"&request_uri=https%3A%2F%2Frp.example.org%2Frequest\" +\n * \"&request_uri_method=post\";\n *\n * const result = await fetchAuthorizationRequest({\n * authorizeRequestUrl: url,\n * callbacks: { fetch },\n * walletMetadata: {\n * authorization_endpoint: \"https://wallet.example.org/authorize\",\n * response_types_supported: [\"vp_token\"],\n * },\n * walletNonce: \"random-nonce\",\n * });\n * // result.sendBy === \"reference\"\n * // result.requestObjectJwt === fetched JWT from request_uri\n * ```\n */\nexport async function fetchAuthorizationRequest(\n options: FetchAuthorizationRequestOptions,\n): Promise<FetchAuthorizationRequestResult> {\n try {\n const url = new URL(options.authorizeRequestUrl);\n\n // Extract and validate URL parameters using Zod schema\n const rawParams = {\n client_id: url.searchParams.get(\"client_id\") ?? undefined,\n request: url.searchParams.get(\"request\") ?? undefined,\n request_uri: url.searchParams.get(\"request_uri\") ?? undefined,\n request_uri_method:\n url.searchParams.get(\"request_uri_method\") ?? undefined,\n state: url.searchParams.get(\"state\") ?? undefined,\n };\n\n // Parse and validate URL parameters with Zod schema\n const parsedParams = zAuthorizationRequestUrlParams.parse(rawParams);\n\n // Validate business logic (mutual exclusivity, etc.)\n const validatedParams = validateAuthorizationRequestParams(parsedParams);\n\n // Determine transmission mode\n const sendBy = validatedParams.request ? \"value\" : \"reference\";\n\n // Get JWT: either inline or fetch from URI\n let requestObjectJwt: string;\n if (validatedParams.request) {\n requestObjectJwt = validatedParams.request;\n } else {\n // Type system guarantees request_uri is defined here due to validation\n requestObjectJwt = await fetchRequestObjectJwt(\n validatedParams.request_uri as string,\n {\n fetch: options.callbacks.fetch,\n method: validatedParams.request_uri_method ?? \"get\",\n walletMetadata: options.walletMetadata,\n walletNonce: options.walletNonce,\n },\n );\n }\n\n return {\n parsedQrCode: {\n clientId: validatedParams.client_id,\n requestUri: validatedParams.request_uri,\n requestUriMethod:\n sendBy === \"reference\"\n ? (validatedParams.request_uri_method ?? \"get\")\n : undefined,\n },\n requestObjectJwt,\n sendBy,\n };\n } catch (error) {\n if (\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError ||\n error instanceof Oid4vpError ||\n error instanceof UnexpectedStatusCodeError\n ) {\n throw error;\n }\n\n throw new Oid4vpError(\n `Unexpected error during fetch authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { InvalidRequestUriMethodError, Oid4vpError } from \"../errors\";\nimport { AuthorizationRequestUrlParams } from \"./z-authorization-request-url\";\n\n/**\n * Validates authorization request URL parameters according to IT-Wallet and OpenID4VP specifications.\n *\n * Validation rules:\n * 1. Exactly one of `request` or `request_uri` must be present (mutual exclusivity)\n * 2. `request_uri_method` must be \"get\" or \"post\" (case-insensitive) if present\n * 3. `request_uri_method` can only be used with `request_uri` parameter\n *\n * @param params - Parsed authorization request URL parameters\n * @returns Type-narrowed params ensuring mutual exclusivity\n * @throws {Oid4vpError} When both or neither request/request_uri are present\n * @throws {InvalidRequestUriMethodError} When request_uri_method is not \"get\" or \"post\"\n * @throws {Oid4vpError} When request_uri_method is used without request_uri\n */\nexport function validateAuthorizationRequestParams(\n params: AuthorizationRequestUrlParams,\n) {\n // Mutual exclusivity check\n if (params.request && params.request_uri) {\n throw new Oid4vpError(\n \"request and request_uri cannot both be present in an authorization request\",\n );\n }\n\n // At least one must be present\n if (!params.request && !params.request_uri) {\n throw new Oid4vpError(\n \"Either request or request_uri parameter must be present\",\n );\n }\n\n // Validate request_uri_method if present\n if (params.request_uri_method) {\n const normalizedMethod = params.request_uri_method.toLowerCase();\n if (normalizedMethod !== \"get\" && normalizedMethod !== \"post\") {\n throw new InvalidRequestUriMethodError(\n `Invalid request_uri_method: '${params.request_uri_method}'. Must be 'get' or 'post'`,\n );\n }\n }\n\n // request_uri_method only allowed with request_uri\n if (params.request_uri_method && !params.request_uri) {\n throw new Oid4vpError(\n \"request_uri_method can only be used with request_uri parameter\",\n );\n }\n\n // Normalize request_uri_method to lowercase if present\n const normalizedMethod = params.request_uri_method\n ? (params.request_uri_method.toLowerCase() as \"get\" | \"post\")\n : undefined;\n\n return {\n ...params,\n request_uri_method: normalizedMethod,\n } as (\n | {\n request?: never;\n request_uri: string;\n request_uri_method?: \"get\" | \"post\";\n }\n | { request: string; request_uri?: never; request_uri_method?: never }\n ) &\n typeof params;\n}\n","import z from \"zod\";\n\n/**\n * Schema for authorization request URL query parameters.\n * Note: `request` contains the signed Request Object JWT, it is NOT a claim inside the Request Object.\n */\nexport const zAuthorizationRequestUrlParams = z.looseObject({\n client_id: z.string(),\n request: z.string().optional(), // JWT containing Request Object (by value)\n request_uri: z.url().optional(), // URI to fetch Request Object (by reference)\n request_uri_method: z.string().optional(), // HTTP method for request_uri (validated in business logic)\n state: z.string().optional(), // Optional state parameter\n});\n\nexport type AuthorizationRequestUrlParams = z.infer<\n typeof zAuthorizationRequestUrlParams\n>;\n","import {\n CallbackContext,\n JwtSigner,\n Oauth2JwtParseError,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport { decodeJwt } from \"@pagopa/io-wallet-oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n ValidationError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { ParseAuthorizeRequestError } from \"../errors\";\nimport {\n Openid4vpAuthorizationRequestHeader,\n Openid4vpAuthorizationRequestPayload,\n zOpenid4vpAuthorizationRequestHeaderV1_0,\n zOpenid4vpAuthorizationRequestHeaderV1_3,\n zOpenid4vpAuthorizationRequestPayload,\n} from \"./z-authorization-request\";\n\n/**\n * Enum representing the client_id prefix types according to IT Wallet specifications\n */\nexport enum ClientIdPrefix {\n NONE = \"none\",\n OPENID_FEDERATION = \"openid_federation\",\n X509_HASH = \"x509_hash\",\n}\n\n/**\n * Extracts the prefix from a client_id string\n * @param clientId - The client_id from the request object\n * @returns The prefix type (x509_hash, openid_federation, or none)\n */\nexport function extractClientIdPrefix(clientId: string): ClientIdPrefix {\n if (clientId.startsWith(\"x509_hash:\")) {\n return ClientIdPrefix.X509_HASH;\n }\n if (clientId.startsWith(\"openid_federation:\")) {\n return ClientIdPrefix.OPENID_FEDERATION;\n }\n return ClientIdPrefix.NONE;\n}\n\n/**\n * Retrieves the public key for verifying the Request Object JWT signature\n * according to IT Wallet specifications.\n *\n * Priority order:\n * 1. If client_id has x509_hash prefix: use x5c certificate chain from header\n * 2. If client_id has openid_federation prefix or no prefix: return a federation signer; if trust_chain\n * is present it is forwarded, otherwise the verifyJwt callback is responsible for reconstructing\n * the chain from client_id\n *\n * @param options - Parse options containing decoded JWT\n * @returns The JWK to use for signature verification\n * @throws {ParseAuthorizeRequestError} When no valid public key can be found\n */\nfunction getPublicKeyForVerification(options: {\n header: Openid4vpAuthorizationRequestHeader;\n payload: Openid4vpAuthorizationRequestPayload;\n}): JwtSigner {\n const { header, payload } = options;\n\n const clientIdPrefix = extractClientIdPrefix(payload.client_id);\n\n // Priority 1: x509_hash prefix - use x5c certificate chain from header\n if (clientIdPrefix === ClientIdPrefix.X509_HASH) {\n if (!Array.isArray(header.x5c) || header.x5c.length === 0) {\n throw new ParseAuthorizeRequestError(\n \"x5c is required in JWT header for x509_hash client_id\",\n );\n }\n\n return {\n alg: header.alg,\n kid: header.kid,\n method: \"x5c\" as const,\n x5c: header.x5c,\n };\n }\n\n // Priority 2: openid_federation prefix or no prefix - use trust_chain if present,\n // otherwise delegate chain reconstruction to the verifyJwt callback\n if (\n clientIdPrefix === ClientIdPrefix.OPENID_FEDERATION ||\n clientIdPrefix === ClientIdPrefix.NONE\n ) {\n if (!header.kid) {\n throw new ParseAuthorizeRequestError(\n \"kid is required in JWT header for openid_federation client_id or no prefix\",\n );\n }\n\n return {\n alg: header.alg,\n kid: header.kid,\n method: \"federation\" as const,\n ...(header.trust_chain && { trustChain: header.trust_chain }),\n };\n }\n\n throw new ParseAuthorizeRequestError(\n \"Unable to determine public key for Request Object verification\",\n );\n}\n\nexport interface ParseAuthorizeRequestOptions {\n /**\n * Optional callback context for JWT signature verification.\n * If not provided, signature verification is skipped.\n */\n callbacks?: Pick<CallbackContext, \"verifyJwt\">;\n\n config: IoWalletSdkConfig;\n\n /**\n * The Authorization Request Object JWT.\n */\n requestObjectJwt: string;\n}\n\nexport interface ParsedAuthorizeRequestResult {\n /**\n * The JWT header of the authorization request object.\n */\n header: Openid4vpAuthorizationRequestHeader;\n /**\n * The parsed authorization request object.\n */\n payload: Openid4vpAuthorizationRequestPayload;\n}\n\n/**\n * Parses and optionally verifies a JWT containing an OpenID4VP Request Object.\n *\n * This method decodes the Request Object JWT and validates its structure. If the `verifyJwt`\n * callback is provided, it also verifies the JWT signature using the public key obtained\n * according to IT Wallet specifications:\n * 1. If client_id has x509_hash prefix: use x5c certificate chain from header\n * 2. If client_id has openid_federation prefix or no prefix: pass a federation signer to the callback;\n * trust_chain is forwarded when present, otherwise the callback must reconstruct the chain from client_id\n *\n * @param options {@link ParseAuthorizeRequestOptions}\n * @returns A {@link ParsedAuthorizeRequestResult} containing the RP required credentials payload and the {@link Openid4vpAuthorizationRequestHeader} JWT header\n * @throws {@link ValidationError} in case there are errors validating the Request Object structure\n * @throws {@link Oauth2JwtParseError} in case the request object jwt is malformed (e.g missing header, bad encoding)\n * @throws {@link ParseAuthorizeRequestError} in case the JWT signature is invalid (when verifyJwt is provided) or there are unexpected errors\n *\n * @security If `verifyJwt` callback is not provided in options, JWT signature verification is skipped.\n */\nexport async function parseAuthorizeRequest(\n options: ParseAuthorizeRequestOptions,\n): Promise<ParsedAuthorizeRequestResult> {\n try {\n const headerSchema = options.config.isVersion(ItWalletSpecsVersion.V1_0)\n ? zOpenid4vpAuthorizationRequestHeaderV1_0\n : zOpenid4vpAuthorizationRequestHeaderV1_3;\n\n const decoded = decodeJwt({\n errorMessagePrefix: \"Error decoding authorization request JWT:\",\n headerSchema,\n jwt: options.requestObjectJwt,\n payloadSchema: zOpenid4vpAuthorizationRequestPayload,\n });\n\n if (options.callbacks?.verifyJwt) {\n const signer = getPublicKeyForVerification({\n header: decoded.header,\n payload: decoded.payload,\n });\n\n await verifyJwt({\n compact: options.requestObjectJwt,\n errorMessage: \"Error verifying Request Object signature\",\n header: decoded.header,\n payload: decoded.payload,\n signer,\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n }\n\n return {\n header: decoded.header,\n payload: decoded.payload,\n };\n } catch (error) {\n if (\n error instanceof ValidationError ||\n error instanceof Oauth2JwtParseError\n )\n throw error;\n throw new ParseAuthorizeRequestError(\n `Unexpected error during Request Object parsing: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type {\n ItWalletCredentialVerifierMetadata,\n ItWalletCredentialVerifierMetadataV1_3,\n} from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext, JweEncryptor } from \"@pagopa/io-wallet-oauth2\";\nimport { Jwk } from \"@pagopa/io-wallet-oauth2\";\nimport { encodeToBase64Url } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientIdPrefix,\n extractClientIdPrefix,\n} from \"../authorization-request/parse-authorization-request\";\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request/z-authorization-request\";\nimport { CreateAuthorizationResponseError } from \"../errors\";\nimport { extractEncryptionJwkFromJwks } from \"../jarm/jarm-extract-jwks\";\nimport { VpToken } from \"../vp-token/z-vp-token\";\nimport { Openid4vpAuthorizationResponse } from \"./z-authorization-response\";\n\nexport interface CreateAuthorizationResponseOptions {\n /**\n * JARM encryption algorithm (JWE alg), should be one of the values supported by the verifier's metadata.\n * falls back to \"ECDH-ES\" if not provided.\n */\n authorization_encrypted_response_alg?: string;\n\n /**\n * JARM encryption encoding (JWE enc), should be one of the values supported by the verifier's metadata.\n * falls back to \"A256GCM\" if not provided.\n */\n authorization_encrypted_response_enc?: string;\n\n /**\n * Callbacks for authorization response generation\n */\n callbacks: Pick<CallbackContext, \"encryptJwe\" | \"generateRandom\">;\n\n /**\n * Presentation's Request Object\n */\n requestObject: Pick<\n Openid4vpAuthorizationRequestPayload,\n \"client_id\" | \"client_metadata\" | \"nonce\" | \"state\"\n >;\n\n /**\n * Relying Party metadata JWKS\n */\n rpJwks: {\n encrypted_response_enc_values_supported?: string[];\n } & Pick<\n ItWalletCredentialVerifierMetadata | ItWalletCredentialVerifierMetadataV1_3,\n \"jwks\"\n >;\n\n /**\n * Array containing the vp_tokens of the credentials\n * to present\n */\n vp_token: VpToken;\n}\n\n/**\n * Result of createAuthorizationResponse function\n * Contains the generated JARM payload and the encrypted response to send to the verifier\n */\nexport interface CreateAuthorizationResponseResult {\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n jarm: {\n encryptionJwk: Jwk;\n responseJwe: string;\n };\n}\n\n/**\n * Creates an encrypted JARM authorization response for OpenID4VP presentation.\n *\n * This function generates a JARM (JWT Secured Authorization Response Mode) response\n * containing the VP tokens from the wallet to the verifier.\n *\n * **Version Compatibility:**\n * - v1.0 metadata: JARM algorithms are read from rpJwks if not explicitly provided\n * - v1.3 metadata: JARM algorithms may be provided explicitly; when omitted, values are\n * resolved from rpJwks or fall back to implementation defaults (e.g. ECDH-ES / A256GCM)\n *\n * @param options - Configuration for creating the authorization response\n * @param options.authorization_encrypted_response_alg - Optional JARM encryption algorithm (JWE alg). If omitted, falls back to \"ECDH-ES\".\n * @param options.authorization_encrypted_response_enc - Optional JARM encryption encoding (JWE enc). If omitted, the first value from metadata's encrypted_response_enc_values_supported is used, or falls back to \"A256GCM\".\n * @param options.callbacks - Cryptographic callbacks for JWE encryption\n * @param options.requestObject - The authorization request object to respond to\n * @param options.rpJwks - Relying Party JWKS with optional enc values (v1.0 or v1.3)\n * @param options.vp_token - Array of VP tokens to include in the response\n *\n * @returns An encrypted JARM authorization response (JWE compact serialization)\n *\n * @throws {CreateAuthorizationResponseError} If response generation or encryption fails\n */\nexport async function createAuthorizationResponse(\n options: CreateAuthorizationResponseOptions,\n): Promise<CreateAuthorizationResponseResult> {\n try {\n const encryptionAlg: string =\n options.authorization_encrypted_response_alg ?? \"ECDH-ES\";\n\n const encryptionEnc: string =\n options.authorization_encrypted_response_enc ?? \"A256GCM\";\n\n // Determine which metadata to use based on client_id prefix\n const { requestObject } = options;\n const clientMetadata = requestObject.client_metadata;\n const clientIdPrefix = extractClientIdPrefix(requestObject.client_id);\n\n if (clientIdPrefix === ClientIdPrefix.X509_HASH && !clientMetadata) {\n throw new CreateAuthorizationResponseError(\n \"clientMetadata is required when client_id uses x509_hash prefix\",\n );\n }\n\n // When using OpenID Federation, client_metadata may be present in the request\n // but per the Italian specification most of its content should be ignored —\n // use rpJwks for encryption parameters instead.\n const effectiveClientMetadata =\n clientIdPrefix === ClientIdPrefix.OPENID_FEDERATION\n ? undefined\n : clientMetadata;\n\n const authorizationResponsePayload: Openid4vpAuthorizationResponse = {\n state: requestObject.state,\n vp_token: options.vp_token,\n };\n\n // Extract encryption JWK from effective metadata\n const encryptionJwks = effectiveClientMetadata\n ? effectiveClientMetadata.jwks\n : options.rpJwks.jwks;\n const encryptionJwk = extractEncryptionJwkFromJwks(encryptionJwks, {\n supportedAlgValues: [encryptionAlg],\n });\n if (!encryptionJwk) {\n throw new CreateAuthorizationResponseError(\n \"No encryption JWK found in metadata\",\n );\n }\n\n const encValuesSupported =\n effectiveClientMetadata?.encrypted_response_enc_values_supported ??\n options.rpJwks.encrypted_response_enc_values_supported;\n\n let enc: string;\n if (encValuesSupported) {\n if (options.authorization_encrypted_response_enc !== undefined) {\n // Explicit value provided: use it if supported, otherwise take the first supported value\n enc =\n encValuesSupported.find(\n (e) => e === options.authorization_encrypted_response_enc,\n ) ??\n encValuesSupported[0] ??\n options.authorization_encrypted_response_enc;\n } else {\n // No explicit value: take the first (most preferred) value from the metadata\n enc = encValuesSupported[0] ?? encryptionEnc;\n }\n } else {\n enc = encryptionEnc;\n }\n\n const alg = encryptionJwk.alg ?? encryptionAlg;\n\n const nonceBytes = await options.callbacks.generateRandom(32);\n\n const jweEncryptor: JweEncryptor = {\n alg,\n apu: encodeToBase64Url(nonceBytes),\n apv: encodeToBase64Url(requestObject.nonce),\n enc,\n method: \"jwk\",\n publicJwk: encryptionJwk,\n };\n\n const plaintext = JSON.stringify(authorizationResponsePayload);\n\n const { encryptionJwk: usedJwk, jwe } = await options.callbacks.encryptJwe(\n jweEncryptor,\n plaintext,\n );\n\n return {\n authorizationResponsePayload,\n jarm: {\n encryptionJwk: usedJwk,\n responseJwe: jwe,\n },\n };\n } catch (error) {\n if (error instanceof CreateAuthorizationResponseError) {\n throw error;\n }\n throw new CreateAuthorizationResponseError(\n `Unexpected error during authorization response creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import type { JwkSet } from \"@pagopa/io-wallet-oauth2\";\n\nexport function extractEncryptionJwkFromJwks(\n jwks: JwkSet,\n {\n kid,\n supportedAlgValues,\n }: {\n kid?: string;\n supportedAlgValues?: string[];\n },\n) {\n if (kid) {\n return jwks.keys.find((jwk) => jwk.kid === kid);\n }\n\n let algFiltered = jwks.keys.filter(\n (key) => key.alg && supportedAlgValues?.includes(key.alg),\n );\n if (algFiltered.length === 0) algFiltered = jwks.keys;\n\n let encFiltered = algFiltered.filter((key) => key.use === \"enc\");\n if (encFiltered.length === 0) {\n encFiltered = algFiltered.filter((key) => key.use !== \"sig\");\n }\n\n return encFiltered.length > 0 ? encFiltered[0] : jwks.keys[0];\n}\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 { FetchAuthorizationResponseError } from \"../errors\";\nimport {\n Openid4vpAuthorizationResponseResult,\n zOpenid4vpAuthorizationResponseResult,\n} from \"./z-authorization-response\";\n\n/**\n * Configuration options for fetching OID4VP Presentation Result\n */\nexport interface FetchAuthorizationResponseOptions {\n /**\n * The signed and encrypted {@link Openid4vpAuthorizationResponse} in base64 format\n */\n authorizationResponseJarm: string;\n\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The response_uri field contained in the {@link Openid4vpAuthorizationRequestPayload}\n */\n presentationResponseUri: string;\n}\n\n/**\n * Sends the {@link Openid4vpAuthorizationResponse} to the response uri provided by the session's\n * {@link Openid4vpAuthorizationRequestPayload} and returns the {@link Openid4vpAuthorizationResponseResult} object\n * containing the redirect_uri at which to continue the presentation\n *\n * @param options {@link FetchAuthorizationResponseOptions}\n * @returns Promise that resolves to the parsed {@link Openid4vpAuthorizationResponseResult}\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchAuthorizationResponse(\n options: FetchAuthorizationResponseOptions,\n): Promise<Openid4vpAuthorizationResponseResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const authorizationResponseResult = await fetch(\n options.presentationResponseUri,\n {\n body: new URLSearchParams({\n response: options.authorizationResponseJarm,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(\n 200,\n UnexpectedStatusCodeError,\n )(authorizationResponseResult);\n\n const authorizationResponseResultJson =\n await authorizationResponseResult.json();\n\n //Response could be anything, so it's returned as is for further processing\n return parseWithErrorHandling(\n zOpenid4vpAuthorizationResponseResult,\n authorizationResponseResultJson,\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchAuthorizationResponseError(\n `Unexpected error sending authorization response: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\nimport { zVpToken } from \"../vp-token/z-vp-token\";\n\nexport const zOpenid4vpAuthorizationResponse = z.object({\n state: z.string(),\n vp_token: zVpToken,\n});\n\nexport type Openid4vpAuthorizationResponse = z.infer<\n typeof zOpenid4vpAuthorizationResponse\n>;\n\nexport const zOpenid4vpAuthorizationResponseResult = z.object({\n redirect_uri: z.url().optional(),\n});\n\nexport type Openid4vpAuthorizationResponseResult = z.infer<\n typeof zOpenid4vpAuthorizationResponseResult\n>;\n","import { z } from \"zod\";\n\nexport const zVpToken = z.record(\n z.string(),\n z.string().or(z.array(z.string()).nonempty()),\n {\n message:\n \"vp_token must be an object where each key is a string and each value is a non-empty array of strings (v1.3) or a string (v1.0)\",\n },\n);\n\nexport type VpToken = z.infer<typeof zVpToken>;\n","import { CallbackContext } from \"@pagopa/io-wallet-oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request/z-authorization-request\";\nimport { Oid4vpError } from \"../errors\";\nimport { parseJarmAuthorizationResponse } from \"../jarm/parse-jarm-authorization-response\";\nimport { VerifyJarmAuthorizationResponseResult } from \"../jarm/verify-jarm-authorization-response\";\nimport { JarmHeader } from \"../jarm/z-jarm\";\nimport {\n ValidateOpenid4vpAuthorizationResponseResult,\n validateOpenid4vpAuthorizationResponsePayload,\n} from \"./validate-authorization-response\";\nimport {\n Openid4vpAuthorizationResponse,\n zOpenid4vpAuthorizationResponse,\n} from \"./z-authorization-response\";\n\nexport interface ParseAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to validate response parameters.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Authorization response received from the verifier endpoint or redirect URI.\n */\n authorizationResponse: Record<string, unknown>;\n /**\n * Callbacks required when the response is returned in JARM format.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n}\n\n/**\n * Parsed and validated authorization response.\n */\nexport type ParseAuthorizationResponseResult = {\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n expectedNonce: string;\n jarm?: {\n jarmHeader: JarmHeader;\n } & VerifyJarmAuthorizationResponseResult;\n} & ValidateOpenid4vpAuthorizationResponseResult;\n\n/**\n * Parses an OpenID4VP authorization response and validates it against the request.\n *\n * If the response includes a `response` parameter, the JARM flow is used.\n * Otherwise, the plain authorization response payload is parsed and validated.\n *\n * @param options {@link ParseAuthorizationResponseOptions}\n * @returns A parsed and validated authorization response.\n */\nexport async function parseAuthorizationResponse(\n options: ParseAuthorizationResponseOptions,\n): Promise<ParseAuthorizationResponseResult> {\n const { authorizationRequestPayload, authorizationResponse, callbacks } =\n options;\n\n if (authorizationResponse.response) {\n if (typeof authorizationResponse.response !== \"string\") {\n throw new Oid4vpError(\n \"Invalid jarm authorization response: 'response' parameter must be a jwt string.\",\n );\n }\n\n return parseJarmAuthorizationResponse({\n authorizationRequestPayload,\n callbacks,\n jarmResponseJwt: authorizationResponse.response,\n });\n }\n\n const authorizationResponsePayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationResponse,\n authorizationResponse,\n \"Failed to parse openid4vp authorization response.\",\n );\n\n const validatedOpenId4vpResponse =\n validateOpenid4vpAuthorizationResponsePayload({\n authorizationRequestPayload: authorizationRequestPayload,\n authorizationResponsePayload: authorizationResponsePayload,\n });\n\n return {\n ...validatedOpenId4vpResponse,\n authorizationResponsePayload,\n expectedNonce: authorizationRequestPayload.nonce,\n };\n}\n","import {\n type CallbackContext,\n decodeJwtHeader,\n zCompactJwe,\n zCompactJwt,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request/z-authorization-request\";\nimport { ParseAuthorizationResponseResult } from \"../authorization-response/parse-authorization-response\";\nimport { validateOpenid4vpAuthorizationResponsePayload } from \"../authorization-response/validate-authorization-response\";\nimport { zOpenid4vpAuthorizationResponse } from \"../authorization-response/z-authorization-response\";\nimport { verifyJarmAuthorizationResponse } from \"./verify-jarm-authorization-response\";\nimport { zJarmHeader } from \"./z-jarm\";\n\nexport interface ParseJarmAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to validate JARM claims.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Callbacks used to decrypt and verify JARM JWT/JWE responses.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n /**\n * Compact JARM authorization response (`response` parameter value).\n */\n jarmResponseJwt: string;\n /**\n * Current time used for temporal claim validation (`exp`, `nbf`).\n * Defaults to current date-time when omitted.\n */\n now?: Date;\n}\n\n/**\n * Parses and validates a JARM authorization response for OpenID4VP.\n *\n * This function validates compact format, decrypts and/or verifies the JARM token,\n * parses the resulting OpenID4VP authorization response, and validates it against\n * the originating authorization request.\n *\n * @param options {@link ParseJarmAuthorizationResponseOptions}\n * @returns Parsed authorization response enriched with JARM metadata.\n */\nexport async function parseJarmAuthorizationResponse(\n options: ParseJarmAuthorizationResponseOptions,\n): Promise<ParseAuthorizationResponseResult> {\n const { authorizationRequestPayload, callbacks, jarmResponseJwt, now } =\n options;\n\n const jarmAuthorizationResponseJwt = parseWithErrorHandling(\n z.union([zCompactJwt, zCompactJwe]),\n jarmResponseJwt,\n \"Invalid jarm authorization response jwt.\",\n );\n\n const verifiedJarmResponse = await verifyJarmAuthorizationResponse({\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n now,\n });\n\n const { header: jarmHeader } = decodeJwtHeader({\n headerSchema: zJarmHeader,\n jwt: jarmAuthorizationResponseJwt,\n });\n\n const authorizationResponsePayload = parseWithErrorHandling(\n zOpenid4vpAuthorizationResponse,\n verifiedJarmResponse.jarmAuthorizationResponse,\n \"Failed to parse openid4vp authorization response.\",\n );\n\n const validateOpenId4vpResponse =\n validateOpenid4vpAuthorizationResponsePayload({\n authorizationRequestPayload: authorizationRequestPayload,\n authorizationResponsePayload: authorizationResponsePayload,\n });\n\n return {\n ...validateOpenId4vpResponse,\n authorizationResponsePayload,\n expectedNonce: authorizationRequestPayload.nonce,\n jarm: { ...verifiedJarmResponse, jarmHeader },\n };\n}\n","import { parseIfJson, parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { zVpToken } from \"./z-vp-token\";\n\nexport function parseVpToken(vpToken: unknown) {\n return parseWithErrorHandling(\n zVpToken,\n parseIfJson(vpToken),\n \"Could not parse dcql vp_token. Expected an object where the values are encoded presentations\",\n );\n}\n","import { Openid4vpAuthorizationRequestPayload } from \"../authorization-request/z-authorization-request\";\nimport { Oid4vpError } from \"../errors\";\nimport { parseVpToken } from \"../vp-token/parse-vp-token\";\nimport { Openid4vpAuthorizationResponse } from \"./z-authorization-response\";\n\nexport interface ValidateOpenid4vpAuthorizationResponseOptions {\n /**\n * Parsed request payload used as validation source.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Parsed authorization response payload to validate.\n */\n authorizationResponsePayload: Openid4vpAuthorizationResponse;\n}\n\n/**\n * Result of authorization response validation.\n */\nexport interface ValidateOpenid4vpAuthorizationResponseResult {\n presentations: ReturnType<typeof parseVpToken>;\n query: Openid4vpAuthorizationRequestPayload[\"dcql_query\"];\n}\n\n/**\n * Validates the OpenID4VP authorization response payload against the request payload.\n *\n * @param options {@link ValidateOpenid4vpAuthorizationResponseOptions}\n * @returns Presentations and query extracted from the validated flow.\n * @throws {Oid4vpError} If `state` is present in the request and does not match the response.\n */\nexport function validateOpenid4vpAuthorizationResponsePayload(\n options: ValidateOpenid4vpAuthorizationResponseOptions,\n): ValidateOpenid4vpAuthorizationResponseResult {\n const { authorizationRequestPayload, authorizationResponsePayload } = options;\n\n if (\n authorizationRequestPayload.state !== authorizationResponsePayload.state\n ) {\n throw new Oid4vpError(\"OpenId4Vp Authorization Response state mismatch.\");\n }\n\n const presentations = parseVpToken(authorizationResponsePayload.vp_token);\n\n return {\n presentations,\n query: authorizationRequestPayload.dcql_query,\n };\n}\n","import { jwtSignerFromJwt } from \"@openid4vc/oauth2\";\nimport {\n type CallbackContext,\n type Jwk,\n Oauth2Error,\n decodeJwt,\n decodeJwtHeader,\n zCompactJwe,\n zCompactJwt,\n zJwtHeader,\n} from \"@pagopa/io-wallet-oauth2\";\nimport { stringToJsonWithErrorHandling } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { Openid4vpAuthorizationRequestPayload } from \"../authorization-request/z-authorization-request\";\nimport { extractEncryptionJwkFromJwks } from \"./jarm-extract-jwks\";\nimport {\n JarmAuthorizationResponse,\n JarmAuthorizationResponseEncryptedOnly,\n zEncryptedJarmHeader,\n zJarmAuthorizationResponse,\n zJarmAuthorizationResponseEncryptedOnly,\n} from \"./z-jarm\";\n\n/**\n * Supported JARM serialization/processing modes.\n */\nexport enum JarmMode {\n Encrypted = \"Encrypted\",\n Signed = \"Signed\",\n SignedEncrypted = \"SignedEncrypted\",\n}\n\nconst decryptJarmAuthorizationResponseJwt = async (options: {\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n callbacks: Pick<CallbackContext, \"decryptJwe\">;\n jarmAuthorizationResponseJwt: string;\n}) => {\n const {\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n } = options;\n\n let encryptionJwk: Jwk | undefined;\n const { header } = decodeJwtHeader({\n headerSchema: zEncryptedJarmHeader,\n jwt: jarmAuthorizationResponseJwt,\n });\n\n const jwks = authorizationRequestPayload.client_metadata?.jwks;\n\n if (jwks) {\n encryptionJwk = extractEncryptionJwkFromJwks(jwks, { kid: header.kid });\n }\n\n const result = await callbacks.decryptJwe(jarmAuthorizationResponseJwt, {\n jwk: encryptionJwk,\n });\n\n if (!result.decrypted) {\n throw new Oauth2Error(\"Failed to decrypt jarm auth response.\");\n }\n\n return {\n decryptionJwk: result.decryptionJwk,\n payload: result.payload,\n };\n};\n\nexport interface VerifyJarmAuthorizationResponseOptions {\n /**\n * Parsed authorization request payload used to resolve metadata and key material.\n */\n authorizationRequestPayload: Openid4vpAuthorizationRequestPayload;\n /**\n * Callbacks required for JWE decryption and JWT signature verification.\n */\n callbacks: Pick<CallbackContext, \"decryptJwe\" | \"verifyJwt\">;\n /**\n * Compact serialized JARM response received from the verifier.\n */\n jarmAuthorizationResponseJwt: string;\n /**\n * Current time used for temporal claim validation (`exp`, `nbf`).\n * Defaults to current date-time when omitted.\n */\n now?: Date;\n}\n\n/**\n * Verified JARM authorization response data returned by {@link verifyJarmAuthorizationResponse}.\n */\nexport interface VerifyJarmAuthorizationResponseResult {\n /**\n * JWK used for decryption when the response is encrypted, or `undefined` if the response was not encrypted.\n */\n decryptionJwk: Jwk | undefined;\n /**\n * The `iss` claim from the JARM response, representing the issuer of the response.\n */\n issuer: string | undefined;\n /**\n * The parsed JARM authorization response body, containing claims like `iss`, `aud`, `exp`, etc.\n */\n jarmAuthorizationResponse:\n | JarmAuthorizationResponse\n | JarmAuthorizationResponseEncryptedOnly;\n /**\n * Detected JARM processing mode indicating whether the response was signed, encrypted, or both.\n */\n type: JarmMode;\n}\n\n/**\n * Verifies a JARM authorization response in signed, encrypted, or signed+encrypted mode.\n *\n * The function detects the response mode, performs decryption when needed, verifies\n * JWS signatures for signed payloads, and returns the parsed JARM body with metadata.\n *\n * @param options {@link VerifyJarmAuthorizationResponseOptions}\n * @returns Decryption and verification artifacts with parsed JARM payload.\n * @throws {Oauth2Error} If the response mode is invalid, decryption fails, or signature verification fails.\n */\nexport async function verifyJarmAuthorizationResponse(\n options: VerifyJarmAuthorizationResponseOptions,\n) {\n const {\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n } = options;\n\n const requestDataIsEncrypted = zCompactJwe.safeParse(\n jarmAuthorizationResponseJwt,\n ).success;\n const decryptedRequestData = requestDataIsEncrypted\n ? await decryptJarmAuthorizationResponseJwt({\n authorizationRequestPayload,\n callbacks,\n jarmAuthorizationResponseJwt,\n })\n : { decryptionJwk: undefined, payload: jarmAuthorizationResponseJwt };\n\n const responseIsSigned = zCompactJwt.safeParse(\n decryptedRequestData.payload,\n ).success;\n\n if (!requestDataIsEncrypted && !responseIsSigned) {\n throw new Oauth2Error(\n \"Jarm Auth Response must be either encrypted, signed, or signed and encrypted.\",\n );\n }\n\n let jarmAuthorizationResponse:\n | JarmAuthorizationResponse\n | JarmAuthorizationResponseEncryptedOnly;\n\n if (responseIsSigned) {\n const { header: jwsProtectedHeader, payload: jwsPayload } = decodeJwt({\n errorMessagePrefix: \"Error decoding JARM authorization response JWT:\",\n headerSchema: z.object({ ...zJwtHeader.shape, kid: z.string() }),\n jwt: decryptedRequestData.payload,\n });\n\n const response = zJarmAuthorizationResponse.parse(jwsPayload);\n const jwtSigner = jwtSignerFromJwt({\n header: jwsProtectedHeader,\n payload: jwsPayload,\n });\n\n const verificationResult = await options.callbacks.verifyJwt(jwtSigner, {\n compact: decryptedRequestData.payload,\n header: jwsProtectedHeader,\n payload: jwsPayload,\n });\n\n if (!verificationResult.verified) {\n throw new Oauth2Error(\"Jarm Auth Response is not valid.\");\n }\n\n const expectedAudience = authorizationRequestPayload.client_id;\n const expectedIssuer = authorizationRequestPayload.iss;\n if (response.aud !== expectedAudience) {\n throw new Oauth2Error(\n `Jarm Auth Response contains 'aud' value '${response.aud}', but expected '${expectedAudience}'.`,\n );\n }\n\n if (response.iss !== expectedIssuer) {\n throw new Oauth2Error(\n `Jarm Auth Response contains 'iss' value '${response.iss}', but expected '${expectedIssuer}'.`,\n );\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (response.exp < nowSeconds) {\n throw new Oauth2Error(\"Jarm Auth Response has expired.\");\n }\n\n if (response.nbf !== undefined && response.nbf > nowSeconds) {\n throw new Oauth2Error(\"Jarm Auth Response is not active yet.\");\n }\n\n jarmAuthorizationResponse = response;\n } else {\n const jsonRequestData = stringToJsonWithErrorHandling(\n decryptedRequestData.payload,\n \"Unable to parse decrypted JARM JWE body to JSON\",\n );\n jarmAuthorizationResponse =\n zJarmAuthorizationResponseEncryptedOnly.parse(jsonRequestData);\n }\n\n const type: JarmMode =\n requestDataIsEncrypted && responseIsSigned\n ? JarmMode.SignedEncrypted\n : requestDataIsEncrypted\n ? JarmMode.Encrypted\n : JarmMode.Signed;\n\n const issuer = jarmAuthorizationResponse.iss;\n\n return {\n decryptionJwk: decryptedRequestData.decryptionJwk,\n issuer,\n jarmAuthorizationResponse,\n type,\n };\n}\n","import { zJwtHeader, zJwtPayload } from \"@pagopa/io-wallet-oauth2\";\nimport { z } from \"zod\";\n\nexport const zJarmHeader = z.object({\n ...zJwtHeader.shape,\n apu: z.string().optional(),\n apv: z.string().optional(),\n kid: z.string(),\n});\n\nexport type JarmHeader = z.infer<typeof zJarmHeader>;\n\nexport const zEncryptedJarmHeader = z.object({\n ...zJwtHeader.shape,\n apu: z.string().optional(),\n apv: z.string().optional(),\n enc: z.string().optional(),\n kid: z.string(),\n});\n\nexport type EncryptedJarmHeader = z.infer<typeof zEncryptedJarmHeader>;\n\nexport const zJarmAuthorizationResponse = z.looseObject({\n /**\n * iss: The issuer URL of the authorization server that created the response\n * aud: The client_id of the client the response is intended for\n * exp: The expiration time of the JWT. A maximum JWT lifetime of 10 minutes is RECOMMENDED.\n */\n ...zJwtPayload.shape,\n ...zJwtPayload.pick({ aud: true, exp: true, iss: true }).required().shape,\n state: z.optional(z.string()),\n});\n\nexport type JarmAuthorizationResponse = z.infer<\n typeof zJarmAuthorizationResponse\n>;\n\nexport const zJarmAuthorizationResponseEncryptedOnly = z.looseObject({\n ...zJwtPayload.shape,\n state: z.optional(z.string()),\n});\n\nexport type JarmAuthorizationResponseEncryptedO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ACF;AAEA,QAAM,4BACJ,8CAA8C;AAAA,IAC5C;AAAA,IACA;AAAA,EACF,CAAC;AAEH,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,eAAe,4BAA4B;AAAA,IAC3C,MAAM,EAAE,GAAG,sBAAsB,WAAW;AAAA,EAC9C;AACF;;;ADpCA,eAAsB,2BACpB,SAC2C;AAC3C,QAAM,EAAE,6BAA6B,uBAAuB,UAAU,IACpE;AAEF,MAAI,sBAAsB,UAAU;AAClC,QAAI,OAAO,sBAAsB,aAAa,UAAU;AACtD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO,+BAA+B;AAAA,MACpC;AAAA,MACA;AAAA,MACA,iBAAiB,sBAAsB;AAAA,IACzC,CAAC;AAAA,EACH;AAEA,QAAM,mCAA+B;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,6BACJ,8CAA8C;AAAA,IAC5C;AAAA,IACA;AAAA,EACF,CAAC;AAEH,SAAO;AAAA,IACL,GAAG;AAAA,IACH;AAAA,IACA,eAAe,4BAA4B;AAAA,EAC7C;AACF;;;AbtEA,uBAKO;","names":["import_io_wallet_oauth2","import_io_wallet_utils","normalizedMethod","import_zod","z","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","ClientIdPrefix","import_io_wallet_utils","import_io_wallet_utils","import_zod","import_zod","z","import_io_wallet_utils","import_io_wallet_oauth2","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_oauth2","import_io_wallet_oauth2","import_io_wallet_utils","import_zod","import_io_wallet_oauth2","import_zod","JarmMode","z","z"]}