@pagopa/io-wallet-oauth2 1.1.1 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -2
- package/dist/index.d.ts +1 -2
- package/dist/index.js +3 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +14 -16
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/access-token/create-token-request.ts","../src/access-token/create-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/common/jwt/z-jwt.ts","../src/common/jwk/z-jwk.ts","../src/common/z-common.ts","../src/access-token/fetch-token-response.ts","../src/access-token/parse-token-request.ts","../src/client-attestation/client-attestation-pop.ts","../src/common/jwt/decode-jwt.ts","../src/common/jwt/decode-jwt-header.ts","../src/client-attestation/types.ts","../src/client-attestation/client-authentication.ts","../src/client-attestation/v1.0/index.ts","../src/client-attestation/v1.0/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.0/z-wallet-attestation.ts","../src/client-attestation/verify-wallet-attestation-jwt-base.ts","../src/client-attestation/v1.0/verify-wallet-attestation-jwt.ts","../src/client-attestation/v1.3/index.ts","../src/client-attestation/v1.3/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.3/z-wallet-attestation.ts","../src/client-attestation/v1.3/verify-wallet-attestation-jwt.ts","../src/client-attestation/verify-client-attestation.ts","../src/client-attestation/wallet-attestation.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/dpop-utils.ts","../src/token-dpop/z-dpop.ts","../src/token-dpop/verify-token-dpop.ts","../src/access-token/z-grant-type.ts","../src/pkce.ts","../src/access-token/verify-access-token-request.ts","../src/authorization-request/create-authorization-request.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-response.ts","../src/authorization-request/parse-authorization-request.ts","../src/authorization-request/parse-pushed-authorization-request.ts","../src/jar/create-jar-request.ts","../src/jar/fetch-jar-request-object.ts","../src/jar/validate-jar-request.ts","../src/jar/parse-jar-request.ts","../src/jar/verify-jar-request.ts","../src/jar/z-jar.ts","../src/authorization-request/verify-authorization-request.ts","../src/authorization-request/verify-pushed-authorization-request.ts","../src/common/jwt/z-jwe.ts","../src/jarm-form-post-jwt.ts","../src/mrtd-pop/create-mrtd-validation-jwt.ts","../src/mrtd-pop/z-mrtd-pop.ts","../src/mrtd-pop/fetch-mrtd-pop-init.ts","../src/mrtd-pop/fetch-mrtd-pop-verify.ts","../src/mrtd-pop/parse-mrtd-challenge.ts","../src/mrtd-pop/verify-mrtd-challenge.ts","../src/index.ts"],"sourcesContent":["import { CallbackContext } from \"@openid4vc/oauth2\";\n\nimport { AuthorizationCodeGrantType } from \"./z-token\";\n\nexport interface RetrieveAuthorizationCodeAccessTokenOptions {\n /**\n * Additional payload to include in the access token request. Items will be encoded and sent\n * using x-www-form-urlencoded format. Nested items (JSON) will be stringified and url encoded.\n */\n additionalRequestPayload?: Record<string, unknown>;\n\n /**\n * The authorization code\n */\n authorizationCode: string;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<\n CallbackContext,\n \"clientAuthentication\" | \"fetch\" | \"generateRandom\" | \"hash\" | \"signJwt\"\n >;\n\n /**\n * PKCE Code verifier that was used in the authorization request.\n */\n pkceCodeVerifier: string;\n\n /**\n * Redirect uri to include in the access token request.\n * It MUST be set as in the Request Object.\n */\n redirectUri: string;\n}\n\nexport const createTokenRequest = async (\n options: RetrieveAuthorizationCodeAccessTokenOptions,\n) =>\n ({\n code: options.authorizationCode,\n code_verifier: options.pkceCodeVerifier,\n grant_type: \"authorization_code\",\n redirect_uri: options.redirectUri,\n ...options.additionalRequestPayload,\n }) satisfies AuthorizationCodeGrantType;\n","import {\n CallbackContext,\n HashAlgorithm,\n JwtSigner,\n calculateJwkThumbprint,\n jwtHeaderFromJwtSigner,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { CreateTokenResponseError } from \"../errors\";\nimport {\n AccessTokenProfileJwtHeader,\n AccessTokenProfileJwtPayload,\n AccessTokenResponse,\n zAccessTokenProfileJwtHeader,\n zAccessTokenProfileJwtPayload,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface CreateAccessTokenResponseOptions {\n /**\n * Additional claims copied into both the access token JWT payload and token\n * response envelope.\n */\n additionalPayload?: Record<string, unknown>;\n\n /**\n * Intended recipient of the access token (`aud` claim).\n */\n audience: string;\n\n /**\n * Authorization server identifier (`iss` claim).\n */\n authorizationServer: string;\n\n /**\n * Runtime callbacks used to generate random values, compute JWK thumbprints,\n * and sign the access token JWT.\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * OAuth client identifier (`client_id` claim).\n */\n clientId: string;\n\n /**\n * DPoP public key used to bind the access token (`cnf.jkt` claim).\n */\n dpop?: {\n jwk: Jwk;\n };\n\n /**\n * Access token lifetime in seconds, used for both `exp` and `expires_in`.\n */\n expiresInSeconds: number;\n\n /**\n * Optional \"not before\" timestamp in epoch seconds (`nbf` claim).\n */\n nbf?: number;\n\n /**\n * Reference time used for `iat` and `exp`. Defaults to current time.\n */\n now?: Date;\n\n /**\n * Optional refresh token included in the OAuth token response.\n */\n refreshToken?: string;\n\n /**\n * Optional scope string included in both the access token JWT payload and token\n * response envelope.\n */\n scope?: string;\n\n /**\n * Signer used to produce the access token JWT.\n */\n signer: JwtSigner;\n\n /**\n * Subject identifier represented by the access token (`sub` claim).\n */\n subject: string;\n\n /**\n * Token type returned in the OAuth token response.\n * NOTE: When using `Bearer` it is supposed to be used only for PDND Interoperability API, not for credential issuance flows.\n */\n tokenType: \"Bearer\" | \"DPoP\";\n}\n\n/**\n * Creates an OAuth 2.0 access token response where `access_token` is a signed\n * JWT access token profile (`typ=at+jwt`) and `token_type` is `DPoP` or `Bearer`.\n *\n * The JWT payload always includes `aud`, `iss`, `sub`, `client_id`, `iat`,\n * `exp`, and a random `jti`. When `dpop` is provided, `cnf.jkt` is added using\n * the SHA-256 JWK thumbprint.\n */\nexport async function createAccessTokenResponse(\n options: CreateAccessTokenResponseOptions,\n) {\n try {\n const now = options.now ?? new Date();\n\n if (options.tokenType === \"DPoP\" && !options.dpop) {\n throw new CreateTokenResponseError(\n \"token_type is DPoP but dpop option is not provided. Please provide a DPoP public key in the dpop option or set tokenType to 'Bearer'.\",\n );\n }\n\n const header = parseWithErrorHandling(zAccessTokenProfileJwtHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: \"at+jwt\",\n } satisfies AccessTokenProfileJwtHeader);\n\n const payload = parseWithErrorHandling(zAccessTokenProfileJwtPayload, {\n aud: options.audience,\n client_id: options.clientId,\n cnf: options.dpop\n ? {\n jkt: await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpop.jwk,\n }),\n }\n : undefined,\n exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n nbf: options.nbf,\n scope: options.scope,\n sub: options.subject,\n ...options.additionalPayload,\n } satisfies AccessTokenProfileJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: options.refreshToken,\n token_type: options.tokenType,\n ...options.additionalPayload,\n } satisfies AccessTokenResponse);\n\n return accessTokenResponse;\n } catch (error) {\n if (error instanceof CreateTokenResponseError) {\n throw error;\n }\n throw new CreateTokenResponseError(\n `Error creating access token JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Error thrown during MRTD (Machine Readable Travel Document) Proof of Possession operations.\n * Used in eID Substantial Authentication with MRTD Verification flow (IT-Wallet L2+ specification).\n */\nexport class MrtdPopError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"MrtdPopError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n\nexport class CreateTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"CreateTokenResponseError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during client attestation (wallet attestation) creation.\n */\nexport class ClientAttestationError extends Oauth2Error {\n constructor(\n message: string,\n public readonly originalError?: unknown,\n ) {\n super(message);\n this.name = \"ClientAttestationError\";\n }\n}\n","import { z } from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zAccessTokenRequest = z.discriminatedUnion(\"grant_type\", [\n z.object({\n code: z.string().nonempty(),\n code_verifier: z.string().nonempty(),\n grant_type: z.literal(\"authorization_code\"),\n redirect_uri: z.string().nonempty(),\n }),\n z.object({\n grant_type: z.literal(\"refresh_token\"),\n refresh_token: z.string().nonempty(),\n scope: z.string().optional(),\n }),\n]);\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport type AuthorizationCodeGrantType = Extract<\n AccessTokenRequest,\n { grant_type: \"authorization_code\" }\n>;\n\nexport type RefreshTokenGrantType = Extract<\n AccessTokenRequest,\n { grant_type: \"refresh_token\" }\n>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.union([z.literal(\"Bearer\"), z.literal(\"DPoP\")]),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n\nexport const zAccessTokenProfileJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z.enum([\"application/at+jwt\", \"at+jwt\"]),\n })\n .passthrough();\n\nexport type AccessTokenProfileJwtHeader = z.infer<\n typeof zAccessTokenProfileJwtHeader\n>;\n\nexport const zAccessTokenProfileJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n aud: z.string(),\n client_id: z.string(),\n cnf: z\n .object({\n jkt: z.string(),\n })\n .optional(),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n jti: z.string(),\n nbf: z.number().optional(),\n scope: z.string().optional(),\n sub: z.string(),\n })\n .passthrough();\n\nexport type AccessTokenProfileJwtPayload = z.infer<\n typeof zAccessTokenProfileJwtPayload\n>;\n","import z from \"zod\";\n\nimport { Jwk, zJwk } from \"../jwk/z-jwk\";\nimport { zAlgValueNotNone } from \"../z-common\";\n\nexport interface JwtSignerDid {\n alg: string;\n didUrl: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the didUrl.\n */\n kid?: string;\n\n method: \"did\";\n}\n\nexport interface JwtSignerJwk {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the jwk.\n *\n * If not provided the kid can also be extracted from the `publicJwk`. Providing it here means the `kid` won't\n * be included in the JWT header.\n */\n kid?: string;\n method: \"jwk\";\n\n publicJwk: Jwk;\n}\n\nexport interface JwtSignerX5c {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the leaf certificate.\n */\n kid?: string;\n method: \"x5c\";\n\n x5c: string[];\n}\n\nexport interface JwtSignerFederation {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with a key present in the federation.\n */\n kid: string;\n method: \"federation\";\n\n trustChain?: [string, ...string[]];\n}\n\n// In case of custom nothing will be added to the header\nexport interface JwtSignerCustom {\n alg: string;\n /**\n * The key id that should be used for signing.\n */\n kid?: string;\n\n method: \"custom\";\n}\n\nexport type JwtSigner =\n | JwtSignerCustom\n | JwtSignerDid\n | JwtSignerFederation\n | JwtSignerJwk\n | JwtSignerX5c;\n\nexport type JwtSignerWithJwk = { publicJwk: Jwk } & JwtSigner;\n\nexport type JweEncryptor = {\n /**\n * base64-url encoded apu\n */\n apu?: string;\n\n /**\n * base64-url encoded apv\n */\n apv?: string;\n\n enc: string;\n} & JwtSignerJwk;\n\nexport const zCompactJwt = z\n .string()\n .regex(/^([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)$/, {\n message: \"Not a valid compact jwt\",\n });\n\nexport const zJwtConfirmationPayload = z\n .object({\n // RFC9449. jwk thumbprint of the dpop public key to which the access token is bound\n jkt: z.string().optional(),\n\n jwk: zJwk.optional(),\n })\n .passthrough();\n\nexport const zJwtPayload = z\n .object({\n aud: z.string().optional(),\n cnf: zJwtConfirmationPayload.optional(),\n exp: z.number().int().optional(),\n iat: z.number().int().optional(),\n iss: z.string().optional(),\n jti: z.string().optional(),\n nbf: z.number().int().optional(),\n\n nonce: z.string().optional(),\n\n // Reserved for status parameters\n status: z.record(z.string(), z.any()).optional(),\n\n // Reserved for OpenID Federation\n trust_chain: z.array(z.string()).nonempty().optional(),\n })\n .passthrough();\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>;\n\nexport const zJwtHeader = z\n .object({\n alg: zAlgValueNotNone,\n jwk: zJwk.optional(),\n\n kid: z.string().optional(),\n // Reserved for OpenID Federation\n trust_chain: z.array(z.string()).nonempty().optional(),\n typ: z.string().optional(),\n\n x5c: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>;\n","import z from \"zod\";\n\nexport const zJwk = z\n .object({\n alg: z.optional(z.string()),\n crv: z.optional(z.string()),\n d: z.optional(z.string()),\n dp: z.optional(z.string()),\n dq: z.optional(z.string()),\n e: z.optional(z.string()),\n ext: z.optional(z.boolean()),\n k: z.optional(z.string()),\n key_ops: z.optional(z.array(z.string())),\n kid: z.optional(z.string()),\n kty: z.string(),\n n: z.optional(z.string()),\n oth: z.optional(\n z.array(\n z\n .object({\n d: z.optional(z.string()),\n r: z.optional(z.string()),\n t: z.optional(z.string()),\n })\n .passthrough(),\n ),\n ),\n p: z.optional(z.string()),\n q: z.optional(z.string()),\n qi: z.optional(z.string()),\n use: z.optional(z.string()),\n x: z.optional(z.string()),\n x5c: z.optional(z.array(z.string())),\n x5t: z.optional(z.string()),\n \"x5t#S256\": z.optional(z.string()),\n x5u: z.optional(z.string()),\n y: z.optional(z.string()),\n })\n .passthrough();\n\nexport type Jwk = z.infer<typeof zJwk>;\n\nexport const zJwkSet = z.object({ keys: z.array(zJwk) }).passthrough();\n\nexport type JwkSet = z.infer<typeof zJwkSet>;\n","import { FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nexport const zAlgValueNotNone = z\n .string()\n .refine((alg) => alg !== \"none\", { message: `alg value may not be 'none'` });\n\nexport interface RequestLike {\n headers: FetchHeaders;\n method: HttpMethod;\n url: string;\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 { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * DPoP proof for the token request\n */\n dPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.DPOP]: options.dPoP,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","import {\n FetchHeaders,\n RequestLike,\n formatZodError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { extractClientAttestationJwtsFromHeaders } from \"../client-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop\";\nimport {\n AuthorizationCodeGrantIdentifier,\n RefreshTokenGrantIdentifier,\n authorizationCodeGrantIdentifier,\n refreshTokenGrantIdentifier,\n} from \"./z-grant-type\";\nimport { AccessTokenRequest, zAccessTokenRequest } from \"./z-token\";\n\nexport interface ParsedAccessTokenAuthorizationCodeRequestGrant {\n code: string;\n grantType: AuthorizationCodeGrantIdentifier;\n}\n\nexport interface ParsedAccessTokenRefreshTokenRequestGrant {\n grantType: RefreshTokenGrantIdentifier;\n refreshToken: string;\n}\n\ntype ParsedAccessTokenRequestGrant =\n | ParsedAccessTokenAuthorizationCodeRequestGrant\n | ParsedAccessTokenRefreshTokenRequestGrant;\n\nexport interface ParseAccessTokenRequestResult {\n accessTokenRequest: AccessTokenRequest;\n /**\n * The client attestation jwts from the access token request headers\n */\n clientAttestation: {\n clientAttestationPopJwt: string;\n walletAttestationJwt: string;\n };\n\n /**\n * The dpop jwt from the access token request headers\n */\n dpop: {\n jwt: string;\n };\n\n grant: ParsedAccessTokenRequestGrant;\n\n /**\n * The pkce code verifier from the access token request\n */\n pkceCodeVerifier?: string;\n}\n\nexport interface ParseAccessTokenRequestOptions {\n /**\n * The access token request as a JSON object. Your server should decode the\n * `x-www-url-form-urlencoded` body into an object (e.g. using `bodyParser.urlEncoded()` in express)\n */\n accessTokenRequest: Record<string, unknown>;\n\n request: RequestLike;\n}\n\n/**\n * Parses and validates an OAuth 2.0 access token request.\n *\n * This function performs the following steps:\n * 1. Validates the request body against the access token request schema\n * 2. Extracts and validates grant-specific parameters (authorization code or refresh token)\n * 3. Parses security headers (DPoP and Client Attestation JWTs)\n * 4. Extracts PKCE code verifier if present\n *\n * Note: This function only parses and validates the structure of the request.\n * Cryptographic verification of JWTs and tokens should be performed separately.\n *\n * @param options - Configuration object containing the access token request body and HTTP request\n * @returns Parsed access token request with typed grant parameters and extracted security headers\n * @throws {Oauth2Error} If validation fails or required parameters are missing\n *\n * @example\n * ```typescript\n * const result = parseAccessTokenRequest({\n * accessTokenRequest: {\n * grant_type: 'authorization_code',\n * code: 'auth_code_123',\n * client_id: 'client_123',\n * code_verifier: 'verifier_xyz'\n * },\n * request: httpRequest\n * });\n * ```\n */\nexport function parseAccessTokenRequest(\n options: ParseAccessTokenRequestOptions,\n): ParseAccessTokenRequestResult {\n const validationResult = zAccessTokenRequest.safeParse(\n options.accessTokenRequest,\n );\n\n if (!validationResult.success) {\n throw new Oauth2Error(\n `Access token request validation failed:\\n${formatZodError(validationResult.error)}`,\n );\n }\n\n const accessTokenRequest = validationResult.data;\n const grant = parseGrantParameters(accessTokenRequest);\n const securityHeaders = parseSecurityHeaders(options.request.headers);\n const pkceCodeVerifier =\n accessTokenRequest.grant_type === \"authorization_code\"\n ? accessTokenRequest.code_verifier\n : undefined;\n\n return {\n accessTokenRequest,\n grant,\n pkceCodeVerifier,\n ...securityHeaders,\n };\n}\n\n/**\n * Parses the grant-specific parameters from an access token request.\n *\n * Validates that the required parameters for the grant type are present\n * and returns a typed grant object.\n *\n * @param accessTokenRequest - The validated access token request\n * @returns Typed grant object containing grant-specific parameters\n * @throws {Oauth2Error} If required grant parameters are missing or grant type is unsupported\n */\nfunction parseGrantParameters(\n accessTokenRequest: AccessTokenRequest,\n): ParsedAccessTokenRequestGrant {\n if (accessTokenRequest.grant_type === authorizationCodeGrantIdentifier) {\n return {\n code: accessTokenRequest.code,\n grantType: authorizationCodeGrantIdentifier,\n };\n }\n\n if (accessTokenRequest.grant_type === refreshTokenGrantIdentifier) {\n return {\n grantType: refreshTokenGrantIdentifier,\n refreshToken: accessTokenRequest.refresh_token,\n };\n }\n\n throw new Oauth2Error(\n `Unsupported grant type. Supported types are: '${authorizationCodeGrantIdentifier}', '${refreshTokenGrantIdentifier}'`,\n );\n}\n\n/**\n * Extracts and validates security headers (DPoP and Client Attestation) from the request.\n *\n * This function only parses the headers without verifying the cryptographic signatures.\n * Signature verification should be performed separately.\n *\n * @param headers - The HTTP request headers\n * @returns Object containing extracted DPoP JWT and Client Attestation JWTs if present\n * @throws {Oauth2Error} If headers are present but malformed\n */\nfunction parseSecurityHeaders(headers: FetchHeaders) {\n const extractedDpopJwt = extractDpopJwtFromHeaders(headers);\n if (!extractedDpopJwt.valid) {\n throw new Oauth2Error(\n \"Request contains a 'DPoP' header, but the value is not a valid JWT format\",\n );\n }\n\n if (!extractedDpopJwt.dpopJwt) {\n throw new Oauth2Error(\"Request is missing required 'DPoP' header\");\n }\n\n const extractedClientAttestationJwts =\n extractClientAttestationJwtsFromHeaders(headers);\n\n if (!extractedClientAttestationJwts.valid) {\n throw new Oauth2Error(\n \"Request contains client attestation headers, but the values are not in valid JWT format\",\n );\n }\n\n if (!extractedClientAttestationJwts.walletAttestationHeader) {\n throw new Oauth2Error(\n \"Request is missing required 'OAuth-Client-Attestation' header\",\n );\n }\n\n if (!extractedClientAttestationJwts.clientAttestationPopHeader) {\n throw new Oauth2Error(\n \"Request is missing required 'OAuth-Client-Attestation-PoP' header\",\n );\n }\n\n return {\n clientAttestation: {\n clientAttestationPopJwt:\n extractedClientAttestationJwts.clientAttestationPopHeader,\n walletAttestationJwt:\n extractedClientAttestationJwts.walletAttestationHeader,\n },\n dpop: { jwt: extractedDpopJwt.dpopJwt },\n };\n}\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n JwtSignerJwk,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\n\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { decodeJwtHeader } from \"./decode-jwt-header\";\nimport { zJwtHeader, zJwtPayload } from \"./z-jwt\";\n\nexport interface DecodeJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> {\n /**\n * Schema to use for validating the header. If not provided the\n * default `zJwtHeader` schema will be used\n */\n headerSchema?: HeaderSchema;\n\n /**\n * The compact encoded jwt\n */\n jwt: string;\n\n /**\n * Schema to use for validating the payload. If not provided the\n * default `zJwtPayload` schema will be used\n */\n payloadSchema?: PayloadSchema;\n}\n\nexport interface DecodeJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>;\n signature: string;\n}\n\nexport function decodeJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(\n options: DecodeJwtOptions<HeaderSchema, PayloadSchema>,\n): DecodeJwtResult<HeaderSchema, PayloadSchema> {\n const jwtParts = options.jwt.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n let payloadJson: Record<string, unknown>;\n try {\n const payloadPart = jwtParts[1];\n if (payloadPart === undefined) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n payloadJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(payloadPart)),\n \"Unable to parse jwt payload to JSON\",\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n );\n }\n\n const signaturePart = jwtParts[2];\n if (signaturePart === undefined) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n const { header } = decodeJwtHeader({\n headerSchema: options.headerSchema,\n jwt: options.jwt,\n });\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n );\n\n return {\n header: header as InferSchemaOrDefaultOutput<\n HeaderSchema,\n typeof zJwtHeader\n >,\n payload: payload as InferSchemaOrDefaultOutput<\n PayloadSchema,\n typeof zJwtPayload\n >,\n signature: signaturePart,\n };\n}\n\n// Helper type to check if a schema is provided\ntype IsSchemaProvided<T> = T extends undefined ? false : true;\n\n// Helper type to infer the output type based on whether a schema is provided\nexport type InferSchemaOrDefaultOutput<\n ProvidedSchema extends BaseSchema | undefined,\n DefaultSchema extends BaseSchema,\n> =\n IsSchemaProvided<ProvidedSchema> extends true\n ? ProvidedSchema extends BaseSchema\n ? z.infer<ProvidedSchema>\n : never\n : z.infer<DefaultSchema>;\n","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { InferSchemaOrDefaultOutput } from \"./decode-jwt\";\n\nimport { zJwtHeader } from \"./z-jwt\";\n\nexport interface DecodeJwtHeaderOptions<\n HeaderSchema extends BaseSchema | undefined,\n> {\n /**\n * Schema to use for validating the header. If not provided the\n * default `zJwtHeader` schema will be used\n */\n headerSchema?: HeaderSchema;\n\n /**\n * The compact encoded jwt\n */\n jwt: string;\n}\n\nexport interface DecodeJwtHeaderResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n}\n\nexport function decodeJwtHeader<\n HeaderSchema extends BaseSchema | undefined = undefined,\n>(\n options: DecodeJwtHeaderOptions<HeaderSchema>,\n): DecodeJwtHeaderResult<HeaderSchema> {\n const jwtParts = options.jwt.split(\".\");\n if (jwtParts.length <= 2) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n const [headerPart] = jwtParts as [string, ...string[]];\n\n let headerJson: Record<string, unknown>;\n try {\n headerJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(headerPart)),\n \"Unable to parse jwt header to JSON\",\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n );\n }\n\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n ) as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n\n return {\n header,\n };\n}\n","import {\n CallbackContext,\n ClientAttestationJwtPayload,\n} from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nexport interface BaseVerifyWalletAttestationJwtOptions {\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n now?: Date;\n walletAttestationJwt: string;\n}\n\n/**\n * Base options shared across all wallet attestation versions\n */\nexport interface BaseWalletAttestationOptions {\n callbacks: Pick<CallbackContext, \"signJwt\">;\n dpopJwkPublic: ClientAttestationJwtPayload[\"cnf\"][\"jwk\"];\n expiresAt?: Date;\n issuer: string;\n walletLink?: string;\n walletName?: string;\n}\n\nexport const zOauthClientAttestationHeader = z.literal(\n \"OAuth-Client-Attestation\",\n);\n\nexport const oauthClientAttestationHeader = zOauthClientAttestationHeader.value;\n\nexport const zOauthClientAttestationPopHeader = z.literal(\n \"OAuth-Client-Attestation-PoP\",\n);\n\nexport const oauthClientAttestationPopHeader =\n zOauthClientAttestationPopHeader.value;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { ContentType, FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\n\nimport { createClientAttestationPopJwt } from \"./client-attestation-pop\";\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\n\n/**\n * Supported OAuth 2.0 client authentication methods.\n */\nexport const SupportedClientAuthenticationMethod = {\n ClientSecretBasic: \"client_secret_basic\",\n ClientSecretPost: \"client_secret_post\",\n None: \"none\",\n WalletAttestationJwt: \"attest_jwt_client_auth\",\n} as const;\n\n/**\n * Union type of supported client authentication methods.\n */\nexport type SupportedClientAuthenticationMethod =\n (typeof SupportedClientAuthenticationMethod)[keyof typeof SupportedClientAuthenticationMethod];\n\n/**\n * Options for checking client attestation support.\n */\nexport interface IsClientAttestationSupportedOptions {\n /** Authorization server metadata containing supported authentication methods. */\n authorizationServerMetadata: AuthorizationServerMetadata;\n}\n\n/**\n * Checks whether the authorization server supports client attestation authentication.\n *\n * @param options - Configuration including authorization server metadata\n * @returns Object with `supported` boolean indicating if client attestation is available\n */\nexport function isClientAttestationSupported(\n options: IsClientAttestationSupportedOptions,\n) {\n if (\n !options.authorizationServerMetadata\n .token_endpoint_auth_methods_supported ||\n !options.authorizationServerMetadata.token_endpoint_auth_methods_supported.includes(\n SupportedClientAuthenticationMethod.WalletAttestationJwt,\n )\n ) {\n return {\n supported: false,\n };\n }\n\n return {\n supported: true,\n };\n}\n\n/**\n * Options for client authentication\n */\nexport interface ClientAuthenticationCallbackOptions {\n /**\n * Metadata of the authorization server\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * The body as a JSON object. If content type `x-www-form-urlencoded`\n * is used, it will be encoded after this call.\n *\n * You can modify this object\n */\n body: Record<string, unknown>;\n\n contentType: ContentType;\n\n /**\n * Headers for the request. You can modify this object\n */\n headers: FetchHeaders;\n\n /**\n * http method that will be used\n */\n method: HttpMethod;\n\n /**\n * URL to which the request will be made\n */\n url: string;\n}\n\n/**\n * Callback method to determine the client authentication for a request.\n */\nexport type ClientAuthenticationCallback = (\n options: ClientAuthenticationCallbackOptions,\n) => Promise<void> | void;\n\n/**\n * Anonymous client authentication\n */\nexport function clientAuthenticationAnonymous(): ClientAuthenticationCallback {\n return () => {\n // No authentication, do nothing\n };\n}\n\nexport interface ClientAuthenticationWalletAttestationJwtOptions {\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"signJwt\">;\n walletAttestationJwt: string;\n}\n\n/**\n * Client authentication using wallet attestation JWT.\n * This method adds the wallet attestation JWT and a proof-of-possession JWT to the request headers.\n */\nexport function clientAuthenticationWalletAttestationJwt(\n options: ClientAuthenticationWalletAttestationJwtOptions,\n): ClientAuthenticationCallback {\n return async ({ authorizationServerMetadata, headers }) => {\n const clientAttestationPop = await createClientAttestationPopJwt({\n authorizationServer: authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestation: options.walletAttestationJwt,\n });\n\n headers.set(oauthClientAttestationHeader, options.walletAttestationJwt);\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop);\n };\n}\n","export * from \"./create-wallet-attestation-jwt\";\nexport * from \"./verify-wallet-attestation-jwt\";\nexport * from \"./z-wallet-attestation\";\n","import {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_0,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n} from \"./z-wallet-attestation\";\n\n/**\n * Options for creating a wallet attestation with v1.0\n * Uses only trust_chain (federation method)\n */\nexport interface WalletAttestationOptionsV1_0\n extends BaseWalletAttestationOptions {\n /**\n * It expresses the strength of the authentication mechanism backing the Wallet instance when interacting with a Relying Party.\n */\n authenticatorAssuranceLevel: string;\n\n signer: {\n alg: string;\n kid: string;\n method: \"federation\";\n trustChain: [string, ...string[]]; // REQUIRED in v1.0\n };\n}\n\n/**\n * Create a Wallet Attestation JWT for IT-Wallet v1.0\n *\n * Version 1.0 specifics:\n * - Uses only `trust_chain` in header (federation method)\n *\n * @param options - Wallet attestation options for v1.0\n * @returns Signed wallet attestation JWT string\n * @throws {ValidationError} When validation of the JWT structure fails\n * @throws {ClientAttestationError} For other unexpected errors during creation\n * @internal This function is called by the WalletProvider router\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_0,\n): Promise<WalletAttestationJwtV1_0> => {\n try {\n const { signJwt } = options.callbacks;\n // Calculate default expiration (60 days)\n const exp =\n options.expiresAt ?? addSecondsToDate(new Date(), 3600 * 24 * 60);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(new Date()),\n iss: options.issuer,\n sub: options.dpopJwkPublic.kid,\n ...(options.walletLink && { wallet_link: options.walletLink }),\n ...(options.walletName && { wallet_name: options.walletName }),\n aal: options.authenticatorAssuranceLevel,\n };\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n trust_chain: options.signer.trustChain,\n typ: \"oauth-client-attestation+jwt\",\n };\n\n const result = await signJwt(options.signer, {\n header,\n payload,\n });\n\n decodeJwt({\n headerSchema: zWalletAttestationJwtHeaderV1_0,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_0,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ClientAttestationError(\n `Unexpected error during wallet attestation creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\n\n/**\n * JWT Header schema for IT-Wallet v1.0 Wallet Attestation\n *\n * Version 1.0 specifics:\n * - trust_chain is REQUIRED\n * - x5c is NOT supported\n */\nexport const zWalletAttestationJwtHeaderV1_0 = z\n .object({\n ...zJwtHeader.shape,\n trust_chain: z.array(z.string()).nonempty(), // REQUIRED in v1.0\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n })\n .passthrough();\n\n/**\n * JWT Payload schema for IT-Wallet v1.0 Wallet Attestation\n *\n * Version 1.0 specifics:\n * - Standard claims only\n * - No nbf or status support\n */\nexport const zWalletAttestationJwtPayloadV1_0 = z\n .object({\n ...zJwtPayload.shape,\n aal: z.string(),\n cnf: z.object({\n jwk: zJwk,\n }),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n sub: z.string(),\n wallet_link: z.string().url().optional(),\n wallet_name: z.string().optional(),\n })\n .passthrough();\n\n/**\n * Wallet Attestation JWT type for v1.0\n * The JWT is returned as a compact string\n */\nexport type WalletAttestationJwtV1_0 = string;\n\n/**\n * Zod schema for wallet attestation JWT validation (v1.0)\n * Validates that the result is a non-empty string\n */\nexport const zWalletAttestationJwtV1_0 = z.string().min(1);\n","import { jwtSignerFromJwt, verifyJwt } from \"@openid4vc/oauth2\";\nimport { ZodType, z } from \"zod\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\n\nexport async function verifyWalletAttestationBase<\n THeader extends ZodType,\n TPayload extends ZodType,\n>(\n options: BaseVerifyWalletAttestationJwtOptions,\n headerSchema: THeader,\n payloadSchema: TPayload,\n): Promise<{\n header: z.infer<THeader>;\n payload: z.infer<TPayload>;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}> {\n const { header, payload } = decodeJwt({\n headerSchema,\n jwt: options.walletAttestationJwt,\n payloadSchema,\n });\n\n const { signer } = await verifyJwt({\n compact: options.walletAttestationJwt,\n errorMessage: \"wallet attestation verification failed.\",\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return { header, payload, signer };\n}\n","import {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { BaseVerifyWalletAttestationJwtOptions } from \"../types\";\nimport { verifyWalletAttestationBase } from \"../verify-wallet-attestation-jwt-base\";\nimport {\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_0\n extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_0 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n );\n}\n","export * from \"./create-wallet-attestation-jwt\";\nexport * from \"./verify-wallet-attestation-jwt\";\nexport * from \"./z-wallet-attestation\";\n","import {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_3,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n} from \"./z-wallet-attestation\";\n\n/**\n * Options for creating a wallet attestation with v1.3\n * Requires x5c, optional trust_chain, nbf, and status\n */\nexport interface WalletAttestationOptionsV1_3\n extends BaseWalletAttestationOptions {\n // NEW OPTIONAL CLAIMS\n nbf?: Date; // Not Before timestamp\n\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]]; // OPTIONAL in v1.3\n x5c: [string, ...string[]]; // REQUIRED in v1.3\n };\n status?: {\n status_list: {\n idx: number;\n uri: string;\n };\n }; // Status object for revocation mechanisms\n}\n\n/**\n * Create a Wallet Attestation JWT for IT-Wallet v1.3\n *\n * Version 1.3 specifics:\n * - x5c in header is REQUIRED\n * - trust_chain in header is OPTIONAL\n * - Supports nbf and status claims in payload\n *\n * @param options - Wallet attestation options for v1.3\n * @returns Signed wallet attestation JWT string\n * @throws {ValidationError} When validation fails (including nbf >= exp)\n * @throws {ClientAttestationError} For other unexpected errors during creation\n * @internal This function is called by the WalletProvider router\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_3,\n): Promise<WalletAttestationJwtV1_3> => {\n try {\n const { signJwt } = options.callbacks;\n\n // Calculate default expiration (60 days)\n const exp =\n options.expiresAt ?? addSecondsToDate(new Date(), 3600 * 24 * 60);\n\n // Validate temporal constraints\n if (options.nbf && options.nbf >= exp) {\n throw new ValidationError(\"nbf must be before exp\");\n }\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(new Date()),\n iss: options.issuer,\n sub: options.dpopJwkPublic.kid,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\n ...(options.status && { status: options.status }),\n ...(options.walletLink && { wallet_link: options.walletLink }),\n ...(options.walletName && { wallet_name: options.walletName }),\n };\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n typ: \"oauth-client-attestation+jwt\",\n x5c: options.signer.x5c, // REQUIRED\n ...(options.signer.trustChain && {\n trust_chain: options.signer.trustChain,\n }),\n };\n\n const result = await signJwt(options.signer, {\n header,\n payload,\n });\n\n // Validate the generated JWT structure\n decodeJwt({\n headerSchema: zWalletAttestationJwtHeaderV1_3,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_3,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ClientAttestationError(\n `Unexpected error during wallet attestation creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\n\n/**\n * JWT Header schema for IT-Wallet v1.3 Wallet Attestation\n *\n * Version 1.3 specifics:\n * - x5c is REQUIRED\n * - trust_chain is OPTIONAL\n */\nexport const zWalletAttestationJwtHeaderV1_3 = z\n .object({\n ...zJwtHeader.shape,\n trust_chain: z.array(z.string()).nonempty().optional(), // OPTIONAL in v1.3\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: z.array(z.string()).nonempty(), // REQUIRED in v1.3\n })\n .passthrough();\n\n/**\n * JWT Payload schema for IT-Wallet v1.3 Wallet Attestation\n *\n * Version 1.3 specifics:\n * - Supports nbf (not before) claim\n * - Supports status claim for revocation mechanisms\n */\nexport const zWalletAttestationJwtPayloadV1_3 = z\n .object({\n ...zJwtPayload.shape,\n cnf: z.object({\n jwk: zJwk,\n }),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n nbf: z.number().optional(), // NEW in v1.3\n status: z\n .object({\n status_list: z.object({\n idx: z.number().int(),\n uri: z.string(),\n }),\n })\n .optional(), // NEW in v1.3 - status object for revocation\n sub: z.string(),\n wallet_link: z.string().url().optional(),\n wallet_name: z.string().optional(),\n })\n .passthrough();\n\n/**\n * Wallet Attestation JWT type for v1.3\n * The JWT is returned as a compact string\n */\nexport type WalletAttestationJwtV1_3 = string;\n\n/**\n * Zod schema for wallet attestation JWT validation (v1.3)\n * Validates that the result is a non-empty string\n */\nexport const zWalletAttestationJwtV1_3 = z.string().min(1);\n","import {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { BaseVerifyWalletAttestationJwtOptions } from \"../types\";\nimport { verifyWalletAttestationBase } from \"../verify-wallet-attestation-jwt-base\";\nimport {\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_3\n extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_3 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_3,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n );\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport { verifyClientAttestationPopJwt } from \"./client-attestation-pop\";\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport { verifyWalletAttestationJwt } from \"./wallet-attestation\";\n\nexport interface ClientAttestationOptions {\n /**\n * The client attestation DPoP JWT provided in the request.\n */\n clientAttestationPopJwt: string;\n\n /**\n * Whether to ensure that the key used in client attestation confirmation\n * is the same key used for DPoP. This only has effect if both DPoP and client\n * attestations are present.\n *\n * @default false\n */\n ensureConfirmationKeyMatchesDpopKey?: boolean;\n\n /**\n * The wallet attestation JWT provided in the request.\n */\n walletAttestationJwt: string;\n}\n\nexport interface VerifyClientAttestationOptions {\n /**\n * The authorization server metadata.\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * Callbacks for hashing and JWT verification.\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * The client attestation options.\n */\n clientAttestation: ClientAttestationOptions;\n\n /**\n * The IT-Wallet SDK configuration, used to select the correct version-specific\n * validation schema for the wallet attestation JWT.\n */\n config: IoWalletSdkConfig;\n\n /**\n * The DPoP JWK thumbprint value, if DPoP is being used in the request.\n */\n dpopJwkThumbprint?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The client id provided in the authorization request, if any.\n *\n * Pass this when the authorization request includes a `client_id` parameter.\n * The function will verify that it matches the `sub` claim in the client attestation JWT.\n * If not provided, no client_id validation is performed.\n */\n requestClientId?: string;\n}\n\nexport async function verifyClientAttestation(\n options: VerifyClientAttestationOptions,\n) {\n if (\n !options.clientAttestation.walletAttestationJwt ||\n !options.clientAttestation.clientAttestationPopJwt\n ) {\n throw new Oauth2Error(\n `Missing required client attestation parameters in the request. Make sure to provide the '${oauthClientAttestationHeader}' and '${oauthClientAttestationPopHeader}' header values.`,\n );\n }\n\n const clientAttestation = await verifyWalletAttestationJwt({\n callbacks: options.callbacks,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: options.config as any,\n now: options.now,\n walletAttestationJwt: options.clientAttestation.walletAttestationJwt,\n });\n\n const clientAttestationPop = await verifyClientAttestationPopJwt({\n authorizationServer: options.authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestationPopJwt: options.clientAttestation.clientAttestationPopJwt,\n clientAttestationPublicJwk: clientAttestation.payload.cnf.jwk,\n now: options.now,\n });\n\n if (\n options.requestClientId &&\n options.requestClientId !== clientAttestation.payload.sub\n ) {\n // Ensure the client id matches with the client id provided in the authorization request\n throw new Oauth2Error(\n `The client_id '${options.requestClientId}' in the request does not match the client id '${clientAttestation.payload.sub}' in the client attestation`,\n );\n }\n\n if (\n options.clientAttestation.ensureConfirmationKeyMatchesDpopKey &&\n options.dpopJwkThumbprint\n ) {\n const clientAttestationJkt = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: clientAttestation.payload.cnf.jwk,\n });\n\n if (clientAttestationJkt !== options.dpopJwkThumbprint) {\n throw new Oauth2Error(\n \"Expected the DPoP JWK thumbprint value to match the JWK thumbprint of the client attestation confirmation JWK. Ensure both DPoP and client attestation use the same key.\",\n );\n }\n }\n\n return {\n clientAttestation,\n clientAttestationPop,\n };\n}\n","import { zCompactJwt } from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport * as V1_0 from \"./v1.0\";\nimport * as V1_3 from \"./v1.3\";\n\nfunction isV1_0Options(\n options: VerifyWalletAttestationJwtOptions,\n): options is V1_0.VerifyWalletAttestationJwtOptionsV1_0 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0;\n}\n\nfunction isV1_3Options(\n options: VerifyWalletAttestationJwtOptions,\n): options is V1_3.VerifyWalletAttestationJwtOptionsV1_3 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3;\n}\n\nexport type VerifiedWalletAttestationJwt =\n | V1_0.VerifiedWalletAttestationJwtV1_0\n | V1_3.VerifiedWalletAttestationJwtV1_3;\n\nexport type VerifyWalletAttestationJwtOptions =\n | V1_0.VerifyWalletAttestationJwtOptionsV1_0\n | V1_3.VerifyWalletAttestationJwtOptionsV1_3;\n\nexport async function verifyWalletAttestationJwt(\n options: V1_0.VerifyWalletAttestationJwtOptionsV1_0,\n): Promise<V1_0.VerifiedWalletAttestationJwtV1_0>;\n\nexport async function verifyWalletAttestationJwt(\n options: V1_3.VerifyWalletAttestationJwtOptionsV1_3,\n): Promise<V1_3.VerifiedWalletAttestationJwtV1_3>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptions,\n): Promise<VerifiedWalletAttestationJwt> {\n const version = options.config.itWalletSpecsVersion;\n\n if (isV1_0Options(options)) {\n return V1_0.verifyWalletAttestationJwt(options);\n }\n\n if (isV1_3Options(options)) {\n return V1_3.verifyWalletAttestationJwt(options);\n }\n\n throw new ItWalletSpecsVersionError(\"verifyWalletAttestationJwt\", version, [\n ItWalletSpecsVersion.V1_0,\n ItWalletSpecsVersion.V1_3,\n ]);\n}\n\nexport function extractClientAttestationJwtsFromHeaders(headers: FetchHeaders):\n | {\n clientAttestationPopHeader: string;\n valid: true;\n walletAttestationHeader: string;\n }\n | {\n clientAttestationPopHeader?: undefined;\n valid: true;\n walletAttestationHeader?: undefined;\n }\n | { valid: false } {\n const walletAttestationHeader = headers.get(oauthClientAttestationHeader);\n const clientAttestationPopHeader = headers.get(\n oauthClientAttestationPopHeader,\n );\n\n if (!walletAttestationHeader && !clientAttestationPopHeader) {\n return { valid: true };\n }\n\n if (!walletAttestationHeader || !clientAttestationPopHeader) {\n return { valid: false };\n }\n\n if (\n !zCompactJwt.safeParse(walletAttestationHeader).success ||\n !zCompactJwt.safeParse(clientAttestationPopHeader).success\n ) {\n return { valid: false };\n }\n\n return {\n clientAttestationPopHeader,\n valid: true,\n walletAttestationHeader,\n } as const;\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport { htuFromRequestUrl } from \"./dpop-utils\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function extractDpopJwtFromHeaders(\n headers: FetchHeaders,\n): { dpopJwt?: string; valid: true } | { valid: false } {\n const dpopJwt = headers.get(\"DPoP\");\n\n if (!dpopJwt) {\n return { valid: true };\n }\n\n if (!zCompactJwt.safeParse(dpopJwt).success) {\n return { valid: false };\n }\n\n return { dpopJwt, valid: true };\n}\n","export const htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zHttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { zJwk } from \"../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: z.string().url(),\n iat: z.number().int().nonnegative(),\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n","import {\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n decodeUtf8String,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\nimport { htuFromRequestUrl } from \"./dpop-utils\";\nimport { zDpopJwtHeader, zDpopJwtPayload } from \"./z-dpop\";\n\nexport interface VerifyTokenDPoPOptions {\n /**\n * Access token to which the dpop jwt is bound. If provided the sha-256 hash of the\n * access token needs to match the 'ath' claim.\n */\n accessToken?: string;\n\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * Callbacks used for verifying dpop jwt\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * The compact dpop jwt.\n */\n dpopJwt: string;\n\n /**\n * The expected jwk thumprint 'jti' confirmation method. If provided the thumprint of the\n * jwk used to sign the dpop jwt must match this provided thumbprint value. The 'jti' value\n * can be extracted from the access token payload, or if opaque tokens are used can be retrieved\n * using token introspection.\n */\n expectedJwkThumbprint?: string;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The request for which to verify the dpop jwt\n */\n request: RequestLike;\n}\n\nexport async function verifyTokenDPoP(options: VerifyTokenDPoPOptions) {\n const { header, payload } = decodeJwt({\n headerSchema: zDpopJwtHeader,\n jwt: options.dpopJwt,\n payloadSchema: zDpopJwtPayload,\n });\n\n if (\n options.allowedSigningAlgs &&\n !options.allowedSigningAlgs.includes(header.alg)\n ) {\n throw new Oauth2Error(\n `dpop jwt uses alg value '${header.alg}' but allowed dpop signing alg values are ${options.allowedSigningAlgs.join(\", \")}.`,\n );\n }\n\n if (options.expectedNonce) {\n if (!payload.nonce) {\n throw new Oauth2Error(\n `Dpop jwt does not have a nonce value, but expected nonce value '${options.expectedNonce}'`,\n );\n }\n\n if (payload.nonce !== options.expectedNonce) {\n throw new Oauth2Error(\n `Dpop jwt contains nonce value '${payload.nonce}', but expected nonce value '${options.expectedNonce}'`,\n );\n }\n }\n\n if (options.request.method !== payload.htm) {\n throw new Oauth2Error(\n `Dpop jwt contains htm value '${payload.htm}', but expected htm value '${options.request.method}'`,\n );\n }\n\n const expectedHtu = htuFromRequestUrl(options.request.url);\n if (expectedHtu !== payload.htu) {\n throw new Oauth2Error(\n `Dpop jwt contains htu value '${payload.htu}', but expected htu value '${expectedHtu}'.`,\n );\n }\n\n if (options.accessToken) {\n const expectedAth = encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n );\n\n if (!payload.ath) {\n throw new Oauth2Error(\n `Dpop jwt does not have a ath value, but expected ath value '${expectedAth}'.`,\n );\n }\n\n if (payload.ath !== expectedAth) {\n throw new Oauth2Error(\n `Dpop jwt contains ath value '${payload.ath}', but expected ath value '${expectedAth}'.`,\n );\n }\n }\n\n const jwkThumbprint = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: header.jwk,\n });\n\n if (\n options.expectedJwkThumbprint &&\n options.expectedJwkThumbprint !== jwkThumbprint\n ) {\n throw new Oauth2Error(\n `Dpop is signed with jwk with thumbprint value '${jwkThumbprint}', but expect jwk thumbprint value '${options.expectedJwkThumbprint}'`,\n );\n }\n\n await verifyJwt({\n compact: options.dpopJwt,\n errorMessage: \"dpop jwt verification failed\",\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: header.jwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n jwkThumbprint,\n payload,\n };\n}\n","import { z } from \"zod\";\n\nexport const zAuthorizationCodeGrantIdentifier =\n z.literal(\"authorization_code\");\nexport const authorizationCodeGrantIdentifier =\n zAuthorizationCodeGrantIdentifier.value;\nexport type AuthorizationCodeGrantIdentifier = z.infer<\n typeof zAuthorizationCodeGrantIdentifier\n>;\n\nexport const zRefreshTokenGrantIdentifier = z.literal(\"refresh_token\");\nexport const refreshTokenGrantIdentifier = zRefreshTokenGrantIdentifier.value;\nexport type RefreshTokenGrantIdentifier = z.infer<\n typeof zRefreshTokenGrantIdentifier\n>;\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport const PkceCodeChallengeMethod = {\n Plain: \"plain\",\n S256: \"S256\",\n} as const;\n\nexport type PkceCodeChallengeMethod =\n (typeof PkceCodeChallengeMethod)[keyof typeof PkceCodeChallengeMethod];\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientAttestationOptions,\n VerifiedClientAttestationPopJwt,\n VerifiedWalletAttestationJwt,\n verifyClientAttestation,\n} from \"../client-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { PkceCodeChallengeMethod, verifyPkce } from \"../pkce\";\nimport { verifyTokenDPoP } from \"../token-dpop\";\nimport { ParsedAccessTokenAuthorizationCodeRequestGrant } from \"./parse-token-request\";\nimport { AccessTokenRequest } from \"./z-token\";\n\nexport interface VerifyAccessTokenRequestPkce {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport interface VerifyAccessTokenRequestDpop {\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * The dpop jwt from the access token request\n */\n jwt: string;\n}\n\nexport interface VerifyAccessTokenRequestOptions {\n /**\n * The access token request to verify\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * The authorization server metadata\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * Callbacks used during verification\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * Options for verifying the client attestation\n */\n clientAttestation: ClientAttestationOptions;\n /**\n * The expiration date of the authorization code\n */\n codeExpiresAt?: Date;\n\n config: IoWalletSdkConfig;\n\n /**\n * The dpop verification options\n */\n dpop: VerifyAccessTokenRequestDpop;\n\n /**\n * The expected authorization code\n */\n expectedCode: string;\n\n /**\n * The parsed authorization code grant\n */\n grant: ParsedAccessTokenAuthorizationCodeRequestGrant;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The pkce options including code verifier, challenge and method\n */\n pkce: VerifyAccessTokenRequestPkce;\n\n /**\n * The HTTP request information\n */\n request: RequestLike;\n}\n\nexport interface VerifyAccessTokenRequestResult {\n clientAttestation: {\n clientAttestation: VerifiedWalletAttestationJwt;\n clientAttestationPop: VerifiedClientAttestationPopJwt;\n };\n\n dpop: {\n jwk: Jwk;\n\n /**\n * base64url encoding of the JWK SHA-256 Thumbprint (according to [RFC7638])\n * of the DPoP public key (in JWK format)\n */\n jwkThumbprint: string;\n };\n}\n\n/**\n * Verifies an authorization code token request by validating PKCE, DPoP, and client attestation.\n *\n * This function performs comprehensive validation of an OAuth 2.0 authorization code token request\n * according to Italian IT-Wallet specifications, including:\n * - PKCE code verifier validation against the stored code challenge\n * - DPoP proof JWT verification and JWK thumbprint extraction\n * - Client attestation JWT and attestation PoP JWT verification\n * - Authorization code validity and expiration checks\n *\n * @param options - Configuration options for token request verification\n * @returns A promise that resolves with verified client attestation and DPoP information\n * @throws {Oauth2Error} If the authorization code is invalid or expired\n * @throws {Oauth2Error} If PKCE verification fails\n * @throws {Oauth2Error} If DPoP verification fails\n * @throws {Oauth2Error} If client attestation verification fails\n *\n * @example\n * ```typescript\n * const result = await verifyAccessTokenRequest({\n * accessTokenRequest: parsedRequest,\n * authorizationServerMetadata: metadata,\n * callbacks: { hash, verifyJwt },\n * clientAttestation: { jwt: \"...\", popJwt: \"...\" },\n * codeExpiresAt: new Date(Date.now() + 600000),\n * dpop: { jwt: dpopJwt, allowedSigningAlgs: [\"ES256\"] },\n * expectedCode: \"auth_code_123\",\n * grant: parsedGrant,\n * pkce: { codeChallenge, codeChallengeMethod: \"S256\", codeVerifier },\n * request: httpRequest,\n * });\n * ```\n */\nexport async function verifyAccessTokenRequest(\n options: VerifyAccessTokenRequestOptions,\n): Promise<VerifyAccessTokenRequestResult> {\n await verifyPkce({\n callbacks: options.callbacks,\n codeChallenge: options.pkce.codeChallenge,\n codeChallengeMethod: options.pkce.codeChallengeMethod,\n codeVerifier: options.pkce.codeVerifier,\n });\n\n const { header, jwkThumbprint } = await verifyTokenDPoP({\n allowedSigningAlgs: options.dpop.allowedSigningAlgs,\n callbacks: options.callbacks,\n dpopJwt: options.dpop.jwt,\n now: options.now,\n request: options.request,\n });\n\n const clientAttestationResult = await verifyClientAttestation({\n authorizationServerMetadata: options.authorizationServerMetadata,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestation,\n config: options.config,\n dpopJwkThumbprint: jwkThumbprint,\n now: options.now,\n });\n\n if (options.grant.code !== options.expectedCode) {\n throw new Oauth2Error(`Invalid 'code' provided`);\n }\n\n if (options.codeExpiresAt) {\n const now = options.now ?? new Date();\n\n if (now.getTime() > options.codeExpiresAt.getTime()) {\n throw new Oauth2Error(`Expired 'code' provided`);\n }\n }\n\n if (!header.jwk) {\n throw new Oauth2Error(\"DPoP header does not contain a JWK\");\n }\n\n return {\n clientAttestation: clientAttestationResult,\n dpop: { jwk: header.jwk, jwkThumbprint },\n };\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequest,\n PushedAuthorizationRequestSigned,\n PushedAuthorizationRequestUnsigned,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details?: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Authorization Server metadata for conditional JAR signing.\n * When require_signed_request_object is true, creates a signed JWT (JAR).\n * When require_signed_request_object is false, creates an unsigned authorization request.\n * Defaults to false (unsigned) if not provided.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5}\n */\n authorizationServerMetadata?: {\n require_signed_request_object?: boolean;\n };\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options. Required when `require_signed_request_object` is `true`\n * (enforced at the type level via function overloads). Not used in the\n * unsigned path and can be omitted.\n */\n dpop?: RequestDpopOptions;\n\n /**\n * Expiration time of the JWT. If not provided 1 hour will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope?: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\n/**\n * Creates a Pushed Authorization Request (PAR) for OAuth 2.0 authorization flows.\n *\n * This function conditionally creates signed JWT-Secured Authorization Requests (JAR)\n * based on the Authorization Server's `require_signed_request_object` metadata parameter\n * as defined in RFC 9101. The signing behavior enables compliance with both OAuth 2.0 PAR\n * (RFC 9126) and IT-Wallet v1.3.3 specifications.\n *\n * **Conditional JAR Signing:**\n * - When `require_signed_request_object` is `true`: Creates a signed JAR\n * - When `require_signed_request_object` is `false`: Creates an unsigned authorization request\n * - When metadata not provided: Defaults to unsigned (permissive)\n *\n * **Security Note:**\n * Disabling JAR signing (setting `require_signed_request_object: false`) should only be done\n * when the Authorization Server explicitly supports and allows unsigned requests. Signed\n * requests provide protection against request tampering and replay attacks.\n *\n * @param options - Configuration for creating the PAR\n * @param options.audience - The identifier of the Credential Issuer (used as JWT aud claim)\n * @param options.authorization_details - Fine-grained authorization requirements using JSON data structures\n * @param options.authorizationServerMetadata - Authorization Server metadata for conditional JAR signing\n * @param options.authorizationServerMetadata.require_signed_request_object -\n * When `true`, creates a signed JAR. When `false`, creates an unsigned authorization request.\n * Defaults to `false` if not provided (permissive).\n * @param options.callbacks - Cryptographic callback functions (generateRandom, hash, signJwt)\n * @param options.clientId - Thumbprint of the jwk value in the cnf parameter inside Wallet Attestation\n * @param options.codeChallengeMethodsSupported - Supported code challenge methods from Authorization Server\n * @param options.dpop - DPoP signer options (alg, publicJwk.kid). Required when JAR signing is enabled; omitted for unsigned requests\n * @param options.jti - Optional JWT ID for PAR (auto-generated if not provided)\n * @param options.pkceCodeVerifier - Optional PKCE code verifier (auto-generated if not provided)\n * @param options.redirectUri - Redirect URI for the authorization response\n * @param options.responseMode - Response mode (must be supported by Credential Issuer)\n * @param options.scope - OAuth 2.0 scope to request\n * @param options.state - Optional state parameter (auto-generated if not provided)\n * @param options.expiresAt - Optional JWT expiration time (defaults to 1 hour from issuedAt)\n * @param options.issuedAt - Optional JWT issued at time (defaults to current time)\n *\n * @returns A promise resolving to either:\n * - `PushedAuthorizationRequestSigned` when JAR signing is required (contains `request` JWT)\n * - `PushedAuthorizationRequestUnsigned` when JAR signing is not required (contains `authorizationRequest` object)\n *\n * @throws {PushedAuthorizationRequestError} If DPoP signer is missing required properties (alg, publicJwk.kid)\n * @throws {PushedAuthorizationRequestError} If PKCE code challenge method is not supported\n * @throws {ZodError} If authorization request parameters fail validation\n *\n * @example\n * // Example 1: Create signed PAR (explicit)\n * const signedPar = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * dpop: { signer: { alg: 'ES256', publicJwk: { kid: 'key-1' } } },\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'form_post.jwt',\n * scope: 'openid',\n * authorizationServerMetadata: {\n * require_signed_request_object: true // Creates signed JAR\n * }\n * });\n * // signedPar.request contains the signed JWT\n *\n * @example\n * // Example 2: Create unsigned PAR (when Authorization Server allows it)\n * const unsignedPar = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'query',\n * scope: 'openid',\n * authorizationServerMetadata: {\n * require_signed_request_object: false // Creates unsigned request — dpop not needed\n * }\n * });\n * // unsignedPar.authorizationRequest contains the plain object\n *\n * @example\n * // Example 3: Default behavior (no metadata - unsigned)\n * const par = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'form_post.jwt',\n * scope: 'openid'\n * // No authorizationServerMetadata — defaults to unsigned, dpop not needed\n * });\n * // par.authorizationRequest contains the plain object (permissive default)\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9126 RFC 9126 - OAuth 2.0 Pushed Authorization Requests}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101 RFC 9101 - JWT-Secured Authorization Request (JAR)}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5 - require_signed_request_object}\n */\n// Function overloads for type narrowing based on require_signed_request_object\nexport async function createPushedAuthorizationRequest(\n options: {\n authorizationServerMetadata: { require_signed_request_object: true };\n dpop: RequestDpopOptions;\n } & CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: {\n authorizationServerMetadata: { require_signed_request_object: false };\n } & CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestUnsigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest>;\n\n// Implementation\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest = zAuthorizationRequest.parse({\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n });\n\n // Check if JAR signing is required\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n if (requireSigned) {\n // Create signed JAR (JWT-Secured Authorization Request)\n const { dpop } = options;\n if (!dpop || !dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new PushedAuthorizationRequestError(\n \"DPoP signer must have alg and publicJwk.kid properties\",\n );\n }\n\n const iat = options.issuedAt ?? new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, JWT_EXPIRY_SECONDS);\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: dpop.signer.publicJwk.kid,\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n request: requestJwt.jwt,\n };\n } else {\n // Create unsigned authorization request\n return {\n authorizationRequest,\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n };\n }\n}\n","import z from \"zod\";\n\nconst zOpenidCredentialAuthorizationDetails = z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n});\n\nconst zItL2DocumentProofAuthorizationDetails = z.object({\n challenge_method: z.literal(\"mrtd+ias\"),\n challenge_redirect_uri: z.string().url(),\n idphinting: z.string().url(),\n type: z.literal(\"it_l2+document_proof\"),\n});\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z\n .array(\n z.discriminatedUnion(\"type\", [\n zOpenidCredentialAuthorizationDetails,\n zItL2DocumentProofAuthorizationDetails,\n ]),\n )\n .optional(),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n jti: z.string(),\n redirect_uri: z.string().url(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n })\n .passthrough()\n .refine(\n (data) =>\n data.authorization_details !== undefined || data.scope !== undefined,\n {\n message: \"Either 'authorization_details' or 'scope' must be provided.\",\n path: [\"authorization_details\"],\n },\n );\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n client_id: z\n .string()\n .describe(\n \"MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\",\n ),\n pkceCodeVerifier: z\n .string()\n .describe(\n \"Code verifier for PKCE. If not provided in CreatePushedAuthorizationRequestOptions, SDK will generate one.\",\n ),\n request: z\n .string()\n .describe(\n \"It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\",\n ),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationRequestUnsigned = z\n .object({\n authorizationRequest: zAuthorizationRequest.describe(\n \"The authorization request parameters as a plain object. \" +\n \"Used when require_signed_request_object is false.\",\n ),\n client_id: z\n .string()\n .describe(\n \"Thumbprint of the jwk value in the cnf parameter inside Wallet Attestation.\",\n ),\n pkceCodeVerifier: z\n .string()\n .describe(\n \"PKCE code verifier. Auto-generated if not provided in options.\",\n ),\n })\n .passthrough();\nexport type PushedAuthorizationRequestUnsigned = z.infer<\n typeof zPushedAuthorizationRequestUnsigned\n>;\n\n/**\n * Union type for Pushed Authorization Request - can be either signed (JAR) or unsigned.\n * The variant depends on the Authorization Server's require_signed_request_object metadata.\n */\nexport type PushedAuthorizationRequest =\n | PushedAuthorizationRequestSigned\n | PushedAuthorizationRequestUnsigned;\n\nexport function isPushedAuthorizationRequestSigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestSigned {\n return \"request\" in par && typeof par.request === \"string\";\n}\n\nexport function isPushedAuthorizationRequestUnsigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestUnsigned {\n return \"authorizationRequest\" in par;\n}\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequest,\n PushedAuthorizationResponse,\n isPushedAuthorizationRequestSigned,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The pushed authorization request to send. Accepts both signed (JAR) and unsigned variants\n * as returned by `createPushedAuthorizationRequest`. The correct form body is derived\n * automatically: signed requests POST `{ client_id, request }`, unsigned requests POST\n * every field from `authorizationRequest` as flat form parameters.\n */\n pushedAuthorizationRequest: PushedAuthorizationRequest;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response.\n *\n * Supports both signed (JAR) and unsigned PAR variants as produced by\n * `createPushedAuthorizationRequest`. The form body is built automatically:\n * - **Signed**: posts `{ client_id, request }`.\n * - **Unsigned**: posts every field from `authorizationRequest` as flat form\n * parameters, with object/array values (e.g. `authorization_details`)\n * JSON-serialised.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const body = isPushedAuthorizationRequestSigned(\n options.pushedAuthorizationRequest,\n )\n ? new URLSearchParams({\n client_id: options.pushedAuthorizationRequest.client_id,\n request: options.pushedAuthorizationRequest.request,\n })\n : toURLSearchParams(\n options.pushedAuthorizationRequest.authorizationRequest,\n );\n\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body,\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction toURLSearchParams(data: Record<string, unknown>): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","import type { RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { extractClientAttestationJwtsFromHeaders } from \"../client-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop\";\n\nexport interface ParseAuthorizationRequestOptions {\n request: RequestLike;\n}\n\nexport interface ParseAuthorizationRequestResult {\n /**\n * The client attestation jwts from the authorization request headers.\n * These have not been verified yet.\n */\n clientAttestation?: {\n clientAttestationPopJwt: string;\n walletAttestationJwt: string;\n };\n\n /**\n * The dpop jwt from the authorization request DPoP header.\n *\n * The signer of the jwt has not been verified yet, this only happens during verification.\n */\n dpop?: {\n jwt: string;\n };\n}\n\n/**\n * Parse an authorization request by extracting DPoP and client attestation\n * information from HTTP request headers.\n *\n * **Important:** This function performs extraction and basic format validation\n * but does NOT verify cryptographic signatures. JWT signature verification\n * should be performed separately using the appropriate verification functions.\n *\n * @returns Parsed authorization request result containing:\n * - `dpop` - DPoP information if present (jwt)\n * - `clientAttestation` - Client attestation JWTs if present\n *\n * @throws {Oauth2Error} When DPoP JWT format is invalid\n * @throws {Oauth2Error} When client attestation headers are incomplete\n */\nexport function parseAuthorizationRequest(\n options: ParseAuthorizationRequestOptions,\n): ParseAuthorizationRequestResult {\n // We only parse the dpop, we don't verify it yet\n const extractedDpopJwt = extractDpopJwtFromHeaders(options.request.headers);\n if (!extractedDpopJwt.valid) {\n throw new Oauth2Error(\n \"Request contains a 'DPoP' header, but the value is not a valid DPoP jwt\",\n );\n }\n\n // We only parse the client attestations, we don't verify it yet\n const extractedClientAttestationJwts =\n extractClientAttestationJwtsFromHeaders(options.request.headers);\n if (!extractedClientAttestationJwts.valid) {\n throw new Oauth2Error(\n \"Request contains client attestation header, but the values are not valid client attestation and client attestation PoP header.\",\n );\n }\n\n return {\n clientAttestation: extractedClientAttestationJwts.walletAttestationHeader\n ? {\n clientAttestationPopJwt:\n extractedClientAttestationJwts.clientAttestationPopHeader,\n walletAttestationJwt:\n extractedClientAttestationJwts.walletAttestationHeader,\n }\n : undefined,\n dpop: extractedDpopJwt.dpopJwt\n ? {\n jwt: extractedDpopJwt.dpopJwt,\n }\n : undefined,\n };\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n formatZodError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\nimport {\n isJarAuthorizationRequest,\n parseJarRequest,\n zJarAuthorizationRequest,\n} from \"../jar\";\nimport {\n ParseAuthorizationRequestResult,\n parseAuthorizationRequest,\n} from \"./parse-authorization-request\";\nimport {\n AuthorizationRequest,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nexport interface ParsePushedAuthorizationRequestOptions {\n authorizationRequest: unknown;\n callbacks: Pick<CallbackContext, \"fetch\">;\n request: RequestLike;\n}\n\nexport interface ParsePushedAuthorizationRequestResult\n extends ParseAuthorizationRequestResult {\n authorizationRequest: AuthorizationRequest;\n\n /**\n * The JWT-secured request object, if the request was pushed as a JAR.\n * May be undefined if the request object is not a JAR.\n */\n authorizationRequestJwt?: string;\n}\n\n/**\n * Parses and validates a pushed authorization request (PAR).\n *\n * Handles both standard authorization requests and JWT-secured Authorization Requests (JAR).\n * When a JAR is provided, it validates the JWT structure, decodes it, and extracts the\n * authorization request from the payload. Also extracts client attestation and DPoP proofs\n * from the HTTP request headers.\n *\n * @param options - Configuration for parsing the pushed authorization request\n * @param options.authorizationRequest - The authorization request data to parse (can be standard or JAR format)\n * @param options.callbacks - Callbacks for external operations (requires `fetch` for JAR validation)\n * @param options.request - The HTTP request object containing headers for client attestation and DPoP\n * @returns A promise resolving to the parsed authorization request with extracted metadata\n * @throws {Oauth2Error} When the authorization request is invalid or cannot be parsed\n */\nexport async function parsePushedAuthorizationRequest(\n options: ParsePushedAuthorizationRequestOptions,\n): Promise<ParsePushedAuthorizationRequestResult> {\n const parsed = parseWithErrorHandling(\n z.union([zAuthorizationRequest, zJarAuthorizationRequest]),\n options.authorizationRequest,\n \"Invalid authorization request. Could not parse authorization request or jar.\",\n );\n\n let parsedAuthorizationRequest: ReturnType<\n typeof zAuthorizationRequest.safeParse\n >;\n\n let authorizationRequestJwt: string | undefined;\n if (isJarAuthorizationRequest(parsed)) {\n const parsedJar = await parseJarRequest({\n callbacks: options.callbacks,\n jarRequestParams: parsed,\n });\n\n const jwt = decodeJwt({ jwt: parsedJar.authorizationRequestJwt });\n\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(jwt.payload);\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2Error(\n `Invalid authorization request. Could not parse jar request payload.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n );\n }\n\n authorizationRequestJwt = parsedJar.authorizationRequestJwt;\n } else {\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(\n options.authorizationRequest,\n );\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2Error(\n `Error occurred during validation of pushed authorization request.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n );\n }\n }\n\n const authorizationRequest = parsedAuthorizationRequest.data;\n const { clientAttestation, dpop } = parseAuthorizationRequest({\n request: options.request,\n });\n\n return {\n authorizationRequest,\n authorizationRequestJwt,\n clientAttestation,\n dpop,\n };\n}\n","import { type CallbackContext } from \"@openid4vc/oauth2\";\nimport { addSecondsToDate, dateToSeconds } from \"@pagopa/io-wallet-utils\";\n\nimport type { Jwk } from \"../common/jwk/z-jwk\";\nimport type { JweEncryptor, JwtSigner } from \"../common/jwt/z-jwt\";\nimport type {\n JarAuthorizationRequest,\n JarRequestObjectHeader,\n JarRequestObjectPayload,\n} from \"./z-jar\";\n\nimport { Oauth2Error } from \"../errors\";\n\nexport interface CreateJarRequestOptions {\n /**\n * Additional claims merged into the request object payload before\n * `authorizationRequestPayload`.\n */\n additionalJwtPayload?: Record<string, unknown>;\n\n /**\n * Authorization request claims used as JWT header parameters.\n */\n authorizationRequestHeader: JarRequestObjectHeader;\n\n /**\n * Authorization request claims used as JWT payload.\n */\n authorizationRequestPayload: JarRequestObjectPayload;\n\n /**\n * Cryptographic callbacks used to sign and optionally encrypt the JAR.\n */\n callbacks: Partial<Pick<CallbackContext, \"encryptJwe\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * Request object lifetime in seconds from `now`.\n */\n expiresInSeconds: number;\n\n /**\n * Encryptor configuration. When provided, the signed request object is wrapped\n * as JWE and returned as encrypted `request` value.\n */\n jweEncryptor?: JweEncryptor;\n\n /**\n * Signer configuration used to produce the request object JWT.\n */\n jwtSigner: JwtSigner;\n\n /**\n * Date that should be used as now. If not provided current date will be used.\n */\n now?: Date;\n\n /**\n * Optional request URI for by-reference JAR transmission.\n * When provided, `jarAuthorizationRequest` will include `request_uri` instead of `request`.\n */\n requestUri?: string;\n}\n\nexport interface CreateJarRequestResult {\n /**\n * The signed (and optionally encrypted) JWT string representing the authorization request.\n * This value is included in `jarAuthorizationRequest` when `requestUri` is not provided.\n */\n authorizationRequestJwt: string;\n\n /**\n * The JWK used for encryption when `jweEncryptor` is provided, otherwise undefined.\n */\n encryptionJwk?: Jwk;\n\n /**\n * The JAR authorization request parameters to be sent to the authorization endpoint.\n * Contains either `request` or `request_uri` depending on the presence of `requestUri` in options.\n */\n jarAuthorizationRequest: JarAuthorizationRequest;\n\n /**\n * The JWK used for signing the request object JWT.\n */\n signerJwk: Jwk;\n}\n\n/**\n * Creates a JWT Secured Authorization Request (JAR) request payload.\n *\n * The request object is always signed, and optionally encrypted when `jweEncryptor`\n * is provided. The returned `jarAuthorizationRequest` is created in one of two forms:\n * - by-value, with `request`\n * - by-reference, with `request_uri`\n *\n * @param options - Parameters used to create the JAR request\n * @param options.additionalJwtPayload - Additional JWT claims merged before authorization claims\n * @param options.authorizationRequestPayload - Base authorization request JWT payload\n * @param options.authorizationRequestHeader - JWT header parameters for the request object\n * @param options.callbacks - Callback context with required `signJwt` and optional `encryptJwe`\n * @param options.expiresInSeconds - JWT expiration offset in seconds\n * @param options.jweEncryptor - Optional JWE encryptor to wrap the signed JWT\n * @param options.jwtSigner - JWT signer used for request object signing\n * @param options.now - Optional reference time used for `iat` and `exp`\n * @param options.requestUri - Optional request URI for by-reference transmission\n *\n * @returns Signed (and optionally encrypted) authorization request data, signer key material,\n * and JAR request parameters for transmission.\n */\nexport async function createJarRequest(\n options: CreateJarRequestOptions,\n): Promise<CreateJarRequestResult> {\n const {\n authorizationRequestHeader,\n authorizationRequestPayload,\n callbacks,\n jweEncryptor,\n jwtSigner,\n requestUri,\n } = options;\n\n let authorizationRequestJwt: string | undefined;\n let encryptionJwk: Jwk | undefined;\n\n const now = options.now ?? new Date();\n\n const { jwt, signerJwk } = await callbacks.signJwt(jwtSigner, {\n header: authorizationRequestHeader,\n payload: {\n ...options.additionalJwtPayload,\n ...authorizationRequestPayload,\n exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n iat: dateToSeconds(now),\n },\n });\n\n authorizationRequestJwt = jwt;\n\n if (jweEncryptor) {\n if (!callbacks.encryptJwe) {\n throw new Oauth2Error(\n \"callbacks.encryptJwe is required when jweEncryptor is provided\",\n );\n }\n const encryptionResult = await callbacks.encryptJwe(\n jweEncryptor,\n authorizationRequestJwt,\n );\n authorizationRequestJwt = encryptionResult.jwe;\n encryptionJwk = encryptionResult.encryptionJwk;\n }\n\n const client_id = authorizationRequestPayload.client_id;\n const jarAuthorizationRequest: JarAuthorizationRequest = requestUri\n ? { client_id, request_uri: requestUri }\n : { client_id, request: authorizationRequestJwt };\n\n return {\n authorizationRequestJwt,\n encryptionJwk,\n jarAuthorizationRequest,\n signerJwk,\n };\n}\n","import {\n ContentType,\n type Fetch,\n createFetcher,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\n\nexport async function fetchJarRequestObject(options: {\n fetch?: Fetch;\n requestUri: string;\n}): Promise<string> {\n const { fetch, requestUri } = options;\n\n /**\n * Prioritizes OAuth-specific JWT format, with fallbacks to generic JWT and plain text.\n * Quality values (q) indicate preference: 1.0 (default) > 0.9.\n */\n const JAR_ACCEPT_HEADER = [\n ContentType.OAuthAuthorizationRequestJwt, // Preferred: application/oauth-authz-req+jwt\n `${ContentType.Jwt};q=0.9`, // Fallback: application/jwt\n \"text/plain\", // Final fallback: text/plain\n ].join(\", \");\n\n const response = await createFetcher(fetch)(requestUri, {\n headers: {\n Accept: JAR_ACCEPT_HEADER,\n },\n method: \"GET\",\n }).catch(() => {\n throw new Oauth2Error(\n `Fetching request_object from request_uri '${requestUri}' failed`,\n );\n });\n\n if (!response.ok) {\n throw new Oauth2Error(\n `Fetching request_object from request_uri '${requestUri}' failed with status code '${response.status}'.`,\n );\n }\n\n return await response.text();\n}\n","import { Oauth2Error } from \"../errors\";\nimport { JarAuthorizationRequest } from \"./z-jar\";\n\nexport function validateJarRequestParams(options: {\n jarRequestParams: JarAuthorizationRequest;\n}) {\n const { jarRequestParams } = options;\n\n if (jarRequestParams.request && jarRequestParams.request_uri) {\n throw new Oauth2Error(\n \"request and request_uri cannot both be present in a JAR request\",\n );\n }\n\n if (!jarRequestParams.request && !jarRequestParams.request_uri) {\n throw new Oauth2Error(\"request or request_uri must be present\");\n }\n\n return jarRequestParams as (\n | { request: string; request_uri?: never }\n | { request?: never; request_uri: string }\n ) &\n JarAuthorizationRequest;\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\n\nimport { fetchJarRequestObject } from \"./fetch-jar-request-object\";\nimport { validateJarRequestParams } from \"./validate-jar-request\";\nimport { JarAuthorizationRequest } from \"./z-jar\";\n\nexport interface ParsedJarRequestOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n jarRequestParams: JarAuthorizationRequest;\n}\n\nexport interface ParsedJarRequest {\n authorizationRequestJwt: string;\n sendBy: \"reference\" | \"value\";\n}\n\nexport function isJarAuthorizationRequest(\n request: JarAuthorizationRequest,\n): request is JarAuthorizationRequest {\n return \"request\" in request || \"request_uri\" in request;\n}\n\n/**\n * Parse a JAR (JWT Secured Authorization Request) request by validating and optionally fetch from uri.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns An object containing the transmission method ('value' or 'reference') and the JWT request object.\n */\nexport async function parseJarRequest(\n options: ParsedJarRequestOptions,\n): Promise<ParsedJarRequest> {\n const { callbacks } = options;\n\n const jarRequestParams = {\n ...validateJarRequestParams(options),\n ...options.jarRequestParams,\n } as JarAuthorizationRequest & ReturnType<typeof validateJarRequestParams>;\n\n const sendBy = jarRequestParams.request ? \"value\" : \"reference\";\n\n const authorizationRequestJwt =\n jarRequestParams.request ??\n (await fetchJarRequestObject({\n fetch: callbacks.fetch,\n requestUri: jarRequestParams.request_uri,\n }));\n\n return { authorizationRequestJwt, sendBy };\n}\n","import {\n CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n decodeJwt,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport {\n JarRequestObjectPayload,\n jwtAuthorizationRequestJwtHeaderTyp,\n signedAuthorizationRequestJwtHeaderTyp,\n zJarRequestObjectPayload,\n} from \"./z-jar\";\n\nexport interface VerifyJarRequestOptions {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jarRequestParams: {\n client_id?: string;\n };\n jwtSigner: JwtSigner;\n now?: Date;\n}\n\nexport interface VerifiedJarRequest {\n authorizationRequestPayload: JarRequestObjectPayload;\n jwt: {\n payload: JarRequestObjectPayload;\n } & Omit<ReturnType<typeof decodeJwt>, \"payload\">;\n signer: JwtSignerWithJwk;\n}\n\n/**\n * Verifies a JAR (JWT Secured Authorization Request) request by validating and verifying signatures.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns The verified authorization request parameters and metadata\n */\nexport async function verifyJarRequest(\n options: VerifyJarRequestOptions,\n): Promise<VerifiedJarRequest> {\n const { authorizationRequestJwt, callbacks, jarRequestParams, jwtSigner } =\n options;\n\n /* Encryption is not supported */\n const requestObjectIsEncrypted = zCompactJwe.safeParse(\n authorizationRequestJwt,\n ).success;\n if (requestObjectIsEncrypted) {\n throw new Oauth2Error(\"Encrypted JWE request objects are not supported.\");\n }\n\n const requestIsSigned = zCompactJwt.safeParse(\n authorizationRequestJwt,\n ).success;\n if (!requestIsSigned) {\n throw new Oauth2Error(\"JAR request object is not a valid JWT.\");\n }\n\n const { authorizationRequestPayload, jwt, signer } =\n await verifyJarRequestObject({\n authorizationRequestJwt,\n callbacks,\n jwtSigner,\n });\n\n if (!authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n 'Jar Request Object is missing the required \"client_id\" field.',\n );\n }\n\n // Expect the client_id from the jar request to match the payload\n if (jarRequestParams.client_id !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n \"client_id does not match the request object client_id.\",\n );\n }\n\n if (jwt.payload.iss !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\"iss claim in request JWT does not match client_id\");\n }\n\n // RFC 9101 §4: exp claim MUST be present and not in the past\n if (jwt.payload.exp === undefined) {\n throw new Oauth2Error(\"exp claim in request JWT is missing\");\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (nowSeconds > jwt.payload.exp) {\n throw new Oauth2Error(\"exp claim in request JWT is expired\");\n }\n\n // IT-Wallet requirement: iat MUST be present\n if (jwt.payload.iat === undefined) {\n throw new Oauth2Error(\"iat claim in request JWT is missing\");\n }\n\n // IT-Wallet requirement: iat MUST not be more than 5 minutes in the past\n const MAX_IAT_AGE_SECONDS = 5 * 60;\n if (nowSeconds - jwt.payload.iat > MAX_IAT_AGE_SECONDS) {\n throw new Oauth2Error(\n \"iat claim in request JWT is too old (must be within 5 minutes)\",\n );\n }\n\n // IT-Wallet requirement: iat MUST not be more than clock-skew tolerance in the future\n const CLOCK_SKEW_TOLERANCE_SECONDS = 60;\n if (jwt.payload.iat - nowSeconds > CLOCK_SKEW_TOLERANCE_SECONDS) {\n throw new Oauth2Error(\"iat claim in request JWT is too far in the future\");\n }\n\n return {\n authorizationRequestPayload,\n jwt,\n signer,\n };\n}\n\nasync function verifyJarRequestObject(options: {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jwtSigner: JwtSigner;\n}) {\n const { authorizationRequestJwt, callbacks, jwtSigner } = options;\n\n const jwt = decodeJwt({ jwt: authorizationRequestJwt });\n const authorizationRequestPayload = parseWithErrorHandling(\n zJarRequestObjectPayload,\n jwt.payload,\n );\n\n const { signer } = await verifyJwt({\n compact: authorizationRequestJwt,\n header: jwt.header,\n payload: authorizationRequestPayload,\n signer: jwtSigner,\n\n verifyJwtCallback: callbacks.verifyJwt,\n });\n\n // Some existing deployments may alternatively be using both type\n if (\n jwt.header.typ !== signedAuthorizationRequestJwtHeaderTyp &&\n jwt.header.typ !== jwtAuthorizationRequestJwtHeaderTyp\n ) {\n throw new Oauth2Error(\n `Invalid Jar Request Object typ header. Expected \"oauth-authz-req+jwt\" or \"jwt\", received \"${jwt.header.typ}\".`,\n );\n }\n\n return {\n authorizationRequestPayload,\n jwt: {\n ...jwt,\n payload: authorizationRequestPayload,\n },\n signer,\n };\n}\n","import z from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zJarAuthorizationRequest = z\n .object({\n client_id: z.optional(z.string()),\n request: z.optional(z.string()),\n request_uri: z.string().url().optional(),\n })\n .passthrough();\n\nexport type JarAuthorizationRequest = z.infer<typeof zJarAuthorizationRequest>;\n\nexport const zJarRequestObjectPayload = z\n .object({\n ...zJwtPayload.shape,\n client_id: z.string(),\n })\n .passthrough();\n\nexport type JarRequestObjectPayload = z.infer<typeof zJarRequestObjectPayload>;\n\nexport const zSignedAuthorizationRequestJwtHeaderTyp = z.literal(\n \"oauth-authz-req+jwt\",\n);\n\nexport const zJarRequestObjectHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n })\n .passthrough();\n\nexport type JarRequestObjectHeader = z.infer<typeof zJarRequestObjectHeader>;\n\nexport const signedAuthorizationRequestJwtHeaderTyp =\n zSignedAuthorizationRequestJwtHeaderTyp.value;\n\nconst zJwtAuthorizationRequestJwtHeaderTyp = z.literal(\"jwt\");\nexport const jwtAuthorizationRequestJwtHeaderTyp =\n zJwtAuthorizationRequestJwtHeaderTyp.value;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientAttestationOptions,\n VerifiedClientAttestationPopJwt,\n VerifiedWalletAttestationJwt,\n verifyClientAttestation,\n} from \"../client-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { verifyTokenDPoP } from \"../token-dpop\";\n\nexport interface VerifyAuthorizationRequestDPoP {\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * The dpop jwt from the pushed authorization request.\n * If dpop is required, `jwt` MUST be provided\n */\n jwt?: string;\n\n /**\n * Whether dpop is required.\n */\n required?: boolean;\n}\n\nexport interface VerifyAuthorizationRequestResult {\n /**\n * The verified client attestation if any were provided.\n */\n clientAttestation?: {\n clientAttestation: VerifiedWalletAttestationJwt;\n clientAttestationPop: VerifiedClientAttestationPopJwt;\n };\n\n dpop?: {\n /**\n * The JWK will be returned if a DPoP proof was provided in the header.\n */\n jwk?: Jwk;\n\n /**\n * base64url encoding of the JWK SHA-256 Thumbprint (according to [RFC7638])\n * of the DPoP public key (in JWK format).\n *\n * This will always be returned if dpop is used for the PAR endpoint\n */\n jwkThumbprint: string;\n };\n}\n\nexport interface VerifyAuthorizationRequestOptions {\n authorizationRequest: {\n client_id?: string;\n };\n\n authorizationServerMetadata: AuthorizationServerMetadata;\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n clientAttestation: ClientAttestationOptions;\n config: IoWalletSdkConfig;\n dpop?: VerifyAuthorizationRequestDPoP;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n request: RequestLike;\n}\n\n/**\n * Verifies an authorization request by validating DPoP and client attestation credentials.\n *\n * This function performs cryptographic verification of DPoP proofs and client attestation\n * JWTs extracted from authorization request headers. It validates signatures, checks\n * expiration times, and optionally ensures that DPoP and client attestation use the same key.\n *\n * **Important:** This function performs verification only. Use `parseAuthorizationRequest`\n * first to extract the necessary JWTs from request headers.\n *\n * @param options - The verification options\n * @param options.authorizationRequest - The authorization request parameters containing client_id\n * @param options.authorizationServerMetadata - Authorization server metadata including issuer\n * @param options.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.dpop.jwt - The DPoP JWT extracted from request headers\n * @param options.dpop.required - Whether DPoP is required (will throw if missing)\n * @param options.dpop.allowedSigningAlgs - Allowed signing algorithms for DPoP\n * @param options.clientAttestation - Client attestation verification configuration\n * @param options.clientAttestation.walletAttestationJwt - The wallet attestation JWT from headers\n * @param options.clientAttestation.clientAttestationPopJwt - The client attestation PoP JWT from headers\n * @param options.clientAttestation.ensureConfirmationKeyMatchesDpopKey - Whether to verify DPoP and client attestation use the same key\n * @param options.request - The HTTP request object containing URL and headers\n * @param options.now - Optional date for time-based validation (defaults to current time)\n *\n * @returns A promise resolving to verification results containing:\n * - `dpop` - Verified DPoP information including JWK and thumbprint (if DPoP was provided)\n * - `clientAttestation` - Verified client attestation JWTs (if client attestation was provided)\n *\n * @throws {Oauth2Error} When DPoP is required but missing\n * @throws {Oauth2Error} When client attestation is required but missing\n * @throws {Oauth2Error} When client_id doesn't match between request and client attestation\n * @throws {Oauth2Error} When DPoP and client attestation keys don't match (if ensureConfirmationKeyMatchesDpopKey is true)\n * @throws {Oauth2Error} When JWT signature verification fails\n * @throws {Oauth2Error} When JWT is expired or has invalid claims\n *\n * @example\n * ```typescript\n * const result = await verifyAuthorizationRequest({\n * authorizationRequest: { client_id: 'client-123' },\n * authorizationServerMetadata: { issuer: 'https://auth.example.com' },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * dpop: {\n * jwt: dpopJwtFromHeaders,\n * required: true,\n * allowedSigningAlgs: ['ES256']\n * },\n * clientAttestation: {\n * walletAttestationJwt: clientAttJwtFromHeaders,\n * clientAttestationPopJwt: clientAttPopJwtFromHeaders,\n * required: true,\n * ensureConfirmationKeyMatchesDpopKey: true\n * },\n * request: httpRequest\n * });\n *\n * console.log(result.dpop?.jwkThumbprint);\n * console.log(result.clientAttestation?.clientAttestation.payload.sub);\n * ```\n */\nexport async function verifyAuthorizationRequest(\n options: VerifyAuthorizationRequestOptions,\n): Promise<VerifyAuthorizationRequestResult> {\n const dpopResult = options.dpop\n ? await verifyAuthorizationRequestDpop(\n options.dpop,\n options.request,\n options.callbacks,\n options.now,\n )\n : undefined;\n\n const clientAttestationResult = await verifyClientAttestation({\n authorizationServerMetadata: options.authorizationServerMetadata,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestation,\n config: options.config,\n dpopJwkThumbprint: dpopResult?.jwkThumbprint,\n now: options.now,\n requestClientId: options.authorizationRequest.client_id,\n });\n\n return {\n clientAttestation: clientAttestationResult,\n dpop: dpopResult?.jwkThumbprint\n ? {\n jwk: dpopResult.jwk,\n jwkThumbprint: dpopResult.jwkThumbprint,\n }\n : undefined,\n };\n}\n\nasync function verifyAuthorizationRequestDpop(\n options: VerifyAuthorizationRequestDPoP,\n request: RequestLike,\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">,\n now?: Date,\n) {\n if (options.required && !options.jwt) {\n throw new Oauth2Error(\n `Missing required DPoP parameters in authorization request. DPoP header is required.`,\n );\n }\n\n const verifyDpopResult = options.jwt\n ? await verifyTokenDPoP({\n allowedSigningAlgs: options.allowedSigningAlgs,\n callbacks,\n dpopJwt: options.jwt,\n now,\n request,\n })\n : undefined;\n\n return {\n jwk: verifyDpopResult?.header.jwk,\n jwkThumbprint: verifyDpopResult?.jwkThumbprint,\n };\n}\n","import { JwtSigner } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { VerifiedJarRequest, verifyJarRequest } from \"../jar\";\nimport {\n type VerifyAuthorizationRequestOptions,\n type VerifyAuthorizationRequestResult,\n verifyAuthorizationRequest,\n} from \"./verify-authorization-request\";\n\nexport interface VerifyPushedAuthorizationRequestReturn\n extends VerifyAuthorizationRequestResult {\n /**\n * The verified JAR request, if `authorizationRequestJwt` was provided\n */\n jar?: VerifiedJarRequest;\n}\n\nexport interface VerifyPushedAuthorizationRequestOptions\n extends Omit<\n VerifyAuthorizationRequestOptions,\n \"authorizationServerMetadata\"\n > {\n /**\n * The authorization request JWT to verify. If this value was returned from `parsePushedAuthorizationRequest`\n * you MUST provide this value to ensure the JWT is verified.\n */\n authorizationRequestJwt?: {\n jwt: string;\n signer: JwtSigner;\n };\n\n /**\n * Authorization Server metadata for enforcing JAR signing policy.\n * Includes standard Authorization Server metadata plus require_signed_request_object.\n * When require_signed_request_object is true, the server will reject unsigned requests.\n * Defaults to false (permissive) if not provided.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5}\n */\n authorizationServerMetadata: {\n require_signed_request_object?: boolean;\n } & VerifyAuthorizationRequestOptions[\"authorizationServerMetadata\"];\n}\n\n/**\n * Verifies a pushed authorization request (PAR) including JAR, DPoP, and client attestation.\n *\n * This function extends `verifyAuthorizationRequest` by adding support for JWT-secured\n * Authorization Requests (JAR). It performs comprehensive verification of all security\n * mechanisms used in pushed authorization requests according to RFC 9126 (PAR) and\n * RFC 9101 (JAR).\n *\n * The verification process includes:\n * 1. JAR signing policy enforcement (per RFC 9101 Section 10.5) - validates require_signed_request_object\n * 2. JAR request object verification (if provided) - validates JWT signature and claims\n * 3. RFC 9101 §4 claim validation - validates iss, aud, exp, iat claims\n * 4. IT-Wallet specific validations - iat age limits and key binding with wallet attestation\n * 5. DPoP proof verification (if provided) - validates proof of possession\n * 6. Client attestation verification - validates client identity\n *\n * **JAR Signing Policy (RFC 9101):**\n * When `authorizationServerMetadata.require_signed_request_object` is true:\n * - Rejects requests without signed JAR (downgrade attack protection)\n * - Rejects JAR with algorithm \"none\" (security requirement)\n * When false or omitted (default): accepts both signed and unsigned requests\n *\n * **Important:** Use `parsePushedAuthorizationRequest` first to extract the necessary\n * JWTs from request headers and body.\n *\n * @param options - The verification options\n * @param options.authorizationRequest - The authorization request parameters containing client_id\n * @param options.authorizationServerMetadata - Authorization server metadata\n * @param options.authorizationServerMetadata.issuer - Authorization server issuer URL\n * @param options.authorizationServerMetadata.require_signed_request_object - Whether to enforce JAR signing (defaults to false)\n * @param options.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.authorizationRequestJwt - Optional JAR JWT and signer information\n * @param options.authorizationRequestJwt.jwt - The JAR JWT string from request parameter\n * @param options.authorizationRequestJwt.signer - The JWT signer for verification (from federation metadata)\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.dpop.jwt - The DPoP JWT extracted from request headers\n * @param options.dpop.required - Whether DPoP is required (will throw if missing)\n * @param options.dpop.allowedSigningAlgs - Allowed signing algorithms for DPoP\n * @param options.clientAttestation - Optional client attestation verification configuration\n * @param options.clientAttestation.walletAttestationJwt - The wallet attestation JWT from headers\n * @param options.clientAttestation.clientAttestationPopJwt - The client attestation PoP JWT from headers\n * @param options.clientAttestation.required - Whether client attestation is required (will throw if missing)\n * @param options.clientAttestation.ensureConfirmationKeyMatchesDpopKey - Whether to verify DPoP and client attestation use the same key\n * @param options.request - The HTTP request object containing URL and headers\n * @param options.now - Optional date for time-based validation (defaults to current time)\n *\n * @returns A promise resolving to verification results containing:\n * - `jar` - Verified JAR request including decoded payload and signer (if JAR was provided)\n * - `dpop` - Verified DPoP information including JWK and thumbprint (if DPoP was provided)\n * - `clientAttestation` - Verified client attestation JWTs (if client attestation was provided)\n *\n * @throws {PushedAuthorizationRequestError} When require_signed_request_object is true but request is unsigned\n * @throws {PushedAuthorizationRequestError} When require_signed_request_object is true but JAR uses alg=\"none\"\n * @throws {PushedAuthorizationRequestError} When iss claim doesn't match client_id (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When aud claim doesn't match authorization server issuer (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When exp claim is missing or expired (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When iat claim is missing, too old (>5 min), or in future (>60s)\n * @throws {PushedAuthorizationRequestError} When kid doesn't match between JAR and wallet attestation cnf.jwk\n * @throws {PushedAuthorizationRequestError} When cnf.jwk is missing from wallet attestation\n * @throws {Oauth2Error} When JAR JWT verification fails\n * @throws {Oauth2Error} When JAR client_id doesn't match request client_id\n * @throws {Oauth2Error} When JAR request object is encrypted (not supported)\n * @throws {Oauth2Error} When DPoP is required but missing\n * @throws {Oauth2Error} When client attestation is required but missing\n * @throws {Oauth2Error} When client_id doesn't match between request and client attestation\n * @throws {Oauth2Error} When DPoP and client attestation keys don't match (if ensureConfirmationKeyMatchesDpopKey is true)\n * @throws {Oauth2Error} When any JWT signature verification fails\n * @throws {Oauth2Error} When any JWT is expired or has invalid claims\n *\n * @example\n * ```typescript\n * // Example 1: Enforce signed JAR (strict mode)\n * const result = await verifyPushedAuthorizationRequest({\n * authorizationRequest: parsed.authorizationRequest,\n * authorizationServerMetadata: {\n * issuer: 'https://auth.example.com',\n * require_signed_request_object: true // Reject unsigned requests\n * },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * authorizationRequestJwt: {\n * jwt: parsed.authorizationRequestJwt,\n * signer: clientSignerFromFederation\n * },\n * request: httpRequest\n * });\n *\n * // Example 2: Accept both signed and unsigned (permissive mode)\n * const result = await verifyPushedAuthorizationRequest({\n * authorizationRequest: parsed.authorizationRequest,\n * authorizationServerMetadata: {\n * issuer: 'https://auth.example.com',\n * require_signed_request_object: false // Accept unsigned requests\n * },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * authorizationRequestJwt: parsed.authorizationRequestJwt ? {\n * jwt: parsed.authorizationRequestJwt,\n * signer: clientSignerFromFederation\n * } : undefined,\n * request: httpRequest\n * });\n * ```\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5 - require_signed_request_object}\n */\nexport async function verifyPushedAuthorizationRequest(\n options: VerifyPushedAuthorizationRequestOptions,\n): Promise<VerifyPushedAuthorizationRequestReturn> {\n // Check if signed request objects are required (default to false for permissive server behavior)\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n // Enforce require_signed_request_object policy\n if (requireSigned && !options.authorizationRequestJwt) {\n throw new PushedAuthorizationRequestError(\n \"Authorization Server requires signed request objects (JAR) per RFC 9101, but request does not include a signed JWT\",\n );\n }\n\n let jar: VerifiedJarRequest | undefined;\n\n if (options.authorizationRequestJwt) {\n // Fail-fast: reject alg=\"none\" before expensive signature verification (RFC 9101 Section 10.5)\n if (requireSigned) {\n const decoded = decodeJwt({ jwt: options.authorizationRequestJwt.jwt });\n if (decoded.header.alg === \"none\") {\n throw new PushedAuthorizationRequestError(\n 'Authorization Server requires signed request objects, but JAR has algorithm \"none\"',\n );\n }\n }\n\n // Verify JAR signature and claims\n jar = await verifyJarRequest({\n authorizationRequestJwt: options.authorizationRequestJwt.jwt,\n callbacks: options.callbacks,\n jarRequestParams: options.authorizationRequest,\n jwtSigner: options.authorizationRequestJwt.signer,\n now: options.now,\n });\n\n // aud claim MUST identify this Authorization Server\n const issuer = options.authorizationServerMetadata.issuer;\n if (!issuer) {\n throw new PushedAuthorizationRequestError(\n \"authorizationServerMetadata.issuer is required to validate the aud claim in the request JWT\",\n );\n }\n const aud = jar.jwt.payload.aud;\n const audMatches =\n aud === issuer || (Array.isArray(aud) && aud.includes(issuer));\n if (!audMatches) {\n throw new PushedAuthorizationRequestError(\n \"aud claim in request JWT does not match the authorization server issuer\",\n );\n }\n }\n\n const { clientAttestation, dpop } = await verifyAuthorizationRequest(options);\n\n if (jar && clientAttestation) {\n const cnfJwk = clientAttestation.clientAttestation.payload.cnf.jwk;\n if (!cnfJwk) {\n throw new PushedAuthorizationRequestError(\n \"Missing wallet attestation or cnf.jwk\",\n );\n }\n // Validate kid match if present in both JAR header and cnf.jwk\n if (cnfJwk.kid !== undefined && jar.jwt.header.kid !== cnfJwk.kid) {\n throw new PushedAuthorizationRequestError(\n \"kid in request JWT header does not match wallet attestation cnf.jwk kid\",\n );\n }\n }\n\n return {\n clientAttestation,\n dpop,\n jar,\n };\n}\n","import { z } from \"zod\";\n\nexport const zCompactJwe = z\n .string()\n .regex(\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/,\n {\n message: \"Not a valid compact jwe\",\n },\n );\n","import z from \"zod\";\n\nimport { DecodeJwtResult, decodeJwt } from \"./common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import { CallbackContext, JwtSignerJwk } from \"@openid4vc/oauth2\";\nimport { dateToSeconds, parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdValidationJwtHeader,\n MrtdValidationJwtPayload,\n zMrtdValidationJwtHeader,\n zMrtdValidationJwtPayload,\n} from \"./z-mrtd-pop\";\n\nconst JWT_EXPIRY_SECONDS = 300;\n\n/**\n * NFC-read document evidence from CIE (Italian ID card) containing:\n * - Data Groups (DG1, DG11) with personal information\n * - Security Objects of Document (SOD) for MRTD and IAS applications\n * - IAS public key and Anti-Cloning challenge signature\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.5 (Validation JWT Structure)\n */\nexport interface MrtdDocumentData {\n /** Anti-Cloning signed challenge response (base64) */\n challengeSigned: string;\n /** Data Group 1 - MRZ info (base64) */\n dg1: string;\n /** Data Group 11 - additional personal data (base64) */\n dg11: string;\n /** IAS public key in DER format (base64) */\n iasPk: string;\n /** Security Object of Document for IAS (base64) */\n sodIas: string;\n /** Security Object of Document for MRTD (base64) */\n sodMrtd: string;\n}\n\nexport interface CreateMrtdValidationJwtOptions {\n /** PID Provider identifier (JWT aud) */\n audience: string;\n callbacks: Pick<CallbackContext, \"signJwt\">;\n /** Wallet Instance identifier (JWT iss) */\n clientId: string;\n /** NFC-read document evidence */\n documentData: MrtdDocumentData;\n issuedAt?: Date;\n signer: JwtSignerJwk;\n}\n\n/**\n * Creates a signed JWT containing MRTD validation data for Phase 3 of L2+ flow.\n *\n * The JWT is sent to the PID Provider for cryptographic verification of the CIE document.\n * Includes Data Groups (DG1, DG11), Security Objects, and Anti-Cloning challenge response.\n *\n * @param options - Configuration including document data, signer, and callback context\n * @returns Signed JWT with typ=\"mrtd-ias+jwt\"\n * @throws {MrtdPopError} If signer lacks kid or signing fails\n *\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.4 (MRTD PoP Validation Request)\n */\nexport async function createMrtdValidationJwt(\n options: CreateMrtdValidationJwtOptions,\n): Promise<{ jwt: string }> {\n try {\n const kid = options.signer.publicJwk.kid;\n if (!kid) {\n throw new MrtdPopError(\"Signer must have a publicJwk.kid property\");\n }\n\n const iat = dateToSeconds(options.issuedAt);\n\n const header = parseWithErrorHandling(zMrtdValidationJwtHeader, {\n alg: options.signer.alg,\n kid,\n typ: \"mrtd-ias+jwt\",\n } satisfies MrtdValidationJwtHeader);\n\n const payload = parseWithErrorHandling(zMrtdValidationJwtPayload, {\n aud: options.audience,\n document_type: \"cie\",\n exp: iat + JWT_EXPIRY_SECONDS,\n ias: {\n challenge_signed: options.documentData.challengeSigned,\n ias_pk: options.documentData.iasPk,\n sod_ias: options.documentData.sodIas,\n },\n iat,\n iss: options.clientId,\n mrtd: {\n dg1: options.documentData.dg1,\n dg11: options.documentData.dg11,\n sod_mrtd: options.documentData.sodMrtd,\n },\n } satisfies MrtdValidationJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n return { jwt };\n } catch (error) {\n if (error instanceof MrtdPopError) {\n throw error;\n }\n throw new MrtdPopError(\n `Error creating MRTD validation JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\n/**\n * Zod schemas for MRTD (Machine Readable Travel Document) Proof of Possession flow.\n *\n * Implements IT-Wallet L2+ specification for eID Substantial Authentication with MRTD Verification.\n * Defines JWT structures and response formats for the multi-step document validation protocol.\n *\n * @see IT-Wallet L2+ specification Section 12.1.3 (eID Substantial Authentication with MRTD Verification)\n */\n\n// --- MRTD Challenge JWT (received via redirect, typ: \"mrtd-ias+jwt\") ---\n\n/** JWT header for MRTD challenge (Phase 3.1) */\nexport const zMrtdChallengeJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n })\n .passthrough();\nexport type MrtdChallengeJwtHeader = z.infer<typeof zMrtdChallengeJwtHeader>;\n\n/** JWT payload for MRTD challenge containing session correlation and endpoint parameters */\nexport const zMrtdChallengeJwtPayload = z\n .object({\n aud: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.string().url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_auth_session: z.string(),\n mrtd_pop_jwt_nonce: z.string(),\n state: z.string(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"mrtd+ias\"),\n })\n .passthrough();\nexport type MrtdChallengeJwtPayload = z.infer<typeof zMrtdChallengeJwtPayload>;\n\n// --- MRTD PoP Init Response JWT (typ: \"mrtd-ias-pop+jwt\") ---\n\n/** JWT header for MRTD PoP initialization response (Phase 3.3) */\nexport const zMrtdPopInitResponseJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias-pop+jwt\"),\n })\n .passthrough();\nexport type MrtdPopInitResponseJwtHeader = z.infer<\n typeof zMrtdPopInitResponseJwtHeader\n>;\n\n/** JWT payload for MRTD PoP initialization response containing challenge and nonce */\nexport const zMrtdPopInitResponseJwtPayload = z\n .object({\n aud: z.string(),\n challenge: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.string().url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_pop_nonce: z.string(),\n mrz: z.string().optional(),\n })\n .passthrough();\nexport type MrtdPopInitResponseJwtPayload = z.infer<\n typeof zMrtdPopInitResponseJwtPayload\n>;\n\n// --- MRTD Validation JWT (created by Wallet, typ: \"mrtd-ias+jwt\") ---\n\n/** MRTD application data from NFC reading (DG1, DG11, SOD) */\nconst zMrtdData = z\n .object({\n dg1: z.string(),\n dg11: z.string(),\n sod_mrtd: z.string(),\n })\n .passthrough();\n\n/** IAS (Anti-Cloning) application data from NFC reading (public key, signed challenge, SOD) */\nconst zIasData = z\n .object({\n challenge_signed: z.string(),\n ias_pk: z.string(),\n sod_ias: z.string(),\n })\n .passthrough();\n\n/** JWT header for MRTD validation (signed by Wallet Instance) */\nexport const zMrtdValidationJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n })\n .passthrough();\nexport type MrtdValidationJwtHeader = z.infer<typeof zMrtdValidationJwtHeader>;\n\n/** JWT payload for MRTD validation containing NFC-read document evidence */\nexport const zMrtdValidationJwtPayload = z\n .object({\n aud: z.string(),\n document_type: z.literal(\"cie\"),\n exp: z.number(),\n ias: zIasData,\n iat: z.number(),\n iss: z.string(),\n mrtd: zMrtdData,\n })\n .passthrough();\nexport type MrtdValidationJwtPayload = z.infer<\n typeof zMrtdValidationJwtPayload\n>;\n\n// --- MRTD PoP Verify Response (JSON, not JWT) ---\n\n/** Response from MRTD PoP verification endpoint (Phase 3.8) */\nexport const zMrtdPopVerifyResponse = z\n .object({\n mrtd_val_pop_nonce: z.string(),\n redirect_uri: z.string().url(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"redirect_to_web\"),\n })\n .passthrough();\nexport type MrtdPopVerifyResponse = z.infer<typeof zMrtdPopVerifyResponse>;\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n zMrtdPopInitResponseJwtHeader,\n zMrtdPopInitResponseJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface FetchMrtdPopInitOptions {\n callbacks: Pick<CallbackContext, \"fetch\" | \"verifyJwt\">;\n clientAttestationDPoP: string;\n /** From challenge JWT payload */\n mrtdAuthSession: string;\n /** From challenge JWT payload */\n mrtdPopJwtNonce: string;\n /** From challenge JWT payload htu */\n popInitEndpoint: string;\n\n /**\n * Optional custom signer for verifying the MRTD PoP init response JWT.\n * If not provided, the library will attempt to verify using JWT header.\n */\n signer?: JwtSigner;\n\n /**\n * Attestation header value for the wallet's own attestation, to be included in the request.\n */\n walletAttestation: string;\n}\n\nexport interface FetchMrtdPopInitResult {\n challenge: string;\n mrtdPopNonce: string;\n mrz?: string;\n /** htu from the init response — the verify endpoint */\n popVerifyEndpoint: string;\n signer: JwtSigner;\n}\n\n/**\n * Initiates MRTD Proof of Possession validation (Phase 3.2 of L2+ flow).\n *\n * Sends session correlation parameters to the MRTD PoP Service and receives:\n * - Cryptographic challenge for Anti-Cloning Internal Authentication\n * - Nonce for next step\n * - Optional MRZ data from CIE National Registry\n *\n * @param options - Session parameters, attestation headers, and callbacks\n * @returns Challenge, nonce, optional MRZ, and verify endpoint URL\n * @throws {UnexpectedStatusCodeError} If response is not HTTP 202\n * @throws {MrtdPopError} For network or parsing failures\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.2-3 (MRTD PoP Request/Response)\n */\nexport async function fetchMrtdPopInit(\n options: FetchMrtdPopInitOptions,\n): Promise<FetchMrtdPopInitResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const response = await fetch(options.popInitEndpoint, {\n body: JSON.stringify({\n mrtd_auth_session: options.mrtdAuthSession,\n mrtd_pop_jwt_nonce: options.mrtdPopJwtNonce,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(202, UnexpectedStatusCodeError)(response);\n\n const responseJwt = await response.text();\n\n const jwt = decodeJwt({\n headerSchema: zMrtdPopInitResponseJwtHeader,\n jwt: responseJwt,\n payloadSchema: zMrtdPopInitResponseJwtPayload,\n });\n\n const { signer } = await verifyJwt({\n compact: responseJwt,\n errorMessage: \"Error verifying MRTD PoP init response JWT\",\n header: jwt.header,\n payload: jwt.payload,\n signer:\n options.signer ??\n jwtSignerFromJwt({ header: jwt.header, payload: jwt.payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n challenge: jwt.payload.challenge,\n mrtdPopNonce: jwt.payload.mrtd_pop_nonce,\n mrz: jwt.payload.mrz,\n popVerifyEndpoint: jwt.payload.htu,\n signer,\n };\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new MrtdPopError(\n `Unexpected error during MRTD PoP init: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\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 { MrtdPopError } from \"../errors\";\nimport { zMrtdPopVerifyResponse } from \"./z-mrtd-pop\";\n\nexport interface FetchMrtdPopVerifyOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n clientAttestationDPoP: string;\n mrtdAuthSession: string;\n mrtdPopNonce: string;\n mrtdValidationJwt: string;\n popVerifyEndpoint: string;\n walletAttestation: string;\n}\n\nexport interface FetchMrtdPopVerifyResult {\n mrtdValPopNonce: string;\n redirectUri: string;\n}\n\n/**\n * Submits MRTD validation evidence for final verification (Phase 3.4 of L2+ flow).\n *\n * Sends the validation JWT containing NFC-read document data to the MRTD PoP Service.\n * The service performs cryptographic verification, identity correlation, and document status checks.\n *\n * @param options - Validation JWT, session correlation parameters, and attestation headers\n * @returns Final nonce and redirect URI for browser-based confirmation\n * @throws {UnexpectedStatusCodeError} If response is not HTTP 202\n * @throws {ValidationError} If response body is invalid\n * @throws {MrtdPopError} For network failures\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.4 (MRTD PoP Validation Request)\n */\nexport async function fetchMrtdPopVerify(\n options: FetchMrtdPopVerifyOptions,\n): Promise<FetchMrtdPopVerifyResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const response = await fetch(options.popVerifyEndpoint, {\n body: JSON.stringify({\n mrtd_auth_session: options.mrtdAuthSession,\n mrtd_pop_nonce: options.mrtdPopNonce,\n mrtd_validation_jwt: options.mrtdValidationJwt,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(202, UnexpectedStatusCodeError)(response);\n\n const parsed = parseWithErrorHandling(\n zMrtdPopVerifyResponse,\n await response.json(),\n \"Failed to parse MRTD PoP verify response\",\n );\n\n return {\n mrtdValPopNonce: parsed.mrtd_val_pop_nonce,\n redirectUri: parsed.redirect_uri,\n };\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new MrtdPopError(\n `Unexpected error during MRTD PoP verify: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { zCompactJwt } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdChallengeJwtHeader,\n MrtdChallengeJwtPayload,\n zMrtdChallengeJwtHeader,\n zMrtdChallengeJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface ParseMrtdChallengeOptions {\n /** The full redirect URL containing ?challenge_info=<jwt> */\n redirectUrl: string;\n}\n\nexport interface ParseMrtdChallengeResult {\n challengeJwt: string;\n header: MrtdChallengeJwtHeader;\n payload: MrtdChallengeJwtPayload;\n}\n\n/**\n * Extracts and decodes the MRTD challenge JWT from authorization redirect (Phase 3.1 of L2+ flow).\n *\n * After primary authentication (LoA3), the Authorization Server redirects to the Wallet\n * with a JWT containing challenge requirements for document validation.\n *\n * @param options - Redirect URL containing challenge_info query parameter\n * @returns Decoded JWT header and payload (signature not yet verified)\n * @throws {MrtdPopError} If challenge_info is missing or JWT format is invalid\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.1 (MRTD Proof JWT)\n */\nexport function parseMrtdChallenge(\n options: ParseMrtdChallengeOptions,\n): ParseMrtdChallengeResult {\n const url = new URL(options.redirectUrl);\n const challengeJwt = url.searchParams.get(\"challenge_info\");\n\n if (!challengeJwt) {\n throw new MrtdPopError(\n \"Missing 'challenge_info' query parameter in redirect URL\",\n );\n }\n\n if (!zCompactJwt.safeParse(challengeJwt).success) {\n throw new MrtdPopError(\n \"Invalid JWT format in 'challenge_info' query parameter\",\n );\n }\n\n const { header, payload } = decodeJwt({\n headerSchema: zMrtdChallengeJwtHeader,\n jwt: challengeJwt,\n payloadSchema: zMrtdChallengeJwtPayload,\n });\n\n return { challengeJwt, header, payload };\n}\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { JwtPayload } from \"../common/jwt/z-jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdChallengeJwtHeader,\n MrtdChallengeJwtPayload,\n zMrtdChallengeJwtHeader,\n zMrtdChallengeJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface VerifyMrtdChallengeOptions {\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n challengeJwt: string;\n /** Expected client_id — must match JWT aud */\n clientId: string;\n\n /**\n * Optional custom signer for verifying the MRTD challenge JWT.\n * If not provided, the library will attempt to verify using JWT header.\n */\n signer?: JwtSigner;\n}\n\nexport interface VerifyMrtdChallengeResult {\n header: MrtdChallengeJwtHeader;\n payload: MrtdChallengeJwtPayload;\n signer: JwtSigner;\n}\n\n/**\n * Verifies the MRTD challenge JWT signature and validates claims.\n *\n * Ensures the challenge was issued by the trusted PID Provider and is intended\n * for this Wallet Instance. Validates expiration, audience, and required parameters.\n *\n * @param options - Challenge JWT, expected client_id, and verification callback\n * @returns Verified header and payload\n * @throws {Error} If aud doesn't match clientId\n * @throws {Oauth2JwtVerificationError} If signature verification fails\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.1 (MRTD Proof JWT)\n */\nexport async function verifyMrtdChallenge(\n options: VerifyMrtdChallengeOptions,\n): Promise<VerifyMrtdChallengeResult> {\n const { callbacks, challengeJwt, clientId } = options;\n\n const jwt = decodeJwt({\n headerSchema: zMrtdChallengeJwtHeader,\n jwt: challengeJwt,\n payloadSchema: zMrtdChallengeJwtPayload,\n });\n\n if (jwt.payload.aud !== clientId) {\n throw new MrtdPopError(\n \"Invalid challenge: aud claim does not match client_id\",\n );\n }\n\n // MRTD spec uses `status` as a string literal, but upstream JwtPayload types it as an object.\n // The cast is safe because verifyJwt only uses standard claims (exp, aud, iss, etc.).\n const payload = jwt.payload as unknown as JwtPayload;\n\n const { signer } = await verifyJwt({\n compact: challengeJwt,\n errorMessage: \"Error verifying MRTD challenge JWT\",\n header: jwt.header,\n payload,\n\n signer: options.signer ?? jwtSignerFromJwt({ header: jwt.header, payload }),\n verifyJwtCallback: callbacks.verifyJwt,\n });\n\n return { header: jwt.header, payload: jwt.payload, signer };\n}\n","export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation\";\nexport * from \"./common\";\nexport * from \"./errors\";\nexport * from \"./jar\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./mrtd-pop\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type ClientAttestationPopJwtHeader,\n type ClientAttestationPopJwtPayload,\n type DecryptJweCallback,\n type EncryptJweCallback,\n type GenerateRandomCallback,\n HashAlgorithm,\n type JweEncryptor,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n"],"mappings":";;;;;;;AAoCO,IAAM,qBAAqB,OAChC,aAEC;AAAA,EACC,MAAM,QAAQ;AAAA,EACd,eAAe,QAAQ;AAAA,EACvB,YAAY;AAAA,EACZ,cAAc,QAAQ;AAAA,EACtB,GAAG,QAAQ;AACb;;;AC7CF;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACTA,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,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,uBAAN,cAAmC,YAAY;AAAA,EACpD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,eAAN,cAA2B,YAAY;AAAA,EAC5C,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,YAAY;AAAA,EACvD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,2BAAN,cAAuC,YAAY;AAAA,EACxD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,yBAAN,cAAqC,YAAY;AAAA,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AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAACC,aAAY,UAAU,YAAY,EAAE,SAAS;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI,UAAU;AAAA,IACpC,cAAc;AAAA,IACd,KAAK;AAAA,IACL,eAAe;AAAA,EACjB,CAAC;AAED,SAAO,EAAE,cAAc,QAAQ,QAAQ;AACzC;;;AC5DA;AAAA,EAGE,oBAAAC;AAAA,EACA,aAAAC;AAAA,OACK;AA6CP,eAAsB,oBACpB,SACoC;AACpC,QAAM,EAAE,WAAW,cAAc,SAAS,IAAI;AAE9C,QAAM,MAAM,UAAU;AAAA,IACpB,cAAc;AAAA,IACd,KAAK;AAAA,IACL,eAAe;AAAA,EACjB,CAAC;AAED,MAAI,IAAI,QAAQ,QAAQ,UAAU;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAIA,QAAM,UAAU,IAAI;AAEpB,QAAM,EAAE,OAAO,IAAI,MAAMC,WAAU;AAAA,IACjC,SAAS;AAAA,IACT,cAAc;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ;AAAA,IAEA,QAAQ,QAAQ,UAAUC,kBAAiB,EAAE,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AAAA,IAC1E,mBAAmB,UAAU;AAAA,EAC/B,CAAC;AAED,SAAO,EAAE,QAAQ,IAAI,QAAQ,SAAS,IAAI,SAAS,OAAO;AAC5D;;;ACvEA;AAAA,EAOE,iBAAAC;AAAA,EAIA,uBAAAC;AAAA,EAIA,aAAAC;AAAA,OACK;","names":["z","z","z","z","z","parseWithErrorHandling","parseWithErrorHandling","addSecondsToDate","dateToSeconds","encodeToBase64Url","Oauth2JwtParseError","decodeBase64","encodeToUtf8String","parseWithErrorHandling","stringToJsonWithErrorHandling","parseWithErrorHandling","parseWithErrorHandling","Oauth2JwtParseError","stringToJsonWithErrorHandling","encodeToUtf8String","decodeBase64","parseWithErrorHandling","addSecondsToDate","encodeToBase64Url","dateToSeconds","z","ValidationError","addSecondsToDate","dateToSeconds","z","z","addSecondsToDate","dateToSeconds","ValidationError","verifyJwt","verifyJwt","v1_exports","createWalletAttestationJwt","verifyWalletAttestationJwt","ValidationError","addSecondsToDate","dateToSeconds","z","z","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","verifyWalletAttestationJwt","HashAlgorithm","calculateJwkThumbprint","zCompactJwt","verifyWalletAttestationJwt","zCompactJwt","verifyWalletAttestationJwt","calculateJwkThumbprint","HashAlgorithm","HashAlgorithm","zCompactJwt","ValidationError","dateToSeconds","encodeToBase64Url","parseWithErrorHandling","z","z","encodeToBase64Url","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","zCompactJwt","HashAlgorithm","calculateJwkThumbprint","verifyJwt","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","calculateJwkThumbprint","verifyJwt","z","HashAlgorithm","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","addSecondsToDate","dateToSeconds","encodeToBase64Url","z","encodeToBase64Url","addSecondsToDate","dateToSeconds","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","toURLSearchParams","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","formatZodError","parseWithErrorHandling","z","addSecondsToDate","dateToSeconds","dateToSeconds","addSecondsToDate","createFetcher","createFetcher","decodeJwt","verifyJwt","zCompactJwt","parseWithErrorHandling","z","z","zCompactJwt","decodeJwt","parseWithErrorHandling","verifyJwt","parseWithErrorHandling","z","formatZodError","z","zCompactJwe","dateToSeconds","parseWithErrorHandling","z","JWT_EXPIRY_SECONDS","dateToSeconds","parseWithErrorHandling","jwtSignerFromJwt","verifyJwt","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","verifyJwt","jwtSignerFromJwt","ValidationError","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","parseWithErrorHandling","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","parseWithErrorHandling","ValidationError","zCompactJwt","zCompactJwt","jwtSignerFromJwt","verifyJwt","verifyJwt","jwtSignerFromJwt","HashAlgorithm","Oauth2JwtParseError","verifyJwt"]}
|
|
1
|
+
{"version":3,"sources":["../src/access-token/create-token-request.ts","../src/access-token/create-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/common/jwt/z-jwt.ts","../src/common/jwk/z-jwk.ts","../src/common/z-common.ts","../src/access-token/fetch-token-response.ts","../src/access-token/parse-token-request.ts","../src/client-attestation/client-attestation-pop.ts","../src/common/jwt/decode-jwt.ts","../src/common/jwt/decode-jwt-header.ts","../src/client-attestation/types.ts","../src/client-attestation/client-authentication.ts","../src/client-attestation/v1.0/index.ts","../src/client-attestation/v1.0/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.0/z-wallet-attestation.ts","../src/client-attestation/verify-wallet-attestation-jwt-base.ts","../src/client-attestation/v1.0/verify-wallet-attestation-jwt.ts","../src/client-attestation/v1.3/index.ts","../src/client-attestation/v1.3/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.3/z-wallet-attestation.ts","../src/client-attestation/v1.3/verify-wallet-attestation-jwt.ts","../src/client-attestation/verify-client-attestation.ts","../src/client-attestation/wallet-attestation.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/dpop-utils.ts","../src/token-dpop/z-dpop.ts","../src/token-dpop/verify-token-dpop.ts","../src/access-token/z-grant-type.ts","../src/pkce.ts","../src/access-token/verify-access-token-request.ts","../src/authorization-request/create-authorization-request.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/fetch-authorization-response.ts","../src/authorization-request/parse-authorization-request.ts","../src/authorization-request/parse-pushed-authorization-request.ts","../src/jar/create-jar-request.ts","../src/jar/fetch-jar-request-object.ts","../src/jar/validate-jar-request.ts","../src/jar/parse-jar-request.ts","../src/jar/verify-jar-request.ts","../src/jar/z-jar.ts","../src/authorization-request/verify-authorization-request.ts","../src/authorization-request/verify-pushed-authorization-request.ts","../src/common/jwt/z-jwe.ts","../src/jarm-form-post-jwt.ts","../src/mrtd-pop/create-mrtd-validation-jwt.ts","../src/mrtd-pop/z-mrtd-pop.ts","../src/mrtd-pop/fetch-mrtd-pop-init.ts","../src/mrtd-pop/fetch-mrtd-pop-verify.ts","../src/mrtd-pop/parse-mrtd-challenge.ts","../src/mrtd-pop/verify-mrtd-challenge.ts","../src/index.ts"],"sourcesContent":["import { CallbackContext } from \"@openid4vc/oauth2\";\n\nimport { AuthorizationCodeGrantType } from \"./z-token\";\n\nexport interface RetrieveAuthorizationCodeAccessTokenOptions {\n /**\n * Additional payload to include in the access token request. Items will be encoded and sent\n * using x-www-form-urlencoded format. Nested items (JSON) will be stringified and url encoded.\n */\n additionalRequestPayload?: Record<string, unknown>;\n\n /**\n * The authorization code\n */\n authorizationCode: string;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<\n CallbackContext,\n \"clientAuthentication\" | \"fetch\" | \"generateRandom\" | \"hash\" | \"signJwt\"\n >;\n\n /**\n * PKCE Code verifier that was used in the authorization request.\n */\n pkceCodeVerifier: string;\n\n /**\n * Redirect uri to include in the access token request.\n * It MUST be set as in the Request Object.\n */\n redirectUri: string;\n}\n\nexport const createTokenRequest = async (\n options: RetrieveAuthorizationCodeAccessTokenOptions,\n) =>\n ({\n code: options.authorizationCode,\n code_verifier: options.pkceCodeVerifier,\n grant_type: \"authorization_code\",\n redirect_uri: options.redirectUri,\n ...options.additionalRequestPayload,\n }) satisfies AuthorizationCodeGrantType;\n","import {\n CallbackContext,\n HashAlgorithm,\n JwtSigner,\n calculateJwkThumbprint,\n jwtHeaderFromJwtSigner,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { CreateTokenResponseError } from \"../errors\";\nimport {\n AccessTokenProfileJwtHeader,\n AccessTokenProfileJwtPayload,\n AccessTokenResponse,\n zAccessTokenProfileJwtHeader,\n zAccessTokenProfileJwtPayload,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface CreateAccessTokenResponseOptions {\n /**\n * Additional claims copied into both the access token JWT payload and token\n * response envelope.\n */\n additionalPayload?: Record<string, unknown>;\n\n /**\n * Intended recipient of the access token (`aud` claim).\n */\n audience: string;\n\n /**\n * Authorization server identifier (`iss` claim).\n */\n authorizationServer: string;\n\n /**\n * Runtime callbacks used to generate random values, compute JWK thumbprints,\n * and sign the access token JWT.\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * OAuth client identifier (`client_id` claim).\n */\n clientId: string;\n\n /**\n * DPoP public key used to bind the access token (`cnf.jkt` claim).\n */\n dpop?: {\n jwk: Jwk;\n };\n\n /**\n * Access token lifetime in seconds, used for both `exp` and `expires_in`.\n */\n expiresInSeconds: number;\n\n /**\n * Optional \"not before\" timestamp in epoch seconds (`nbf` claim).\n */\n nbf?: number;\n\n /**\n * Reference time used for `iat` and `exp`. Defaults to current time.\n */\n now?: Date;\n\n /**\n * Optional refresh token included in the OAuth token response.\n */\n refreshToken?: string;\n\n /**\n * Optional scope string included in both the access token JWT payload and token\n * response envelope.\n */\n scope?: string;\n\n /**\n * Signer used to produce the access token JWT.\n */\n signer: JwtSigner;\n\n /**\n * Subject identifier represented by the access token (`sub` claim).\n */\n subject: string;\n\n /**\n * Token type returned in the OAuth token response.\n * NOTE: When using `Bearer` it is supposed to be used only for PDND Interoperability API, not for credential issuance flows.\n */\n tokenType: \"Bearer\" | \"DPoP\";\n}\n\n/**\n * Creates an OAuth 2.0 access token response where `access_token` is a signed\n * JWT access token profile (`typ=at+jwt`) and `token_type` is `DPoP` or `Bearer`.\n *\n * The JWT payload always includes `aud`, `iss`, `sub`, `client_id`, `iat`,\n * `exp`, and a random `jti`. When `dpop` is provided, `cnf.jkt` is added using\n * the SHA-256 JWK thumbprint.\n */\nexport async function createAccessTokenResponse(\n options: CreateAccessTokenResponseOptions,\n) {\n try {\n const now = options.now ?? new Date();\n\n if (options.tokenType === \"DPoP\" && !options.dpop) {\n throw new CreateTokenResponseError(\n \"token_type is DPoP but dpop option is not provided. Please provide a DPoP public key in the dpop option or set tokenType to 'Bearer'.\",\n );\n }\n\n const header = parseWithErrorHandling(zAccessTokenProfileJwtHeader, {\n ...jwtHeaderFromJwtSigner(options.signer),\n typ: \"at+jwt\",\n } satisfies AccessTokenProfileJwtHeader);\n\n const payload = parseWithErrorHandling(zAccessTokenProfileJwtPayload, {\n aud: options.audience,\n client_id: options.clientId,\n cnf: options.dpop\n ? {\n jkt: await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpop.jwk,\n }),\n }\n : undefined,\n exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n nbf: options.nbf,\n scope: options.scope,\n sub: options.subject,\n ...options.additionalPayload,\n } satisfies AccessTokenProfileJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: options.refreshToken,\n token_type: options.tokenType,\n ...options.additionalPayload,\n } satisfies AccessTokenResponse);\n\n return accessTokenResponse;\n } catch (error) {\n if (error instanceof CreateTokenResponseError) {\n throw error;\n }\n throw new CreateTokenResponseError(\n `Error creating access token JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"Oauth2Error\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"PushedAuthorizationRequestError\";\n }\n}\n\n/**\n * Error thrown in case {@link createTokenDPoP} is called without neither a custom jti\n * nor a generateRandom callback or when the signJwt callback throws\n */\nexport class CreateTokenDPoPError extends Oauth2Error {\n constructor(message: string) {\n super(message);\n this.name = \"CreateTokenDPoPError\";\n }\n}\n\n/**\n * Error thrown during MRTD (Machine Readable Travel Document) Proof of Possession operations.\n * Used in eID Substantial Authentication with MRTD Verification flow (IT-Wallet L2+ specification).\n */\nexport class MrtdPopError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"MrtdPopError\";\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"fetchTokenResponseError\";\n }\n}\n\nexport class CreateTokenResponseError extends Oauth2Error {\n constructor(\n message: string,\n public readonly statusCode?: number,\n ) {\n super(message);\n this.name = \"CreateTokenResponseError\";\n }\n}\n\n/**\n * Error thrown when an unexpected error occurs during client attestation (wallet attestation) creation.\n */\nexport class ClientAttestationError extends Oauth2Error {\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = \"ClientAttestationError\";\n this.cause = cause;\n }\n}\n","import { z } from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zAccessTokenRequest = z.discriminatedUnion(\"grant_type\", [\n z.object({\n code: z.string().nonempty(),\n code_verifier: z.string().nonempty(),\n grant_type: z.literal(\"authorization_code\"),\n redirect_uri: z.string().nonempty(),\n }),\n z.object({\n grant_type: z.literal(\"refresh_token\"),\n refresh_token: z.string().nonempty(),\n scope: z.string().optional(),\n }),\n]);\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport type AuthorizationCodeGrantType = Extract<\n AccessTokenRequest,\n { grant_type: \"authorization_code\" }\n>;\n\nexport type RefreshTokenGrantType = Extract<\n AccessTokenRequest,\n { grant_type: \"refresh_token\" }\n>;\n\nexport const zAccessTokenResponse = z\n .object({\n access_token: z.string(),\n authorization_details: z\n .array(\n z\n .object({\n credential_configuration_id: z.optional(z.string()),\n credential_identifiers: z.optional(z.array(z.string())),\n type: z.literal(\"openid_credential\"),\n })\n .passthrough(),\n )\n .optional(),\n expires_in: z.optional(z.number().int()),\n refresh_token: z.optional(z.string()),\n token_type: z.union([z.literal(\"Bearer\"), z.literal(\"DPoP\")]),\n })\n .passthrough();\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n\nexport const zAccessTokenProfileJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: z.enum([\"application/at+jwt\", \"at+jwt\"]),\n })\n .passthrough();\n\nexport type AccessTokenProfileJwtHeader = z.infer<\n typeof zAccessTokenProfileJwtHeader\n>;\n\nexport const zAccessTokenProfileJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n aud: z.string(),\n client_id: z.string(),\n cnf: z\n .object({\n jkt: z.string(),\n })\n .optional(),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n jti: z.string(),\n nbf: z.number().optional(),\n scope: z.string().optional(),\n sub: z.string(),\n })\n .passthrough();\n\nexport type AccessTokenProfileJwtPayload = z.infer<\n typeof zAccessTokenProfileJwtPayload\n>;\n","import z from \"zod\";\n\nimport { Jwk, zJwk } from \"../jwk/z-jwk\";\nimport { zAlgValueNotNone } from \"../z-common\";\n\nexport interface JwtSignerDid {\n alg: string;\n didUrl: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the didUrl.\n */\n kid?: string;\n\n method: \"did\";\n}\n\nexport interface JwtSignerJwk {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the jwk.\n *\n * If not provided the kid can also be extracted from the `publicJwk`. Providing it here means the `kid` won't\n * be included in the JWT header.\n */\n kid?: string;\n method: \"jwk\";\n\n publicJwk: Jwk;\n}\n\nexport interface JwtSignerX5c {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with the key associated with the leaf certificate.\n */\n kid?: string;\n method: \"x5c\";\n\n x5c: string[];\n}\n\nexport interface JwtSignerFederation {\n alg: string;\n /**\n * The key id that should be used for signing. You need to make sure the kid actually matches\n * with a key present in the federation.\n */\n kid: string;\n method: \"federation\";\n\n trustChain?: [string, ...string[]];\n}\n\n// In case of custom nothing will be added to the header\nexport interface JwtSignerCustom {\n alg: string;\n /**\n * The key id that should be used for signing.\n */\n kid?: string;\n\n method: \"custom\";\n}\n\nexport type JwtSigner =\n | JwtSignerCustom\n | JwtSignerDid\n | JwtSignerFederation\n | JwtSignerJwk\n | JwtSignerX5c;\n\nexport type JwtSignerWithJwk = { publicJwk: Jwk } & JwtSigner;\n\nexport type JweEncryptor = {\n /**\n * base64-url encoded apu\n */\n apu?: string;\n\n /**\n * base64-url encoded apv\n */\n apv?: string;\n\n enc: string;\n} & JwtSignerJwk;\n\nexport const zCompactJwt = z\n .string()\n .regex(/^([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)$/, {\n message: \"Not a valid compact jwt\",\n });\n\nexport const zJwtConfirmationPayload = z\n .object({\n // RFC9449. jwk thumbprint of the dpop public key to which the access token is bound\n jkt: z.string().optional(),\n\n jwk: zJwk.optional(),\n })\n .passthrough();\n\nexport const zJwtPayload = z\n .object({\n aud: z.string().optional(),\n cnf: zJwtConfirmationPayload.optional(),\n exp: z.number().int().optional(),\n iat: z.number().int().optional(),\n iss: z.string().optional(),\n jti: z.string().optional(),\n nbf: z.number().int().optional(),\n\n nonce: z.string().optional(),\n\n // Reserved for status parameters\n status: z.record(z.string(), z.any()).optional(),\n\n // Reserved for OpenID Federation\n trust_chain: z.array(z.string()).nonempty().optional(),\n })\n .passthrough();\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>;\n\nexport const zJwtHeader = z\n .object({\n alg: zAlgValueNotNone,\n jwk: zJwk.optional(),\n\n kid: z.string().optional(),\n // Reserved for OpenID Federation\n trust_chain: z.array(z.string()).nonempty().optional(),\n typ: z.string().optional(),\n\n x5c: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>;\n","import z from \"zod\";\n\nexport const zJwk = z\n .object({\n alg: z.optional(z.string()),\n crv: z.optional(z.string()),\n d: z.optional(z.string()),\n dp: z.optional(z.string()),\n dq: z.optional(z.string()),\n e: z.optional(z.string()),\n ext: z.optional(z.boolean()),\n k: z.optional(z.string()),\n key_ops: z.optional(z.array(z.string())),\n kid: z.optional(z.string()),\n kty: z.string(),\n n: z.optional(z.string()),\n oth: z.optional(\n z.array(\n z\n .object({\n d: z.optional(z.string()),\n r: z.optional(z.string()),\n t: z.optional(z.string()),\n })\n .passthrough(),\n ),\n ),\n p: z.optional(z.string()),\n q: z.optional(z.string()),\n qi: z.optional(z.string()),\n use: z.optional(z.string()),\n x: z.optional(z.string()),\n x5c: z.optional(z.array(z.string())),\n x5t: z.optional(z.string()),\n \"x5t#S256\": z.optional(z.string()),\n x5u: z.optional(z.string()),\n y: z.optional(z.string()),\n })\n .passthrough();\n\nexport type Jwk = z.infer<typeof zJwk>;\n\nexport const zJwkSet = z.object({ keys: z.array(zJwk) }).passthrough();\n\nexport type JwkSet = z.infer<typeof zJwkSet>;\n","import { FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nexport const zAlgValueNotNone = z\n .string()\n .refine((alg) => alg !== \"none\", { message: `alg value may not be 'none'` });\n\nexport interface RequestLike {\n headers: FetchHeaders;\n method: HttpMethod;\n url: string;\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 { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface FetchTokenResponseOptions {\n /**\n * The endpoint URL where the access token request will be sent\n * This should be the authorization server's token endpoint\n */\n accessTokenEndpoint: string;\n\n /**\n * The access token request payload\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * Callbacks to use for requesting access token\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * DPoP proof for the token request\n */\n dPoP: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * @param options - Configuration options for the access token request\n * @returns Promise that resolves to the parsed access token response\n * @throws {UnexpectedStatusCodeError} When the server returns a non-200 status code\n * @throws {ValidationError} When the response cannot be parsed as a valid access token response\n * @throws {FetchTokenResponseError} When an unexpected error occurs during the request\n */\n\nexport async function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n const tokenResponse = await fetch(options.accessTokenEndpoint, {\n body: toURLSearchParams(options.accessTokenRequest),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.DPOP]: options.dPoP,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(tokenResponse);\n\n return parseWithErrorHandling(\n zAccessTokenResponse,\n await tokenResponse.json(),\n \"Failed to parse token response\",\n );\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new FetchTokenResponseError(\n `Unexpected error during token respone: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function toURLSearchParams(data: AccessTokenRequest): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","import {\n FetchHeaders,\n RequestLike,\n formatZodError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { extractClientAttestationJwtsFromHeaders } from \"../client-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop\";\nimport {\n AuthorizationCodeGrantIdentifier,\n RefreshTokenGrantIdentifier,\n authorizationCodeGrantIdentifier,\n refreshTokenGrantIdentifier,\n} from \"./z-grant-type\";\nimport { AccessTokenRequest, zAccessTokenRequest } from \"./z-token\";\n\nexport interface ParsedAccessTokenAuthorizationCodeRequestGrant {\n code: string;\n grantType: AuthorizationCodeGrantIdentifier;\n}\n\nexport interface ParsedAccessTokenRefreshTokenRequestGrant {\n grantType: RefreshTokenGrantIdentifier;\n refreshToken: string;\n}\n\ntype ParsedAccessTokenRequestGrant =\n | ParsedAccessTokenAuthorizationCodeRequestGrant\n | ParsedAccessTokenRefreshTokenRequestGrant;\n\nexport interface ParseAccessTokenRequestResult {\n accessTokenRequest: AccessTokenRequest;\n /**\n * The client attestation jwts from the access token request headers\n */\n clientAttestation: {\n clientAttestationPopJwt: string;\n walletAttestationJwt: string;\n };\n\n /**\n * The dpop jwt from the access token request headers\n */\n dpop: {\n jwt: string;\n };\n\n grant: ParsedAccessTokenRequestGrant;\n\n /**\n * The pkce code verifier from the access token request\n */\n pkceCodeVerifier?: string;\n}\n\nexport interface ParseAccessTokenRequestOptions {\n /**\n * The access token request as a JSON object. Your server should decode the\n * `x-www-url-form-urlencoded` body into an object (e.g. using `bodyParser.urlEncoded()` in express)\n */\n accessTokenRequest: Record<string, unknown>;\n\n request: RequestLike;\n}\n\n/**\n * Parses and validates an OAuth 2.0 access token request.\n *\n * This function performs the following steps:\n * 1. Validates the request body against the access token request schema\n * 2. Extracts and validates grant-specific parameters (authorization code or refresh token)\n * 3. Parses security headers (DPoP and Client Attestation JWTs)\n * 4. Extracts PKCE code verifier if present\n *\n * Note: This function only parses and validates the structure of the request.\n * Cryptographic verification of JWTs and tokens should be performed separately.\n *\n * @param options - Configuration object containing the access token request body and HTTP request\n * @returns Parsed access token request with typed grant parameters and extracted security headers\n * @throws {Oauth2Error} If validation fails or required parameters are missing\n *\n * @example\n * ```typescript\n * const result = parseAccessTokenRequest({\n * accessTokenRequest: {\n * grant_type: 'authorization_code',\n * code: 'auth_code_123',\n * client_id: 'client_123',\n * code_verifier: 'verifier_xyz'\n * },\n * request: httpRequest\n * });\n * ```\n */\nexport function parseAccessTokenRequest(\n options: ParseAccessTokenRequestOptions,\n): ParseAccessTokenRequestResult {\n const validationResult = zAccessTokenRequest.safeParse(\n options.accessTokenRequest,\n );\n\n if (!validationResult.success) {\n throw new Oauth2Error(\n `Access token request validation failed:\\n${formatZodError(validationResult.error)}`,\n );\n }\n\n const accessTokenRequest = validationResult.data;\n const grant = parseGrantParameters(accessTokenRequest);\n const securityHeaders = parseSecurityHeaders(options.request.headers);\n const pkceCodeVerifier =\n accessTokenRequest.grant_type === \"authorization_code\"\n ? accessTokenRequest.code_verifier\n : undefined;\n\n return {\n accessTokenRequest,\n grant,\n pkceCodeVerifier,\n ...securityHeaders,\n };\n}\n\n/**\n * Parses the grant-specific parameters from an access token request.\n *\n * Validates that the required parameters for the grant type are present\n * and returns a typed grant object.\n *\n * @param accessTokenRequest - The validated access token request\n * @returns Typed grant object containing grant-specific parameters\n * @throws {Oauth2Error} If required grant parameters are missing or grant type is unsupported\n */\nfunction parseGrantParameters(\n accessTokenRequest: AccessTokenRequest,\n): ParsedAccessTokenRequestGrant {\n if (accessTokenRequest.grant_type === authorizationCodeGrantIdentifier) {\n return {\n code: accessTokenRequest.code,\n grantType: authorizationCodeGrantIdentifier,\n };\n }\n\n if (accessTokenRequest.grant_type === refreshTokenGrantIdentifier) {\n return {\n grantType: refreshTokenGrantIdentifier,\n refreshToken: accessTokenRequest.refresh_token,\n };\n }\n\n throw new Oauth2Error(\n `Unsupported grant type. Supported types are: '${authorizationCodeGrantIdentifier}', '${refreshTokenGrantIdentifier}'`,\n );\n}\n\n/**\n * Extracts and validates security headers (DPoP and Client Attestation) from the request.\n *\n * This function only parses the headers without verifying the cryptographic signatures.\n * Signature verification should be performed separately.\n *\n * @param headers - The HTTP request headers\n * @returns Object containing extracted DPoP JWT and Client Attestation JWTs if present\n * @throws {Oauth2Error} If headers are present but malformed\n */\nfunction parseSecurityHeaders(headers: FetchHeaders) {\n const extractedDpopJwt = extractDpopJwtFromHeaders(headers);\n if (!extractedDpopJwt.valid) {\n throw new Oauth2Error(\n \"Request contains a 'DPoP' header, but the value is not a valid JWT format\",\n );\n }\n\n if (!extractedDpopJwt.dpopJwt) {\n throw new Oauth2Error(\"Request is missing required 'DPoP' header\");\n }\n\n const extractedClientAttestationJwts =\n extractClientAttestationJwtsFromHeaders(headers);\n\n if (!extractedClientAttestationJwts.valid) {\n throw new Oauth2Error(\n \"Request contains client attestation headers, but the values are not in valid JWT format\",\n );\n }\n\n if (!extractedClientAttestationJwts.walletAttestationHeader) {\n throw new Oauth2Error(\n \"Request is missing required 'OAuth-Client-Attestation' header\",\n );\n }\n\n if (!extractedClientAttestationJwts.clientAttestationPopHeader) {\n throw new Oauth2Error(\n \"Request is missing required 'OAuth-Client-Attestation-PoP' header\",\n );\n }\n\n return {\n clientAttestation: {\n clientAttestationPopJwt:\n extractedClientAttestationJwts.clientAttestationPopHeader,\n walletAttestationJwt:\n extractedClientAttestationJwts.walletAttestationHeader,\n },\n dpop: { jwt: extractedDpopJwt.dpopJwt },\n };\n}\n","import {\n CallbackContext,\n ClientAttestationPopJwtHeader,\n ClientAttestationPopJwtPayload,\n JwtSignerJwk,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\n\nexport interface VerifyClientAttestationPopJwtOptions {\n /**\n * The issuer identifier of the authorization server handling the client attestation\n */\n authorizationServer: string;\n\n /**\n * Callbacks used for verifying client attestation pop jwt.\n */\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n\n /**\n * The compact client attestation pop jwt.\n */\n clientAttestationPopJwt: string;\n\n /**\n * The public JWK to verify the client attestation pop jwt.\n */\n clientAttestationPublicJwk: Jwk;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<\n ReturnType<typeof verifyClientAttestationPopJwt>\n>;\n\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n jwt: options.clientAttestationPopJwt,\n });\n\n if (payload.aud !== options.authorizationServer) {\n throw new Oauth2Error(\n `Client Attestation Pop jwt contains 'aud' value '${payload.aud}', but expected authorization server identifier '${options.authorizationServer}'`,\n );\n }\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedNonce: options.expectedNonce,\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: options.clientAttestationPublicJwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n payload,\n signer,\n };\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * The audience authorization server identifier\n */\n authorizationServer: string;\n\n /**\n * Callback used for dpop\n * generateRandom is mandatory if jti is not provided\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * The client attestation to create the Pop for\n */\n clientAttestation: string;\n\n /**\n * Expiration time of the JWT. If not provided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * Optional jti to set in the payload. If not provided a random one will be generated\n */\n jti?: string;\n\n /**\n * The signer of jwt. Only jwk signer allowed.\n *\n * If not provided, the signer will be derived based on the\n * `cnf.jwk` and `alg` in the client attestation.\n */\n signer?: JwtSignerJwk;\n}\n\nexport async function createClientAttestationPopJwt(\n options: CreateClientAttestationPopJwtOptions,\n) {\n try {\n const clientAttestation = decodeJwt({\n jwt: options.clientAttestation,\n });\n\n const jwk = clientAttestation.payload.cnf?.jwk;\n if (!jwk) {\n throw new Oauth2Error(\n \"Client attestation does not contain 'cnf.jwk', cannot create client attestation pop jwt\",\n );\n }\n\n const sub = clientAttestation.payload.sub;\n if (!sub || typeof sub !== \"string\") {\n throw new Oauth2Error(\n \"Client attestation does not contain 'sub', cannot create client attestation pop jwt\",\n );\n }\n\n const signer = options.signer ?? {\n alg: clientAttestation.header.alg,\n method: \"jwk\",\n publicJwk: jwk,\n };\n\n const header = {\n alg: signer.alg,\n typ: \"oauth-client-attestation-pop+jwt\",\n } satisfies ClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\n const expiresAt = options.expiresAt ?? addSecondsToDate(issuedAt, 1 * 60);\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? encodeToBase64Url(await options.callbacks.generateRandom(32))\n : undefined);\n\n if (!jti) {\n throw new Oauth2Error(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const payload = {\n aud: options.authorizationServer,\n exp: dateToSeconds(expiresAt),\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n } satisfies ClientAttestationPopJwtPayload;\n\n const { jwt } = await options.callbacks.signJwt(signer, {\n header,\n payload,\n });\n\n return jwt;\n } catch (error) {\n if (error instanceof Oauth2Error) throw error;\n throw new Oauth2Error(\n `Error creating client attestation pop jwt : ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { decodeJwtHeader } from \"./decode-jwt-header\";\nimport { zJwtHeader, zJwtPayload } from \"./z-jwt\";\n\nexport interface DecodeJwtOptions<\n HeaderSchema extends BaseSchema | undefined,\n PayloadSchema extends BaseSchema | undefined,\n> {\n /**\n * Schema to use for validating the header. If not provided the\n * default `zJwtHeader` schema will be used\n */\n headerSchema?: HeaderSchema;\n\n /**\n * The compact encoded jwt\n */\n jwt: string;\n\n /**\n * Schema to use for validating the payload. If not provided the\n * default `zJwtPayload` schema will be used\n */\n payloadSchema?: PayloadSchema;\n}\n\nexport interface DecodeJwtResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>;\n signature: string;\n}\n\nexport function decodeJwt<\n HeaderSchema extends BaseSchema | undefined = undefined,\n PayloadSchema extends BaseSchema | undefined = undefined,\n>(\n options: DecodeJwtOptions<HeaderSchema, PayloadSchema>,\n): DecodeJwtResult<HeaderSchema, PayloadSchema> {\n const jwtParts = options.jwt.split(\".\");\n if (jwtParts.length !== 3) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n let payloadJson: Record<string, unknown>;\n try {\n const payloadPart = jwtParts[1];\n if (payloadPart === undefined) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n payloadJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(payloadPart)),\n \"Unable to parse jwt payload to JSON\",\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n );\n }\n\n const signaturePart = jwtParts[2];\n if (signaturePart === undefined) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n const { header } = decodeJwtHeader({\n headerSchema: options.headerSchema,\n jwt: options.jwt,\n });\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n );\n\n return {\n header: header as InferSchemaOrDefaultOutput<\n HeaderSchema,\n typeof zJwtHeader\n >,\n payload: payload as InferSchemaOrDefaultOutput<\n PayloadSchema,\n typeof zJwtPayload\n >,\n signature: signaturePart,\n };\n}\n\n// Helper type to check if a schema is provided\ntype IsSchemaProvided<T> = T extends undefined ? false : true;\n\n// Helper type to infer the output type based on whether a schema is provided\nexport type InferSchemaOrDefaultOutput<\n ProvidedSchema extends BaseSchema | undefined,\n DefaultSchema extends BaseSchema,\n> =\n IsSchemaProvided<ProvidedSchema> extends true\n ? ProvidedSchema extends BaseSchema\n ? z.infer<ProvidedSchema>\n : never\n : z.infer<DefaultSchema>;\n","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { InferSchemaOrDefaultOutput } from \"./decode-jwt\";\n\nimport { zJwtHeader } from \"./z-jwt\";\n\nexport interface DecodeJwtHeaderOptions<\n HeaderSchema extends BaseSchema | undefined,\n> {\n /**\n * Schema to use for validating the header. If not provided the\n * default `zJwtHeader` schema will be used\n */\n headerSchema?: HeaderSchema;\n\n /**\n * The compact encoded jwt\n */\n jwt: string;\n}\n\nexport interface DecodeJwtHeaderResult<\n HeaderSchema extends BaseSchema | undefined = undefined,\n> {\n header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n}\n\nexport function decodeJwtHeader<\n HeaderSchema extends BaseSchema | undefined = undefined,\n>(\n options: DecodeJwtHeaderOptions<HeaderSchema>,\n): DecodeJwtHeaderResult<HeaderSchema> {\n const jwtParts = options.jwt.split(\".\");\n if (jwtParts.length <= 2) {\n throw new Oauth2JwtParseError(\"Jwt is not a valid jwt, unable to decode\");\n }\n\n const [headerPart] = jwtParts as [string, ...string[]];\n\n let headerJson: Record<string, unknown>;\n try {\n headerJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(headerPart)),\n \"Unable to parse jwt header to JSON\",\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n );\n }\n\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n ) as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n\n return {\n header,\n };\n}\n","import {\n CallbackContext,\n ClientAttestationJwtPayload,\n} from \"@openid4vc/oauth2\";\nimport z from \"zod\";\n\nexport interface BaseVerifyWalletAttestationJwtOptions {\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n now?: Date;\n walletAttestationJwt: string;\n}\n\n/**\n * Base options shared across all wallet attestation versions\n */\nexport interface BaseWalletAttestationOptions {\n callbacks: Pick<CallbackContext, \"signJwt\">;\n dpopJwkPublic: ClientAttestationJwtPayload[\"cnf\"][\"jwk\"];\n expiresAt?: Date;\n issuer: string;\n walletLink?: string;\n walletName?: string;\n}\n\nexport const zOauthClientAttestationHeader = z.literal(\n \"OAuth-Client-Attestation\",\n);\n\nexport const oauthClientAttestationHeader = zOauthClientAttestationHeader.value;\n\nexport const zOauthClientAttestationPopHeader = z.literal(\n \"OAuth-Client-Attestation-PoP\",\n);\n\nexport const oauthClientAttestationPopHeader =\n zOauthClientAttestationPopHeader.value;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { ContentType, FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\n\nimport { createClientAttestationPopJwt } from \"./client-attestation-pop\";\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\n\n/**\n * Supported OAuth 2.0 client authentication methods.\n */\nexport const SupportedClientAuthenticationMethod = {\n ClientSecretBasic: \"client_secret_basic\",\n ClientSecretPost: \"client_secret_post\",\n None: \"none\",\n WalletAttestationJwt: \"attest_jwt_client_auth\",\n} as const;\n\n/**\n * Union type of supported client authentication methods.\n */\nexport type SupportedClientAuthenticationMethod =\n (typeof SupportedClientAuthenticationMethod)[keyof typeof SupportedClientAuthenticationMethod];\n\n/**\n * Options for checking client attestation support.\n */\nexport interface IsClientAttestationSupportedOptions {\n /** Authorization server metadata containing supported authentication methods. */\n authorizationServerMetadata: AuthorizationServerMetadata;\n}\n\n/**\n * Checks whether the authorization server supports client attestation authentication.\n *\n * @param options - Configuration including authorization server metadata\n * @returns Object with `supported` boolean indicating if client attestation is available\n */\nexport function isClientAttestationSupported(\n options: IsClientAttestationSupportedOptions,\n) {\n if (\n !options.authorizationServerMetadata\n .token_endpoint_auth_methods_supported ||\n !options.authorizationServerMetadata.token_endpoint_auth_methods_supported.includes(\n SupportedClientAuthenticationMethod.WalletAttestationJwt,\n )\n ) {\n return {\n supported: false,\n };\n }\n\n return {\n supported: true,\n };\n}\n\n/**\n * Options for client authentication\n */\nexport interface ClientAuthenticationCallbackOptions {\n /**\n * Metadata of the authorization server\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * The body as a JSON object. If content type `x-www-form-urlencoded`\n * is used, it will be encoded after this call.\n *\n * You can modify this object\n */\n body: Record<string, unknown>;\n\n contentType: ContentType;\n\n /**\n * Headers for the request. You can modify this object\n */\n headers: FetchHeaders;\n\n /**\n * http method that will be used\n */\n method: HttpMethod;\n\n /**\n * URL to which the request will be made\n */\n url: string;\n}\n\n/**\n * Callback method to determine the client authentication for a request.\n */\nexport type ClientAuthenticationCallback = (\n options: ClientAuthenticationCallbackOptions,\n) => Promise<void> | void;\n\n/**\n * Anonymous client authentication\n */\nexport function clientAuthenticationAnonymous(): ClientAuthenticationCallback {\n return () => {\n // No authentication, do nothing\n };\n}\n\nexport interface ClientAuthenticationWalletAttestationJwtOptions {\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"signJwt\">;\n walletAttestationJwt: string;\n}\n\n/**\n * Client authentication using wallet attestation JWT.\n * This method adds the wallet attestation JWT and a proof-of-possession JWT to the request headers.\n */\nexport function clientAuthenticationWalletAttestationJwt(\n options: ClientAuthenticationWalletAttestationJwtOptions,\n): ClientAuthenticationCallback {\n return async ({ authorizationServerMetadata, headers }) => {\n const clientAttestationPop = await createClientAttestationPopJwt({\n authorizationServer: authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestation: options.walletAttestationJwt,\n });\n\n headers.set(oauthClientAttestationHeader, options.walletAttestationJwt);\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop);\n };\n}\n","export * from \"./create-wallet-attestation-jwt\";\nexport * from \"./verify-wallet-attestation-jwt\";\nexport * from \"./z-wallet-attestation\";\n","import {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_0,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n} from \"./z-wallet-attestation\";\n\n/**\n * Options for creating a wallet attestation with v1.0\n * Uses only trust_chain (federation method)\n */\nexport interface WalletAttestationOptionsV1_0\n extends BaseWalletAttestationOptions {\n /**\n * It expresses the strength of the authentication mechanism backing the Wallet instance when interacting with a Relying Party.\n */\n authenticatorAssuranceLevel: string;\n\n signer: {\n alg: string;\n kid: string;\n method: \"federation\";\n trustChain: [string, ...string[]]; // REQUIRED in v1.0\n };\n}\n\n/**\n * Create a Wallet Attestation JWT for IT-Wallet v1.0\n *\n * Version 1.0 specifics:\n * - Uses only `trust_chain` in header (federation method)\n *\n * @param options - Wallet attestation options for v1.0\n * @returns Signed wallet attestation JWT string\n * @throws {ValidationError} When validation of the JWT structure fails\n * @throws {ClientAttestationError} For other unexpected errors during creation\n * @internal This function is called by the WalletProvider router\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_0,\n): Promise<WalletAttestationJwtV1_0> => {\n try {\n const { signJwt } = options.callbacks;\n // Calculate default expiration (60 days)\n const exp =\n options.expiresAt ?? addSecondsToDate(new Date(), 3600 * 24 * 60);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(new Date()),\n iss: options.issuer,\n sub: options.dpopJwkPublic.kid,\n ...(options.walletLink && { wallet_link: options.walletLink }),\n ...(options.walletName && { wallet_name: options.walletName }),\n aal: options.authenticatorAssuranceLevel,\n };\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n trust_chain: options.signer.trustChain,\n typ: \"oauth-client-attestation+jwt\",\n };\n\n const result = await signJwt(options.signer, {\n header,\n payload,\n });\n\n decodeJwt({\n headerSchema: zWalletAttestationJwtHeaderV1_0,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_0,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ClientAttestationError(\n `Unexpected error during wallet attestation creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\n\n/**\n * JWT Header schema for IT-Wallet v1.0 Wallet Attestation\n *\n * Version 1.0 specifics:\n * - trust_chain is REQUIRED\n * - x5c is NOT supported\n */\nexport const zWalletAttestationJwtHeaderV1_0 = z\n .object({\n ...zJwtHeader.shape,\n trust_chain: z.array(z.string()).nonempty(), // REQUIRED in v1.0\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n })\n .passthrough();\n\n/**\n * JWT Payload schema for IT-Wallet v1.0 Wallet Attestation\n *\n * Version 1.0 specifics:\n * - Standard claims only\n * - No nbf or status support\n */\nexport const zWalletAttestationJwtPayloadV1_0 = z\n .object({\n ...zJwtPayload.shape,\n aal: z.string(),\n cnf: z.object({\n jwk: zJwk,\n }),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n sub: z.string(),\n wallet_link: z.string().url().optional(),\n wallet_name: z.string().optional(),\n })\n .passthrough();\n\n/**\n * Wallet Attestation JWT type for v1.0\n * The JWT is returned as a compact string\n */\nexport type WalletAttestationJwtV1_0 = string;\n\n/**\n * Zod schema for wallet attestation JWT validation (v1.0)\n * Validates that the result is a non-empty string\n */\nexport const zWalletAttestationJwtV1_0 = z.string().min(1);\n","import { jwtSignerFromJwt, verifyJwt } from \"@openid4vc/oauth2\";\nimport { ZodType, z } from \"zod\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\n\nexport async function verifyWalletAttestationBase<\n THeader extends ZodType,\n TPayload extends ZodType,\n>(\n options: BaseVerifyWalletAttestationJwtOptions,\n headerSchema: THeader,\n payloadSchema: TPayload,\n): Promise<{\n header: z.infer<THeader>;\n payload: z.infer<TPayload>;\n signer: Awaited<ReturnType<typeof verifyJwt>>[\"signer\"];\n}> {\n const { header, payload } = decodeJwt({\n headerSchema,\n jwt: options.walletAttestationJwt,\n payloadSchema,\n });\n\n const { signer } = await verifyJwt({\n compact: options.walletAttestationJwt,\n errorMessage: \"wallet attestation verification failed.\",\n header,\n now: options.now,\n payload,\n signer: jwtSignerFromJwt({ header, payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return { header, payload, signer };\n}\n","import {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { BaseVerifyWalletAttestationJwtOptions } from \"../types\";\nimport { verifyWalletAttestationBase } from \"../verify-wallet-attestation-jwt-base\";\nimport {\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_0\n extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_0 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n );\n}\n","export * from \"./create-wallet-attestation-jwt\";\nexport * from \"./verify-wallet-attestation-jwt\";\nexport * from \"./z-wallet-attestation\";\n","import {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_3,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n} from \"./z-wallet-attestation\";\n\n/**\n * Options for creating a wallet attestation with v1.3\n * Requires x5c, optional trust_chain, nbf, and status\n */\nexport interface WalletAttestationOptionsV1_3\n extends BaseWalletAttestationOptions {\n // NEW OPTIONAL CLAIMS\n nbf?: Date; // Not Before timestamp\n\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]]; // OPTIONAL in v1.3\n x5c: [string, ...string[]]; // REQUIRED in v1.3\n };\n status?: {\n status_list: {\n idx: number;\n uri: string;\n };\n }; // Status object for revocation mechanisms\n}\n\n/**\n * Create a Wallet Attestation JWT for IT-Wallet v1.3\n *\n * Version 1.3 specifics:\n * - x5c in header is REQUIRED\n * - trust_chain in header is OPTIONAL\n * - Supports nbf and status claims in payload\n *\n * @param options - Wallet attestation options for v1.3\n * @returns Signed wallet attestation JWT string\n * @throws {ValidationError} When validation fails (including nbf >= exp)\n * @throws {ClientAttestationError} For other unexpected errors during creation\n * @internal This function is called by the WalletProvider router\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_3,\n): Promise<WalletAttestationJwtV1_3> => {\n try {\n const { signJwt } = options.callbacks;\n\n // Calculate default expiration (60 days)\n const exp =\n options.expiresAt ?? addSecondsToDate(new Date(), 3600 * 24 * 60);\n\n // Validate temporal constraints\n if (options.nbf && options.nbf >= exp) {\n throw new ValidationError(\"nbf must be before exp\");\n }\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(new Date()),\n iss: options.issuer,\n sub: options.dpopJwkPublic.kid,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\n ...(options.status && { status: options.status }),\n ...(options.walletLink && { wallet_link: options.walletLink }),\n ...(options.walletName && { wallet_name: options.walletName }),\n };\n\n const header = {\n alg: options.signer.alg,\n kid: options.signer.kid,\n typ: \"oauth-client-attestation+jwt\",\n x5c: options.signer.x5c, // REQUIRED\n ...(options.signer.trustChain && {\n trust_chain: options.signer.trustChain,\n }),\n };\n\n const result = await signJwt(options.signer, {\n header,\n payload,\n });\n\n // Validate the generated JWT structure\n decodeJwt({\n headerSchema: zWalletAttestationJwtHeaderV1_3,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_3,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ClientAttestationError(\n `Unexpected error during wallet attestation creation: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n};\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\n\n/**\n * JWT Header schema for IT-Wallet v1.3 Wallet Attestation\n *\n * Version 1.3 specifics:\n * - x5c is REQUIRED\n * - trust_chain is OPTIONAL\n */\nexport const zWalletAttestationJwtHeaderV1_3 = z\n .object({\n ...zJwtHeader.shape,\n trust_chain: z.array(z.string()).nonempty().optional(), // OPTIONAL in v1.3\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: z.array(z.string()).nonempty(), // REQUIRED in v1.3\n })\n .passthrough();\n\n/**\n * JWT Payload schema for IT-Wallet v1.3 Wallet Attestation\n *\n * Version 1.3 specifics:\n * - Supports nbf (not before) claim\n * - Supports status claim for revocation mechanisms\n */\nexport const zWalletAttestationJwtPayloadV1_3 = z\n .object({\n ...zJwtPayload.shape,\n cnf: z.object({\n jwk: zJwk,\n }),\n exp: z.number(),\n iat: z.number(),\n iss: z.string(),\n nbf: z.number().optional(), // NEW in v1.3\n status: z\n .object({\n status_list: z.object({\n idx: z.number().int(),\n uri: z.string(),\n }),\n })\n .optional(), // NEW in v1.3 - status object for revocation\n sub: z.string(),\n wallet_link: z.string().url().optional(),\n wallet_name: z.string().optional(),\n })\n .passthrough();\n\n/**\n * Wallet Attestation JWT type for v1.3\n * The JWT is returned as a compact string\n */\nexport type WalletAttestationJwtV1_3 = string;\n\n/**\n * Zod schema for wallet attestation JWT validation (v1.3)\n * Validates that the result is a non-empty string\n */\nexport const zWalletAttestationJwtV1_3 = z.string().min(1);\n","import {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { BaseVerifyWalletAttestationJwtOptions } from \"../types\";\nimport { verifyWalletAttestationBase } from \"../verify-wallet-attestation-jwt-base\";\nimport {\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_3\n extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_3 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_3,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n );\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport { verifyClientAttestationPopJwt } from \"./client-attestation-pop\";\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport { verifyWalletAttestationJwt } from \"./wallet-attestation\";\n\nexport interface ClientAttestationOptions {\n /**\n * The client attestation DPoP JWT provided in the request.\n */\n clientAttestationPopJwt: string;\n\n /**\n * Whether to ensure that the key used in client attestation confirmation\n * is the same key used for DPoP. This only has effect if both DPoP and client\n * attestations are present.\n *\n * @default false\n */\n ensureConfirmationKeyMatchesDpopKey?: boolean;\n\n /**\n * The wallet attestation JWT provided in the request.\n */\n walletAttestationJwt: string;\n}\n\nexport interface VerifyClientAttestationOptions {\n /**\n * The authorization server metadata.\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * Callbacks for hashing and JWT verification.\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * The client attestation options.\n */\n clientAttestation: ClientAttestationOptions;\n\n /**\n * The IT-Wallet SDK configuration, used to select the correct version-specific\n * validation schema for the wallet attestation JWT.\n */\n config: IoWalletSdkConfig;\n\n /**\n * The DPoP JWK thumbprint value, if DPoP is being used in the request.\n */\n dpopJwkThumbprint?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The client id provided in the authorization request, if any.\n *\n * Pass this when the authorization request includes a `client_id` parameter.\n * The function will verify that it matches the `sub` claim in the client attestation JWT.\n * If not provided, no client_id validation is performed.\n */\n requestClientId?: string;\n}\n\nexport async function verifyClientAttestation(\n options: VerifyClientAttestationOptions,\n) {\n if (\n !options.clientAttestation.walletAttestationJwt ||\n !options.clientAttestation.clientAttestationPopJwt\n ) {\n throw new Oauth2Error(\n `Missing required client attestation parameters in the request. Make sure to provide the '${oauthClientAttestationHeader}' and '${oauthClientAttestationPopHeader}' header values.`,\n );\n }\n\n const clientAttestation = await verifyWalletAttestationJwt({\n callbacks: options.callbacks,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: options.config as any,\n now: options.now,\n walletAttestationJwt: options.clientAttestation.walletAttestationJwt,\n });\n\n const clientAttestationPop = await verifyClientAttestationPopJwt({\n authorizationServer: options.authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestationPopJwt: options.clientAttestation.clientAttestationPopJwt,\n clientAttestationPublicJwk: clientAttestation.payload.cnf.jwk,\n now: options.now,\n });\n\n if (\n options.requestClientId &&\n options.requestClientId !== clientAttestation.payload.sub\n ) {\n // Ensure the client id matches with the client id provided in the authorization request\n throw new Oauth2Error(\n `The client_id '${options.requestClientId}' in the request does not match the client id '${clientAttestation.payload.sub}' in the client attestation`,\n );\n }\n\n if (\n options.clientAttestation.ensureConfirmationKeyMatchesDpopKey &&\n options.dpopJwkThumbprint\n ) {\n const clientAttestationJkt = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: clientAttestation.payload.cnf.jwk,\n });\n\n if (clientAttestationJkt !== options.dpopJwkThumbprint) {\n throw new Oauth2Error(\n \"Expected the DPoP JWK thumbprint value to match the JWK thumbprint of the client attestation confirmation JWK. Ensure both DPoP and client attestation use the same key.\",\n );\n }\n }\n\n return {\n clientAttestation,\n clientAttestationPop,\n };\n}\n","import { zCompactJwt } from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ItWalletSpecsVersion,\n ItWalletSpecsVersionError,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport * as V1_0 from \"./v1.0\";\nimport * as V1_3 from \"./v1.3\";\n\nfunction isV1_0Options(\n options: VerifyWalletAttestationJwtOptions,\n): options is V1_0.VerifyWalletAttestationJwtOptionsV1_0 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0;\n}\n\nfunction isV1_3Options(\n options: VerifyWalletAttestationJwtOptions,\n): options is V1_3.VerifyWalletAttestationJwtOptionsV1_3 {\n return options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_3;\n}\n\nexport type VerifiedWalletAttestationJwt =\n | V1_0.VerifiedWalletAttestationJwtV1_0\n | V1_3.VerifiedWalletAttestationJwtV1_3;\n\nexport type VerifyWalletAttestationJwtOptions =\n | V1_0.VerifyWalletAttestationJwtOptionsV1_0\n | V1_3.VerifyWalletAttestationJwtOptionsV1_3;\n\nexport async function verifyWalletAttestationJwt(\n options: V1_0.VerifyWalletAttestationJwtOptionsV1_0,\n): Promise<V1_0.VerifiedWalletAttestationJwtV1_0>;\n\nexport async function verifyWalletAttestationJwt(\n options: V1_3.VerifyWalletAttestationJwtOptionsV1_3,\n): Promise<V1_3.VerifiedWalletAttestationJwtV1_3>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptions,\n): Promise<VerifiedWalletAttestationJwt> {\n const version = options.config.itWalletSpecsVersion;\n\n if (isV1_0Options(options)) {\n return V1_0.verifyWalletAttestationJwt(options);\n }\n\n if (isV1_3Options(options)) {\n return V1_3.verifyWalletAttestationJwt(options);\n }\n\n throw new ItWalletSpecsVersionError(\"verifyWalletAttestationJwt\", version, [\n ItWalletSpecsVersion.V1_0,\n ItWalletSpecsVersion.V1_3,\n ]);\n}\n\nexport function extractClientAttestationJwtsFromHeaders(headers: FetchHeaders):\n | {\n clientAttestationPopHeader: string;\n valid: true;\n walletAttestationHeader: string;\n }\n | {\n clientAttestationPopHeader?: undefined;\n valid: true;\n walletAttestationHeader?: undefined;\n }\n | { valid: false } {\n const walletAttestationHeader = headers.get(oauthClientAttestationHeader);\n const clientAttestationPopHeader = headers.get(\n oauthClientAttestationPopHeader,\n );\n\n if (!walletAttestationHeader && !clientAttestationPopHeader) {\n return { valid: true };\n }\n\n if (!walletAttestationHeader || !clientAttestationPopHeader) {\n return { valid: false };\n }\n\n if (\n !zCompactJwt.safeParse(walletAttestationHeader).success ||\n !zCompactJwt.safeParse(clientAttestationPopHeader).success\n ) {\n return { valid: false };\n }\n\n return {\n clientAttestationPopHeader,\n valid: true,\n walletAttestationHeader,\n } as const;\n}\n","import {\n CallbackContext,\n HashAlgorithm,\n HttpMethod,\n JwtSignerJwk,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport { Base64 } from \"js-base64\";\n\nimport { CreateTokenDPoPError } from \"../errors\";\nimport { htuFromRequestUrl } from \"./dpop-utils\";\nimport {\n DpopJwtHeader,\n DpopJwtPayload,\n zDpopJwtHeader,\n zDpopJwtPayload,\n} from \"./z-dpop\";\n\n/**\n * Options for Token Request DPoP generation\n */\nexport interface CreateTokenDPoPOptions {\n /**\n * The access token to which the dpop jwt should be bound. Required\n * when the dpop will be sent along with an access token.\n */\n accessToken?: string;\n\n /**\n * Object containing callbacks for DPoP generation and signature\n */\n callbacks: Partial<Pick<CallbackContext, \"generateRandom\">> &\n Pick<CallbackContext, \"hash\" | \"signJwt\">;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti claim for the DPoP JWT. If not provided, a random one will be generated\n * if a generateRandom callback is provided\n */\n jti?: string;\n\n /**\n * The signer of the dpop jwt. Only jwk signer allowed.\n */\n signer: JwtSignerJwk;\n\n /**\n * The request for which to create the dpop jwt\n */\n tokenRequest: {\n method: HttpMethod;\n url: string;\n };\n}\n\n/**\n * Creates a signed Token DPoP with the given cryptographic material and data.\n * It is used to create DPoP proofs for token requests and credential requests.\n * @param options {@link CreateTokenDPoPOptions}\n * @returns A Promise that resolves with an object containing the signed DPoP JWT and\n * its corresponding public JWK\n * @throws {@link CreateTokenDPoPError} in case neither a default jti nor a generateRandom\n * callback have been provided or the signJwt callback throws\n */\nexport async function createTokenDPoP(options: CreateTokenDPoPOptions) {\n try {\n // Calculate access token hash\n const ath = options.accessToken\n ? encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n )\n : undefined;\n\n const jti =\n options.jti ??\n (options.callbacks.generateRandom\n ? Base64.fromUint8Array(\n await options.callbacks.generateRandom(32),\n true,\n )\n : undefined);\n\n if (!jti) {\n throw new CreateTokenDPoPError(\n \"Error: neither a default jti nor a generateRandom callback have been provided\",\n );\n }\n\n const header = parseWithErrorHandling(zDpopJwtHeader, {\n alg: options.signer.alg,\n jwk: options.signer.publicJwk,\n typ: \"dpop+jwt\",\n } satisfies DpopJwtHeader);\n\n const payload = parseWithErrorHandling(zDpopJwtPayload, {\n ath,\n htm: options.tokenRequest.method,\n htu: htuFromRequestUrl(options.tokenRequest.url),\n iat: dateToSeconds(options.issuedAt),\n jti,\n } satisfies DpopJwtPayload);\n\n return options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n } catch (error) {\n if (\n error instanceof CreateTokenDPoPError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new CreateTokenDPoPError(\n `Error during jwt signature, details: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nexport function extractDpopJwtFromHeaders(\n headers: FetchHeaders,\n): { dpopJwt?: string; valid: true } | { valid: false } {\n const dpopJwt = headers.get(\"DPoP\");\n\n if (!dpopJwt) {\n return { valid: true };\n }\n\n if (!zCompactJwt.safeParse(dpopJwt).success) {\n return { valid: false };\n }\n\n return { dpopJwt, valid: true };\n}\n","export const htuFromRequestUrl = (requestUrl: string) => {\n const htu = new URL(requestUrl);\n htu.search = \"\";\n htu.hash = \"\";\n\n return htu.toString();\n};\n","import { zHttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { zJwk } from \"../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zDpopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: z.string().url(),\n iat: z.number().int().nonnegative(),\n\n jti: z.string(),\n })\n .passthrough();\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z\n .object({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n })\n .passthrough();\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\n","import {\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n decodeUtf8String,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\nimport { htuFromRequestUrl } from \"./dpop-utils\";\nimport { zDpopJwtHeader, zDpopJwtPayload } from \"./z-dpop\";\n\nexport interface VerifyTokenDPoPOptions {\n /**\n * Access token to which the dpop jwt is bound. If provided the sha-256 hash of the\n * access token needs to match the 'ath' claim.\n */\n accessToken?: string;\n\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * Callbacks used for verifying dpop jwt\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * The compact dpop jwt.\n */\n dpopJwt: string;\n\n /**\n * The expected jwk thumprint 'jti' confirmation method. If provided the thumprint of the\n * jwk used to sign the dpop jwt must match this provided thumbprint value. The 'jti' value\n * can be extracted from the access token payload, or if opaque tokens are used can be retrieved\n * using token introspection.\n */\n expectedJwkThumbprint?: string;\n\n /**\n * Expected nonce in the payload. If not provided the nonce won't be validated.\n */\n expectedNonce?: string;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The request for which to verify the dpop jwt\n */\n request: RequestLike;\n}\n\nexport async function verifyTokenDPoP(options: VerifyTokenDPoPOptions) {\n const { header, payload } = decodeJwt({\n headerSchema: zDpopJwtHeader,\n jwt: options.dpopJwt,\n payloadSchema: zDpopJwtPayload,\n });\n\n if (\n options.allowedSigningAlgs &&\n !options.allowedSigningAlgs.includes(header.alg)\n ) {\n throw new Oauth2Error(\n `dpop jwt uses alg value '${header.alg}' but allowed dpop signing alg values are ${options.allowedSigningAlgs.join(\", \")}.`,\n );\n }\n\n if (options.expectedNonce) {\n if (!payload.nonce) {\n throw new Oauth2Error(\n `Dpop jwt does not have a nonce value, but expected nonce value '${options.expectedNonce}'`,\n );\n }\n\n if (payload.nonce !== options.expectedNonce) {\n throw new Oauth2Error(\n `Dpop jwt contains nonce value '${payload.nonce}', but expected nonce value '${options.expectedNonce}'`,\n );\n }\n }\n\n if (options.request.method !== payload.htm) {\n throw new Oauth2Error(\n `Dpop jwt contains htm value '${payload.htm}', but expected htm value '${options.request.method}'`,\n );\n }\n\n const expectedHtu = htuFromRequestUrl(options.request.url);\n if (expectedHtu !== payload.htu) {\n throw new Oauth2Error(\n `Dpop jwt contains htu value '${payload.htu}', but expected htu value '${expectedHtu}'.`,\n );\n }\n\n if (options.accessToken) {\n const expectedAth = encodeToBase64Url(\n await options.callbacks.hash(\n decodeUtf8String(options.accessToken),\n HashAlgorithm.Sha256,\n ),\n );\n\n if (!payload.ath) {\n throw new Oauth2Error(\n `Dpop jwt does not have a ath value, but expected ath value '${expectedAth}'.`,\n );\n }\n\n if (payload.ath !== expectedAth) {\n throw new Oauth2Error(\n `Dpop jwt contains ath value '${payload.ath}', but expected ath value '${expectedAth}'.`,\n );\n }\n }\n\n const jwkThumbprint = await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: header.jwk,\n });\n\n if (\n options.expectedJwkThumbprint &&\n options.expectedJwkThumbprint !== jwkThumbprint\n ) {\n throw new Oauth2Error(\n `Dpop is signed with jwk with thumbprint value '${jwkThumbprint}', but expect jwk thumbprint value '${options.expectedJwkThumbprint}'`,\n );\n }\n\n await verifyJwt({\n compact: options.dpopJwt,\n errorMessage: \"dpop jwt verification failed\",\n header,\n now: options.now,\n payload,\n signer: {\n alg: header.alg,\n method: \"jwk\",\n publicJwk: header.jwk,\n },\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n header,\n jwkThumbprint,\n payload,\n };\n}\n","import { z } from \"zod\";\n\nexport const zAuthorizationCodeGrantIdentifier =\n z.literal(\"authorization_code\");\nexport const authorizationCodeGrantIdentifier =\n zAuthorizationCodeGrantIdentifier.value;\nexport type AuthorizationCodeGrantIdentifier = z.infer<\n typeof zAuthorizationCodeGrantIdentifier\n>;\n\nexport const zRefreshTokenGrantIdentifier = z.literal(\"refresh_token\");\nexport const refreshTokenGrantIdentifier = zRefreshTokenGrantIdentifier.value;\nexport type RefreshTokenGrantIdentifier = z.infer<\n typeof zRefreshTokenGrantIdentifier\n>;\n","import {\n CallbackContext,\n HashAlgorithm,\n HashCallback,\n} from \"@openid4vc/oauth2\";\nimport { decodeUtf8String, encodeToBase64Url } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"./errors\";\n\nexport const PkceCodeChallengeMethod = {\n Plain: \"plain\",\n S256: \"S256\",\n} as const;\n\nexport type PkceCodeChallengeMethod =\n (typeof PkceCodeChallengeMethod)[keyof typeof PkceCodeChallengeMethod];\n\nexport interface CreatePkceOptions {\n /**\n * Also allows string values so it can be directly passed from the\n * 'code_challenge_methods_supported' metadata parameter\n */\n allowedCodeChallengeMethods?: (PkceCodeChallengeMethod | string)[];\n\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\">;\n\n /**\n * Code verifier to use. If not provided a value will be generated.\n */\n codeVerifier?: string;\n}\n\nexport interface CreatePkceReturn {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport async function createPkce(\n options: CreatePkceOptions,\n): Promise<CreatePkceReturn> {\n const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n PkceCodeChallengeMethod.S256,\n PkceCodeChallengeMethod.Plain,\n ];\n\n if (allowedCodeChallengeMethods.length === 0) {\n throw new Oauth2Error(\n `Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`,\n );\n }\n\n const codeChallengeMethod = allowedCodeChallengeMethods.includes(\n PkceCodeChallengeMethod.S256,\n )\n ? PkceCodeChallengeMethod.S256\n : PkceCodeChallengeMethod.Plain;\n\n const codeVerifier =\n options.codeVerifier ??\n encodeToBase64Url(await options.callbacks.generateRandom(64));\n return {\n codeChallenge: await calculateCodeChallenge({\n codeChallengeMethod,\n codeVerifier,\n hashCallback: options.callbacks.hash,\n }),\n codeChallengeMethod,\n codeVerifier,\n };\n}\n\nexport interface VerifyPkceOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n\n /**\n * secure random code verifier\n */\n codeVerifier: string;\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n const calculatedCodeChallenge = await calculateCodeChallenge({\n codeChallengeMethod: options.codeChallengeMethod,\n codeVerifier: options.codeVerifier,\n hashCallback: options.callbacks.hash,\n });\n\n if (options.codeChallenge !== calculatedCodeChallenge) {\n throw new Oauth2Error(\n `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`,\n );\n }\n}\n\nasync function calculateCodeChallenge(options: {\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n hashCallback: HashCallback;\n}) {\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.Plain) {\n return options.codeVerifier;\n }\n\n if (options.codeChallengeMethod === PkceCodeChallengeMethod.S256) {\n return encodeToBase64Url(\n await options.hashCallback(\n decodeUtf8String(options.codeVerifier),\n HashAlgorithm.Sha256,\n ),\n );\n }\n\n throw new Oauth2Error(\n `Unsupported code challenge method ${options.codeChallengeMethod}`,\n );\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientAttestationOptions,\n VerifiedClientAttestationPopJwt,\n VerifiedWalletAttestationJwt,\n verifyClientAttestation,\n} from \"../client-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { PkceCodeChallengeMethod, verifyPkce } from \"../pkce\";\nimport { verifyTokenDPoP } from \"../token-dpop\";\nimport { ParsedAccessTokenAuthorizationCodeRequestGrant } from \"./parse-token-request\";\nimport { AccessTokenRequest } from \"./z-token\";\n\nexport interface VerifyAccessTokenRequestPkce {\n codeChallenge: string;\n codeChallengeMethod: PkceCodeChallengeMethod;\n codeVerifier: string;\n}\n\nexport interface VerifyAccessTokenRequestDpop {\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * The dpop jwt from the access token request\n */\n jwt: string;\n}\n\nexport interface VerifyAccessTokenRequestOptions {\n /**\n * The access token request to verify\n */\n accessTokenRequest: AccessTokenRequest;\n\n /**\n * The authorization server metadata\n */\n authorizationServerMetadata: AuthorizationServerMetadata;\n\n /**\n * Callbacks used during verification\n */\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n /**\n * Options for verifying the client attestation\n */\n clientAttestation: ClientAttestationOptions;\n /**\n * The expiration date of the authorization code\n */\n codeExpiresAt?: Date;\n\n config: IoWalletSdkConfig;\n\n /**\n * The dpop verification options\n */\n dpop: VerifyAccessTokenRequestDpop;\n\n /**\n * The expected authorization code\n */\n expectedCode: string;\n\n /**\n * The parsed authorization code grant\n */\n grant: ParsedAccessTokenAuthorizationCodeRequestGrant;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n /**\n * The pkce options including code verifier, challenge and method\n */\n pkce: VerifyAccessTokenRequestPkce;\n\n /**\n * The HTTP request information\n */\n request: RequestLike;\n}\n\nexport interface VerifyAccessTokenRequestResult {\n clientAttestation: {\n clientAttestation: VerifiedWalletAttestationJwt;\n clientAttestationPop: VerifiedClientAttestationPopJwt;\n };\n\n dpop: {\n jwk: Jwk;\n\n /**\n * base64url encoding of the JWK SHA-256 Thumbprint (according to [RFC7638])\n * of the DPoP public key (in JWK format)\n */\n jwkThumbprint: string;\n };\n}\n\n/**\n * Verifies an authorization code token request by validating PKCE, DPoP, and client attestation.\n *\n * This function performs comprehensive validation of an OAuth 2.0 authorization code token request\n * according to Italian IT-Wallet specifications, including:\n * - PKCE code verifier validation against the stored code challenge\n * - DPoP proof JWT verification and JWK thumbprint extraction\n * - Client attestation JWT and attestation PoP JWT verification\n * - Authorization code validity and expiration checks\n *\n * @param options - Configuration options for token request verification\n * @returns A promise that resolves with verified client attestation and DPoP information\n * @throws {Oauth2Error} If the authorization code is invalid or expired\n * @throws {Oauth2Error} If PKCE verification fails\n * @throws {Oauth2Error} If DPoP verification fails\n * @throws {Oauth2Error} If client attestation verification fails\n *\n * @example\n * ```typescript\n * const result = await verifyAccessTokenRequest({\n * accessTokenRequest: parsedRequest,\n * authorizationServerMetadata: metadata,\n * callbacks: { hash, verifyJwt },\n * clientAttestation: { jwt: \"...\", popJwt: \"...\" },\n * codeExpiresAt: new Date(Date.now() + 600000),\n * dpop: { jwt: dpopJwt, allowedSigningAlgs: [\"ES256\"] },\n * expectedCode: \"auth_code_123\",\n * grant: parsedGrant,\n * pkce: { codeChallenge, codeChallengeMethod: \"S256\", codeVerifier },\n * request: httpRequest,\n * });\n * ```\n */\nexport async function verifyAccessTokenRequest(\n options: VerifyAccessTokenRequestOptions,\n): Promise<VerifyAccessTokenRequestResult> {\n await verifyPkce({\n callbacks: options.callbacks,\n codeChallenge: options.pkce.codeChallenge,\n codeChallengeMethod: options.pkce.codeChallengeMethod,\n codeVerifier: options.pkce.codeVerifier,\n });\n\n const { header, jwkThumbprint } = await verifyTokenDPoP({\n allowedSigningAlgs: options.dpop.allowedSigningAlgs,\n callbacks: options.callbacks,\n dpopJwt: options.dpop.jwt,\n now: options.now,\n request: options.request,\n });\n\n const clientAttestationResult = await verifyClientAttestation({\n authorizationServerMetadata: options.authorizationServerMetadata,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestation,\n config: options.config,\n dpopJwkThumbprint: jwkThumbprint,\n now: options.now,\n });\n\n if (options.grant.code !== options.expectedCode) {\n throw new Oauth2Error(`Invalid 'code' provided`);\n }\n\n if (options.codeExpiresAt) {\n const now = options.now ?? new Date();\n\n if (now.getTime() > options.codeExpiresAt.getTime()) {\n throw new Oauth2Error(`Expired 'code' provided`);\n }\n }\n\n if (!header.jwk) {\n throw new Oauth2Error(\"DPoP header does not contain a JWK\");\n }\n\n return {\n clientAttestation: clientAttestationResult,\n dpop: { jwk: header.jwk, jwkThumbprint },\n };\n}\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n RequestDpopOptions,\n} from \"@openid4vc/oauth2\";\nimport {\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequest,\n PushedAuthorizationRequest,\n PushedAuthorizationRequestSigned,\n PushedAuthorizationRequestUnsigned,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\nexport interface CreatePushedAuthorizationRequestOptions {\n /**\n * It MUST be set to the identifier of the Credential Issuer.\n */\n audience: string;\n\n /**\n * Allows clients to specify their fine-grained authorization requirements using the expressiveness of JSON data structures\n */\n authorization_details?: AuthorizationRequest[\"authorization_details\"];\n\n /**\n * Authorization Server metadata for conditional JAR signing.\n * When require_signed_request_object is true, creates a signed JWT (JAR).\n * When require_signed_request_object is false, creates an unsigned authorization request.\n * Defaults to false (unsigned) if not provided.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5}\n */\n authorizationServerMetadata?: {\n require_signed_request_object?: boolean;\n };\n\n /**\n * Callback context mostly for crypto related functionality\n */\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"hash\" | \"signJwt\">;\n\n /**\n * MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\n */\n clientId: string;\n\n codeChallengeMethodsSupported: AuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n /**\n * DPoP options. Required when `require_signed_request_object` is `true`\n * (enforced at the type level via function overloads). Not used in the\n * unsigned path and can be omitted.\n */\n dpop?: RequestDpopOptions;\n\n /**\n * Expiration time of the JWT. If not provided 1 hour will be added to the `issuedAt`\n */\n expiresAt?: Date;\n\n /**\n * Creation time of the JWT. If not provided the current date will be used\n */\n issuedAt?: Date;\n\n /**\n * jti parameter to use for PAR. If not provided a value will generated automatically\n */\n jti?: string;\n\n /**\n * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n */\n pkceCodeVerifier?: string;\n\n /**\n * Redirect uri to include in the authorization request\n */\n redirectUri: string;\n\n /**\n * It MUST be one of the supported values (response_modes_supported) provided in the metadata of the Credential Issuer.\n */\n responseMode: string;\n\n /**\n * Scope to request for the authorization request\n */\n scope?: string;\n\n /**\n * state parameter to use for PAR. If not provided a value will generated automatically\n */\n state?: string;\n}\n\n/**\n * Creates a Pushed Authorization Request (PAR) for OAuth 2.0 authorization flows.\n *\n * This function conditionally creates signed JWT-Secured Authorization Requests (JAR)\n * based on the Authorization Server's `require_signed_request_object` metadata parameter\n * as defined in RFC 9101. The signing behavior enables compliance with both OAuth 2.0 PAR\n * (RFC 9126) and IT-Wallet v1.3.3 specifications.\n *\n * **Conditional JAR Signing:**\n * - When `require_signed_request_object` is `true`: Creates a signed JAR\n * - When `require_signed_request_object` is `false`: Creates an unsigned authorization request\n * - When metadata not provided: Defaults to unsigned (permissive)\n *\n * **Security Note:**\n * Disabling JAR signing (setting `require_signed_request_object: false`) should only be done\n * when the Authorization Server explicitly supports and allows unsigned requests. Signed\n * requests provide protection against request tampering and replay attacks.\n *\n * @param options - Configuration for creating the PAR\n * @param options.audience - The identifier of the Credential Issuer (used as JWT aud claim)\n * @param options.authorization_details - Fine-grained authorization requirements using JSON data structures\n * @param options.authorizationServerMetadata - Authorization Server metadata for conditional JAR signing\n * @param options.authorizationServerMetadata.require_signed_request_object -\n * When `true`, creates a signed JAR. When `false`, creates an unsigned authorization request.\n * Defaults to `false` if not provided (permissive).\n * @param options.callbacks - Cryptographic callback functions (generateRandom, hash, signJwt)\n * @param options.clientId - Thumbprint of the jwk value in the cnf parameter inside Wallet Attestation\n * @param options.codeChallengeMethodsSupported - Supported code challenge methods from Authorization Server\n * @param options.dpop - DPoP signer options (alg, publicJwk.kid). Required when JAR signing is enabled; omitted for unsigned requests\n * @param options.jti - Optional JWT ID for PAR (auto-generated if not provided)\n * @param options.pkceCodeVerifier - Optional PKCE code verifier (auto-generated if not provided)\n * @param options.redirectUri - Redirect URI for the authorization response\n * @param options.responseMode - Response mode (must be supported by Credential Issuer)\n * @param options.scope - OAuth 2.0 scope to request\n * @param options.state - Optional state parameter (auto-generated if not provided)\n * @param options.expiresAt - Optional JWT expiration time (defaults to 1 hour from issuedAt)\n * @param options.issuedAt - Optional JWT issued at time (defaults to current time)\n *\n * @returns A promise resolving to either:\n * - `PushedAuthorizationRequestSigned` when JAR signing is required (contains `request` JWT)\n * - `PushedAuthorizationRequestUnsigned` when JAR signing is not required (contains `authorizationRequest` object)\n *\n * @throws {PushedAuthorizationRequestError} If DPoP signer is missing required properties (alg, publicJwk.kid)\n * @throws {PushedAuthorizationRequestError} If PKCE code challenge method is not supported\n * @throws {ZodError} If authorization request parameters fail validation\n *\n * @example\n * // Example 1: Create signed PAR (explicit)\n * const signedPar = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * dpop: { signer: { alg: 'ES256', publicJwk: { kid: 'key-1' } } },\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'form_post.jwt',\n * scope: 'openid',\n * authorizationServerMetadata: {\n * require_signed_request_object: true // Creates signed JAR\n * }\n * });\n * // signedPar.request contains the signed JWT\n *\n * @example\n * // Example 2: Create unsigned PAR (when Authorization Server allows it)\n * const unsignedPar = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'query',\n * scope: 'openid',\n * authorizationServerMetadata: {\n * require_signed_request_object: false // Creates unsigned request — dpop not needed\n * }\n * });\n * // unsignedPar.authorizationRequest contains the plain object\n *\n * @example\n * // Example 3: Default behavior (no metadata - unsigned)\n * const par = await createPushedAuthorizationRequest({\n * audience: 'https://issuer.example.com',\n * callbacks: { generateRandom, hash, signJwt },\n * clientId: 'wallet_client_thumbprint',\n * codeChallengeMethodsSupported: ['S256'],\n * redirectUri: 'https://wallet.example.com/callback',\n * responseMode: 'form_post.jwt',\n * scope: 'openid'\n * // No authorizationServerMetadata — defaults to unsigned, dpop not needed\n * });\n * // par.authorizationRequest contains the plain object (permissive default)\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9126 RFC 9126 - OAuth 2.0 Pushed Authorization Requests}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101 RFC 9101 - JWT-Secured Authorization Request (JAR)}\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5 - require_signed_request_object}\n */\n// Function overloads for type narrowing based on require_signed_request_object\nexport async function createPushedAuthorizationRequest(\n options: {\n authorizationServerMetadata: { require_signed_request_object: true };\n dpop: RequestDpopOptions;\n } & CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestSigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: {\n authorizationServerMetadata: { require_signed_request_object: false };\n } & CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequestUnsigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest>;\n\n// Implementation\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest> {\n // PKCE\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const authorizationRequest = zAuthorizationRequest.parse({\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n redirect_uri: options.redirectUri,\n response_mode: options.responseMode,\n response_type: \"code\",\n scope: options.scope,\n state:\n options.state ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n });\n\n // Check if JAR signing is required\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n if (requireSigned) {\n // Create signed JAR (JWT-Secured Authorization Request)\n const { dpop } = options;\n if (!dpop || !dpop.signer.alg || !dpop.signer.publicJwk?.kid) {\n throw new PushedAuthorizationRequestError(\n \"DPoP signer must have alg and publicJwk.kid properties\",\n );\n }\n\n const iat = options.issuedAt ?? new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, JWT_EXPIRY_SECONDS);\n const requestJwt = await options.callbacks.signJwt(dpop.signer, {\n header: {\n alg: dpop.signer.alg,\n kid: dpop.signer.publicJwk.kid,\n typ: \"jwt\",\n },\n payload: {\n aud: options.audience,\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: dpop.signer.publicJwk.kid,\n ...authorizationRequest,\n },\n });\n\n return {\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n request: requestJwt.jwt,\n };\n } else {\n // Create unsigned authorization request\n return {\n authorizationRequest,\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n };\n }\n}\n","import z from \"zod\";\n\nconst zOpenidCredentialAuthorizationDetails = z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n});\n\nconst zItL2DocumentProofAuthorizationDetails = z.object({\n challenge_method: z.literal(\"mrtd+ias\"),\n challenge_redirect_uri: z.string().url(),\n idphinting: z.string().url(),\n type: z.literal(\"it_l2+document_proof\"),\n});\n\nexport const zAuthorizationRequest = z\n .object({\n authorization_details: z\n .array(\n z.discriminatedUnion(\"type\", [\n zOpenidCredentialAuthorizationDetails,\n zItL2DocumentProofAuthorizationDetails,\n ]),\n )\n .optional(),\n client_id: z.string(),\n code_challenge: z.string(),\n code_challenge_method: z.string(),\n issuer_state: z.optional(z.string()),\n jti: z.string(),\n redirect_uri: z.string().url(),\n response_mode: z.string(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n })\n .passthrough()\n .refine(\n (data) =>\n data.authorization_details !== undefined || data.scope !== undefined,\n {\n message: \"Either 'authorization_details' or 'scope' must be provided.\",\n path: [\"authorization_details\"],\n },\n );\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>;\n\nexport const zPushedAuthorizationRequestSigned = z\n .object({\n client_id: z\n .string()\n .describe(\n \"MUST be set to the thumbprint of the jwk value in the cnf parameter inside the Wallet Attestation.\",\n ),\n pkceCodeVerifier: z\n .string()\n .describe(\n \"Code verifier for PKCE. If not provided in CreatePushedAuthorizationRequestOptions, SDK will generate one.\",\n ),\n request: z\n .string()\n .describe(\n \"It MUST be a signed JWT. The private key corresponding to the public one in the cnf parameter inside the Wallet Attestation MUST be used for signing the Request Object.\",\n ),\n })\n .passthrough();\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nexport const zPushedAuthorizationRequestUnsigned = z\n .object({\n authorizationRequest: zAuthorizationRequest.describe(\n \"The authorization request parameters as a plain object. \" +\n \"Used when require_signed_request_object is false.\",\n ),\n client_id: z\n .string()\n .describe(\n \"Thumbprint of the jwk value in the cnf parameter inside Wallet Attestation.\",\n ),\n pkceCodeVerifier: z\n .string()\n .describe(\n \"PKCE code verifier. Auto-generated if not provided in options.\",\n ),\n })\n .passthrough();\nexport type PushedAuthorizationRequestUnsigned = z.infer<\n typeof zPushedAuthorizationRequestUnsigned\n>;\n\n/**\n * Union type for Pushed Authorization Request - can be either signed (JAR) or unsigned.\n * The variant depends on the Authorization Server's require_signed_request_object metadata.\n */\nexport type PushedAuthorizationRequest =\n | PushedAuthorizationRequestSigned\n | PushedAuthorizationRequestUnsigned;\n\nexport function isPushedAuthorizationRequestSigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestSigned {\n return \"request\" in par && typeof par.request === \"string\";\n}\n\nexport function isPushedAuthorizationRequestUnsigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestUnsigned {\n return \"authorizationRequest\" in par;\n}\n\nexport const zPushedAuthorizationResponse = z\n .object({\n expires_in: z.number().int(),\n request_uri: z.string(),\n })\n .passthrough();\nexport type PushedAuthorizationResponse = z.infer<\n typeof zPushedAuthorizationResponse\n>;\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n PushedAuthorizationRequest,\n PushedAuthorizationResponse,\n isPushedAuthorizationRequestSigned,\n zPushedAuthorizationResponse,\n} from \"./z-authorization-request\";\n\n/**\n * Configuration options for fetching pushed authorization response\n */\nexport interface fetchPushedAuthorizationResponseOptions {\n /**\n * Callback functions for making HTTP requests\n * Allows for custom fetch implementations\n */\n callbacks: Pick<CallbackContext, \"fetch\">;\n\n /**\n * The client attestation Demonstration of Proof-of-Possession (DPoP) token\n * Used for OAuth-Client-Attestation-PoP header to prove possession of the client key\n */\n clientAttestationDPoP: string;\n\n /**\n * The pushed authorization request to send. Accepts both signed (JAR) and unsigned variants\n * as returned by `createPushedAuthorizationRequest`. The correct form body is derived\n * automatically: signed requests POST `{ client_id, request }`, unsigned requests POST\n * every field from `authorizationRequest` as flat form parameters.\n */\n pushedAuthorizationRequest: PushedAuthorizationRequest;\n\n /**\n * The endpoint URL where the pushed authorization request will be sent\n * This should be the authorization server's PAR endpoint\n */\n pushedAuthorizationRequestEndpoint: string;\n\n /**\n * The wallet attestation JWT that proves the client's identity and capabilities\n * Used for OAuth-Client-Attestation header\n */\n walletAttestation: string;\n}\n\n/**\n * Sends a pushed authorization request to the authorization server and returns the response.\n *\n * Supports both signed (JAR) and unsigned PAR variants as produced by\n * `createPushedAuthorizationRequest`. The form body is built automatically:\n * - **Signed**: posts `{ client_id, request }`.\n * - **Unsigned**: posts every field from `authorizationRequest` as flat form\n * parameters, with object/array values (e.g. `authorization_details`)\n * JSON-serialised.\n *\n * @param options - Configuration options for the pushed authorization request\n * @returns Promise that resolves to the parsed pushed authorization response containing request_uri and expires_in\n * @throws {UnexpectedStatusCodeError} When the server returns a non-201 status code\n * @throws {ValidationError} When the response cannot be parsed or is invalid\n */\nexport async function fetchPushedAuthorizationResponse(\n options: fetchPushedAuthorizationResponseOptions,\n): Promise<PushedAuthorizationResponse> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const body = isPushedAuthorizationRequestSigned(\n options.pushedAuthorizationRequest,\n )\n ? new URLSearchParams({\n client_id: options.pushedAuthorizationRequest.client_id,\n request: options.pushedAuthorizationRequest.request,\n })\n : toURLSearchParams(\n options.pushedAuthorizationRequest.authorizationRequest,\n );\n\n const parResponse = await fetch(\n options.pushedAuthorizationRequestEndpoint,\n {\n body,\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.FORM_URLENCODED,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n },\n );\n\n await hasStatusOrThrow(201, UnexpectedStatusCodeError)(parResponse);\n\n const parResponseJson = await parResponse.json();\n\n const parsedParResponse =\n zPushedAuthorizationResponse.safeParse(parResponseJson);\n if (!parsedParResponse.success) {\n throw new ValidationError(\n `Failed to parse pushed authorization response`,\n parsedParResponse.error,\n );\n }\n\n return parsedParResponse.data;\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new PushedAuthorizationRequestError(\n `Unexpected error during pushed authorization request: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n\nfunction toURLSearchParams(data: Record<string, unknown>): URLSearchParams {\n const params = new URLSearchParams();\n\n Object.entries(data).forEach(([key, value]) => {\n if (value === undefined) return;\n\n params.append(\n key,\n typeof value === \"object\" ? JSON.stringify(value) : String(value),\n );\n });\n\n return params;\n}\n","import type { RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { extractClientAttestationJwtsFromHeaders } from \"../client-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop\";\n\nexport interface ParseAuthorizationRequestOptions {\n request: RequestLike;\n}\n\nexport interface ParseAuthorizationRequestResult {\n /**\n * The client attestation jwts from the authorization request headers.\n * These have not been verified yet.\n */\n clientAttestation?: {\n clientAttestationPopJwt: string;\n walletAttestationJwt: string;\n };\n\n /**\n * The dpop jwt from the authorization request DPoP header.\n *\n * The signer of the jwt has not been verified yet, this only happens during verification.\n */\n dpop?: {\n jwt: string;\n };\n}\n\n/**\n * Parse an authorization request by extracting DPoP and client attestation\n * information from HTTP request headers.\n *\n * **Important:** This function performs extraction and basic format validation\n * but does NOT verify cryptographic signatures. JWT signature verification\n * should be performed separately using the appropriate verification functions.\n *\n * @returns Parsed authorization request result containing:\n * - `dpop` - DPoP information if present (jwt)\n * - `clientAttestation` - Client attestation JWTs if present\n *\n * @throws {Oauth2Error} When DPoP JWT format is invalid\n * @throws {Oauth2Error} When client attestation headers are incomplete\n */\nexport function parseAuthorizationRequest(\n options: ParseAuthorizationRequestOptions,\n): ParseAuthorizationRequestResult {\n // We only parse the dpop, we don't verify it yet\n const extractedDpopJwt = extractDpopJwtFromHeaders(options.request.headers);\n if (!extractedDpopJwt.valid) {\n throw new Oauth2Error(\n \"Request contains a 'DPoP' header, but the value is not a valid DPoP jwt\",\n );\n }\n\n // We only parse the client attestations, we don't verify it yet\n const extractedClientAttestationJwts =\n extractClientAttestationJwtsFromHeaders(options.request.headers);\n if (!extractedClientAttestationJwts.valid) {\n throw new Oauth2Error(\n \"Request contains client attestation header, but the values are not valid client attestation and client attestation PoP header.\",\n );\n }\n\n return {\n clientAttestation: extractedClientAttestationJwts.walletAttestationHeader\n ? {\n clientAttestationPopJwt:\n extractedClientAttestationJwts.clientAttestationPopHeader,\n walletAttestationJwt:\n extractedClientAttestationJwts.walletAttestationHeader,\n }\n : undefined,\n dpop: extractedDpopJwt.dpopJwt\n ? {\n jwt: extractedDpopJwt.dpopJwt,\n }\n : undefined,\n };\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n formatZodError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"../errors\";\nimport {\n isJarAuthorizationRequest,\n parseJarRequest,\n zJarAuthorizationRequest,\n} from \"../jar\";\nimport {\n ParseAuthorizationRequestResult,\n parseAuthorizationRequest,\n} from \"./parse-authorization-request\";\nimport {\n AuthorizationRequest,\n zAuthorizationRequest,\n} from \"./z-authorization-request\";\n\nexport interface ParsePushedAuthorizationRequestOptions {\n authorizationRequest: unknown;\n callbacks: Pick<CallbackContext, \"fetch\">;\n request: RequestLike;\n}\n\nexport interface ParsePushedAuthorizationRequestResult\n extends ParseAuthorizationRequestResult {\n authorizationRequest: AuthorizationRequest;\n\n /**\n * The JWT-secured request object, if the request was pushed as a JAR.\n * May be undefined if the request object is not a JAR.\n */\n authorizationRequestJwt?: string;\n}\n\n/**\n * Parses and validates a pushed authorization request (PAR).\n *\n * Handles both standard authorization requests and JWT-secured Authorization Requests (JAR).\n * When a JAR is provided, it validates the JWT structure, decodes it, and extracts the\n * authorization request from the payload. Also extracts client attestation and DPoP proofs\n * from the HTTP request headers.\n *\n * @param options - Configuration for parsing the pushed authorization request\n * @param options.authorizationRequest - The authorization request data to parse (can be standard or JAR format)\n * @param options.callbacks - Callbacks for external operations (requires `fetch` for JAR validation)\n * @param options.request - The HTTP request object containing headers for client attestation and DPoP\n * @returns A promise resolving to the parsed authorization request with extracted metadata\n * @throws {Oauth2Error} When the authorization request is invalid or cannot be parsed\n */\nexport async function parsePushedAuthorizationRequest(\n options: ParsePushedAuthorizationRequestOptions,\n): Promise<ParsePushedAuthorizationRequestResult> {\n const parsed = parseWithErrorHandling(\n z.union([zAuthorizationRequest, zJarAuthorizationRequest]),\n options.authorizationRequest,\n \"Invalid authorization request. Could not parse authorization request or jar.\",\n );\n\n let parsedAuthorizationRequest: ReturnType<\n typeof zAuthorizationRequest.safeParse\n >;\n\n let authorizationRequestJwt: string | undefined;\n if (isJarAuthorizationRequest(parsed)) {\n const parsedJar = await parseJarRequest({\n callbacks: options.callbacks,\n jarRequestParams: parsed,\n });\n\n const jwt = decodeJwt({ jwt: parsedJar.authorizationRequestJwt });\n\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(jwt.payload);\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2Error(\n `Invalid authorization request. Could not parse jar request payload.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n );\n }\n\n authorizationRequestJwt = parsedJar.authorizationRequestJwt;\n } else {\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(\n options.authorizationRequest,\n );\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2Error(\n `Error occurred during validation of pushed authorization request.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n );\n }\n }\n\n const authorizationRequest = parsedAuthorizationRequest.data;\n const { clientAttestation, dpop } = parseAuthorizationRequest({\n request: options.request,\n });\n\n return {\n authorizationRequest,\n authorizationRequestJwt,\n clientAttestation,\n dpop,\n };\n}\n","import { type CallbackContext } from \"@openid4vc/oauth2\";\nimport { addSecondsToDate, dateToSeconds } from \"@pagopa/io-wallet-utils\";\n\nimport type { Jwk } from \"../common/jwk/z-jwk\";\nimport type { JweEncryptor, JwtSigner } from \"../common/jwt/z-jwt\";\nimport type {\n JarAuthorizationRequest,\n JarRequestObjectHeader,\n JarRequestObjectPayload,\n} from \"./z-jar\";\n\nimport { Oauth2Error } from \"../errors\";\n\nexport interface CreateJarRequestOptions {\n /**\n * Additional claims merged into the request object payload before\n * `authorizationRequestPayload`.\n */\n additionalJwtPayload?: Record<string, unknown>;\n\n /**\n * Authorization request claims used as JWT header parameters.\n */\n authorizationRequestHeader: JarRequestObjectHeader;\n\n /**\n * Authorization request claims used as JWT payload.\n */\n authorizationRequestPayload: JarRequestObjectPayload;\n\n /**\n * Cryptographic callbacks used to sign and optionally encrypt the JAR.\n */\n callbacks: Partial<Pick<CallbackContext, \"encryptJwe\">> &\n Pick<CallbackContext, \"signJwt\">;\n\n /**\n * Request object lifetime in seconds from `now`.\n */\n expiresInSeconds: number;\n\n /**\n * Encryptor configuration. When provided, the signed request object is wrapped\n * as JWE and returned as encrypted `request` value.\n */\n jweEncryptor?: JweEncryptor;\n\n /**\n * Signer configuration used to produce the request object JWT.\n */\n jwtSigner: JwtSigner;\n\n /**\n * Date that should be used as now. If not provided current date will be used.\n */\n now?: Date;\n\n /**\n * Optional request URI for by-reference JAR transmission.\n * When provided, `jarAuthorizationRequest` will include `request_uri` instead of `request`.\n */\n requestUri?: string;\n}\n\nexport interface CreateJarRequestResult {\n /**\n * The signed (and optionally encrypted) JWT string representing the authorization request.\n * This value is included in `jarAuthorizationRequest` when `requestUri` is not provided.\n */\n authorizationRequestJwt: string;\n\n /**\n * The JWK used for encryption when `jweEncryptor` is provided, otherwise undefined.\n */\n encryptionJwk?: Jwk;\n\n /**\n * The JAR authorization request parameters to be sent to the authorization endpoint.\n * Contains either `request` or `request_uri` depending on the presence of `requestUri` in options.\n */\n jarAuthorizationRequest: JarAuthorizationRequest;\n\n /**\n * The JWK used for signing the request object JWT.\n */\n signerJwk: Jwk;\n}\n\n/**\n * Creates a JWT Secured Authorization Request (JAR) request payload.\n *\n * The request object is always signed, and optionally encrypted when `jweEncryptor`\n * is provided. The returned `jarAuthorizationRequest` is created in one of two forms:\n * - by-value, with `request`\n * - by-reference, with `request_uri`\n *\n * @param options - Parameters used to create the JAR request\n * @param options.additionalJwtPayload - Additional JWT claims merged before authorization claims\n * @param options.authorizationRequestPayload - Base authorization request JWT payload\n * @param options.authorizationRequestHeader - JWT header parameters for the request object\n * @param options.callbacks - Callback context with required `signJwt` and optional `encryptJwe`\n * @param options.expiresInSeconds - JWT expiration offset in seconds\n * @param options.jweEncryptor - Optional JWE encryptor to wrap the signed JWT\n * @param options.jwtSigner - JWT signer used for request object signing\n * @param options.now - Optional reference time used for `iat` and `exp`\n * @param options.requestUri - Optional request URI for by-reference transmission\n *\n * @returns Signed (and optionally encrypted) authorization request data, signer key material,\n * and JAR request parameters for transmission.\n */\nexport async function createJarRequest(\n options: CreateJarRequestOptions,\n): Promise<CreateJarRequestResult> {\n const {\n authorizationRequestHeader,\n authorizationRequestPayload,\n callbacks,\n jweEncryptor,\n jwtSigner,\n requestUri,\n } = options;\n\n let authorizationRequestJwt: string | undefined;\n let encryptionJwk: Jwk | undefined;\n\n const now = options.now ?? new Date();\n\n const { jwt, signerJwk } = await callbacks.signJwt(jwtSigner, {\n header: authorizationRequestHeader,\n payload: {\n ...options.additionalJwtPayload,\n ...authorizationRequestPayload,\n exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n iat: dateToSeconds(now),\n },\n });\n\n authorizationRequestJwt = jwt;\n\n if (jweEncryptor) {\n if (!callbacks.encryptJwe) {\n throw new Oauth2Error(\n \"callbacks.encryptJwe is required when jweEncryptor is provided\",\n );\n }\n const encryptionResult = await callbacks.encryptJwe(\n jweEncryptor,\n authorizationRequestJwt,\n );\n authorizationRequestJwt = encryptionResult.jwe;\n encryptionJwk = encryptionResult.encryptionJwk;\n }\n\n const client_id = authorizationRequestPayload.client_id;\n const jarAuthorizationRequest: JarAuthorizationRequest = requestUri\n ? { client_id, request_uri: requestUri }\n : { client_id, request: authorizationRequestJwt };\n\n return {\n authorizationRequestJwt,\n encryptionJwk,\n jarAuthorizationRequest,\n signerJwk,\n };\n}\n","import {\n ContentType,\n type Fetch,\n UnexpectedStatusCodeError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\n\nexport async function fetchJarRequestObject(options: {\n fetch?: Fetch;\n requestUri: string;\n}): Promise<string> {\n const { fetch, requestUri } = options;\n\n /**\n * Prioritizes OAuth-specific JWT format, with fallbacks to generic JWT and plain text.\n * Quality values (q) indicate preference: 1.0 (default) > 0.9.\n */\n const JAR_ACCEPT_HEADER = [\n ContentType.OAuthAuthorizationRequestJwt, // Preferred: application/oauth-authz-req+jwt\n `${ContentType.Jwt};q=0.9`, // Fallback: application/jwt\n \"text/plain\", // Final fallback: text/plain\n ].join(\", \");\n\n const response = await createFetcher(fetch)(requestUri, {\n headers: {\n Accept: JAR_ACCEPT_HEADER,\n },\n method: \"GET\",\n }).catch(() => {\n throw new Oauth2Error(\n `Fetching request_object from request_uri '${requestUri}' failed`,\n );\n });\n\n await hasStatusOrThrow(200, UnexpectedStatusCodeError)(response);\n\n return await response.text();\n}\n","import { Oauth2Error } from \"../errors\";\nimport { JarAuthorizationRequest } from \"./z-jar\";\n\nexport function validateJarRequestParams(options: {\n jarRequestParams: JarAuthorizationRequest;\n}) {\n const { jarRequestParams } = options;\n\n if (jarRequestParams.request && jarRequestParams.request_uri) {\n throw new Oauth2Error(\n \"request and request_uri cannot both be present in a JAR request\",\n );\n }\n\n if (!jarRequestParams.request && !jarRequestParams.request_uri) {\n throw new Oauth2Error(\"request or request_uri must be present\");\n }\n\n return jarRequestParams as (\n | { request: string; request_uri?: never }\n | { request?: never; request_uri: string }\n ) &\n JarAuthorizationRequest;\n}\n","import { CallbackContext } from \"@openid4vc/oauth2\";\n\nimport { fetchJarRequestObject } from \"./fetch-jar-request-object\";\nimport { validateJarRequestParams } from \"./validate-jar-request\";\nimport { JarAuthorizationRequest } from \"./z-jar\";\n\nexport interface ParsedJarRequestOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n jarRequestParams: JarAuthorizationRequest;\n}\n\nexport interface ParsedJarRequest {\n authorizationRequestJwt: string;\n sendBy: \"reference\" | \"value\";\n}\n\nexport function isJarAuthorizationRequest(\n request: JarAuthorizationRequest,\n): request is JarAuthorizationRequest {\n return \"request\" in request || \"request_uri\" in request;\n}\n\n/**\n * Parse a JAR (JWT Secured Authorization Request) request by validating and optionally fetch from uri.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns An object containing the transmission method ('value' or 'reference') and the JWT request object.\n */\nexport async function parseJarRequest(\n options: ParsedJarRequestOptions,\n): Promise<ParsedJarRequest> {\n const { callbacks } = options;\n\n const jarRequestParams = {\n ...validateJarRequestParams(options),\n ...options.jarRequestParams,\n } as JarAuthorizationRequest & ReturnType<typeof validateJarRequestParams>;\n\n const sendBy = jarRequestParams.request ? \"value\" : \"reference\";\n\n const authorizationRequestJwt =\n jarRequestParams.request ??\n (await fetchJarRequestObject({\n fetch: callbacks.fetch,\n requestUri: jarRequestParams.request_uri,\n }));\n\n return { authorizationRequestJwt, sendBy };\n}\n","import {\n CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n decodeJwt,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport {\n JarRequestObjectPayload,\n jwtAuthorizationRequestJwtHeaderTyp,\n signedAuthorizationRequestJwtHeaderTyp,\n zJarRequestObjectPayload,\n} from \"./z-jar\";\n\nexport interface VerifyJarRequestOptions {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jarRequestParams: {\n client_id?: string;\n };\n jwtSigner: JwtSigner;\n now?: Date;\n}\n\nexport interface VerifiedJarRequest {\n authorizationRequestPayload: JarRequestObjectPayload;\n jwt: {\n payload: JarRequestObjectPayload;\n } & Omit<ReturnType<typeof decodeJwt>, \"payload\">;\n signer: JwtSignerWithJwk;\n}\n\n/**\n * Verifies a JAR (JWT Secured Authorization Request) request by validating and verifying signatures.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns The verified authorization request parameters and metadata\n */\nexport async function verifyJarRequest(\n options: VerifyJarRequestOptions,\n): Promise<VerifiedJarRequest> {\n const { authorizationRequestJwt, callbacks, jarRequestParams, jwtSigner } =\n options;\n\n /* Encryption is not supported */\n const requestObjectIsEncrypted = zCompactJwe.safeParse(\n authorizationRequestJwt,\n ).success;\n if (requestObjectIsEncrypted) {\n throw new Oauth2Error(\"Encrypted JWE request objects are not supported.\");\n }\n\n const requestIsSigned = zCompactJwt.safeParse(\n authorizationRequestJwt,\n ).success;\n if (!requestIsSigned) {\n throw new Oauth2Error(\"JAR request object is not a valid JWT.\");\n }\n\n const { authorizationRequestPayload, jwt, signer } =\n await verifyJarRequestObject({\n authorizationRequestJwt,\n callbacks,\n jwtSigner,\n });\n\n if (!authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n 'Jar Request Object is missing the required \"client_id\" field.',\n );\n }\n\n // Expect the client_id from the jar request to match the payload\n if (jarRequestParams.client_id !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n \"client_id does not match the request object client_id.\",\n );\n }\n\n if (jwt.payload.iss !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\"iss claim in request JWT does not match client_id\");\n }\n\n // RFC 9101 §4: exp claim MUST be present and not in the past\n if (jwt.payload.exp === undefined) {\n throw new Oauth2Error(\"exp claim in request JWT is missing\");\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (nowSeconds > jwt.payload.exp) {\n throw new Oauth2Error(\"exp claim in request JWT is expired\");\n }\n\n // IT-Wallet requirement: iat MUST be present\n if (jwt.payload.iat === undefined) {\n throw new Oauth2Error(\"iat claim in request JWT is missing\");\n }\n\n // IT-Wallet requirement: iat MUST not be more than 5 minutes in the past\n const MAX_IAT_AGE_SECONDS = 5 * 60;\n if (nowSeconds - jwt.payload.iat > MAX_IAT_AGE_SECONDS) {\n throw new Oauth2Error(\n \"iat claim in request JWT is too old (must be within 5 minutes)\",\n );\n }\n\n // IT-Wallet requirement: iat MUST not be more than clock-skew tolerance in the future\n const CLOCK_SKEW_TOLERANCE_SECONDS = 60;\n if (jwt.payload.iat - nowSeconds > CLOCK_SKEW_TOLERANCE_SECONDS) {\n throw new Oauth2Error(\"iat claim in request JWT is too far in the future\");\n }\n\n return {\n authorizationRequestPayload,\n jwt,\n signer,\n };\n}\n\nasync function verifyJarRequestObject(options: {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jwtSigner: JwtSigner;\n}) {\n const { authorizationRequestJwt, callbacks, jwtSigner } = options;\n\n const jwt = decodeJwt({ jwt: authorizationRequestJwt });\n const authorizationRequestPayload = parseWithErrorHandling(\n zJarRequestObjectPayload,\n jwt.payload,\n );\n\n const { signer } = await verifyJwt({\n compact: authorizationRequestJwt,\n header: jwt.header,\n payload: authorizationRequestPayload,\n signer: jwtSigner,\n\n verifyJwtCallback: callbacks.verifyJwt,\n });\n\n // Some existing deployments may alternatively be using both type\n if (\n jwt.header.typ !== signedAuthorizationRequestJwtHeaderTyp &&\n jwt.header.typ !== jwtAuthorizationRequestJwtHeaderTyp\n ) {\n throw new Oauth2Error(\n `Invalid Jar Request Object typ header. Expected \"oauth-authz-req+jwt\" or \"jwt\", received \"${jwt.header.typ}\".`,\n );\n }\n\n return {\n authorizationRequestPayload,\n jwt: {\n ...jwt,\n payload: authorizationRequestPayload,\n },\n signer,\n };\n}\n","import z from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zJarAuthorizationRequest = z\n .object({\n client_id: z.optional(z.string()),\n request: z.optional(z.string()),\n request_uri: z.string().url().optional(),\n })\n .passthrough();\n\nexport type JarAuthorizationRequest = z.infer<typeof zJarAuthorizationRequest>;\n\nexport const zJarRequestObjectPayload = z\n .object({\n ...zJwtPayload.shape,\n client_id: z.string(),\n })\n .passthrough();\n\nexport type JarRequestObjectPayload = z.infer<typeof zJarRequestObjectPayload>;\n\nexport const zSignedAuthorizationRequestJwtHeaderTyp = z.literal(\n \"oauth-authz-req+jwt\",\n);\n\nexport const zJarRequestObjectHeader = z\n .object({\n ...zJwtHeader.shape,\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n })\n .passthrough();\n\nexport type JarRequestObjectHeader = z.infer<typeof zJarRequestObjectHeader>;\n\nexport const signedAuthorizationRequestJwtHeaderTyp =\n zSignedAuthorizationRequestJwtHeaderTyp.value;\n\nconst zJwtAuthorizationRequestJwtHeaderTyp = z.literal(\"jwt\");\nexport const jwtAuthorizationRequestJwtHeaderTyp =\n zJwtAuthorizationRequestJwtHeaderTyp.value;\n","import {\n AuthorizationServerMetadata,\n CallbackContext,\n} from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport {\n ClientAttestationOptions,\n VerifiedClientAttestationPopJwt,\n VerifiedWalletAttestationJwt,\n verifyClientAttestation,\n} from \"../client-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { verifyTokenDPoP } from \"../token-dpop\";\n\nexport interface VerifyAuthorizationRequestDPoP {\n /**\n * Allowed dpop signing alg values. If not provided\n * any alg values are allowed and it's up to the `verifyJwtCallback`\n * to handle the alg.\n */\n allowedSigningAlgs?: string[];\n\n /**\n * The dpop jwt from the pushed authorization request.\n * If dpop is required, `jwt` MUST be provided\n */\n jwt?: string;\n\n /**\n * Whether dpop is required.\n */\n required?: boolean;\n}\n\nexport interface VerifyAuthorizationRequestResult {\n /**\n * The verified client attestation if any were provided.\n */\n clientAttestation?: {\n clientAttestation: VerifiedWalletAttestationJwt;\n clientAttestationPop: VerifiedClientAttestationPopJwt;\n };\n\n dpop?: {\n /**\n * The JWK will be returned if a DPoP proof was provided in the header.\n */\n jwk?: Jwk;\n\n /**\n * base64url encoding of the JWK SHA-256 Thumbprint (according to [RFC7638])\n * of the DPoP public key (in JWK format).\n *\n * This will always be returned if dpop is used for the PAR endpoint\n */\n jwkThumbprint: string;\n };\n}\n\nexport interface VerifyAuthorizationRequestOptions {\n authorizationRequest: {\n client_id?: string;\n };\n\n authorizationServerMetadata: AuthorizationServerMetadata;\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">;\n\n clientAttestation: ClientAttestationOptions;\n config: IoWalletSdkConfig;\n dpop?: VerifyAuthorizationRequestDPoP;\n\n /**\n * The current time to use when verifying the JWTs.\n * If not provided current time will be used.\n *\n * @default new Date()\n */\n now?: Date;\n\n request: RequestLike;\n}\n\n/**\n * Verifies an authorization request by validating DPoP and client attestation credentials.\n *\n * This function performs cryptographic verification of DPoP proofs and client attestation\n * JWTs extracted from authorization request headers. It validates signatures, checks\n * expiration times, and optionally ensures that DPoP and client attestation use the same key.\n *\n * **Important:** This function performs verification only. Use `parseAuthorizationRequest`\n * first to extract the necessary JWTs from request headers.\n *\n * @param options - The verification options\n * @param options.authorizationRequest - The authorization request parameters containing client_id\n * @param options.authorizationServerMetadata - Authorization server metadata including issuer\n * @param options.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.dpop.jwt - The DPoP JWT extracted from request headers\n * @param options.dpop.required - Whether DPoP is required (will throw if missing)\n * @param options.dpop.allowedSigningAlgs - Allowed signing algorithms for DPoP\n * @param options.clientAttestation - Client attestation verification configuration\n * @param options.clientAttestation.walletAttestationJwt - The wallet attestation JWT from headers\n * @param options.clientAttestation.clientAttestationPopJwt - The client attestation PoP JWT from headers\n * @param options.clientAttestation.ensureConfirmationKeyMatchesDpopKey - Whether to verify DPoP and client attestation use the same key\n * @param options.request - The HTTP request object containing URL and headers\n * @param options.now - Optional date for time-based validation (defaults to current time)\n *\n * @returns A promise resolving to verification results containing:\n * - `dpop` - Verified DPoP information including JWK and thumbprint (if DPoP was provided)\n * - `clientAttestation` - Verified client attestation JWTs (if client attestation was provided)\n *\n * @throws {Oauth2Error} When DPoP is required but missing\n * @throws {Oauth2Error} When client attestation is required but missing\n * @throws {Oauth2Error} When client_id doesn't match between request and client attestation\n * @throws {Oauth2Error} When DPoP and client attestation keys don't match (if ensureConfirmationKeyMatchesDpopKey is true)\n * @throws {Oauth2Error} When JWT signature verification fails\n * @throws {Oauth2Error} When JWT is expired or has invalid claims\n *\n * @example\n * ```typescript\n * const result = await verifyAuthorizationRequest({\n * authorizationRequest: { client_id: 'client-123' },\n * authorizationServerMetadata: { issuer: 'https://auth.example.com' },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * dpop: {\n * jwt: dpopJwtFromHeaders,\n * required: true,\n * allowedSigningAlgs: ['ES256']\n * },\n * clientAttestation: {\n * walletAttestationJwt: clientAttJwtFromHeaders,\n * clientAttestationPopJwt: clientAttPopJwtFromHeaders,\n * required: true,\n * ensureConfirmationKeyMatchesDpopKey: true\n * },\n * request: httpRequest\n * });\n *\n * console.log(result.dpop?.jwkThumbprint);\n * console.log(result.clientAttestation?.clientAttestation.payload.sub);\n * ```\n */\nexport async function verifyAuthorizationRequest(\n options: VerifyAuthorizationRequestOptions,\n): Promise<VerifyAuthorizationRequestResult> {\n const dpopResult = options.dpop\n ? await verifyAuthorizationRequestDpop(\n options.dpop,\n options.request,\n options.callbacks,\n options.now,\n )\n : undefined;\n\n const clientAttestationResult = await verifyClientAttestation({\n authorizationServerMetadata: options.authorizationServerMetadata,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestation,\n config: options.config,\n dpopJwkThumbprint: dpopResult?.jwkThumbprint,\n now: options.now,\n requestClientId: options.authorizationRequest.client_id,\n });\n\n return {\n clientAttestation: clientAttestationResult,\n dpop: dpopResult?.jwkThumbprint\n ? {\n jwk: dpopResult.jwk,\n jwkThumbprint: dpopResult.jwkThumbprint,\n }\n : undefined,\n };\n}\n\nasync function verifyAuthorizationRequestDpop(\n options: VerifyAuthorizationRequestDPoP,\n request: RequestLike,\n callbacks: Pick<CallbackContext, \"hash\" | \"verifyJwt\">,\n now?: Date,\n) {\n if (options.required && !options.jwt) {\n throw new Oauth2Error(\n `Missing required DPoP parameters in authorization request. DPoP header is required.`,\n );\n }\n\n const verifyDpopResult = options.jwt\n ? await verifyTokenDPoP({\n allowedSigningAlgs: options.allowedSigningAlgs,\n callbacks,\n dpopJwt: options.jwt,\n now,\n request,\n })\n : undefined;\n\n return {\n jwk: verifyDpopResult?.header.jwk,\n jwkThumbprint: verifyDpopResult?.jwkThumbprint,\n };\n}\n","import { JwtSigner } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { VerifiedJarRequest, verifyJarRequest } from \"../jar\";\nimport {\n type VerifyAuthorizationRequestOptions,\n type VerifyAuthorizationRequestResult,\n verifyAuthorizationRequest,\n} from \"./verify-authorization-request\";\n\nexport interface VerifyPushedAuthorizationRequestReturn\n extends VerifyAuthorizationRequestResult {\n /**\n * The verified JAR request, if `authorizationRequestJwt` was provided\n */\n jar?: VerifiedJarRequest;\n}\n\nexport interface VerifyPushedAuthorizationRequestOptions\n extends Omit<\n VerifyAuthorizationRequestOptions,\n \"authorizationServerMetadata\"\n > {\n /**\n * The authorization request JWT to verify. If this value was returned from `parsePushedAuthorizationRequest`\n * you MUST provide this value to ensure the JWT is verified.\n */\n authorizationRequestJwt?: {\n jwt: string;\n signer: JwtSigner;\n };\n\n /**\n * Authorization Server metadata for enforcing JAR signing policy.\n * Includes standard Authorization Server metadata plus require_signed_request_object.\n * When require_signed_request_object is true, the server will reject unsigned requests.\n * Defaults to false (permissive) if not provided.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5}\n */\n authorizationServerMetadata: {\n require_signed_request_object?: boolean;\n } & VerifyAuthorizationRequestOptions[\"authorizationServerMetadata\"];\n}\n\n/**\n * Verifies a pushed authorization request (PAR) including JAR, DPoP, and client attestation.\n *\n * This function extends `verifyAuthorizationRequest` by adding support for JWT-secured\n * Authorization Requests (JAR). It performs comprehensive verification of all security\n * mechanisms used in pushed authorization requests according to RFC 9126 (PAR) and\n * RFC 9101 (JAR).\n *\n * The verification process includes:\n * 1. JAR signing policy enforcement (per RFC 9101 Section 10.5) - validates require_signed_request_object\n * 2. JAR request object verification (if provided) - validates JWT signature and claims\n * 3. RFC 9101 §4 claim validation - validates iss, aud, exp, iat claims\n * 4. IT-Wallet specific validations - iat age limits and key binding with wallet attestation\n * 5. DPoP proof verification (if provided) - validates proof of possession\n * 6. Client attestation verification - validates client identity\n *\n * **JAR Signing Policy (RFC 9101):**\n * When `authorizationServerMetadata.require_signed_request_object` is true:\n * - Rejects requests without signed JAR (downgrade attack protection)\n * - Rejects JAR with algorithm \"none\" (security requirement)\n * When false or omitted (default): accepts both signed and unsigned requests\n *\n * **Important:** Use `parsePushedAuthorizationRequest` first to extract the necessary\n * JWTs from request headers and body.\n *\n * @param options - The verification options\n * @param options.authorizationRequest - The authorization request parameters containing client_id\n * @param options.authorizationServerMetadata - Authorization server metadata\n * @param options.authorizationServerMetadata.issuer - Authorization server issuer URL\n * @param options.authorizationServerMetadata.require_signed_request_object - Whether to enforce JAR signing (defaults to false)\n * @param options.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.authorizationRequestJwt - Optional JAR JWT and signer information\n * @param options.authorizationRequestJwt.jwt - The JAR JWT string from request parameter\n * @param options.authorizationRequestJwt.signer - The JWT signer for verification (from federation metadata)\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.dpop.jwt - The DPoP JWT extracted from request headers\n * @param options.dpop.required - Whether DPoP is required (will throw if missing)\n * @param options.dpop.allowedSigningAlgs - Allowed signing algorithms for DPoP\n * @param options.clientAttestation - Optional client attestation verification configuration\n * @param options.clientAttestation.walletAttestationJwt - The wallet attestation JWT from headers\n * @param options.clientAttestation.clientAttestationPopJwt - The client attestation PoP JWT from headers\n * @param options.clientAttestation.required - Whether client attestation is required (will throw if missing)\n * @param options.clientAttestation.ensureConfirmationKeyMatchesDpopKey - Whether to verify DPoP and client attestation use the same key\n * @param options.request - The HTTP request object containing URL and headers\n * @param options.now - Optional date for time-based validation (defaults to current time)\n *\n * @returns A promise resolving to verification results containing:\n * - `jar` - Verified JAR request including decoded payload and signer (if JAR was provided)\n * - `dpop` - Verified DPoP information including JWK and thumbprint (if DPoP was provided)\n * - `clientAttestation` - Verified client attestation JWTs (if client attestation was provided)\n *\n * @throws {PushedAuthorizationRequestError} When require_signed_request_object is true but request is unsigned\n * @throws {PushedAuthorizationRequestError} When require_signed_request_object is true but JAR uses alg=\"none\"\n * @throws {PushedAuthorizationRequestError} When iss claim doesn't match client_id (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When aud claim doesn't match authorization server issuer (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When exp claim is missing or expired (RFC 9101 §4)\n * @throws {PushedAuthorizationRequestError} When iat claim is missing, too old (>5 min), or in future (>60s)\n * @throws {PushedAuthorizationRequestError} When kid doesn't match between JAR and wallet attestation cnf.jwk\n * @throws {PushedAuthorizationRequestError} When cnf.jwk is missing from wallet attestation\n * @throws {Oauth2Error} When JAR JWT verification fails\n * @throws {Oauth2Error} When JAR client_id doesn't match request client_id\n * @throws {Oauth2Error} When JAR request object is encrypted (not supported)\n * @throws {Oauth2Error} When DPoP is required but missing\n * @throws {Oauth2Error} When client attestation is required but missing\n * @throws {Oauth2Error} When client_id doesn't match between request and client attestation\n * @throws {Oauth2Error} When DPoP and client attestation keys don't match (if ensureConfirmationKeyMatchesDpopKey is true)\n * @throws {Oauth2Error} When any JWT signature verification fails\n * @throws {Oauth2Error} When any JWT is expired or has invalid claims\n *\n * @example\n * ```typescript\n * // Example 1: Enforce signed JAR (strict mode)\n * const result = await verifyPushedAuthorizationRequest({\n * authorizationRequest: parsed.authorizationRequest,\n * authorizationServerMetadata: {\n * issuer: 'https://auth.example.com',\n * require_signed_request_object: true // Reject unsigned requests\n * },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * authorizationRequestJwt: {\n * jwt: parsed.authorizationRequestJwt,\n * signer: clientSignerFromFederation\n * },\n * request: httpRequest\n * });\n *\n * // Example 2: Accept both signed and unsigned (permissive mode)\n * const result = await verifyPushedAuthorizationRequest({\n * authorizationRequest: parsed.authorizationRequest,\n * authorizationServerMetadata: {\n * issuer: 'https://auth.example.com',\n * require_signed_request_object: false // Accept unsigned requests\n * },\n * callbacks: { hash: hashCallback, verifyJwt: verifyJwtCallback },\n * authorizationRequestJwt: parsed.authorizationRequestJwt ? {\n * jwt: parsed.authorizationRequestJwt,\n * signer: clientSignerFromFederation\n * } : undefined,\n * request: httpRequest\n * });\n * ```\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc9101#section-10.5 RFC 9101 Section 10.5 - require_signed_request_object}\n */\nexport async function verifyPushedAuthorizationRequest(\n options: VerifyPushedAuthorizationRequestOptions,\n): Promise<VerifyPushedAuthorizationRequestReturn> {\n // Check if signed request objects are required (default to false for permissive server behavior)\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n // Enforce require_signed_request_object policy\n if (requireSigned && !options.authorizationRequestJwt) {\n throw new PushedAuthorizationRequestError(\n \"Authorization Server requires signed request objects (JAR) per RFC 9101, but request does not include a signed JWT\",\n );\n }\n\n let jar: VerifiedJarRequest | undefined;\n\n if (options.authorizationRequestJwt) {\n // Fail-fast: reject alg=\"none\" before expensive signature verification (RFC 9101 Section 10.5)\n if (requireSigned) {\n const decoded = decodeJwt({ jwt: options.authorizationRequestJwt.jwt });\n if (decoded.header.alg === \"none\") {\n throw new PushedAuthorizationRequestError(\n 'Authorization Server requires signed request objects, but JAR has algorithm \"none\"',\n );\n }\n }\n\n // Verify JAR signature and claims\n jar = await verifyJarRequest({\n authorizationRequestJwt: options.authorizationRequestJwt.jwt,\n callbacks: options.callbacks,\n jarRequestParams: options.authorizationRequest,\n jwtSigner: options.authorizationRequestJwt.signer,\n now: options.now,\n });\n\n // aud claim MUST identify this Authorization Server\n const issuer = options.authorizationServerMetadata.issuer;\n if (!issuer) {\n throw new PushedAuthorizationRequestError(\n \"authorizationServerMetadata.issuer is required to validate the aud claim in the request JWT\",\n );\n }\n const aud = jar.jwt.payload.aud;\n const audMatches =\n aud === issuer || (Array.isArray(aud) && aud.includes(issuer));\n if (!audMatches) {\n throw new PushedAuthorizationRequestError(\n \"aud claim in request JWT does not match the authorization server issuer\",\n );\n }\n }\n\n const { clientAttestation, dpop } = await verifyAuthorizationRequest(options);\n\n if (jar && clientAttestation) {\n const cnfJwk = clientAttestation.clientAttestation.payload.cnf.jwk;\n if (!cnfJwk) {\n throw new PushedAuthorizationRequestError(\n \"Missing wallet attestation or cnf.jwk\",\n );\n }\n // Validate kid match if present in both JAR header and cnf.jwk\n if (cnfJwk.kid !== undefined && jar.jwt.header.kid !== cnfJwk.kid) {\n throw new PushedAuthorizationRequestError(\n \"kid in request JWT header does not match wallet attestation cnf.jwk kid\",\n );\n }\n }\n\n return {\n clientAttestation,\n dpop,\n jar,\n };\n}\n","import { z } from \"zod\";\n\nexport const zCompactJwe = z\n .string()\n .regex(\n /^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/,\n {\n message: \"Not a valid compact jwe\",\n },\n );\n","import z from \"zod\";\n\nimport { DecodeJwtResult, decodeJwt } from \"./common/jwt/decode-jwt\";\nimport { Oauth2Error } from \"./errors\";\n\n/**\n * Options for extracting and decoding the JWT from a form_post.jwt response\n */\nexport interface GetJwtFromFormPostOptions<T> {\n /**\n * Raw HTML containing the autosubmitted form with the jwt response\n */\n formData: string;\n\n /**\n * Schema for parsing and validating\n */\n schema: z.ZodSchema<T>;\n}\n\n/*\n * Decode a form_post.jwt and return the final JWT.\n * The formData here is in form_post.jwt format as defined in\n * JWT Secured Authorization Response Mode for OAuth 2.0 (JARM)\n <!DOCTYPE html>\n <html>\n <head>\n <meta charset=\"utf-8\" />\n </head>\n <body onload=\"document.forms[0].submit()\">\n <noscript>\n <p>\n <strong>Note:</strong> Since your browser does not support JavaScript, you must press the Continue button once to proceed.\n </p>\n </noscript>\n <form action=\"iowalletexample//cb\" method=\"post\"> \n <div>\n <input type=\"hidden\" name=\"response\" value=\"somevalue\" />\n </div>\n <noscript>\n <div>\n <input type=\"submit\" value=\"Continue\" />\n </div>\n </noscript>\n </form>\n </body>\n </html>\n */\nexport const getJwtFromFormPost = async <T>(\n options: GetJwtFromFormPostOptions<T>,\n): Promise<{\n decodedJwt: DecodeJwtResult<undefined, z.ZodSchema<T>>;\n jwt: string;\n}> => {\n const inputRegex = /<input[^<>]*>/gi;\n const nameRegex = /name=\"response\"/gi;\n const valueRegex = /value=\"([^\"]*)\"/gi;\n const lineExpressionRegex = /\\r\\n|\\n\\r|\\n|\\r|\\s+/g;\n\n let match = inputRegex.exec(options.formData);\n while (match) {\n let matchName = nameRegex.exec(match[0]);\n while (matchName) {\n let matchValue = valueRegex.exec(match[0]);\n while (matchValue && matchValue[1]) {\n const responseJwt = matchValue[1];\n\n if (responseJwt) {\n const jwt = responseJwt.replace(lineExpressionRegex, \"\");\n const decodedJwt = decodeJwt({\n jwt,\n payloadSchema: options.schema,\n });\n return {\n decodedJwt,\n jwt,\n };\n }\n\n matchValue = valueRegex.exec(match[0]);\n }\n matchName = nameRegex.exec(match[0]);\n }\n\n match = inputRegex.exec(options.formData);\n }\n\n throw new Oauth2Error(\n `Unable to obtain JWT from form_post.jwt. Form data: ${options.formData}`,\n );\n};\n","import { CallbackContext, JwtSignerJwk } from \"@openid4vc/oauth2\";\nimport { dateToSeconds, parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdValidationJwtHeader,\n MrtdValidationJwtPayload,\n zMrtdValidationJwtHeader,\n zMrtdValidationJwtPayload,\n} from \"./z-mrtd-pop\";\n\nconst JWT_EXPIRY_SECONDS = 300;\n\n/**\n * NFC-read document evidence from CIE (Italian ID card) containing:\n * - Data Groups (DG1, DG11) with personal information\n * - Security Objects of Document (SOD) for MRTD and IAS applications\n * - IAS public key and Anti-Cloning challenge signature\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.5 (Validation JWT Structure)\n */\nexport interface MrtdDocumentData {\n /** Anti-Cloning signed challenge response (base64) */\n challengeSigned: string;\n /** Data Group 1 - MRZ info (base64) */\n dg1: string;\n /** Data Group 11 - additional personal data (base64) */\n dg11: string;\n /** IAS public key in DER format (base64) */\n iasPk: string;\n /** Security Object of Document for IAS (base64) */\n sodIas: string;\n /** Security Object of Document for MRTD (base64) */\n sodMrtd: string;\n}\n\nexport interface CreateMrtdValidationJwtOptions {\n /** PID Provider identifier (JWT aud) */\n audience: string;\n callbacks: Pick<CallbackContext, \"signJwt\">;\n /** Wallet Instance identifier (JWT iss) */\n clientId: string;\n /** NFC-read document evidence */\n documentData: MrtdDocumentData;\n issuedAt?: Date;\n signer: JwtSignerJwk;\n}\n\n/**\n * Creates a signed JWT containing MRTD validation data for Phase 3 of L2+ flow.\n *\n * The JWT is sent to the PID Provider for cryptographic verification of the CIE document.\n * Includes Data Groups (DG1, DG11), Security Objects, and Anti-Cloning challenge response.\n *\n * @param options - Configuration including document data, signer, and callback context\n * @returns Signed JWT with typ=\"mrtd-ias+jwt\"\n * @throws {MrtdPopError} If signer lacks kid or signing fails\n *\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.4 (MRTD PoP Validation Request)\n */\nexport async function createMrtdValidationJwt(\n options: CreateMrtdValidationJwtOptions,\n): Promise<{ jwt: string }> {\n try {\n const kid = options.signer.publicJwk.kid;\n if (!kid) {\n throw new MrtdPopError(\"Signer must have a publicJwk.kid property\");\n }\n\n const iat = dateToSeconds(options.issuedAt);\n\n const header = parseWithErrorHandling(zMrtdValidationJwtHeader, {\n alg: options.signer.alg,\n kid,\n typ: \"mrtd-ias+jwt\",\n } satisfies MrtdValidationJwtHeader);\n\n const payload = parseWithErrorHandling(zMrtdValidationJwtPayload, {\n aud: options.audience,\n document_type: \"cie\",\n exp: iat + JWT_EXPIRY_SECONDS,\n ias: {\n challenge_signed: options.documentData.challengeSigned,\n ias_pk: options.documentData.iasPk,\n sod_ias: options.documentData.sodIas,\n },\n iat,\n iss: options.clientId,\n mrtd: {\n dg1: options.documentData.dg1,\n dg11: options.documentData.dg11,\n sod_mrtd: options.documentData.sodMrtd,\n },\n } satisfies MrtdValidationJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n return { jwt };\n } catch (error) {\n if (error instanceof MrtdPopError) {\n throw error;\n }\n throw new MrtdPopError(\n `Error creating MRTD validation JWT: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import z from \"zod\";\n\n/**\n * Zod schemas for MRTD (Machine Readable Travel Document) Proof of Possession flow.\n *\n * Implements IT-Wallet L2+ specification for eID Substantial Authentication with MRTD Verification.\n * Defines JWT structures and response formats for the multi-step document validation protocol.\n *\n * @see IT-Wallet L2+ specification Section 12.1.3 (eID Substantial Authentication with MRTD Verification)\n */\n\n// --- MRTD Challenge JWT (received via redirect, typ: \"mrtd-ias+jwt\") ---\n\n/** JWT header for MRTD challenge (Phase 3.1) */\nexport const zMrtdChallengeJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n })\n .passthrough();\nexport type MrtdChallengeJwtHeader = z.infer<typeof zMrtdChallengeJwtHeader>;\n\n/** JWT payload for MRTD challenge containing session correlation and endpoint parameters */\nexport const zMrtdChallengeJwtPayload = z\n .object({\n aud: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.string().url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_auth_session: z.string(),\n mrtd_pop_jwt_nonce: z.string(),\n state: z.string(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"mrtd+ias\"),\n })\n .passthrough();\nexport type MrtdChallengeJwtPayload = z.infer<typeof zMrtdChallengeJwtPayload>;\n\n// --- MRTD PoP Init Response JWT (typ: \"mrtd-ias-pop+jwt\") ---\n\n/** JWT header for MRTD PoP initialization response (Phase 3.3) */\nexport const zMrtdPopInitResponseJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias-pop+jwt\"),\n })\n .passthrough();\nexport type MrtdPopInitResponseJwtHeader = z.infer<\n typeof zMrtdPopInitResponseJwtHeader\n>;\n\n/** JWT payload for MRTD PoP initialization response containing challenge and nonce */\nexport const zMrtdPopInitResponseJwtPayload = z\n .object({\n aud: z.string(),\n challenge: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.string().url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_pop_nonce: z.string(),\n mrz: z.string().optional(),\n })\n .passthrough();\nexport type MrtdPopInitResponseJwtPayload = z.infer<\n typeof zMrtdPopInitResponseJwtPayload\n>;\n\n// --- MRTD Validation JWT (created by Wallet, typ: \"mrtd-ias+jwt\") ---\n\n/** MRTD application data from NFC reading (DG1, DG11, SOD) */\nconst zMrtdData = z\n .object({\n dg1: z.string(),\n dg11: z.string(),\n sod_mrtd: z.string(),\n })\n .passthrough();\n\n/** IAS (Anti-Cloning) application data from NFC reading (public key, signed challenge, SOD) */\nconst zIasData = z\n .object({\n challenge_signed: z.string(),\n ias_pk: z.string(),\n sod_ias: z.string(),\n })\n .passthrough();\n\n/** JWT header for MRTD validation (signed by Wallet Instance) */\nexport const zMrtdValidationJwtHeader = z\n .object({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n })\n .passthrough();\nexport type MrtdValidationJwtHeader = z.infer<typeof zMrtdValidationJwtHeader>;\n\n/** JWT payload for MRTD validation containing NFC-read document evidence */\nexport const zMrtdValidationJwtPayload = z\n .object({\n aud: z.string(),\n document_type: z.literal(\"cie\"),\n exp: z.number(),\n ias: zIasData,\n iat: z.number(),\n iss: z.string(),\n mrtd: zMrtdData,\n })\n .passthrough();\nexport type MrtdValidationJwtPayload = z.infer<\n typeof zMrtdValidationJwtPayload\n>;\n\n// --- MRTD PoP Verify Response (JSON, not JWT) ---\n\n/** Response from MRTD PoP verification endpoint (Phase 3.8) */\nexport const zMrtdPopVerifyResponse = z\n .object({\n mrtd_val_pop_nonce: z.string(),\n redirect_uri: z.string().url(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"redirect_to_web\"),\n })\n .passthrough();\nexport type MrtdPopVerifyResponse = z.infer<typeof zMrtdPopVerifyResponse>;\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n CONTENT_TYPES,\n HEADERS,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n hasStatusOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n zMrtdPopInitResponseJwtHeader,\n zMrtdPopInitResponseJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface FetchMrtdPopInitOptions {\n callbacks: Pick<CallbackContext, \"fetch\" | \"verifyJwt\">;\n clientAttestationDPoP: string;\n /** From challenge JWT payload */\n mrtdAuthSession: string;\n /** From challenge JWT payload */\n mrtdPopJwtNonce: string;\n /** From challenge JWT payload htu */\n popInitEndpoint: string;\n\n /**\n * Optional custom signer for verifying the MRTD PoP init response JWT.\n * If not provided, the library will attempt to verify using JWT header.\n */\n signer?: JwtSigner;\n\n /**\n * Attestation header value for the wallet's own attestation, to be included in the request.\n */\n walletAttestation: string;\n}\n\nexport interface FetchMrtdPopInitResult {\n challenge: string;\n mrtdPopNonce: string;\n mrz?: string;\n /** htu from the init response — the verify endpoint */\n popVerifyEndpoint: string;\n signer: JwtSigner;\n}\n\n/**\n * Initiates MRTD Proof of Possession validation (Phase 3.2 of L2+ flow).\n *\n * Sends session correlation parameters to the MRTD PoP Service and receives:\n * - Cryptographic challenge for Anti-Cloning Internal Authentication\n * - Nonce for next step\n * - Optional MRZ data from CIE National Registry\n *\n * @param options - Session parameters, attestation headers, and callbacks\n * @returns Challenge, nonce, optional MRZ, and verify endpoint URL\n * @throws {UnexpectedStatusCodeError} If response is not HTTP 202\n * @throws {MrtdPopError} For network or parsing failures\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.2-3 (MRTD PoP Request/Response)\n */\nexport async function fetchMrtdPopInit(\n options: FetchMrtdPopInitOptions,\n): Promise<FetchMrtdPopInitResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const response = await fetch(options.popInitEndpoint, {\n body: JSON.stringify({\n mrtd_auth_session: options.mrtdAuthSession,\n mrtd_pop_jwt_nonce: options.mrtdPopJwtNonce,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(202, UnexpectedStatusCodeError)(response);\n\n const responseJwt = await response.text();\n\n const jwt = decodeJwt({\n headerSchema: zMrtdPopInitResponseJwtHeader,\n jwt: responseJwt,\n payloadSchema: zMrtdPopInitResponseJwtPayload,\n });\n\n const { signer } = await verifyJwt({\n compact: responseJwt,\n errorMessage: \"Error verifying MRTD PoP init response JWT\",\n header: jwt.header,\n payload: jwt.payload,\n signer:\n options.signer ??\n jwtSignerFromJwt({ header: jwt.header, payload: jwt.payload }),\n verifyJwtCallback: options.callbacks.verifyJwt,\n });\n\n return {\n challenge: jwt.payload.challenge,\n mrtdPopNonce: jwt.payload.mrtd_pop_nonce,\n mrz: jwt.payload.mrz,\n popVerifyEndpoint: jwt.payload.htu,\n signer,\n };\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new MrtdPopError(\n `Unexpected error during MRTD PoP init: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\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 { MrtdPopError } from \"../errors\";\nimport { zMrtdPopVerifyResponse } from \"./z-mrtd-pop\";\n\nexport interface FetchMrtdPopVerifyOptions {\n callbacks: Pick<CallbackContext, \"fetch\">;\n clientAttestationDPoP: string;\n mrtdAuthSession: string;\n mrtdPopNonce: string;\n mrtdValidationJwt: string;\n popVerifyEndpoint: string;\n walletAttestation: string;\n}\n\nexport interface FetchMrtdPopVerifyResult {\n mrtdValPopNonce: string;\n redirectUri: string;\n}\n\n/**\n * Submits MRTD validation evidence for final verification (Phase 3.4 of L2+ flow).\n *\n * Sends the validation JWT containing NFC-read document data to the MRTD PoP Service.\n * The service performs cryptographic verification, identity correlation, and document status checks.\n *\n * @param options - Validation JWT, session correlation parameters, and attestation headers\n * @returns Final nonce and redirect URI for browser-based confirmation\n * @throws {UnexpectedStatusCodeError} If response is not HTTP 202\n * @throws {ValidationError} If response body is invalid\n * @throws {MrtdPopError} For network failures\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.4 (MRTD PoP Validation Request)\n */\nexport async function fetchMrtdPopVerify(\n options: FetchMrtdPopVerifyOptions,\n): Promise<FetchMrtdPopVerifyResult> {\n try {\n const fetch = createFetcher(options.callbacks.fetch);\n\n const response = await fetch(options.popVerifyEndpoint, {\n body: JSON.stringify({\n mrtd_auth_session: options.mrtdAuthSession,\n mrtd_pop_nonce: options.mrtdPopNonce,\n mrtd_validation_jwt: options.mrtdValidationJwt,\n }),\n headers: {\n [HEADERS.CONTENT_TYPE]: CONTENT_TYPES.JSON,\n [HEADERS.OAUTH_CLIENT_ATTESTATION]: options.walletAttestation,\n [HEADERS.OAUTH_CLIENT_ATTESTATION_POP]: options.clientAttestationDPoP,\n },\n method: \"POST\",\n });\n\n await hasStatusOrThrow(202, UnexpectedStatusCodeError)(response);\n\n const parsed = parseWithErrorHandling(\n zMrtdPopVerifyResponse,\n await response.json(),\n \"Failed to parse MRTD PoP verify response\",\n );\n\n return {\n mrtdValPopNonce: parsed.mrtd_val_pop_nonce,\n redirectUri: parsed.redirect_uri,\n };\n } catch (error) {\n if (\n error instanceof UnexpectedStatusCodeError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n throw new MrtdPopError(\n `Unexpected error during MRTD PoP verify: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n}\n","import { zCompactJwt } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdChallengeJwtHeader,\n MrtdChallengeJwtPayload,\n zMrtdChallengeJwtHeader,\n zMrtdChallengeJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface ParseMrtdChallengeOptions {\n /** The full redirect URL containing ?challenge_info=<jwt> */\n redirectUrl: string;\n}\n\nexport interface ParseMrtdChallengeResult {\n challengeJwt: string;\n header: MrtdChallengeJwtHeader;\n payload: MrtdChallengeJwtPayload;\n}\n\n/**\n * Extracts and decodes the MRTD challenge JWT from authorization redirect (Phase 3.1 of L2+ flow).\n *\n * After primary authentication (LoA3), the Authorization Server redirects to the Wallet\n * with a JWT containing challenge requirements for document validation.\n *\n * @param options - Redirect URL containing challenge_info query parameter\n * @returns Decoded JWT header and payload (signature not yet verified)\n * @throws {MrtdPopError} If challenge_info is missing or JWT format is invalid\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.1 (MRTD Proof JWT)\n */\nexport function parseMrtdChallenge(\n options: ParseMrtdChallengeOptions,\n): ParseMrtdChallengeResult {\n const url = new URL(options.redirectUrl);\n const challengeJwt = url.searchParams.get(\"challenge_info\");\n\n if (!challengeJwt) {\n throw new MrtdPopError(\n \"Missing 'challenge_info' query parameter in redirect URL\",\n );\n }\n\n if (!zCompactJwt.safeParse(challengeJwt).success) {\n throw new MrtdPopError(\n \"Invalid JWT format in 'challenge_info' query parameter\",\n );\n }\n\n const { header, payload } = decodeJwt({\n headerSchema: zMrtdChallengeJwtHeader,\n jwt: challengeJwt,\n payloadSchema: zMrtdChallengeJwtPayload,\n });\n\n return { challengeJwt, header, payload };\n}\n","import {\n CallbackContext,\n JwtSigner,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { JwtPayload } from \"../common/jwt/z-jwt\";\nimport { MrtdPopError } from \"../errors\";\nimport {\n MrtdChallengeJwtHeader,\n MrtdChallengeJwtPayload,\n zMrtdChallengeJwtHeader,\n zMrtdChallengeJwtPayload,\n} from \"./z-mrtd-pop\";\n\nexport interface VerifyMrtdChallengeOptions {\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n challengeJwt: string;\n /** Expected client_id — must match JWT aud */\n clientId: string;\n\n /**\n * Optional custom signer for verifying the MRTD challenge JWT.\n * If not provided, the library will attempt to verify using JWT header.\n */\n signer?: JwtSigner;\n}\n\nexport interface VerifyMrtdChallengeResult {\n header: MrtdChallengeJwtHeader;\n payload: MrtdChallengeJwtPayload;\n signer: JwtSigner;\n}\n\n/**\n * Verifies the MRTD challenge JWT signature and validates claims.\n *\n * Ensures the challenge was issued by the trusted PID Provider and is intended\n * for this Wallet Instance. Validates expiration, audience, and required parameters.\n *\n * @param options - Challenge JWT, expected client_id, and verification callback\n * @returns Verified header and payload\n * @throws {Error} If aud doesn't match clientId\n * @throws {Oauth2JwtVerificationError} If signature verification fails\n *\n * It is alligned to the IT-Wallet v1.3 specs\n * @see IT-Wallet L2+ specification Section 12.1.3.5.3.1 (MRTD Proof JWT)\n */\nexport async function verifyMrtdChallenge(\n options: VerifyMrtdChallengeOptions,\n): Promise<VerifyMrtdChallengeResult> {\n const { callbacks, challengeJwt, clientId } = options;\n\n const jwt = decodeJwt({\n headerSchema: zMrtdChallengeJwtHeader,\n jwt: challengeJwt,\n payloadSchema: zMrtdChallengeJwtPayload,\n });\n\n if (jwt.payload.aud !== clientId) {\n throw new MrtdPopError(\n \"Invalid challenge: aud claim does not match client_id\",\n );\n }\n\n // MRTD spec uses `status` as a string literal, but upstream JwtPayload types it as an object.\n // The cast is safe because verifyJwt only uses standard claims (exp, aud, iss, etc.).\n const payload = jwt.payload as unknown as JwtPayload;\n\n const { signer } = await verifyJwt({\n compact: challengeJwt,\n errorMessage: \"Error verifying MRTD challenge JWT\",\n header: jwt.header,\n payload,\n\n signer: options.signer ?? jwtSignerFromJwt({ header: jwt.header, payload }),\n verifyJwtCallback: callbacks.verifyJwt,\n });\n\n return { header: jwt.header, payload: jwt.payload, signer };\n}\n","export * from \"./access-token\";\nexport * from \"./authorization-request\";\nexport * from \"./client-attestation\";\nexport * from \"./common\";\nexport * from \"./errors\";\nexport * from \"./jar\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./mrtd-pop\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop\";\n\nexport {\n type CallbackContext,\n type ClientAttestationPopJwtHeader,\n type ClientAttestationPopJwtPayload,\n type DecryptJweCallback,\n type EncryptJweCallback,\n type GenerateRandomCallback,\n HashAlgorithm,\n type JweEncryptor,\n type JwtSigner,\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n"],"mappings":";;;;;;;AAoCO,IAAM,qBAAqB,OAChC,aAEC;AAAA,EACC,MAAM,QAAQ;AAAA,EACd,eAAe,QAAQ;AAAA,EACvB,YAAY;AAAA,EACZ,cAAc,QAAQ;AAAA,EACtB,GAAG,QAAQ;AACb;;;AC7CF;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACTA,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,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,uBAAN,cAAmC,YAAY;AAAA,EACpD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,eAAN,cAA2B,YAAY;AAAA,EAC5C,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,IAAM,0BAAN,cAAsC,YAAY;AAAA,EACvD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,2BAAN,cAAuC,YAAY;AAAA,EACxD,YACE,SACgB,YAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAKO,I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AAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,MAAI,CAACC,aAAY,UAAU,YAAY,EAAE,SAAS;AAChD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI,UAAU;AAAA,IACpC,cAAc;AAAA,IACd,KAAK;AAAA,IACL,eAAe;AAAA,EACjB,CAAC;AAED,SAAO,EAAE,cAAc,QAAQ,QAAQ;AACzC;;;AC5DA;AAAA,EAGE,oBAAAC;AAAA,EACA,aAAAC;AAAA,OACK;AA6CP,eAAsB,oBACpB,SACoC;AACpC,QAAM,EAAE,WAAW,cAAc,SAAS,IAAI;AAE9C,QAAM,MAAM,UAAU;AAAA,IACpB,cAAc;AAAA,IACd,KAAK;AAAA,IACL,eAAe;AAAA,EACjB,CAAC;AAED,MAAI,IAAI,QAAQ,QAAQ,UAAU;AAChC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAIA,QAAM,UAAU,IAAI;AAEpB,QAAM,EAAE,OAAO,IAAI,MAAMC,WAAU;AAAA,IACjC,SAAS;AAAA,IACT,cAAc;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ;AAAA,IAEA,QAAQ,QAAQ,UAAUC,kBAAiB,EAAE,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AAAA,IAC1E,mBAAmB,UAAU;AAAA,EAC/B,CAAC;AAED,SAAO,EAAE,QAAQ,IAAI,QAAQ,SAAS,IAAI,SAAS,OAAO;AAC5D;;;ACvEA;AAAA,EAOE,iBAAAC;AAAA,EAIA,uBAAAC;AAAA,EAIA,aAAAC;AAAA,OACK;","names":["z","z","z","z","z","parseWithErrorHandling","parseWithErrorHandling","addSecondsToDate","dateToSeconds","encodeToBase64Url","Oauth2JwtParseError","decodeBase64","encodeToUtf8String","parseWithErrorHandling","stringToJsonWithErrorHandling","parseWithErrorHandling","parseWithErrorHandling","Oauth2JwtParseError","stringToJsonWithErrorHandling","encodeToUtf8String","decodeBase64","parseWithErrorHandling","addSecondsToDate","encodeToBase64Url","dateToSeconds","z","ValidationError","addSecondsToDate","dateToSeconds","z","z","addSecondsToDate","dateToSeconds","ValidationError","verifyJwt","verifyJwt","v1_exports","createWalletAttestationJwt","verifyWalletAttestationJwt","ValidationError","addSecondsToDate","dateToSeconds","z","z","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","verifyWalletAttestationJwt","HashAlgorithm","calculateJwkThumbprint","zCompactJwt","verifyWalletAttestationJwt","zCompactJwt","verifyWalletAttestationJwt","calculateJwkThumbprint","HashAlgorithm","HashAlgorithm","zCompactJwt","ValidationError","dateToSeconds","encodeToBase64Url","parseWithErrorHandling","z","z","encodeToBase64Url","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","zCompactJwt","HashAlgorithm","calculateJwkThumbprint","verifyJwt","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","calculateJwkThumbprint","verifyJwt","z","HashAlgorithm","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","addSecondsToDate","dateToSeconds","encodeToBase64Url","z","encodeToBase64Url","addSecondsToDate","dateToSeconds","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","toURLSearchParams","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","formatZodError","parseWithErrorHandling","z","addSecondsToDate","dateToSeconds","dateToSeconds","addSecondsToDate","UnexpectedStatusCodeError","createFetcher","hasStatusOrThrow","createFetcher","hasStatusOrThrow","UnexpectedStatusCodeError","decodeJwt","verifyJwt","zCompactJwt","parseWithErrorHandling","z","z","zCompactJwt","decodeJwt","parseWithErrorHandling","verifyJwt","parseWithErrorHandling","z","formatZodError","z","zCompactJwe","dateToSeconds","parseWithErrorHandling","z","JWT_EXPIRY_SECONDS","dateToSeconds","parseWithErrorHandling","jwtSignerFromJwt","verifyJwt","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","verifyJwt","jwtSignerFromJwt","ValidationError","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","parseWithErrorHandling","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","parseWithErrorHandling","ValidationError","zCompactJwt","zCompactJwt","jwtSignerFromJwt","verifyJwt","verifyJwt","jwtSignerFromJwt","HashAlgorithm","Oauth2JwtParseError","verifyJwt"]}
|