@pagopa/io-wallet-oauth2 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/access-token/create-token-request.ts","../src/access-token/create-token-response.ts","../src/common/jwt/decode-jwt-header.ts","../src/common/jwt/z-jwt.ts","../src/common/jwk/z-jwk.ts","../src/common/z-common.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/access-token/fetch-token-response.ts","../src/access-token/parse-token-request.ts","../src/client-attestation/wallet-attestation.ts","../src/client-attestation/types.ts","../src/client-attestation/verify-wallet-attestation-jwt-base.ts","../src/common/jwt/decode-jwt.ts","../src/client-attestation/v1.0/z-wallet-attestation.ts","../src/client-attestation/v1.0/verify-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/v1.4/z-wallet-attestation.ts","../src/client-attestation/v1.4/verify-wallet-attestation-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/dpop-utils.ts","../src/token-dpop/z-dpop.ts","../src/access-token/z-grant-type.ts","../src/client-attestation/verify-client-attestation.ts","../src/client-attestation/client-attestation-pop.ts","../src/client-attestation/z-client-attestation-pop.ts","../src/pkce.ts","../src/token-dpop/verify-token-dpop.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/fetch-jar-request-object.ts","../src/jar/validate-jar-request.ts","../src/jar/parse-jar-request.ts","../src/jar/z-jar.ts","../src/authorization-request/verify-authorization-request.ts","../src/jar/verify-jar-request.ts","../src/authorization-request/verify-pushed-authorization-request.ts","../src/client-attestation/client-authentication.ts","../src/client-attestation/v1.0/create-wallet-attestation-jwt.ts","../src/client-attestation/jwk-thumbprint.ts","../src/client-attestation/v1.3/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.4/create-wallet-attestation-jwt.ts","../src/common/jwt/z-jwe.ts","../src/jar/create-jar-request.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"],"sourcesContent":["export * from \"./access-token/create-token-request\";\nexport * from \"./access-token/create-token-response\";\nexport * from \"./access-token/fetch-token-response\";\nexport * from \"./access-token/parse-token-request\";\nexport * from \"./access-token/verify-access-token-request\";\nexport * from \"./access-token/z-grant-type\";\nexport * from \"./access-token/z-token\";\nexport * from \"./authorization-request/create-authorization-request\";\nexport * from \"./authorization-request/fetch-authorization-response\";\nexport * from \"./authorization-request/parse-authorization-request\";\nexport * from \"./authorization-request/parse-pushed-authorization-request\";\nexport * from \"./authorization-request/verify-authorization-request\";\nexport * from \"./authorization-request/verify-pushed-authorization-request\";\nexport * from \"./authorization-request/z-authorization-request\";\nexport * from \"./client-attestation/client-attestation-pop\";\nexport * from \"./client-attestation/client-authentication\";\nexport type * from \"./client-attestation/types\";\nexport {\n type WalletAttestationOptionsV1_0,\n createWalletAttestationJwt as createWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_0,\n type VerifyWalletAttestationJwtOptionsV1_0,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_0,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n zWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/z-wallet-attestation\";\nexport {\n type WalletAttestationOptionsV1_3,\n createWalletAttestationJwt as createWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_3,\n type VerifyWalletAttestationJwtOptionsV1_3,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_3,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n zWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/z-wallet-attestation\";\nexport {\n type WalletAttestationOptionsV1_4,\n createWalletAttestationJwt as createWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_4,\n type VerifyWalletAttestationJwtOptionsV1_4,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n zWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/z-wallet-attestation\";\nexport * from \"./client-attestation/verify-client-attestation\";\nexport * from \"./client-attestation/wallet-attestation\";\nexport * from \"./client-attestation/z-client-attestation-pop\";\nexport * from \"./common/jwk/z-jwk\";\nexport * from \"./common/jwt/decode-jwt\";\nexport * from \"./common/jwt/decode-jwt-header\";\nexport * from \"./common/jwt/z-jwe\";\nexport * from \"./common/jwt/z-jwt\";\nexport * from \"./common/z-common\";\nexport * from \"./errors\";\nexport * from \"./jar/create-jar-request\";\nexport * from \"./jar/fetch-jar-request-object\";\nexport * from \"./jar/parse-jar-request\";\nexport * from \"./jar/validate-jar-request\";\nexport * from \"./jar/verify-jar-request\";\nexport * from \"./jar/z-jar\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./mrtd-pop/create-mrtd-validation-jwt\";\nexport * from \"./mrtd-pop/fetch-mrtd-pop-init\";\nexport * from \"./mrtd-pop/fetch-mrtd-pop-verify\";\nexport * from \"./mrtd-pop/parse-mrtd-challenge\";\nexport * from \"./mrtd-pop/verify-mrtd-challenge\";\nexport * from \"./mrtd-pop/z-mrtd-pop\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop/create-token-dpop\";\nexport * from \"./token-dpop/dpop-utils\";\nexport * from \"./token-dpop/verify-token-dpop\";\nexport * from \"./token-dpop/z-dpop\";\n\nexport {\n /** @deprecated Use `CallbackContext` from `@pagopa/io-wallet-utils` instead. */\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 /** @deprecated Use `JwtSignerJwk` from `@pagopa/io-wallet-utils` instead. */\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n","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\n/**\n * Creates an OAuth 2.0 authorization-code access token request body.\n *\n * @param options - Access token request inputs.\n * @param options.additionalRequestPayload - Extra form fields to include in the token request.\n * @param options.authorizationCode - Authorization code received from the authorization response.\n * @param options.pkceCodeVerifier - PKCE verifier associated with the authorization request.\n * @param options.redirectUri - Redirect URI used in the authorization request.\n * @returns URL-form-encodable authorization-code grant request data.\n */\nexport const createTokenRequest = async (\n options: RetrieveAuthorizationCodeAccessTokenOptions,\n) =>\n ({\n ...options.additionalRequestPayload,\n code: options.authorizationCode,\n code_verifier: options.pkceCodeVerifier,\n grant_type: \"authorization_code\",\n redirect_uri: options.redirectUri,\n }) satisfies AuthorizationCodeGrantType;\n","import {\n CallbackContext,\n HashAlgorithm,\n JwtSigner,\n calculateJwkThumbprint,\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 { jwtHeaderFromJwtSigner } from \"../common/jwt/decode-jwt-header\";\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 *\n * @param options - Access token response creation options.\n * @returns OAuth token response with a signed access token JWT.\n * @throws {CreateTokenResponseError} If DPoP binding is required but missing, or if response creation fails, including validation failures from the generated JWT header or payload.\n * @throws {ValidationError} If the generated JWT header or payload fails validation.\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 ...options.additionalPayload,\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 } satisfies AccessTokenProfileJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n ...options.additionalPayload,\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: options.refreshToken,\n token_type: options.tokenType,\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","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n formatError,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { InferSchemaOrDefaultOutput } from \"./decode-jwt\";\n\nimport { JwtSigner, zJwtHeader } from \"./z-jwt\";\n\nexport interface DecodeJwtHeaderOptions<\n HeaderSchema extends BaseSchema | undefined,\n> {\n /**\n * Optional prefix for error messages thrown during decoding, to provide more context on where the error occurred\n */\n errorMessagePrefix?: string;\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\n/**\n * Decodes and validates the header of a compact JWT.\n *\n * This helper does not verify the JWT signature or parse the payload.\n *\n * @param options - Header decode options.\n * @param options.errorMessagePrefix - Optional context prefix for thrown parse/validation errors.\n * @param options.headerSchema - Optional schema for the JWT header; defaults to `zJwtHeader`.\n * @param options.jwt - Compact JWT to decode.\n * @returns Decoded and schema-validated JWT header.\n * @throws {Oauth2JwtParseError} If the JWT shape or header JSON is invalid.\n * @throws {ValidationError} If header schema validation fails.\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(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\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 formatError(\n \"Unable to parse jwt header to JSON\",\n options.errorMessagePrefix,\n ),\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n formatError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n options.errorMessagePrefix,\n ),\n );\n }\n\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n formatError(\"Invalid JWT header\", options.errorMessagePrefix),\n ) as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n\n return {\n header,\n };\n}\n\n/**\n * Builds a JWT header from an SDK signer descriptor.\n *\n * @param signer - Signer descriptor used by SDK signing callbacks.\n * @returns Header fields required by the signer method.\n */\nexport function jwtHeaderFromJwtSigner(signer: JwtSigner) {\n if (signer.method === \"did\") {\n return {\n alg: signer.alg,\n kid: signer.didUrl,\n };\n }\n\n if (signer.method === \"federation\") {\n return {\n alg: signer.alg,\n kid: signer.kid,\n trust_chain: signer.trustChain,\n };\n }\n\n if (signer.method === \"jwk\") {\n return {\n alg: signer.alg,\n jwk: signer.publicJwk,\n };\n }\n\n if (signer.method === \"x5c\") {\n return {\n alg: signer.alg,\n kid: signer.kid,\n trust_chain: signer.trustChain,\n x5c: signer.x5c,\n };\n }\n return { alg: signer.alg };\n}\n","import z from \"zod\";\n\nimport { Jwk, zJwk } from \"../jwk/z-jwk\";\nimport {\n TrustChain,\n zAlgValueNotNone,\n zCertificateChain,\n zTrustChain,\n} from \"../z-common\";\n\nexport const MAX_JTI_LENGTH = 256;\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 trustChain?: TrustChain;\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?: TrustChain;\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.looseObject({\n // RFC9449. jwk thumbprint of the dpop public key to which the access token is bound\n jkt: z.string().optional(),\n jwk: zJwk.optional(),\n});\n\nexport const zJwtPayload = z.looseObject({\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().max(MAX_JTI_LENGTH).optional(),\n nbf: z.number().int().optional(),\n nonce: z.string().optional(),\n // Reserved for status parameters\n status: z.record(z.string(), z.any()).optional(),\n // Reserved for OpenID Federation\n trust_chain: zTrustChain.optional(),\n});\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>;\n\nexport const zJwtHeader = z.looseObject({\n alg: zAlgValueNotNone,\n jwk: zJwk.optional(),\n kid: z.string().optional(),\n // Reserved for OpenID Federation\n trust_chain: zTrustChain.optional(),\n typ: z.string().optional(),\n x5c: zCertificateChain.optional(),\n});\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>;\n","import z from \"zod\";\n\nimport { zCertificateChain } from \"../z-common\";\n\nexport const zJwk = z.looseObject({\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.looseObject({\n d: z.optional(z.string()),\n r: z.optional(z.string()),\n t: z.optional(z.string()),\n }),\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(zCertificateChain),\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\nexport type Jwk = z.infer<typeof zJwk>;\n\nexport const zJwkSet = z.looseObject({ keys: z.array(zJwk) });\n\nexport type JwkSet = z.infer<typeof zJwkSet>;\n","import { FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nexport const zTrustChain = z.tuple([z.string()], z.string());\nexport type TrustChain = z.infer<typeof zTrustChain>;\n\nexport const zCertificateChain = z.array(z.string()).nonempty();\nexport type CertificateChain = z.infer<typeof zCertificateChain>;\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","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"Oauth2Error\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"PushedAuthorizationRequestError\";\n this.statusCode = options?.statusCode;\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, options?: ErrorOptions) {\n super(message, options);\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 readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"MrtdPopError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"FetchTokenResponseError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown when access token response creation fails.\n */\nexport class CreateTokenResponseError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"CreateTokenResponseError\";\n this.statusCode = options?.statusCode;\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, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ClientAttestationError\";\n }\n}\n","import { z } from \"zod\";\n\nimport { MAX_JTI_LENGTH, 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.looseObject({\n access_token: z.string(),\n authorization_details: z\n .array(\n z.looseObject({\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 )\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\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n\nexport const zAccessTokenProfileJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n typ: z.enum([\"application/at+jwt\", \"at+jwt\"]),\n});\n\nexport type AccessTokenProfileJwtHeader = z.infer<\n typeof zAccessTokenProfileJwtHeader\n>;\n\nexport const zAccessTokenProfileJwtPayload = z.looseObject({\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().max(MAX_JTI_LENGTH),\n nbf: z.number().optional(),\n scope: z.string().optional(),\n sub: z.string(),\n});\n\nexport type AccessTokenProfileJwtPayload = z.infer<\n typeof zAccessTokenProfileJwtPayload\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\n/**\n * Converts an access token request object into URL-encoded form parameters.\n *\n * Object values are JSON-stringified so structured extension parameters such as\n * `authorization_details` can be sent in `application/x-www-form-urlencoded` requests.\n *\n * @param data - Access token request payload.\n * @returns URLSearchParams containing all defined request fields.\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/wallet-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop/create-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 { zCompactJwt } from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ItWalletSpecsVersion,\n createVersionDispatcher,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type {\n VerifiedWalletAttestationJwtV1_0,\n VerifyWalletAttestationJwtOptionsV1_0,\n} from \"./v1.0/verify-wallet-attestation-jwt\";\nimport type {\n VerifiedWalletAttestationJwtV1_3,\n VerifyWalletAttestationJwtOptionsV1_3,\n} from \"./v1.3/verify-wallet-attestation-jwt\";\nimport type {\n VerifiedWalletAttestationJwtV1_4,\n VerifyWalletAttestationJwtOptionsV1_4,\n} from \"./v1.4/verify-wallet-attestation-jwt\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0 } from \"./v1.0/verify-wallet-attestation-jwt\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3 } from \"./v1.3/verify-wallet-attestation-jwt\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4 } from \"./v1.4/verify-wallet-attestation-jwt\";\n\nconst dispatchVerifyWalletAttestationJwt = createVersionDispatcher<\n VerifyWalletAttestationJwtOptions,\n Promise<VerifiedWalletAttestationJwt>\n>({\n [ItWalletSpecsVersion.V1_0]: (o) =>\n verifyWalletAttestationJwtV1_0(o as VerifyWalletAttestationJwtOptionsV1_0),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n verifyWalletAttestationJwtV1_3(o as VerifyWalletAttestationJwtOptionsV1_3),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n verifyWalletAttestationJwtV1_4(o as VerifyWalletAttestationJwtOptionsV1_4),\n});\n\nexport type VerifiedWalletAttestationJwt =\n | VerifiedWalletAttestationJwtV1_0\n | VerifiedWalletAttestationJwtV1_3\n | VerifiedWalletAttestationJwtV1_4;\n\nexport type VerifyWalletAttestationJwtOptions =\n | VerifyWalletAttestationJwtOptionsV1_0\n | VerifyWalletAttestationJwtOptionsV1_3\n | VerifyWalletAttestationJwtOptionsV1_4;\n\n/**\n * Verifies a wallet/client attestation JWT according to the configured IT-Wallet version.\n *\n * @param options - Version-specific wallet attestation verification options.\n * @returns Decoded and verified wallet attestation data for the configured version.\n * @throws {ValidationError} If JWT header or payload validation fails.\n * @throws {Oauth2JwtParseError} If the attestation JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n * @throws {ItWalletSpecsVersionError} If the configured version is unsupported.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n): Promise<VerifiedWalletAttestationJwtV1_0>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_3,\n): Promise<VerifiedWalletAttestationJwtV1_3>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_4,\n): Promise<VerifiedWalletAttestationJwtV1_4>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptions,\n): Promise<VerifiedWalletAttestationJwt> {\n return dispatchVerifyWalletAttestationJwt(options);\n}\n\n/**\n * Extracts wallet attestation and PoP JWT header values from request headers.\n *\n * @param headers - Request headers to inspect.\n * @returns Parsed header values when both are present, `{ valid: true }` when neither is present,\n * or `{ valid: false }` when the pair is incomplete or malformed.\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 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, \"hash\" | \"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 type { ZodType } from \"zod\";\n\nimport { jwtSignerFromJwt, verifyJwt } from \"@openid4vc/oauth2\";\n\nimport type { JwtHeader, JwtPayload } from \"../common/jwt/z-jwt\";\nimport type { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\n\nexport async function verifyWalletAttestationBase<\n THeader extends ZodType<JwtHeader>,\n TPayload extends ZodType<JwtPayload>,\n>(\n options: BaseVerifyWalletAttestationJwtOptions,\n headerSchema: THeader,\n payloadSchema: TPayload,\n) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n formatError,\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 * Optional prefix for error messages thrown during decoding, to provide more context on where the error occurred\n */\n errorMessagePrefix?: string;\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\n/**\n * Decodes a compact JWT and validates its header and payload with Zod schemas.\n *\n * This helper does not verify the JWT signature.\n *\n * @param options - Decode options.\n * @param options.errorMessagePrefix - Optional context prefix for thrown parse/validation errors.\n * @param options.headerSchema - Optional schema for the JWT header; defaults to `zJwtHeader`.\n * @param options.jwt - Compact JWT to decode.\n * @param options.payloadSchema - Optional schema for the JWT payload; defaults to `zJwtPayload`.\n * @returns Decoded and schema-validated JWT header, payload, and signature segment.\n * @throws {Oauth2JwtParseError} If the JWT shape or base64url JSON segments are invalid.\n * @throws {ValidationError} If header or payload schema validation fails.\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(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n\n let payloadJson: Record<string, unknown>;\n try {\n const payloadPart = jwtParts[1];\n if (payloadPart === undefined) {\n throw new Oauth2JwtParseError(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n payloadJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(payloadPart)),\n formatError(\n \"Unable to parse jwt payload to JSON\",\n options.errorMessagePrefix,\n ),\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n formatError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n options.errorMessagePrefix,\n ),\n );\n }\n\n const signaturePart = jwtParts[2];\n if (signaturePart === undefined) {\n throw new Oauth2JwtParseError(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n\n const { header } = decodeJwtHeader({\n errorMessagePrefix: options.errorMessagePrefix,\n headerSchema: options.headerSchema,\n jwt: options.jwt,\n });\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n formatError(\"Invalid JWT payload\", options.errorMessagePrefix),\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 { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zTrustChain } from \"../../common/z-common\";\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.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain, // REQUIRED in v1.0\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n});\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.looseObject({\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.url().optional(),\n wallet_name: z.string().optional(),\n});\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 {\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 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_0 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.0 wallet attestation JWT.\n *\n * @param options - v1.0 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.0 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n );\n}\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zCertificateChain, zTrustChain } from \"../../common/z-common\";\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.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain.optional(), // OPTIONAL in v1.3\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: zCertificateChain, // REQUIRED in v1.3\n});\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.looseObject({\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.url().optional(),\n wallet_name: z.string().optional(),\n});\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 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_3 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.3 wallet attestation JWT.\n *\n * @param options - v1.3 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.3 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\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 { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zCertificateChain, zTrustChain } from \"../../common/z-common\";\n\nexport const zWalletAttestationStatusV1_4 = z.object({\n status_list: z.object({\n idx: z.number().int(),\n uri: z.string(),\n }),\n});\n\nexport const zEudiWalletInfoV1_4 = z.object({\n general_info: z.object({\n wallet_provider_name: z.string(),\n wallet_solution_certification_information: z.url(),\n wallet_solution_id: z.string(),\n wallet_solution_version: z.string(),\n }),\n});\n\nexport const zWalletAttestationJwtHeaderV1_4 = z.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain.optional(),\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: zCertificateChain,\n});\n\nexport const zWalletAttestationJwtPayloadV1_4 = z.looseObject({\n ...zJwtPayload.shape,\n cnf: z.object({\n jwk: zJwk,\n }),\n eudi_wallet_info: zEudiWalletInfoV1_4.optional(),\n exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n nbf: z.number().optional(),\n status: zWalletAttestationStatusV1_4,\n sub: z.string(),\n wallet_link: z.url(),\n wallet_name: z.string(),\n});\n\nexport type WalletAttestationJwtV1_4 = string;\n\nexport const zWalletAttestationJwtV1_4 = 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_4,\n zWalletAttestationJwtPayloadV1_4,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_4 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_4>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_4 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.4 wallet attestation JWT.\n *\n * @param options - v1.4 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.4 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_4,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n );\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\n/**\n * Extracts and validates the DPoP JWT from request headers.\n *\n * @param headers - Request headers to inspect.\n * @returns The DPoP JWT when present and well-formed, `{ valid: true }` when absent,\n * or `{ valid: false }` when the header is malformed.\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","/**\n * Normalizes a request URL into the DPoP `htu` claim value.\n *\n * @param requestUrl - Full request URL.\n * @returns URL string without query string or fragment.\n */\nexport 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 { MAX_JTI_LENGTH, zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zDpopJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: z.url(),\n iat: z.number().int().nonnegative(),\n jti: z.string().max(MAX_JTI_LENGTH),\n});\n\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n});\n\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport {\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: ItWalletAuthorizationServerMetadata;\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\n/**\n * Verifies wallet attestation and client attestation PoP headers as a pair.\n *\n * @param options - Client attestation verification options.\n * @param options.authorizationServerMetadata - Authorization Server metadata used for issuer/audience checks.\n * @param options.callbacks - Hashing and JWT verification callbacks.\n * @param options.clientAttestation - Wallet attestation and PoP JWT values from the request.\n * @param options.config - IT-Wallet specification version used to validate the wallet attestation.\n * @param options.dpopJwkThumbprint - Optional DPoP JWK thumbprint to compare with the attestation key.\n * @param options.now - Date used for temporal validation.\n * @param options.requestClientId - Optional client_id that must match the attestation subject.\n * @returns Verified wallet attestation and client attestation PoP JWT data.\n * @throws {Oauth2Error} If required headers are missing or any attestation validation fails.\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 { CallbackContext, JwtSignerJwk, verifyJwt } from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n parseWithErrorHandling,\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\";\nimport {\n IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES,\n ItWalletClientAttestationPopJwtHeader,\n ItWalletClientAttestationPopJwtPayload,\n zItWalletClientAttestationPopJwtAlg,\n zItWalletClientAttestationPopJwtHeader,\n zItWalletClientAttestationPopJwtPayload,\n zItWalletClientAttestationPopJwtTyp,\n} from \"./z-client-attestation-pop\";\n\nfunction assertSupportedClientAttestationPopAlg(\n alg: string,\n): asserts alg is (typeof IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES)[number] {\n if (!zItWalletClientAttestationPopJwtAlg.safeParse(alg).success) {\n throw new Oauth2Error(\n `Unsupported alg '${alg}' in client attestation PoP JWT: must be one of ${IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES.join(\", \")}`,\n );\n }\n}\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\n/**\n * Verifies a client attestation proof-of-possession JWT.\n *\n * @param options - Verification options.\n * @param options.authorizationServer - Expected audience, usually the Authorization Server issuer.\n * @param options.callbacks - Callback used to verify the JWT signature.\n * @param options.clientAttestationPopJwt - Compact client attestation PoP JWT.\n * @param options.clientAttestationPublicJwk - Public JWK from the wallet/client attestation confirmation claim.\n * @param options.expectedNonce - Optional nonce expected in the JWT payload.\n * @param options.now - Date used for temporal validation.\n * @returns Decoded JWT header, payload, and resolved signer.\n * @throws {Oauth2Error} If decoding, algorithm validation, signature verification, or claim validation fails.\n */\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding client attestation PoP JWT:\",\n headerSchema: zItWalletClientAttestationPopJwtHeader,\n jwt: options.clientAttestationPopJwt,\n payloadSchema: zItWalletClientAttestationPopJwtPayload,\n });\n\n assertSupportedClientAttestationPopAlg(header.alg);\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedAudience: options.authorizationServer,\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\ninterface BaseCreateClientAttestationPopJwtOptions<\n V extends ItWalletSpecsVersion,\n> {\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 * The IT-Wallet SDK configuration, used to select the correct version-specific\n * payload shape for the client attestation PoP JWT.\n */\n config: IoWalletSdkConfig<V>;\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\ntype NoClientAttestationPopJwtExtraOptions = Record<never, never>;\n\ninterface CreateClientAttestationPopJwtVersionOptions {\n [ItWalletSpecsVersion.V1_0]: {\n /**\n * Expiration time of the JWT.\n * If not provided, 1 minute will be added to `issuedAt`.\n */\n expiresAt?: Date;\n };\n [ItWalletSpecsVersion.V1_3]: NoClientAttestationPopJwtExtraOptions;\n [ItWalletSpecsVersion.V1_4]: NoClientAttestationPopJwtExtraOptions;\n}\n\ntype CreateClientAttestationPopJwtExtraOptions<V extends ItWalletSpecsVersion> =\n [V] extends [keyof CreateClientAttestationPopJwtVersionOptions]\n ? CreateClientAttestationPopJwtVersionOptions[V]\n : NoClientAttestationPopJwtExtraOptions;\n\nexport type CreateClientAttestationPopJwtOptionsForVersion<\n V extends ItWalletSpecsVersion,\n> = BaseCreateClientAttestationPopJwtOptions<V> &\n CreateClientAttestationPopJwtExtraOptions<V>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_0 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_0>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_3 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_3>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_4 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_4>;\n\nexport type CreateClientAttestationPopJwtOptions =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion>;\n\n/**\n * Creates a client attestation proof-of-possession JWT.\n *\n * The signer is derived from the wallet/client attestation `cnf.jwk` when it is\n * not supplied explicitly.\n *\n * @param options - Client attestation PoP creation options.\n * @returns Compact signed client attestation PoP JWT.\n * @throws {Oauth2Error} If required attestation claims are missing, `jti` cannot be generated,\n * or signing/validation fails.\n */\nexport async function createClientAttestationPopJwt<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n>(options: CreateClientAttestationPopJwtOptionsForVersion<V>): Promise<string> {\n try {\n const clientAttestation = decodeJwt({\n errorMessagePrefix: \"Error decoding client attestation JWT:\",\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 assertSupportedClientAttestationPopAlg(signer.alg);\n\n const header = {\n alg: signer.alg,\n typ: zItWalletClientAttestationPopJwtTyp.value,\n } satisfies ItWalletClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\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 = parseWithErrorHandling(\n zItWalletClientAttestationPopJwtPayload,\n {\n aud: options.authorizationServer,\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n ...(options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0\n ? {\n exp: dateToSeconds(\n \"expiresAt\" in options && options.expiresAt\n ? options.expiresAt\n : addSecondsToDate(issuedAt, 1 * 60),\n ),\n }\n : {}),\n } satisfies ItWalletClientAttestationPopJwtPayload,\n );\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 z from \"zod\";\n\nimport { MAX_JTI_LENGTH, zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES = [\n \"ES256\",\n \"ES384\",\n \"ES512\",\n] as const;\n\nexport const zItWalletClientAttestationPopJwtAlg = z.enum(\n IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES,\n);\n\nexport type ItWalletClientAttestationPopJwtAlg = z.infer<\n typeof zItWalletClientAttestationPopJwtAlg\n>;\n\nexport const zItWalletClientAttestationPopJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n aud: z.string(),\n exp: z.number().int().optional(),\n iat: z.number().int(),\n iss: z.string(),\n jti: z.string().max(MAX_JTI_LENGTH),\n nonce: z.string().optional(),\n});\n\nexport type ItWalletClientAttestationPopJwtPayload = z.infer<\n typeof zItWalletClientAttestationPopJwtPayload\n>;\n\nexport const zItWalletClientAttestationPopJwtTyp = z.literal(\n \"oauth-client-attestation-pop+jwt\",\n);\n\nexport const zItWalletClientAttestationPopJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n typ: zItWalletClientAttestationPopJwtTyp,\n});\n\nexport type ItWalletClientAttestationPopJwtHeader = z.infer<\n typeof zItWalletClientAttestationPopJwtHeader\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\n/**\n * Creates a PKCE code verifier and challenge pair.\n *\n * @param options - PKCE creation options.\n * @param options.allowedCodeChallengeMethods - Code challenge methods supported by the server.\n * @param options.callbacks - Random generation and hashing callbacks.\n * @param options.codeVerifier - Optional existing verifier; generated when omitted.\n * @returns Generated verifier, challenge, and selected challenge method.\n * @throws {Oauth2Error} If no challenge method is available or the selected method is unsupported.\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\n/**\n * Verifies that a PKCE code verifier matches a stored code challenge.\n *\n * @param options - PKCE verification options.\n * @param options.callbacks - Hashing callback.\n * @param options.codeChallenge - Expected code challenge.\n * @param options.codeChallengeMethod - Method used to compute the challenge.\n * @param options.codeVerifier - Verifier supplied by the client.\n * @returns Resolves when the verifier matches the challenge.\n * @throws {Oauth2Error} If the verifier does not match or the challenge method is unsupported.\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 `PKCE verification failed: code_verifier does not match the stored 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 CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n decodeUtf8String,\n encodeToBase64Url,\n verifyJwtIatOrThrow,\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\n/**\n * Verifies a DPoP proof JWT against an HTTP request and optional token binding data.\n *\n * @param options - DPoP verification options.\n * @param options.accessToken - Optional access token whose hash must match the `ath` claim.\n * @param options.allowedSigningAlgs - Optional allow-list for DPoP signing algorithms.\n * @param options.callbacks - Hashing and JWT verification callbacks.\n * @param options.dpopJwt - Compact DPoP JWT.\n * @param options.expectedJwkThumbprint - Optional expected confirmation JWK thumbprint.\n * @param options.expectedNonce - Optional nonce expected in the payload.\n * @param options.now - Date used for temporal validation.\n * @param options.request - HTTP request that the DPoP proof must bind to.\n * @returns Decoded JWT header, payload, and resolved signer.\n * @throws {Oauth2Error} If any DPoP claim, token binding, or signature validation fails.\n */\nexport async function verifyTokenDPoP(options: VerifyTokenDPoPOptions) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding access token DPoP JWT:\",\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 !== undefined) {\n if (options.expectedNonce === \"\") {\n throw new Oauth2Error(`Invalid 'expectedNonce' provided`);\n }\n\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 try {\n verifyJwtIatOrThrow({\n iat: payload.iat,\n now: options.now,\n });\n } catch (error) {\n if (error instanceof Error) {\n throw new Oauth2Error(`Invalid iat claim in dpop JWT: ${error.message}`);\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifiedClientAttestationPopJwt } from \"../client-attestation/client-attestation-pop\";\nimport {\n ClientAttestationOptions,\n verifyClientAttestation,\n} from \"../client-attestation/verify-client-attestation\";\nimport { VerifiedWalletAttestationJwt } from \"../client-attestation/wallet-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { PkceCodeChallengeMethod, verifyPkce } from \"../pkce\";\nimport { verifyTokenDPoP } from \"../token-dpop/verify-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 expected DPoP nonce value that must appear in the `nonce` claim of the DPoP proof JWT.\n *\n * AS implementations **SHOULD** issue server-provided nonces (via the `DPoP-Nonce` response\n * header) and pass the expected value here to prevent pre-generated DPoP proofs from being\n * reused across requests within the `iat` window.\n *\n * See RFC 9449 §8 for the full nonce issuance flow.\n */\n expectedNonce?: 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: ItWalletAuthorizationServerMetadata;\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: {\n * allowedSigningAlgs: [\"ES256\"],\n * expectedNonce: \"server-issued-nonce\",\n * jwt: dpopJwt,\n * },\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 if (options.dpop.expectedNonce === \"\") {\n throw new Oauth2Error(`Invalid 'dpop.expectedNonce' provided`);\n }\n\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 expectedNonce: options.dpop.expectedNonce,\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext, RequestDpopOptions } from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n addSecondsToDate,\n dateToSeconds,\n dispatchByVersion,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequestV1_0,\n AuthorizationRequestV1_3,\n PushedAuthorizationRequest,\n PushedAuthorizationRequestSigned,\n PushedAuthorizationRequestUnsignedV1_0,\n PushedAuthorizationRequestUnsignedV1_3,\n zAuthorizationRequestV1_0,\n zAuthorizationRequestV1_3,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\ntype AuthorizationRequest = AuthorizationRequestV1_0 | AuthorizationRequestV1_3;\n\ninterface BaseCreatePushedAuthorizationRequestOptions<\n V extends ItWalletSpecsVersion,\n> {\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: ItWalletAuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n config: IoWalletSdkConfig<V>;\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 * 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\nexport interface CreatePushedAuthorizationRequestOptionsV1_0 extends BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_0> {\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\nexport type CreatePushedAuthorizationRequestOptionsV1_3 =\n BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_3>;\n\nexport type CreatePushedAuthorizationRequestOptionsV1_4 =\n BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_4>;\n\nexport type CreatePushedAuthorizationRequestOptions =\n | CreatePushedAuthorizationRequestOptionsV1_0\n | CreatePushedAuthorizationRequestOptionsV1_3\n | CreatePushedAuthorizationRequestOptionsV1_4;\n\ntype CreatePushedAuthorizationRequestOptionsSigned<\n TOptions extends CreatePushedAuthorizationRequestOptions,\n> = {\n authorizationServerMetadata: { require_signed_request_object: true };\n dpop: RequestDpopOptions;\n} & TOptions;\n\ntype CreatePushedAuthorizationRequestOptionsUnsigned<\n TOptions extends CreatePushedAuthorizationRequestOptions,\n> = {\n authorizationServerMetadata: { require_signed_request_object: false };\n} & TOptions;\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.config - Italian Wallet specification version used to build the request shape\n * @param options.responseMode - Response mode (v1.0 only, 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 * - version-specific unsigned PAR 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 for IT-Wallet v1.0 (explicit)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n * });\n *\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 * config,\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 for IT-Wallet v1.3 (when Authorization Server allows it)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_3,\n * });\n *\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 * config,\n * redirectUri: 'https://wallet.example.com/callback',\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 for IT-Wallet v1.0 (no metadata - unsigned)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n * });\n *\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 * config,\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: CreatePushedAuthorizationRequestOptionsSigned<CreatePushedAuthorizationRequestOptions>,\n): Promise<PushedAuthorizationRequestSigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_0>,\n): Promise<PushedAuthorizationRequestUnsignedV1_0>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptionsV1_0,\n): Promise<\n PushedAuthorizationRequestSigned | PushedAuthorizationRequestUnsignedV1_0\n>;\n\nexport async function createPushedAuthorizationRequest(\n options:\n | CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_3>\n | CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_4>,\n): Promise<PushedAuthorizationRequestUnsignedV1_3>;\n\nexport async function createPushedAuthorizationRequest(\n options:\n | CreatePushedAuthorizationRequestOptionsV1_3\n | CreatePushedAuthorizationRequestOptionsV1_4,\n): Promise<\n PushedAuthorizationRequestSigned | PushedAuthorizationRequestUnsignedV1_3\n>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest> {\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const baseAuthorizationRequest = {\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_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 const authorizationRequest = parseAuthorizationRequestByVersion(\n options,\n baseAuthorizationRequest,\n );\n\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n if (requireSigned) {\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 }\n\n return {\n authorizationRequest,\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n };\n}\n\nfunction parseAuthorizationRequestByVersion(\n options: CreatePushedAuthorizationRequestOptions,\n baseAuthorizationRequest: Omit<\n AuthorizationRequest,\n \"authorization_details\" | \"response_mode\" | \"scope\"\n > &\n Pick<AuthorizationRequest, \"authorization_details\" | \"scope\">,\n): AuthorizationRequest {\n return dispatchByVersion(options.config.itWalletSpecsVersion, {\n [ItWalletSpecsVersion.V1_0]: () =>\n zAuthorizationRequestV1_0.parse({\n ...baseAuthorizationRequest,\n response_mode: (options as CreatePushedAuthorizationRequestOptionsV1_0)\n .responseMode,\n }) satisfies AuthorizationRequestV1_0,\n [ItWalletSpecsVersion.V1_3]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\n // V1_4 reuses V1_3 authorization request schema — no breaking changes between versions.\n // Verified against compare/1.3.3...1.4.1: authorization request parameters identical.\n [ItWalletSpecsVersion.V1_4]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\n });\n}\n","import z from \"zod\";\n\nimport { MAX_JTI_LENGTH } from \"../common/jwt/z-jwt\";\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.url(),\n idphinting: z.url(),\n type: z.literal(\"it_l2+document_proof\"),\n});\n\nconst zAuthorizationRequestBaseObject = z.looseObject({\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().max(MAX_JTI_LENGTH),\n redirect_uri: z.url(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n});\n\nconst zAuthorizationRequestBase = zAuthorizationRequestBaseObject.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);\n\nexport const zAuthorizationRequestV1_0 = zAuthorizationRequestBaseObject\n .extend({\n response_mode: z.string(),\n })\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 );\n\nexport type AuthorizationRequestV1_0 = z.infer<\n typeof zAuthorizationRequestV1_0\n>;\n\nexport const zAuthorizationRequestV1_3 = zAuthorizationRequestBase;\nexport type AuthorizationRequestV1_3 = z.infer<\n typeof zAuthorizationRequestV1_3\n>;\n\nexport const zPushedAuthorizationRequestSigned = z.looseObject({\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\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nconst zPushedAuthorizationRequestUnsignedBase = <\n TAuthorizationRequest extends z.ZodType,\n>(\n authorizationRequest: TAuthorizationRequest,\n) =>\n z.looseObject({\n authorizationRequest: authorizationRequest.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\nexport const zPushedAuthorizationRequestUnsignedV1_0 =\n zPushedAuthorizationRequestUnsignedBase(zAuthorizationRequestV1_0);\nexport type PushedAuthorizationRequestUnsignedV1_0 = z.infer<\n typeof zPushedAuthorizationRequestUnsignedV1_0\n>;\n\nexport const zPushedAuthorizationRequestUnsignedV1_3 =\n zPushedAuthorizationRequestUnsignedBase(zAuthorizationRequestV1_3);\nexport type PushedAuthorizationRequestUnsignedV1_3 = z.infer<\n typeof zPushedAuthorizationRequestUnsignedV1_3\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 | PushedAuthorizationRequestUnsignedV1_0\n | PushedAuthorizationRequestUnsignedV1_3;\n\n/**\n * Checks whether a pushed authorization request is represented as a signed JAR.\n *\n * @param par - Pushed authorization request to inspect.\n * @returns True when the request contains a compact `request` JWT.\n */\nexport function isPushedAuthorizationRequestSigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestSigned {\n return \"request\" in par && typeof par.request === \"string\";\n}\n\n/**\n * Checks whether a pushed authorization request is represented as a plain unsigned request.\n *\n * @param par - Pushed authorization request to inspect.\n * @returns True when the request contains version-specific `authorizationRequest` data.\n */\nexport function isPushedAuthorizationRequestUnsigned(\n par: PushedAuthorizationRequest,\n): par is\n | PushedAuthorizationRequestUnsignedV1_0\n | PushedAuthorizationRequestUnsignedV1_3 {\n return \"authorizationRequest\" in par;\n}\n\nexport const zPushedAuthorizationResponse = z.looseObject({\n expires_in: z.number().int(),\n request_uri: z.string(),\n});\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/wallet-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop/create-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 * @param options - Authorization request parsing options.\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 IoWalletSdkConfig,\n ItWalletSpecsVersion,\n RequestLike,\n dispatchByVersion,\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} from \"../jar/parse-jar-request\";\nimport { zJarAuthorizationRequest } from \"../jar/z-jar\";\nimport {\n ParseAuthorizationRequestResult,\n parseAuthorizationRequest,\n} from \"./parse-authorization-request\";\nimport {\n AuthorizationRequestV1_0,\n AuthorizationRequestV1_3,\n zAuthorizationRequestV1_0,\n zAuthorizationRequestV1_3,\n} from \"./z-authorization-request\";\n\ntype AuthorizationRequest = AuthorizationRequestV1_0 | AuthorizationRequestV1_3;\n\nexport interface ParsePushedAuthorizationRequestOptions {\n authorizationRequest: unknown;\n callbacks: Pick<CallbackContext, \"fetch\">;\n config: IoWalletSdkConfig;\n request: RequestLike;\n}\n\nexport interface ParsePushedAuthorizationRequestResult 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 authorizationRequestSchema = getAuthorizationRequestSchema(\n options.config,\n );\n\n const parsed = parseWithErrorHandling(\n z.union([authorizationRequestSchema, zJarAuthorizationRequest]),\n options.authorizationRequest,\n \"Invalid authorization request. Could not parse authorization request or jar.\",\n );\n\n let parsedAuthorizationRequest: z.ZodSafeParseResult<AuthorizationRequest>;\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({\n errorMessagePrefix: \"Error decoding pushed authorization request JWT:\",\n jwt: parsedJar.authorizationRequestJwt,\n });\n\n parsedAuthorizationRequest = authorizationRequestSchema.safeParse(\n jwt.payload,\n );\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 = authorizationRequestSchema.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\nfunction getAuthorizationRequestSchema(config: IoWalletSdkConfig) {\n return dispatchByVersion(config.itWalletSpecsVersion, {\n [ItWalletSpecsVersion.V1_0]: () => zAuthorizationRequestV1_0,\n [ItWalletSpecsVersion.V1_3]: () => zAuthorizationRequestV1_3,\n // V1_4 reuses V1_3 PAR schema — no breaking changes between versions.\n // Verified against compare/1.3.3...1.4.1: authorization request parameters identical.\n [ItWalletSpecsVersion.V1_4]: () => zAuthorizationRequestV1_3,\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\n/**\n * Fetches a JWT-Secured Authorization Request object from a `request_uri`.\n *\n * @param options - Request object fetch options.\n * @param options.fetch - Optional fetch implementation; defaults to the runtime fetch through `createFetcher`.\n * @param options.requestUri - URI hosting the signed authorization request object.\n * @returns Compact JAR request object JWT.\n * @throws {UnexpectedStatusCodeError} If the endpoint does not return HTTP 200.\n * @throws {Oauth2Error} If the request object cannot be fetched.\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\n/**\n * Validates that JAR parameters identify exactly one request transmission mode.\n *\n * @param options - Validation options.\n * @param options.jarRequestParams - JAR request parameters to validate.\n * @returns The request URI when the request is sent by reference.\n * @throws {Oauth2Error} If both `request` and `request_uri` are present or both are missing.\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\n/**\n * Checks whether authorization request parameters contain a JAR request object or URI.\n *\n * @param request - Authorization request parameters to inspect.\n * @returns True when `request` or `request_uri` is present.\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 z from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zJarAuthorizationRequest = z.looseObject({\n client_id: z.optional(z.string()),\n request: z.optional(z.string()),\n request_uri: z.url().optional(),\n});\n\nexport type JarAuthorizationRequest = z.infer<typeof zJarAuthorizationRequest>;\n\nexport const zJarRequestObjectPayload = z.looseObject({\n ...zJwtPayload.shape,\n client_id: z.string(),\n});\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.looseObject({\n ...zJwtHeader.shape,\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n});\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifiedClientAttestationPopJwt } from \"../client-attestation/client-attestation-pop\";\nimport {\n ClientAttestationOptions,\n verifyClientAttestation,\n} from \"../client-attestation/verify-client-attestation\";\nimport { VerifiedWalletAttestationJwt } from \"../client-attestation/wallet-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { verifyTokenDPoP } from \"../token-dpop/verify-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: ItWalletAuthorizationServerMetadata;\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.clientAttestation - Client attestation verification configuration\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 {\n CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\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({\n errorMessagePrefix: \"Error decoding JAR authorization request JWT:\",\n jwt: authorizationRequestJwt,\n });\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 { JwtSigner } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n VerifiedJarRequest,\n verifyJarRequest,\n} from \"../jar/verify-jar-request\";\nimport {\n type VerifyAuthorizationRequestOptions,\n type VerifyAuthorizationRequestResult,\n verifyAuthorizationRequest,\n} from \"./verify-authorization-request\";\n\nexport interface VerifyPushedAuthorizationRequestReturn extends VerifyAuthorizationRequestResult {\n /**\n * The verified JAR request, if `authorizationRequestJwt` was provided\n */\n jar?: VerifiedJarRequest;\n}\n\nexport interface VerifyPushedAuthorizationRequestOptions 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.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.authorizationRequestJwt - Optional JAR JWT and signer information\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.clientAttestation - Optional client attestation verification configuration\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({\n errorMessagePrefix: \"Error decoding pushed authorization request JWT:\",\n jwt: options.authorizationRequestJwt.jwt,\n });\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ContentType,\n FetchHeaders,\n HttpMethod,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} 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: ItWalletAuthorizationServerMetadata;\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: ItWalletAuthorizationServerMetadata;\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 * Creates a client authentication callback that leaves the request unchanged.\n *\n * @returns Client authentication callback for anonymous requests.\n */\nexport function clientAuthenticationAnonymous(): ClientAuthenticationCallback {\n return () => {\n // No authentication, do nothing\n };\n}\n\nexport interface ClientAuthenticationWalletAttestationJwtOptions<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n> {\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"signJwt\">;\n config: IoWalletSdkConfig<V>;\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 *\n * @param options - Wallet attestation client authentication options.\n * @param options.callbacks - Random generation and signing callbacks for the PoP JWT.\n * @param options.config - IT-Wallet specification version used to create the PoP JWT.\n * @param options.walletAttestationJwt - Wallet attestation JWT to attach to outgoing requests.\n * @returns Client authentication callback that mutates request headers with attestation values.\n * @throws {Oauth2Error} If the PoP JWT cannot be created.\n */\nexport function clientAuthenticationWalletAttestationJwt<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n>(\n options: ClientAuthenticationWalletAttestationJwtOptions<V>,\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 config: options.config,\n });\n\n headers.set(oauthClientAttestationHeader, options.walletAttestationJwt);\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop);\n };\n}\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 { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\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 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 const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\n const dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n sub: dpopJwkThumbprint,\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 errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 {\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { ClientAttestationError } from \"../errors\";\n\nconst SUPPORTED_KTY = [\"RSA\", \"EC\"] as const;\n\ninterface JwkThumbprintOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n dpopJwkPublic: Jwk;\n}\n\nexport const calculateDpopJwkThumbprint = (\n options: JwkThumbprintOptions,\n): Promise<string> => {\n if (\n !SUPPORTED_KTY.includes(\n options.dpopJwkPublic.kty as (typeof SUPPORTED_KTY)[number],\n )\n ) {\n throw new ClientAttestationError(\n `Unsupported JWK key type \"${options.dpopJwkPublic.kty}\" for thumbprint computation. Supported types: ${SUPPORTED_KTY.join(\", \")}.`,\n );\n }\n\n return calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpopJwkPublic,\n });\n};\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 { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\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 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 const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\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 dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n sub: dpopJwkThumbprint,\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 errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_4,\n zEudiWalletInfoV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n zWalletAttestationStatusV1_4,\n} from \"./z-wallet-attestation\";\n\nexport interface WalletAttestationOptionsV1_4 extends Omit<\n BaseWalletAttestationOptions,\n \"walletLink\" | \"walletName\"\n> {\n eudiWalletInfo?: z.infer<typeof zEudiWalletInfoV1_4>;\n nbf?: Date;\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]];\n x5c: [string, ...string[]];\n };\n status: z.infer<typeof zWalletAttestationStatusV1_4>;\n walletLink: string;\n walletName: string;\n}\n\n/**\n * Creates a wallet attestation JWT for IT-Wallet v1.4.\n *\n * @param options - v1.4 wallet attestation creation options.\n * @returns Signed wallet attestation JWT.\n * @throws {ValidationError} If temporal constraints or generated JWT validation fail.\n * @throws {ClientAttestationError} For unexpected errors during attestation creation.\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_4,\n): Promise<WalletAttestationJwtV1_4> => {\n try {\n const { signJwt } = options.callbacks;\n const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\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 dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n status: options.status,\n sub: dpopJwkThumbprint,\n wallet_link: options.walletLink,\n wallet_name: options.walletName,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\n ...(options.eudiWalletInfo && {\n eudi_wallet_info: options.eudiWalletInfo,\n }),\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,\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 decodeJwt({\n errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\n headerSchema: zWalletAttestationJwtHeaderV1_4,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_4,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\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\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 { 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 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 *\n * @param options - Form post extraction options.\n * @param options.formData - Raw HTML form_post.jwt response body.\n * @param options.schema - Zod schema used to validate the decoded JWT payload.\n * @returns The compact JWT and decoded JWT data.\n * @throws {Oauth2Error} If the response input cannot be found in the form data.\n *\n * @example\n * ```html\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 * ```\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 errorMessagePrefix: \"Error decoding JARM form post JWT:\",\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.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n});\n\nexport type MrtdChallengeJwtHeader = z.infer<typeof zMrtdChallengeJwtHeader>;\n\n/** JWT payload for MRTD challenge containing session correlation and endpoint parameters */\nexport const zMrtdChallengeJwtPayload = z.looseObject({\n aud: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.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\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.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias-pop+jwt\"),\n});\n\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.looseObject({\n aud: z.string(),\n challenge: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_pop_nonce: z.string(),\n mrz: z.string().optional(),\n});\n\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.looseObject({\n dg1: z.string(),\n dg11: z.string(),\n sod_mrtd: z.string(),\n});\n\n/** IAS (Anti-Cloning) application data from NFC reading (public key, signed challenge, SOD) */\nconst zIasData = z.looseObject({\n challenge_signed: z.string(),\n ias_pk: z.string(),\n sod_ias: z.string(),\n});\n\n/** JWT header for MRTD validation (signed by Wallet Instance) */\nexport const zMrtdValidationJwtHeader = z.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n});\nexport type MrtdValidationJwtHeader = z.infer<typeof zMrtdValidationJwtHeader>;\n\n/** JWT payload for MRTD validation containing NFC-read document evidence */\nexport const zMrtdValidationJwtPayload = z.looseObject({\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\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.looseObject({\n mrtd_val_pop_nonce: z.string(),\n redirect_uri: z.url(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"redirect_to_web\"),\n});\n\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 errorMessagePrefix: \"Error decoding MRTD PoP init response JWT:\",\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/decode-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 errorMessagePrefix: \"Error decoding MRTD challenge JWT:\",\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 errorMessagePrefix: \"Error decoding MRTD challenge JWT:\",\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wCAAAA;AAAA,EAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCAAAC;AAAA,EAAA;AAAA,wCAAAA;AAAA,EAAA,sCAAAA;AA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AAA,MACR;AAAA,IACF;AAAA,EACF;AAIA,QAAM,UAAU,IAAI;AAEpB,QAAM,EAAE,OAAO,IAAI,UAAM,2BAAU;AAAA,IACjC,SAAS;AAAA,IACT,cAAc;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ;AAAA,IAEA,QAAQ,QAAQ,cAAU,kCAAiB,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;;;AxDQA,IAAAC,kBAkBO;","names":["createWalletAttestationJwt","verifyWalletAttestationJwt","zCompactJwe","import_oauth2","import_io_wallet_utils","import_zod","import_zod","z","z","z","import_zod","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","import_zod","z","import_oauth2","import_oauth2","import_io_wallet_utils","import_zod","import_zod","verifyWalletAttestationJwt","import_zod","verifyWalletAttestationJwt","verifyWalletAttestationJwt","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","import_zod","import_oauth2","import_oauth2","import_io_wallet_utils","import_zod","z","verifyWalletAttestationJwt","import_oauth2","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","import_io_wallet_utils","toURLSearchParams","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_zod","z","z","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","createWalletAttestationJwt","import_io_wallet_utils","createWalletAttestationJwt","import_zod","zCompactJwe","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","JWT_EXPIRY_SECONDS","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_oauth2","import_oauth2"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/access-token/create-token-request.ts","../src/access-token/create-token-response.ts","../src/common/jwt/decode-jwt-header.ts","../src/common/jwt/z-jwt.ts","../src/common/jwk/z-jwk.ts","../src/common/z-common.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/access-token/fetch-token-response.ts","../src/access-token/parse-token-request.ts","../src/client-attestation/wallet-attestation.ts","../src/client-attestation/types.ts","../src/client-attestation/verify-wallet-attestation-jwt-base.ts","../src/common/jwt/decode-jwt.ts","../src/client-attestation/v1.0/z-wallet-attestation.ts","../src/client-attestation/v1.0/verify-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/v1.4/z-wallet-attestation.ts","../src/client-attestation/v1.4/verify-wallet-attestation-jwt.ts","../src/token-dpop/create-token-dpop.ts","../src/token-dpop/dpop-utils.ts","../src/token-dpop/z-dpop.ts","../src/access-token/z-grant-type.ts","../src/client-attestation/verify-client-attestation.ts","../src/client-attestation/client-attestation-pop.ts","../src/client-attestation/z-client-attestation-pop.ts","../src/pkce.ts","../src/token-dpop/verify-token-dpop.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/fetch-jar-request-object.ts","../src/jar/validate-jar-request.ts","../src/jar/parse-jar-request.ts","../src/jar/z-jar.ts","../src/authorization-request/verify-authorization-request.ts","../src/jar/verify-jar-request.ts","../src/authorization-request/verify-pushed-authorization-request.ts","../src/client-attestation/client-authentication.ts","../src/client-attestation/v1.0/create-wallet-attestation-jwt.ts","../src/client-attestation/jwk-thumbprint.ts","../src/client-attestation/v1.3/create-wallet-attestation-jwt.ts","../src/client-attestation/v1.4/create-wallet-attestation-jwt.ts","../src/common/jwt/z-jwe.ts","../src/jar/create-jar-request.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"],"sourcesContent":["export * from \"./access-token/create-token-request\";\nexport * from \"./access-token/create-token-response\";\nexport * from \"./access-token/fetch-token-response\";\nexport * from \"./access-token/parse-token-request\";\nexport * from \"./access-token/verify-access-token-request\";\nexport * from \"./access-token/z-grant-type\";\nexport * from \"./access-token/z-token\";\nexport * from \"./authorization-request/create-authorization-request\";\nexport * from \"./authorization-request/fetch-authorization-response\";\nexport * from \"./authorization-request/parse-authorization-request\";\nexport * from \"./authorization-request/parse-pushed-authorization-request\";\nexport * from \"./authorization-request/verify-authorization-request\";\nexport * from \"./authorization-request/verify-pushed-authorization-request\";\nexport * from \"./authorization-request/z-authorization-request\";\nexport * from \"./client-attestation/client-attestation-pop\";\nexport * from \"./client-attestation/client-authentication\";\nexport type * from \"./client-attestation/types\";\nexport {\n type WalletAttestationOptionsV1_0,\n createWalletAttestationJwt as createWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_0,\n type VerifyWalletAttestationJwtOptionsV1_0,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_0,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n zWalletAttestationJwtV1_0,\n} from \"./client-attestation/v1.0/z-wallet-attestation\";\nexport {\n type WalletAttestationOptionsV1_3,\n createWalletAttestationJwt as createWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_3,\n type VerifyWalletAttestationJwtOptionsV1_3,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_3,\n zWalletAttestationJwtHeaderV1_3,\n zWalletAttestationJwtPayloadV1_3,\n zWalletAttestationJwtV1_3,\n} from \"./client-attestation/v1.3/z-wallet-attestation\";\nexport {\n type WalletAttestationOptionsV1_4,\n createWalletAttestationJwt as createWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/create-wallet-attestation-jwt\";\nexport {\n type VerifiedWalletAttestationJwtV1_4,\n type VerifyWalletAttestationJwtOptionsV1_4,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/verify-wallet-attestation-jwt\";\nexport {\n type WalletAttestationJwtV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n zWalletAttestationJwtV1_4,\n} from \"./client-attestation/v1.4/z-wallet-attestation\";\nexport * from \"./client-attestation/verify-client-attestation\";\nexport * from \"./client-attestation/wallet-attestation\";\nexport * from \"./client-attestation/z-client-attestation-pop\";\nexport * from \"./common/jwk/z-jwk\";\nexport * from \"./common/jwt/decode-jwt\";\nexport * from \"./common/jwt/decode-jwt-header\";\nexport * from \"./common/jwt/z-jwe\";\nexport * from \"./common/jwt/z-jwt\";\nexport * from \"./common/z-common\";\nexport * from \"./errors\";\nexport * from \"./jar/create-jar-request\";\nexport * from \"./jar/fetch-jar-request-object\";\nexport * from \"./jar/parse-jar-request\";\nexport * from \"./jar/validate-jar-request\";\nexport * from \"./jar/verify-jar-request\";\nexport * from \"./jar/z-jar\";\nexport * from \"./jarm-form-post-jwt\";\nexport * from \"./mrtd-pop/create-mrtd-validation-jwt\";\nexport * from \"./mrtd-pop/fetch-mrtd-pop-init\";\nexport * from \"./mrtd-pop/fetch-mrtd-pop-verify\";\nexport * from \"./mrtd-pop/parse-mrtd-challenge\";\nexport * from \"./mrtd-pop/verify-mrtd-challenge\";\nexport * from \"./mrtd-pop/z-mrtd-pop\";\nexport * from \"./pkce\";\nexport * from \"./token-dpop/create-token-dpop\";\nexport * from \"./token-dpop/dpop-utils\";\nexport * from \"./token-dpop/verify-token-dpop\";\nexport * from \"./token-dpop/z-dpop\";\n\nexport {\n /** @deprecated Use `CallbackContext` from `@pagopa/io-wallet-utils` instead. */\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 /** @deprecated Use `JwtSignerJwk` from `@pagopa/io-wallet-utils` instead. */\n type JwtSignerJwk,\n Oauth2JwtParseError,\n type RequestDpopOptions,\n type SignJwtCallback,\n type VerifyJwtCallback,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\n","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\n/**\n * Creates an OAuth 2.0 authorization-code access token request body.\n *\n * @param options - Access token request inputs.\n * @param options.additionalRequestPayload - Extra form fields to include in the token request.\n * @param options.authorizationCode - Authorization code received from the authorization response.\n * @param options.pkceCodeVerifier - PKCE verifier associated with the authorization request.\n * @param options.redirectUri - Redirect URI used in the authorization request.\n * @returns URL-form-encodable authorization-code grant request data.\n */\nexport const createTokenRequest = async (\n options: RetrieveAuthorizationCodeAccessTokenOptions,\n) =>\n ({\n ...options.additionalRequestPayload,\n code: options.authorizationCode,\n code_verifier: options.pkceCodeVerifier,\n grant_type: \"authorization_code\",\n redirect_uri: options.redirectUri,\n }) satisfies AuthorizationCodeGrantType;\n","import {\n CallbackContext,\n HashAlgorithm,\n JwtSigner,\n calculateJwkThumbprint,\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 { jwtHeaderFromJwtSigner } from \"../common/jwt/decode-jwt-header\";\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 *\n * @param options - Access token response creation options.\n * @returns OAuth token response with a signed access token JWT.\n * @throws {CreateTokenResponseError} If DPoP binding is required but missing, or if response creation fails, including validation failures from the generated JWT header or payload.\n * @throws {ValidationError} If the generated JWT header or payload fails validation.\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 ...options.additionalPayload,\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 } satisfies AccessTokenProfileJwtPayload);\n\n const { jwt } = await options.callbacks.signJwt(options.signer, {\n header,\n payload,\n });\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n ...options.additionalPayload,\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: options.refreshToken,\n token_type: options.tokenType,\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","import { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n formatError,\n parseWithErrorHandling,\n stringToJsonWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { InferSchemaOrDefaultOutput } from \"./decode-jwt\";\n\nimport { JwtSigner, zJwtHeader } from \"./z-jwt\";\n\nexport interface DecodeJwtHeaderOptions<\n HeaderSchema extends BaseSchema | undefined,\n> {\n /**\n * Optional prefix for error messages thrown during decoding, to provide more context on where the error occurred\n */\n errorMessagePrefix?: string;\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\n/**\n * Decodes and validates the header of a compact JWT.\n *\n * This helper does not verify the JWT signature or parse the payload.\n *\n * @param options - Header decode options.\n * @param options.errorMessagePrefix - Optional context prefix for thrown parse/validation errors.\n * @param options.headerSchema - Optional schema for the JWT header; defaults to `zJwtHeader`.\n * @param options.jwt - Compact JWT to decode.\n * @returns Decoded and schema-validated JWT header.\n * @throws {Oauth2JwtParseError} If the JWT shape or header JSON is invalid.\n * @throws {ValidationError} If header schema validation fails.\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(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\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 formatError(\n \"Unable to parse jwt header to JSON\",\n options.errorMessagePrefix,\n ),\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n formatError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n options.errorMessagePrefix,\n ),\n );\n }\n\n const header = parseWithErrorHandling(\n options.headerSchema ?? zJwtHeader,\n headerJson,\n formatError(\"Invalid JWT header\", options.errorMessagePrefix),\n ) as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>;\n\n return {\n header,\n };\n}\n\n/**\n * Builds a JWT header from an SDK signer descriptor.\n *\n * @param signer - Signer descriptor used by SDK signing callbacks.\n * @returns Header fields required by the signer method.\n */\nexport function jwtHeaderFromJwtSigner(signer: JwtSigner) {\n if (signer.method === \"did\") {\n return {\n alg: signer.alg,\n kid: signer.didUrl,\n };\n }\n\n if (signer.method === \"federation\") {\n return {\n alg: signer.alg,\n kid: signer.kid,\n trust_chain: signer.trustChain,\n };\n }\n\n if (signer.method === \"jwk\") {\n return {\n alg: signer.alg,\n jwk: signer.publicJwk,\n };\n }\n\n if (signer.method === \"x5c\") {\n return {\n alg: signer.alg,\n kid: signer.kid,\n trust_chain: signer.trustChain,\n x5c: signer.x5c,\n };\n }\n return { alg: signer.alg };\n}\n","import z from \"zod\";\n\nimport { Jwk, zJwk } from \"../jwk/z-jwk\";\nimport {\n TrustChain,\n zAlgValueNotNone,\n zCertificateChain,\n zTrustChain,\n} from \"../z-common\";\n\nexport const MAX_JTI_LENGTH = 256;\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 trustChain?: TrustChain;\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?: TrustChain;\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.looseObject({\n // RFC9449. jwk thumbprint of the dpop public key to which the access token is bound\n jkt: z.string().optional(),\n jwk: zJwk.optional(),\n});\n\nexport const zJwtPayload = z.looseObject({\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().max(MAX_JTI_LENGTH).optional(),\n nbf: z.number().int().optional(),\n nonce: z.string().optional(),\n // Reserved for status parameters\n status: z.record(z.string(), z.any()).optional(),\n // Reserved for OpenID Federation\n trust_chain: zTrustChain.optional(),\n});\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>;\n\nexport const zJwtHeader = z.looseObject({\n alg: zAlgValueNotNone,\n jwk: zJwk.optional(),\n kid: z.string().optional(),\n // Reserved for OpenID Federation\n trust_chain: zTrustChain.optional(),\n typ: z.string().optional(),\n x5c: zCertificateChain.optional(),\n});\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>;\n","import z from \"zod\";\n\nimport { zCertificateChain } from \"../z-common\";\n\nexport const zJwk = z.looseObject({\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.looseObject({\n d: z.optional(z.string()),\n r: z.optional(z.string()),\n t: z.optional(z.string()),\n }),\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(zCertificateChain),\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\nexport type Jwk = z.infer<typeof zJwk>;\n\nexport const zJwkSet = z.looseObject({ keys: z.array(zJwk) });\n\nexport type JwkSet = z.infer<typeof zJwkSet>;\n","import { FetchHeaders, HttpMethod } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nexport const zTrustChain = z.tuple([z.string()], z.string());\nexport type TrustChain = z.infer<typeof zTrustChain>;\n\nexport const zCertificateChain = z.array(z.string()).nonempty();\nexport type CertificateChain = z.infer<typeof zCertificateChain>;\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","/**\n * Generic error thrown on OAuth2 operations\n */\nexport class Oauth2Error extends Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"Oauth2Error\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class PushedAuthorizationRequestError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"PushedAuthorizationRequestError\";\n this.statusCode = options?.statusCode;\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, options?: ErrorOptions) {\n super(message, options);\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 readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"MrtdPopError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Custom error thrown when pushed authorization request operations fail\n */\nexport class FetchTokenResponseError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"FetchTokenResponseError\";\n this.statusCode = options?.statusCode;\n }\n}\n\n/**\n * Error thrown when access token response creation fails.\n */\nexport class CreateTokenResponseError extends Oauth2Error {\n readonly statusCode?: number;\n constructor(\n message: string,\n options?: { statusCode?: number } & ErrorOptions,\n ) {\n super(message, options);\n this.name = \"CreateTokenResponseError\";\n this.statusCode = options?.statusCode;\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, options?: ErrorOptions) {\n super(message, options);\n this.name = \"ClientAttestationError\";\n }\n}\n","import { z } from \"zod\";\n\nimport { MAX_JTI_LENGTH, 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.looseObject({\n access_token: z.string(),\n authorization_details: z\n .array(\n z.looseObject({\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 )\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\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>;\n\nexport const zAccessTokenProfileJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n typ: z.enum([\"application/at+jwt\", \"at+jwt\"]),\n});\n\nexport type AccessTokenProfileJwtHeader = z.infer<\n typeof zAccessTokenProfileJwtHeader\n>;\n\nexport const zAccessTokenProfileJwtPayload = z.looseObject({\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().max(MAX_JTI_LENGTH),\n nbf: z.number().optional(),\n scope: z.string().optional(),\n sub: z.string(),\n});\n\nexport type AccessTokenProfileJwtPayload = z.infer<\n typeof zAccessTokenProfileJwtPayload\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\n/**\n * Converts an access token request object into URL-encoded form parameters.\n *\n * Object values are JSON-stringified so structured extension parameters such as\n * `authorization_details` can be sent in `application/x-www-form-urlencoded` requests.\n *\n * @param data - Access token request payload.\n * @returns URLSearchParams containing all defined request fields.\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/wallet-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop/create-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 { zCompactJwt } from \"@openid4vc/oauth2\";\nimport {\n FetchHeaders,\n ItWalletSpecsVersion,\n createVersionDispatcher,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type {\n VerifiedWalletAttestationJwtV1_0,\n VerifyWalletAttestationJwtOptionsV1_0,\n} from \"./v1.0/verify-wallet-attestation-jwt\";\nimport type {\n VerifiedWalletAttestationJwtV1_3,\n VerifyWalletAttestationJwtOptionsV1_3,\n} from \"./v1.3/verify-wallet-attestation-jwt\";\nimport type {\n VerifiedWalletAttestationJwtV1_4,\n VerifyWalletAttestationJwtOptionsV1_4,\n} from \"./v1.4/verify-wallet-attestation-jwt\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0 } from \"./v1.0/verify-wallet-attestation-jwt\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3 } from \"./v1.3/verify-wallet-attestation-jwt\";\nimport { verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4 } from \"./v1.4/verify-wallet-attestation-jwt\";\n\nconst dispatchVerifyWalletAttestationJwt = createVersionDispatcher<\n VerifyWalletAttestationJwtOptions,\n Promise<VerifiedWalletAttestationJwt>\n>({\n [ItWalletSpecsVersion.V1_0]: (o) =>\n verifyWalletAttestationJwtV1_0(o as VerifyWalletAttestationJwtOptionsV1_0),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n verifyWalletAttestationJwtV1_3(o as VerifyWalletAttestationJwtOptionsV1_3),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n verifyWalletAttestationJwtV1_4(o as VerifyWalletAttestationJwtOptionsV1_4),\n});\n\nexport type VerifiedWalletAttestationJwt =\n | VerifiedWalletAttestationJwtV1_0\n | VerifiedWalletAttestationJwtV1_3\n | VerifiedWalletAttestationJwtV1_4;\n\nexport type VerifyWalletAttestationJwtOptions =\n | VerifyWalletAttestationJwtOptionsV1_0\n | VerifyWalletAttestationJwtOptionsV1_3\n | VerifyWalletAttestationJwtOptionsV1_4;\n\n/**\n * Verifies a wallet/client attestation JWT according to the configured IT-Wallet version.\n *\n * @param options - Version-specific wallet attestation verification options.\n * @returns Decoded and verified wallet attestation data for the configured version.\n * @throws {ValidationError} If JWT header or payload validation fails.\n * @throws {Oauth2JwtParseError} If the attestation JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n * @throws {ItWalletSpecsVersionError} If the configured version is unsupported.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n): Promise<VerifiedWalletAttestationJwtV1_0>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_3,\n): Promise<VerifiedWalletAttestationJwtV1_3>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_4,\n): Promise<VerifiedWalletAttestationJwtV1_4>;\n\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptions,\n): Promise<VerifiedWalletAttestationJwt> {\n return dispatchVerifyWalletAttestationJwt(options);\n}\n\n/**\n * Extracts wallet attestation and PoP JWT header values from request headers.\n *\n * @param headers - Request headers to inspect.\n * @returns Parsed header values when both are present, `{ valid: true }` when neither is present,\n * or `{ valid: false }` when the pair is incomplete or malformed.\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 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, \"hash\" | \"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 type { ZodType } from \"zod\";\n\nimport { jwtSignerFromJwt, verifyJwt } from \"@openid4vc/oauth2\";\n\nimport type { JwtHeader, JwtPayload } from \"../common/jwt/z-jwt\";\nimport type { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\n\nexport async function verifyWalletAttestationBase<\n THeader extends ZodType<JwtHeader>,\n TPayload extends ZodType<JwtPayload>,\n>(\n options: BaseVerifyWalletAttestationJwtOptions,\n headerSchema: THeader,\n payloadSchema: TPayload,\n) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 { Oauth2JwtParseError } from \"@openid4vc/oauth2\";\nimport {\n BaseSchema,\n decodeBase64,\n encodeToUtf8String,\n formatError,\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 * Optional prefix for error messages thrown during decoding, to provide more context on where the error occurred\n */\n errorMessagePrefix?: string;\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\n/**\n * Decodes a compact JWT and validates its header and payload with Zod schemas.\n *\n * This helper does not verify the JWT signature.\n *\n * @param options - Decode options.\n * @param options.errorMessagePrefix - Optional context prefix for thrown parse/validation errors.\n * @param options.headerSchema - Optional schema for the JWT header; defaults to `zJwtHeader`.\n * @param options.jwt - Compact JWT to decode.\n * @param options.payloadSchema - Optional schema for the JWT payload; defaults to `zJwtPayload`.\n * @returns Decoded and schema-validated JWT header, payload, and signature segment.\n * @throws {Oauth2JwtParseError} If the JWT shape or base64url JSON segments are invalid.\n * @throws {ValidationError} If header or payload schema validation fails.\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(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n\n let payloadJson: Record<string, unknown>;\n try {\n const payloadPart = jwtParts[1];\n if (payloadPart === undefined) {\n throw new Oauth2JwtParseError(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n payloadJson = stringToJsonWithErrorHandling(\n encodeToUtf8String(decodeBase64(payloadPart)),\n formatError(\n \"Unable to parse jwt payload to JSON\",\n options.errorMessagePrefix,\n ),\n );\n } catch (error) {\n throw new Oauth2JwtParseError(\n formatError(\n `Error parsing JWT. ${error instanceof Error ? error.message : \"\"}`,\n options.errorMessagePrefix,\n ),\n );\n }\n\n const signaturePart = jwtParts[2];\n if (signaturePart === undefined) {\n throw new Oauth2JwtParseError(\n formatError(\n \"Unable to decode because Jwt is not a valid!\",\n options.errorMessagePrefix,\n ),\n );\n }\n\n const { header } = decodeJwtHeader({\n errorMessagePrefix: options.errorMessagePrefix,\n headerSchema: options.headerSchema,\n jwt: options.jwt,\n });\n const payload = parseWithErrorHandling(\n options.payloadSchema ?? zJwtPayload,\n payloadJson,\n formatError(\"Invalid JWT payload\", options.errorMessagePrefix),\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 { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zTrustChain } from \"../../common/z-common\";\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.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain, // REQUIRED in v1.0\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n});\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.looseObject({\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.url().optional(),\n wallet_name: z.string().optional(),\n});\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 {\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 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_0>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_0 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.0 wallet attestation JWT.\n *\n * @param options - v1.0 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.0 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_0,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_0,\n zWalletAttestationJwtPayloadV1_0,\n );\n}\n","import { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zCertificateChain, zTrustChain } from \"../../common/z-common\";\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.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain.optional(), // OPTIONAL in v1.3\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: zCertificateChain, // REQUIRED in v1.3\n});\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.looseObject({\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.url().optional(),\n wallet_name: z.string().optional(),\n});\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 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_3>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_3 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.3 wallet attestation JWT.\n *\n * @param options - v1.3 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.3 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\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 { z } from \"zod\";\n\nimport { zJwk } from \"../../common/jwk/z-jwk\";\nimport { zJwtHeader, zJwtPayload } from \"../../common/jwt/z-jwt\";\nimport { zCertificateChain, zTrustChain } from \"../../common/z-common\";\n\nexport const zWalletAttestationStatusV1_4 = z.object({\n status_list: z.object({\n idx: z.number().int(),\n uri: z.string(),\n }),\n});\n\nexport const zEudiWalletInfoV1_4 = z.object({\n general_info: z.object({\n wallet_provider_name: z.string(),\n wallet_solution_certification_information: z.url(),\n wallet_solution_id: z.string(),\n wallet_solution_version: z.string(),\n }),\n});\n\nexport const zWalletAttestationJwtHeaderV1_4 = z.looseObject({\n ...zJwtHeader.shape,\n trust_chain: zTrustChain.optional(),\n typ: z.literal(\"oauth-client-attestation+jwt\"),\n x5c: zCertificateChain,\n});\n\nexport const zWalletAttestationJwtPayloadV1_4 = z.looseObject({\n ...zJwtPayload.shape,\n cnf: z.object({\n jwk: zJwk,\n }),\n eudi_wallet_info: zEudiWalletInfoV1_4.optional(),\n exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n nbf: z.number().optional(),\n status: zWalletAttestationStatusV1_4,\n sub: z.string(),\n wallet_link: z.url(),\n wallet_name: z.string(),\n});\n\nexport type WalletAttestationJwtV1_4 = string;\n\nexport const zWalletAttestationJwtV1_4 = 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_4,\n zWalletAttestationJwtPayloadV1_4,\n} from \"./z-wallet-attestation\";\n\nexport interface VerifyWalletAttestationJwtOptionsV1_4 extends BaseVerifyWalletAttestationJwtOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.V1_4>;\n}\n\nexport type VerifiedWalletAttestationJwtV1_4 = Awaited<\n ReturnType<typeof verifyWalletAttestationJwt>\n>;\n\n/**\n * Verifies an IT-Wallet v1.4 wallet attestation JWT.\n *\n * @param options - v1.4 verification options.\n * @returns Decoded and verified wallet attestation JWT data.\n * @throws {ValidationError} If the JWT header or payload does not satisfy the v1.4 schema.\n * @throws {Oauth2JwtParseError} If the JWT cannot be decoded.\n * @throws {Oauth2JwtVerificationError} If signature verification fails.\n */\nexport async function verifyWalletAttestationJwt(\n options: VerifyWalletAttestationJwtOptionsV1_4,\n) {\n return verifyWalletAttestationBase(\n options,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n );\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\n/**\n * Extracts and validates the DPoP JWT from request headers.\n *\n * @param headers - Request headers to inspect.\n * @returns The DPoP JWT when present and well-formed, `{ valid: true }` when absent,\n * or `{ valid: false }` when the header is malformed.\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","/**\n * Normalizes a request URL into the DPoP `htu` claim value.\n *\n * @param requestUrl - Full request URL.\n * @returns URL string without query string or fragment.\n */\nexport 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 { MAX_JTI_LENGTH, zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zDpopJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n ath: z.optional(z.string()),\n htm: zHttpMethod,\n htu: z.url(),\n iat: z.number().int().nonnegative(),\n jti: z.string().max(MAX_JTI_LENGTH),\n});\n\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>;\n\nexport const zDpopJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n jwk: zJwk,\n typ: z.literal(\"dpop+jwt\"),\n});\n\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>;\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport {\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: ItWalletAuthorizationServerMetadata;\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\n/**\n * Verifies wallet attestation and client attestation PoP headers as a pair.\n *\n * @param options - Client attestation verification options.\n * @param options.authorizationServerMetadata - Authorization Server metadata used for issuer/audience checks.\n * @param options.callbacks - Hashing and JWT verification callbacks.\n * @param options.clientAttestation - Wallet attestation and PoP JWT values from the request.\n * @param options.config - IT-Wallet specification version used to validate the wallet attestation.\n * @param options.dpopJwkThumbprint - Optional DPoP JWK thumbprint to compare with the attestation key.\n * @param options.now - Date used for temporal validation.\n * @param options.requestClientId - Optional client_id that must match the attestation subject.\n * @returns Verified wallet attestation and client attestation PoP JWT data.\n * @throws {Oauth2Error} If required headers are missing or any attestation validation fails.\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 { CallbackContext, JwtSignerJwk, verifyJwt } from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n addSecondsToDate,\n dateToSeconds,\n encodeToBase64Url,\n parseWithErrorHandling,\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\";\nimport {\n IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES,\n ItWalletClientAttestationPopJwtHeader,\n ItWalletClientAttestationPopJwtPayload,\n zItWalletClientAttestationPopJwtAlg,\n zItWalletClientAttestationPopJwtHeader,\n zItWalletClientAttestationPopJwtPayload,\n zItWalletClientAttestationPopJwtTyp,\n} from \"./z-client-attestation-pop\";\n\nfunction assertSupportedClientAttestationPopAlg(\n alg: string,\n): asserts alg is (typeof IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES)[number] {\n if (!zItWalletClientAttestationPopJwtAlg.safeParse(alg).success) {\n throw new Oauth2Error(\n `Unsupported alg '${alg}' in client attestation PoP JWT: must be one of ${IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES.join(\", \")}`,\n );\n }\n}\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\n/**\n * Verifies a client attestation proof-of-possession JWT.\n *\n * @param options - Verification options.\n * @param options.authorizationServer - Expected audience, usually the Authorization Server issuer.\n * @param options.callbacks - Callback used to verify the JWT signature.\n * @param options.clientAttestationPopJwt - Compact client attestation PoP JWT.\n * @param options.clientAttestationPublicJwk - Public JWK from the wallet/client attestation confirmation claim.\n * @param options.expectedNonce - Optional nonce expected in the JWT payload.\n * @param options.now - Date used for temporal validation.\n * @returns Decoded JWT header, payload, and resolved signer.\n * @throws {Oauth2Error} If decoding, algorithm validation, signature verification, or claim validation fails.\n */\nexport async function verifyClientAttestationPopJwt(\n options: VerifyClientAttestationPopJwtOptions,\n) {\n try {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding client attestation PoP JWT:\",\n headerSchema: zItWalletClientAttestationPopJwtHeader,\n jwt: options.clientAttestationPopJwt,\n payloadSchema: zItWalletClientAttestationPopJwtPayload,\n });\n\n assertSupportedClientAttestationPopAlg(header.alg);\n\n const { signer } = await verifyJwt({\n compact: options.clientAttestationPopJwt,\n errorMessage: \"client attestation pop jwt verification failed\",\n expectedAudience: options.authorizationServer,\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\ninterface BaseCreateClientAttestationPopJwtOptions<\n V extends ItWalletSpecsVersion,\n> {\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 * The IT-Wallet SDK configuration, used to select the correct version-specific\n * payload shape for the client attestation PoP JWT.\n */\n config: IoWalletSdkConfig<V>;\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\ntype NoClientAttestationPopJwtExtraOptions = Record<never, never>;\n\ninterface CreateClientAttestationPopJwtVersionOptions {\n [ItWalletSpecsVersion.V1_0]: {\n /**\n * Expiration time of the JWT.\n * If not provided, 1 minute will be added to `issuedAt`.\n */\n expiresAt?: Date;\n };\n [ItWalletSpecsVersion.V1_3]: NoClientAttestationPopJwtExtraOptions;\n [ItWalletSpecsVersion.V1_4]: NoClientAttestationPopJwtExtraOptions;\n}\n\ntype CreateClientAttestationPopJwtExtraOptions<V extends ItWalletSpecsVersion> =\n [V] extends [keyof CreateClientAttestationPopJwtVersionOptions]\n ? CreateClientAttestationPopJwtVersionOptions[V]\n : NoClientAttestationPopJwtExtraOptions;\n\nexport type CreateClientAttestationPopJwtOptionsForVersion<\n V extends ItWalletSpecsVersion,\n> = BaseCreateClientAttestationPopJwtOptions<V> &\n CreateClientAttestationPopJwtExtraOptions<V>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_0 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_0>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_3 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_3>;\n\nexport type CreateClientAttestationPopJwtOptionsV1_4 =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion.V1_4>;\n\nexport type CreateClientAttestationPopJwtOptions =\n CreateClientAttestationPopJwtOptionsForVersion<ItWalletSpecsVersion>;\n\n/**\n * Creates a client attestation proof-of-possession JWT.\n *\n * The signer is derived from the wallet/client attestation `cnf.jwk` when it is\n * not supplied explicitly.\n *\n * @param options - Client attestation PoP creation options.\n * @returns Compact signed client attestation PoP JWT.\n * @throws {Oauth2Error} If required attestation claims are missing, `jti` cannot be generated,\n * or signing/validation fails.\n */\nexport async function createClientAttestationPopJwt<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n>(options: CreateClientAttestationPopJwtOptionsForVersion<V>): Promise<string> {\n try {\n const clientAttestation = decodeJwt({\n errorMessagePrefix: \"Error decoding client attestation JWT:\",\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 assertSupportedClientAttestationPopAlg(signer.alg);\n\n const header = {\n alg: signer.alg,\n typ: zItWalletClientAttestationPopJwtTyp.value,\n } satisfies ItWalletClientAttestationPopJwtHeader;\n\n const issuedAt = options.issuedAt ?? new Date();\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 = parseWithErrorHandling(\n zItWalletClientAttestationPopJwtPayload,\n {\n aud: options.authorizationServer,\n iat: dateToSeconds(issuedAt),\n iss: sub,\n jti,\n ...(options.config.itWalletSpecsVersion === ItWalletSpecsVersion.V1_0\n ? {\n exp: dateToSeconds(\n \"expiresAt\" in options && options.expiresAt\n ? options.expiresAt\n : addSecondsToDate(issuedAt, 1 * 60),\n ),\n }\n : {}),\n } satisfies ItWalletClientAttestationPopJwtPayload,\n );\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 z from \"zod\";\n\nimport { MAX_JTI_LENGTH, zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES = [\n \"ES256\",\n \"ES384\",\n \"ES512\",\n] as const;\n\nexport const zItWalletClientAttestationPopJwtAlg = z.enum(\n IT_WALLET_CLIENT_ATTESTATION_POP_ALLOWED_ALG_VALUES,\n);\n\nexport type ItWalletClientAttestationPopJwtAlg = z.infer<\n typeof zItWalletClientAttestationPopJwtAlg\n>;\n\nexport const zItWalletClientAttestationPopJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n aud: z.string(),\n exp: z.number().int().optional(),\n iat: z.number().int(),\n iss: z.string(),\n jti: z.string().max(MAX_JTI_LENGTH),\n nonce: z.string().optional(),\n});\n\nexport type ItWalletClientAttestationPopJwtPayload = z.infer<\n typeof zItWalletClientAttestationPopJwtPayload\n>;\n\nexport const zItWalletClientAttestationPopJwtTyp = z.literal(\n \"oauth-client-attestation-pop+jwt\",\n);\n\nexport const zItWalletClientAttestationPopJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n typ: zItWalletClientAttestationPopJwtTyp,\n});\n\nexport type ItWalletClientAttestationPopJwtHeader = z.infer<\n typeof zItWalletClientAttestationPopJwtHeader\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\n/**\n * Creates a PKCE code verifier and challenge pair.\n *\n * @param options - PKCE creation options.\n * @param options.allowedCodeChallengeMethods - Code challenge methods supported by the server.\n * @param options.callbacks - Random generation and hashing callbacks.\n * @param options.codeVerifier - Optional existing verifier; generated when omitted.\n * @returns Generated verifier, challenge, and selected challenge method.\n * @throws {Oauth2Error} If no challenge method is available or the selected method is unsupported.\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\n/**\n * Verifies that a PKCE code verifier matches a stored code challenge.\n *\n * @param options - PKCE verification options.\n * @param options.callbacks - Hashing callback.\n * @param options.codeChallenge - Expected code challenge.\n * @param options.codeChallengeMethod - Method used to compute the challenge.\n * @param options.codeVerifier - Verifier supplied by the client.\n * @returns Resolves when the verifier matches the challenge.\n * @throws {Oauth2Error} If the verifier does not match or the challenge method is unsupported.\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 `PKCE verification failed: code_verifier does not match the stored 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 CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n verifyJwt,\n} from \"@openid4vc/oauth2\";\nimport {\n RequestLike,\n decodeUtf8String,\n encodeToBase64Url,\n verifyJwtIatOrThrow,\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\n/**\n * Verifies a DPoP proof JWT against an HTTP request and optional token binding data.\n *\n * @param options - DPoP verification options.\n * @param options.accessToken - Optional access token whose hash must match the `ath` claim.\n * @param options.allowedSigningAlgs - Optional allow-list for DPoP signing algorithms.\n * @param options.callbacks - Hashing and JWT verification callbacks.\n * @param options.dpopJwt - Compact DPoP JWT.\n * @param options.expectedJwkThumbprint - Optional expected confirmation JWK thumbprint.\n * @param options.expectedNonce - Optional nonce expected in the payload.\n * @param options.now - Date used for temporal validation.\n * @param options.request - HTTP request that the DPoP proof must bind to.\n * @returns Decoded JWT header, payload, and resolved signer.\n * @throws {Oauth2Error} If any DPoP claim, token binding, or signature validation fails.\n */\nexport async function verifyTokenDPoP(options: VerifyTokenDPoPOptions) {\n const { header, payload } = decodeJwt({\n errorMessagePrefix: \"Error decoding access token DPoP JWT:\",\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 !== undefined) {\n if (options.expectedNonce === \"\") {\n throw new Oauth2Error(`Invalid 'expectedNonce' provided`);\n }\n\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 try {\n verifyJwtIatOrThrow({\n iat: payload.iat,\n now: options.now,\n });\n } catch (error) {\n if (error instanceof Error) {\n throw new Oauth2Error(`Invalid iat claim in dpop JWT: ${error.message}`);\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifiedClientAttestationPopJwt } from \"../client-attestation/client-attestation-pop\";\nimport {\n ClientAttestationOptions,\n verifyClientAttestation,\n} from \"../client-attestation/verify-client-attestation\";\nimport { VerifiedWalletAttestationJwt } from \"../client-attestation/wallet-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { PkceCodeChallengeMethod, verifyPkce } from \"../pkce\";\nimport { verifyTokenDPoP } from \"../token-dpop/verify-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 expected DPoP nonce value that must appear in the `nonce` claim of the DPoP proof JWT.\n *\n * AS implementations **SHOULD** issue server-provided nonces (via the `DPoP-Nonce` response\n * header) and pass the expected value here to prevent pre-generated DPoP proofs from being\n * reused across requests within the `iat` window.\n *\n * See RFC 9449 §8 for the full nonce issuance flow.\n */\n expectedNonce?: 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: ItWalletAuthorizationServerMetadata;\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: {\n * allowedSigningAlgs: [\"ES256\"],\n * expectedNonce: \"server-issued-nonce\",\n * jwt: dpopJwt,\n * },\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 if (options.dpop.expectedNonce === \"\") {\n throw new Oauth2Error(`Invalid 'dpop.expectedNonce' provided`);\n }\n\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 expectedNonce: options.dpop.expectedNonce,\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext, RequestDpopOptions } from \"@openid4vc/oauth2\";\nimport {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n addSecondsToDate,\n dateToSeconds,\n dispatchByVersion,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport { createPkce } from \"../pkce\";\nimport {\n AuthorizationRequestV1_0,\n AuthorizationRequestV1_3,\n PushedAuthorizationRequest,\n PushedAuthorizationRequestSigned,\n PushedAuthorizationRequestUnsignedV1_0,\n PushedAuthorizationRequestUnsignedV1_3,\n zAuthorizationRequestV1_0,\n zAuthorizationRequestV1_3,\n} from \"./z-authorization-request\";\n\nconst JWT_EXPIRY_SECONDS = 3600; // 1 hour\nconst RANDOM_BYTES_SIZE = 32;\n\ntype AuthorizationRequest = AuthorizationRequestV1_0 | AuthorizationRequestV1_3;\n\ninterface BaseCreatePushedAuthorizationRequestOptions<\n V extends ItWalletSpecsVersion,\n> {\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: ItWalletAuthorizationServerMetadata[\"code_challenge_methods_supported\"];\n\n config: IoWalletSdkConfig<V>;\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 * Optional issuer state from the Credential Offer authorization_code grant.\n * Serialized as issuer_state in the authorization request.\n */\n issuerState?: string;\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 * 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\nexport interface CreatePushedAuthorizationRequestOptionsV1_0 extends BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_0> {\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\nexport type CreatePushedAuthorizationRequestOptionsV1_3 =\n BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_3>;\n\nexport type CreatePushedAuthorizationRequestOptionsV1_4 =\n BaseCreatePushedAuthorizationRequestOptions<ItWalletSpecsVersion.V1_4>;\n\nexport type CreatePushedAuthorizationRequestOptions =\n | CreatePushedAuthorizationRequestOptionsV1_0\n | CreatePushedAuthorizationRequestOptionsV1_3\n | CreatePushedAuthorizationRequestOptionsV1_4;\n\ntype CreatePushedAuthorizationRequestOptionsSigned<\n TOptions extends CreatePushedAuthorizationRequestOptions,\n> = {\n authorizationServerMetadata: { require_signed_request_object: true };\n dpop: RequestDpopOptions;\n} & TOptions;\n\ntype CreatePushedAuthorizationRequestOptionsUnsigned<\n TOptions extends CreatePushedAuthorizationRequestOptions,\n> = {\n authorizationServerMetadata: { require_signed_request_object: false };\n} & TOptions;\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.config - Italian Wallet specification version used to build the request shape\n * @param options.responseMode - Response mode (v1.0 only, 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 * - version-specific unsigned PAR 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 for IT-Wallet v1.0 (explicit)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n * });\n *\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 * config,\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 for IT-Wallet v1.3 (when Authorization Server allows it)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_3,\n * });\n *\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 * config,\n * redirectUri: 'https://wallet.example.com/callback',\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 for IT-Wallet v1.0 (no metadata - unsigned)\n * const config = new IoWalletSdkConfig({\n * itWalletSpecsVersion: ItWalletSpecsVersion.V1_0,\n * });\n *\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 * config,\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: CreatePushedAuthorizationRequestOptionsSigned<CreatePushedAuthorizationRequestOptions>,\n): Promise<PushedAuthorizationRequestSigned>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_0>,\n): Promise<PushedAuthorizationRequestUnsignedV1_0>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptionsV1_0,\n): Promise<\n PushedAuthorizationRequestSigned | PushedAuthorizationRequestUnsignedV1_0\n>;\n\nexport async function createPushedAuthorizationRequest(\n options:\n | CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_3>\n | CreatePushedAuthorizationRequestOptionsUnsigned<CreatePushedAuthorizationRequestOptionsV1_4>,\n): Promise<PushedAuthorizationRequestUnsignedV1_3>;\n\nexport async function createPushedAuthorizationRequest(\n options:\n | CreatePushedAuthorizationRequestOptionsV1_3\n | CreatePushedAuthorizationRequestOptionsV1_4,\n): Promise<\n PushedAuthorizationRequestSigned | PushedAuthorizationRequestUnsignedV1_3\n>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest>;\n\nexport async function createPushedAuthorizationRequest(\n options: CreatePushedAuthorizationRequestOptions,\n): Promise<PushedAuthorizationRequest> {\n const pkce = await createPkce({\n allowedCodeChallengeMethods: options.codeChallengeMethodsSupported,\n callbacks: options.callbacks,\n codeVerifier: options.pkceCodeVerifier,\n });\n\n const baseAuthorizationRequest = {\n authorization_details: options.authorization_details,\n client_id: options.clientId,\n code_challenge: pkce.codeChallenge,\n code_challenge_method: pkce.codeChallengeMethod,\n ...(options.issuerState !== undefined\n ? { issuer_state: options.issuerState }\n : {}),\n jti:\n options.jti ??\n encodeToBase64Url(\n await options.callbacks.generateRandom(RANDOM_BYTES_SIZE),\n ),\n redirect_uri: options.redirectUri,\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 const authorizationRequest = parseAuthorizationRequestByVersion(\n options,\n baseAuthorizationRequest,\n );\n\n const requireSigned =\n options.authorizationServerMetadata?.require_signed_request_object ?? false;\n\n if (requireSigned) {\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 }\n\n return {\n authorizationRequest,\n client_id: options.clientId,\n pkceCodeVerifier: pkce.codeVerifier,\n };\n}\n\nfunction parseAuthorizationRequestByVersion(\n options: CreatePushedAuthorizationRequestOptions,\n baseAuthorizationRequest: Omit<\n AuthorizationRequest,\n \"authorization_details\" | \"response_mode\" | \"scope\"\n > &\n Pick<AuthorizationRequest, \"authorization_details\" | \"scope\">,\n): AuthorizationRequest {\n return dispatchByVersion(options.config.itWalletSpecsVersion, {\n [ItWalletSpecsVersion.V1_0]: () =>\n zAuthorizationRequestV1_0.parse({\n ...baseAuthorizationRequest,\n response_mode: (options as CreatePushedAuthorizationRequestOptionsV1_0)\n .responseMode,\n }) satisfies AuthorizationRequestV1_0,\n [ItWalletSpecsVersion.V1_3]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\n // V1_4 reuses V1_3 authorization request schema — no breaking changes between versions.\n // Verified against compare/1.3.3...1.4.1: authorization request parameters identical.\n [ItWalletSpecsVersion.V1_4]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\n });\n}\n","import z from \"zod\";\n\nimport { MAX_JTI_LENGTH } from \"../common/jwt/z-jwt\";\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.url(),\n idphinting: z.url(),\n type: z.literal(\"it_l2+document_proof\"),\n});\n\nconst zAuthorizationRequestBaseObject = z.looseObject({\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().max(MAX_JTI_LENGTH),\n redirect_uri: z.url(),\n response_type: z.string(),\n scope: z.string().optional(),\n state: z.string(),\n});\n\nconst zAuthorizationRequestBase = zAuthorizationRequestBaseObject.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);\n\nexport const zAuthorizationRequestV1_0 = zAuthorizationRequestBaseObject\n .extend({\n response_mode: z.string(),\n })\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 );\n\nexport type AuthorizationRequestV1_0 = z.infer<\n typeof zAuthorizationRequestV1_0\n>;\n\nexport const zAuthorizationRequestV1_3 = zAuthorizationRequestBase;\nexport type AuthorizationRequestV1_3 = z.infer<\n typeof zAuthorizationRequestV1_3\n>;\n\nexport const zPushedAuthorizationRequestSigned = z.looseObject({\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\nexport type PushedAuthorizationRequestSigned = z.infer<\n typeof zPushedAuthorizationRequestSigned\n>;\n\nconst zPushedAuthorizationRequestUnsignedBase = <\n TAuthorizationRequest extends z.ZodType,\n>(\n authorizationRequest: TAuthorizationRequest,\n) =>\n z.looseObject({\n authorizationRequest: authorizationRequest.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\nexport const zPushedAuthorizationRequestUnsignedV1_0 =\n zPushedAuthorizationRequestUnsignedBase(zAuthorizationRequestV1_0);\nexport type PushedAuthorizationRequestUnsignedV1_0 = z.infer<\n typeof zPushedAuthorizationRequestUnsignedV1_0\n>;\n\nexport const zPushedAuthorizationRequestUnsignedV1_3 =\n zPushedAuthorizationRequestUnsignedBase(zAuthorizationRequestV1_3);\nexport type PushedAuthorizationRequestUnsignedV1_3 = z.infer<\n typeof zPushedAuthorizationRequestUnsignedV1_3\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 | PushedAuthorizationRequestUnsignedV1_0\n | PushedAuthorizationRequestUnsignedV1_3;\n\n/**\n * Checks whether a pushed authorization request is represented as a signed JAR.\n *\n * @param par - Pushed authorization request to inspect.\n * @returns True when the request contains a compact `request` JWT.\n */\nexport function isPushedAuthorizationRequestSigned(\n par: PushedAuthorizationRequest,\n): par is PushedAuthorizationRequestSigned {\n return \"request\" in par && typeof par.request === \"string\";\n}\n\n/**\n * Checks whether a pushed authorization request is represented as a plain unsigned request.\n *\n * @param par - Pushed authorization request to inspect.\n * @returns True when the request contains version-specific `authorizationRequest` data.\n */\nexport function isPushedAuthorizationRequestUnsigned(\n par: PushedAuthorizationRequest,\n): par is\n | PushedAuthorizationRequestUnsignedV1_0\n | PushedAuthorizationRequestUnsignedV1_3 {\n return \"authorizationRequest\" in par;\n}\n\nexport const zPushedAuthorizationResponse = z.looseObject({\n expires_in: z.number().int(),\n request_uri: z.string(),\n});\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/wallet-attestation\";\nimport { Oauth2Error } from \"../errors\";\nimport { extractDpopJwtFromHeaders } from \"../token-dpop/create-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 * @param options - Authorization request parsing options.\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 IoWalletSdkConfig,\n ItWalletSpecsVersion,\n RequestLike,\n dispatchByVersion,\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} from \"../jar/parse-jar-request\";\nimport { zJarAuthorizationRequest } from \"../jar/z-jar\";\nimport {\n ParseAuthorizationRequestResult,\n parseAuthorizationRequest,\n} from \"./parse-authorization-request\";\nimport {\n AuthorizationRequestV1_0,\n AuthorizationRequestV1_3,\n zAuthorizationRequestV1_0,\n zAuthorizationRequestV1_3,\n} from \"./z-authorization-request\";\n\ntype AuthorizationRequest = AuthorizationRequestV1_0 | AuthorizationRequestV1_3;\n\nexport interface ParsePushedAuthorizationRequestOptions {\n authorizationRequest: unknown;\n callbacks: Pick<CallbackContext, \"fetch\">;\n config: IoWalletSdkConfig;\n request: RequestLike;\n}\n\nexport interface ParsePushedAuthorizationRequestResult 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 authorizationRequestSchema = getAuthorizationRequestSchema(\n options.config,\n );\n\n const parsed = parseWithErrorHandling(\n z.union([authorizationRequestSchema, zJarAuthorizationRequest]),\n options.authorizationRequest,\n \"Invalid authorization request. Could not parse authorization request or jar.\",\n );\n\n let parsedAuthorizationRequest: z.ZodSafeParseResult<AuthorizationRequest>;\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({\n errorMessagePrefix: \"Error decoding pushed authorization request JWT:\",\n jwt: parsedJar.authorizationRequestJwt,\n });\n\n parsedAuthorizationRequest = authorizationRequestSchema.safeParse(\n jwt.payload,\n );\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 = authorizationRequestSchema.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\nfunction getAuthorizationRequestSchema(config: IoWalletSdkConfig) {\n return dispatchByVersion(config.itWalletSpecsVersion, {\n [ItWalletSpecsVersion.V1_0]: () => zAuthorizationRequestV1_0,\n [ItWalletSpecsVersion.V1_3]: () => zAuthorizationRequestV1_3,\n // V1_4 reuses V1_3 PAR schema — no breaking changes between versions.\n // Verified against compare/1.3.3...1.4.1: authorization request parameters identical.\n [ItWalletSpecsVersion.V1_4]: () => zAuthorizationRequestV1_3,\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\n/**\n * Fetches a JWT-Secured Authorization Request object from a `request_uri`.\n *\n * @param options - Request object fetch options.\n * @param options.fetch - Optional fetch implementation; defaults to the runtime fetch through `createFetcher`.\n * @param options.requestUri - URI hosting the signed authorization request object.\n * @returns Compact JAR request object JWT.\n * @throws {UnexpectedStatusCodeError} If the endpoint does not return HTTP 200.\n * @throws {Oauth2Error} If the request object cannot be fetched.\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\n/**\n * Validates that JAR parameters identify exactly one request transmission mode.\n *\n * @param options - Validation options.\n * @param options.jarRequestParams - JAR request parameters to validate.\n * @returns The request URI when the request is sent by reference.\n * @throws {Oauth2Error} If both `request` and `request_uri` are present or both are missing.\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\n/**\n * Checks whether authorization request parameters contain a JAR request object or URI.\n *\n * @param request - Authorization request parameters to inspect.\n * @returns True when `request` or `request_uri` is present.\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 z from \"zod\";\n\nimport { zJwtHeader, zJwtPayload } from \"../common/jwt/z-jwt\";\n\nexport const zJarAuthorizationRequest = z.looseObject({\n client_id: z.optional(z.string()),\n request: z.optional(z.string()),\n request_uri: z.url().optional(),\n});\n\nexport type JarAuthorizationRequest = z.infer<typeof zJarAuthorizationRequest>;\n\nexport const zJarRequestObjectPayload = z.looseObject({\n ...zJwtPayload.shape,\n client_id: z.string(),\n});\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.looseObject({\n ...zJwtHeader.shape,\n typ: zSignedAuthorizationRequestJwtHeaderTyp,\n});\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport { IoWalletSdkConfig, RequestLike } from \"@pagopa/io-wallet-utils\";\n\nimport { VerifiedClientAttestationPopJwt } from \"../client-attestation/client-attestation-pop\";\nimport {\n ClientAttestationOptions,\n verifyClientAttestation,\n} from \"../client-attestation/verify-client-attestation\";\nimport { VerifiedWalletAttestationJwt } from \"../client-attestation/wallet-attestation\";\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { Oauth2Error } from \"../errors\";\nimport { verifyTokenDPoP } from \"../token-dpop/verify-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: ItWalletAuthorizationServerMetadata;\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.clientAttestation - Client attestation verification configuration\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 {\n CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@openid4vc/oauth2\";\nimport { parseWithErrorHandling } from \"@pagopa/io-wallet-utils\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\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({\n errorMessagePrefix: \"Error decoding JAR authorization request JWT:\",\n jwt: authorizationRequestJwt,\n });\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 { JwtSigner } from \"@openid4vc/oauth2\";\n\nimport { decodeJwt } from \"../common/jwt/decode-jwt\";\nimport { PushedAuthorizationRequestError } from \"../errors\";\nimport {\n VerifiedJarRequest,\n verifyJarRequest,\n} from \"../jar/verify-jar-request\";\nimport {\n type VerifyAuthorizationRequestOptions,\n type VerifyAuthorizationRequestResult,\n verifyAuthorizationRequest,\n} from \"./verify-authorization-request\";\n\nexport interface VerifyPushedAuthorizationRequestReturn extends VerifyAuthorizationRequestResult {\n /**\n * The verified JAR request, if `authorizationRequestJwt` was provided\n */\n jar?: VerifiedJarRequest;\n}\n\nexport interface VerifyPushedAuthorizationRequestOptions 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.callbacks - Cryptographic callback functions for hash and JWT verification\n * @param options.authorizationRequestJwt - Optional JAR JWT and signer information\n * @param options.dpop - Optional DPoP verification configuration\n * @param options.clientAttestation - Optional client attestation verification configuration\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({\n errorMessagePrefix: \"Error decoding pushed authorization request JWT:\",\n jwt: options.authorizationRequestJwt.jwt,\n });\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 type { ItWalletAuthorizationServerMetadata } from \"@pagopa/io-wallet-oid-federation\";\n\nimport { CallbackContext } from \"@openid4vc/oauth2\";\nimport {\n ContentType,\n FetchHeaders,\n HttpMethod,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n} 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: ItWalletAuthorizationServerMetadata;\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: ItWalletAuthorizationServerMetadata;\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 * Creates a client authentication callback that leaves the request unchanged.\n *\n * @returns Client authentication callback for anonymous requests.\n */\nexport function clientAuthenticationAnonymous(): ClientAuthenticationCallback {\n return () => {\n // No authentication, do nothing\n };\n}\n\nexport interface ClientAuthenticationWalletAttestationJwtOptions<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n> {\n callbacks: Pick<CallbackContext, \"generateRandom\" | \"signJwt\">;\n config: IoWalletSdkConfig<V>;\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 *\n * @param options - Wallet attestation client authentication options.\n * @param options.callbacks - Random generation and signing callbacks for the PoP JWT.\n * @param options.config - IT-Wallet specification version used to create the PoP JWT.\n * @param options.walletAttestationJwt - Wallet attestation JWT to attach to outgoing requests.\n * @returns Client authentication callback that mutates request headers with attestation values.\n * @throws {Oauth2Error} If the PoP JWT cannot be created.\n */\nexport function clientAuthenticationWalletAttestationJwt<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion,\n>(\n options: ClientAuthenticationWalletAttestationJwtOptions<V>,\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 config: options.config,\n });\n\n headers.set(oauthClientAttestationHeader, options.walletAttestationJwt);\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop);\n };\n}\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 { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\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 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 const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\n const dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n sub: dpopJwkThumbprint,\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 errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 {\n CallbackContext,\n HashAlgorithm,\n calculateJwkThumbprint,\n} from \"@openid4vc/oauth2\";\n\nimport { Jwk } from \"../common/jwk/z-jwk\";\nimport { ClientAttestationError } from \"../errors\";\n\nconst SUPPORTED_KTY = [\"RSA\", \"EC\"] as const;\n\ninterface JwkThumbprintOptions {\n callbacks: Pick<CallbackContext, \"hash\">;\n dpopJwkPublic: Jwk;\n}\n\nexport const calculateDpopJwkThumbprint = (\n options: JwkThumbprintOptions,\n): Promise<string> => {\n if (\n !SUPPORTED_KTY.includes(\n options.dpopJwkPublic.kty as (typeof SUPPORTED_KTY)[number],\n )\n ) {\n throw new ClientAttestationError(\n `Unsupported JWK key type \"${options.dpopJwkPublic.kty}\" for thumbprint computation. Supported types: ${SUPPORTED_KTY.join(\", \")}.`,\n );\n }\n\n return calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpopJwkPublic,\n });\n};\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 { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\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 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 const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\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 dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n sub: dpopJwkThumbprint,\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 errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\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 {\n ValidationError,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nimport { decodeJwt } from \"../../common/jwt/decode-jwt\";\nimport { ClientAttestationError } from \"../../errors\";\nimport { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_4,\n zEudiWalletInfoV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n zWalletAttestationStatusV1_4,\n} from \"./z-wallet-attestation\";\n\nexport interface WalletAttestationOptionsV1_4 extends Omit<\n BaseWalletAttestationOptions,\n \"walletLink\" | \"walletName\"\n> {\n eudiWalletInfo?: z.infer<typeof zEudiWalletInfoV1_4>;\n nbf?: Date;\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]];\n x5c: [string, ...string[]];\n };\n status: z.infer<typeof zWalletAttestationStatusV1_4>;\n walletLink: string;\n walletName: string;\n}\n\n/**\n * Creates a wallet attestation JWT for IT-Wallet v1.4.\n *\n * @param options - v1.4 wallet attestation creation options.\n * @returns Signed wallet attestation JWT.\n * @throws {ValidationError} If temporal constraints or generated JWT validation fail.\n * @throws {ClientAttestationError} For unexpected errors during attestation creation.\n */\nexport const createWalletAttestationJwt = async (\n options: WalletAttestationOptionsV1_4,\n): Promise<WalletAttestationJwtV1_4> => {\n try {\n const { signJwt } = options.callbacks;\n const iat = new Date();\n const exp = options.expiresAt ?? addSecondsToDate(iat, 3600); // Default expiration of 1 hour\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 dpopJwkThumbprint = await calculateDpopJwkThumbprint(options);\n\n const payload = {\n cnf: { jwk: options.dpopJwkPublic },\n exp: dateToSeconds(exp),\n iat: dateToSeconds(iat),\n iss: options.issuer,\n status: options.status,\n sub: dpopJwkThumbprint,\n wallet_link: options.walletLink,\n wallet_name: options.walletName,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\n ...(options.eudiWalletInfo && {\n eudi_wallet_info: options.eudiWalletInfo,\n }),\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,\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 decodeJwt({\n errorMessagePrefix: \"Error decoding wallet attestation JWT:\",\n headerSchema: zWalletAttestationJwtHeaderV1_4,\n jwt: result.jwt,\n payloadSchema: zWalletAttestationJwtPayloadV1_4,\n });\n\n return result.jwt;\n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\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\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 { 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 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 *\n * @param options - Form post extraction options.\n * @param options.formData - Raw HTML form_post.jwt response body.\n * @param options.schema - Zod schema used to validate the decoded JWT payload.\n * @returns The compact JWT and decoded JWT data.\n * @throws {Oauth2Error} If the response input cannot be found in the form data.\n *\n * @example\n * ```html\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 * ```\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 errorMessagePrefix: \"Error decoding JARM form post JWT:\",\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.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n});\n\nexport type MrtdChallengeJwtHeader = z.infer<typeof zMrtdChallengeJwtHeader>;\n\n/** JWT payload for MRTD challenge containing session correlation and endpoint parameters */\nexport const zMrtdChallengeJwtPayload = z.looseObject({\n aud: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.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\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.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias-pop+jwt\"),\n});\n\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.looseObject({\n aud: z.string(),\n challenge: z.string(),\n exp: z.number(),\n htm: z.literal(\"POST\"),\n htu: z.url(),\n iat: z.number(),\n iss: z.string(),\n mrtd_pop_nonce: z.string(),\n mrz: z.string().optional(),\n});\n\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.looseObject({\n dg1: z.string(),\n dg11: z.string(),\n sod_mrtd: z.string(),\n});\n\n/** IAS (Anti-Cloning) application data from NFC reading (public key, signed challenge, SOD) */\nconst zIasData = z.looseObject({\n challenge_signed: z.string(),\n ias_pk: z.string(),\n sod_ias: z.string(),\n});\n\n/** JWT header for MRTD validation (signed by Wallet Instance) */\nexport const zMrtdValidationJwtHeader = z.looseObject({\n alg: z.string(),\n kid: z.string(),\n typ: z.literal(\"mrtd-ias+jwt\"),\n});\nexport type MrtdValidationJwtHeader = z.infer<typeof zMrtdValidationJwtHeader>;\n\n/** JWT payload for MRTD validation containing NFC-read document evidence */\nexport const zMrtdValidationJwtPayload = z.looseObject({\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\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.looseObject({\n mrtd_val_pop_nonce: z.string(),\n redirect_uri: z.url(),\n status: z.literal(\"require_interaction\"),\n type: z.literal(\"redirect_to_web\"),\n});\n\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 errorMessagePrefix: \"Error decoding MRTD PoP init response JWT:\",\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/decode-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 errorMessagePrefix: \"Error decoding MRTD challenge JWT:\",\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 errorMessagePrefix: \"Error decoding MRTD challenge JWT:\",\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wCAAAA;AAAA,EAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oCAAAC;AAAA,EAAA;AAAA,wCAAAA;AAAA,EAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AE,OAAO,IAAI,UAAM,2BAAU;AAAA,IACjC,SAAS;AAAA,IACT,cAAc;AAAA,IACd,QAAQ,IAAI;AAAA,IACZ;AAAA,IAEA,QAAQ,QAAQ,cAAU,kCAAiB,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;;;AxDQA,IAAAC,kBAkBO;","names":["createWalletAttestationJwt","verifyWalletAttestationJwt","zCompactJwe","import_oauth2","import_io_wallet_utils","import_zod","import_zod","z","z","z","import_zod","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","import_zod","z","import_oauth2","import_oauth2","import_io_wallet_utils","import_zod","import_zod","verifyWalletAttestationJwt","import_zod","verifyWalletAttestationJwt","verifyWalletAttestationJwt","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","import_zod","import_oauth2","import_oauth2","import_io_wallet_utils","import_zod","z","verifyWalletAttestationJwt","import_oauth2","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","import_io_wallet_utils","toURLSearchParams","import_io_wallet_utils","import_zod","import_io_wallet_utils","import_zod","z","z","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_io_wallet_utils","createWalletAttestationJwt","import_io_wallet_utils","createWalletAttestationJwt","import_zod","zCompactJwe","import_io_wallet_utils","import_io_wallet_utils","import_zod","z","JWT_EXPIRY_SECONDS","import_oauth2","import_io_wallet_utils","import_io_wallet_utils","import_oauth2","import_oauth2","import_oauth2"]}