@pagopa/io-wallet-oauth2 2.0.0-launchpad → 2.0.2-apt
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +368 -205
- package/dist/index.d.ts +368 -205
- package/dist/index.js +592 -340
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +401 -145
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/access-token/create-token-request.ts","../src/access-token/create-token-response.ts","../src/errors.ts","../src/access-token/z-token.ts","../src/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/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/authorization-request/verify-pushed-authorization-request.ts","../src/jar/verify-jar-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/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":["import type { CallbackContext } from \"@pagopa/io-wallet-utils\";\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 type CallbackContext,\n type GenerateRandomCallback,\n HashAlgorithm,\n Jwk,\n JwtSigner,\n addSecondsToDate,\n calculateJwkThumbprint,\n dateToSeconds,\n jwtHeaderFromJwtSigner,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { CreateTokenResponseError } from \"../errors\";\nimport {\n AccessTokenProfileJwtHeader,\n AccessTokenProfileJwtPayload,\n AccessTokenResponse,\n RefreshTokenProfileJwtHeader,\n RefreshTokenProfileJwtPayload,\n zAccessTokenProfileJwtHeader,\n zAccessTokenProfileJwtPayload,\n zAccessTokenResponse,\n zRefreshTokenProfileJwtHeader,\n zRefreshTokenProfileJwtPayload,\n} from \"./z-token\";\n\nconst UUID_BYTE_LENGTH = 16;\n\n/**\n * Generates an RFC 4122 version 4 UUID using 16 random bytes obtained through\n * the supplied `generateRandom` callback.\n *\n * @param generateRandom - Callback used to source cryptographically secure random bytes.\n * @returns Canonical lowercase UUID v4 string.\n */\nasync function generateUuidV4(\n generateRandom: GenerateRandomCallback,\n): Promise<string> {\n const bytes = await generateRandom(UUID_BYTE_LENGTH);\n // RFC 4122 requires setting the version (0100) and variant (10) bits directly.\n // eslint-disable-next-line no-bitwise\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n // eslint-disable-next-line no-bitwise\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")\n .match(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/);\n\n if (!hex) {\n throw new CreateTokenResponseError(\n \"Unable to generate a valid UUID v4 from the provided random bytes.\",\n );\n }\n\n return `${hex[1]}-${hex[2]}-${hex[3]}-${hex[4]}-${hex[5]}`;\n}\n\n/**\n * Resolves the `kid` to include in the Refresh Token JOSE header.\n *\n * @param signer - Signer descriptor used to sign the Refresh Token.\n * @returns The signer's key identifier, or `undefined` if none can be resolved.\n */\nfunction resolveRefreshTokenKid(signer: JwtSigner): string | undefined {\n if (signer.kid) {\n return signer.kid;\n }\n if (signer.method === \"did\") {\n return signer.didUrl;\n }\n if (signer.method === \"jwk\") {\n return signer.publicJwk.kid;\n }\n return undefined;\n}\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 * Requests issuance of a DPoP-bound Refresh Token JWT by specifying its\n * lifetime in seconds. The Refresh Token `exp` is set to `now +\n * refreshTokenExpiresInSeconds` and must be later than the Access Token\n * `exp` (`nbf` of the Refresh Token).\n *\n * Requires `tokenType` to be `DPoP` and `dpop` to be provided. Omit this\n * option to keep the specification's optional Refresh Token behavior\n * (e.g. Bearer-only PDND responses).\n */\n refreshTokenExpiresInSeconds?: number;\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 * When `refreshTokenExpiresInSeconds` is provided, a DPoP-bound Refresh Token\n * JWT (`typ=rt+jwt`) is generated, signed, and returned as `refresh_token`.\n * Refresh Token issuance requires `tokenType` to be `DPoP` with a `dpop`\n * public key, and results in `nbf` equal to the Access Token `exp` and `exp`\n * later than that.\n *\n * @param options - Access token response creation options.\n * @returns OAuth token response with a signed access token JWT, and a signed Refresh Token JWT when requested.\n * @throws {CreateTokenResponseError} If DPoP binding is required but missing, if Refresh Token issuance is requested without a valid DPoP configuration or lifetime, if the signer has no resolvable `kid` for the Refresh Token, or if response creation otherwise fails, including validation failures from the generated JWT headers or payloads.\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 if (\n options.refreshTokenExpiresInSeconds !== undefined &&\n (options.tokenType !== \"DPoP\" || !options.dpop)\n ) {\n throw new CreateTokenResponseError(\n \"refreshTokenExpiresInSeconds was provided but Refresh Token issuance requires tokenType to be 'DPoP' with a dpop public key.\",\n );\n }\n\n if (\n options.refreshTokenExpiresInSeconds !== undefined &&\n options.refreshTokenExpiresInSeconds <= options.expiresInSeconds\n ) {\n throw new CreateTokenResponseError(\n `refreshTokenExpiresInSeconds (${options.refreshTokenExpiresInSeconds}) must be greater than expiresInSeconds (${options.expiresInSeconds}) so the Refresh Token remains usable after the Access Token expires.`,\n );\n }\n\n const dpopJkt = options.dpop\n ? await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpop.jwk,\n })\n : undefined;\n\n const accessTokenExpiresAt = addSecondsToDate(\n now,\n options.expiresInSeconds,\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: dpopJkt ? { jkt: dpopJkt } : undefined,\n exp: dateToSeconds(accessTokenExpiresAt),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: await generateUuidV4(options.callbacks.generateRandom),\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 let refreshToken: string | undefined;\n\n if (options.refreshTokenExpiresInSeconds !== undefined && dpopJkt) {\n const kid = resolveRefreshTokenKid(options.signer);\n if (!kid) {\n throw new CreateTokenResponseError(\n \"Unable to resolve a kid for the Refresh Token JOSE header. Provide signer.kid or a publicJwk.kid.\",\n );\n }\n\n const refreshTokenHeader = parseWithErrorHandling(\n zRefreshTokenProfileJwtHeader,\n {\n alg: options.signer.alg,\n kid,\n typ: \"rt+jwt\",\n } satisfies RefreshTokenProfileJwtHeader,\n );\n\n const refreshTokenPayload = parseWithErrorHandling(\n zRefreshTokenProfileJwtPayload,\n {\n aud: options.authorizationServer,\n client_id: options.clientId,\n cnf: { jkt: dpopJkt },\n exp: dateToSeconds(\n addSecondsToDate(now, options.refreshTokenExpiresInSeconds),\n ),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: await generateUuidV4(options.callbacks.generateRandom),\n nbf: dateToSeconds(accessTokenExpiresAt),\n sub: options.subject,\n } satisfies RefreshTokenProfileJwtPayload,\n );\n\n const refreshTokenSignResult = await options.callbacks.signJwt(\n options.signer,\n {\n header: refreshTokenHeader,\n payload: refreshTokenPayload,\n },\n );\n\n refreshToken = refreshTokenSignResult.jwt;\n }\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n ...options.additionalPayload,\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: 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","/**\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 const errorMessage = message ?? \"Unknown error occurred.\";\n const causeMessage =\n options?.cause instanceof Error\n ? ` ${options.cause.message}`\n : options?.cause\n ? ` ${String(options.cause)}`\n : \"\";\n\n super(`${errorMessage}${causeMessage}`, 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 {\n MAX_JTI_LENGTH,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\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\nexport const zRefreshTokenProfileJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n kid: z.string(),\n typ: z.literal(\"rt+jwt\"),\n});\n\nexport type RefreshTokenProfileJwtHeader = z.infer<\n typeof zRefreshTokenProfileJwtHeader\n>;\n\nexport const zRefreshTokenProfileJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n aud: z.string(),\n client_id: z.string(),\n cnf: z.object({\n jkt: z.string(),\n }),\n exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n jti: z.string().max(MAX_JTI_LENGTH),\n nbf: z.number().int(),\n sub: z.string(),\n});\n\nexport type RefreshTokenProfileJwtPayload = z.infer<\n typeof zRefreshTokenProfileJwtPayload\n>;\n","import {\n CONTENT_TYPES,\n type CallbackContext,\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 {\n FetchHeaders,\n ItWalletSpecsVersion,\n createVersionDispatcher,\n zCompactJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport {\n type VerifiedWalletAttestationJwtV1_0,\n type VerifyWalletAttestationJwtOptionsV1_0,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0,\n} from \"./v1.0/verify-wallet-attestation-jwt\";\nimport {\n type VerifiedWalletAttestationJwtV1_3,\n type VerifyWalletAttestationJwtOptionsV1_3,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3,\n} from \"./v1.3/verify-wallet-attestation-jwt\";\nimport {\n type VerifiedWalletAttestationJwtV1_4,\n type VerifyWalletAttestationJwtOptionsV1_4,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4,\n} 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 {JwtParseError} 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 { type CallbackContext, JwtPayload } from \"@pagopa/io-wallet-utils\";\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: NonNullable<NonNullable<JwtPayload[\"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 {\n type JwtHeader,\n type JwtPayload,\n decodeJwt,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\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 {\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\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 {JwtParseError} 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 {\n zCertificateChain,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\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 {JwtParseError} 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 {\n zCertificateChain,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nexport const zWalletAttestationJwtHeaderV1_4 = z.looseObject({\n ...zJwtHeader.shape,\n kid: z.string(),\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 exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n nbf: z.number().optional(),\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 {JwtParseError} 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 type CallbackContext,\n FetchHeaders,\n HashAlgorithm,\n HttpMethod,\n type JwtSignerJwk,\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n zCompactJwt,\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 {\n MAX_JTI_LENGTH,\n zHttpMethod,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 {\n type CallbackContext,\n HashAlgorithm,\n IoWalletSdkConfig,\n calculateJwkThumbprint,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata;\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 {\n CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n Jwk,\n JwtSignerJwk,\n addSecondsToDate,\n dateToSeconds,\n decodeJwt,\n encodeToBase64Url,\n parseWithErrorHandling,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n MAX_JTI_LENGTH,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 type CallbackContext,\n HashAlgorithm,\n type HashCallback,\n decodeUtf8String,\n encodeToBase64Url,\n} 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 type CallbackContext,\n HashAlgorithm,\n RequestLike,\n calculateJwkThumbprint,\n decodeJwt,\n decodeUtf8String,\n encodeToBase64Url,\n verifyJwt,\n verifyJwtIatOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n Jwk,\n RequestLike,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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 { 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: BaseAuthorizationServerMetadata;\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n type RequestDpopOptions,\n addSecondsToDate,\n dateToSeconds,\n dispatchByVersion,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata[\"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 { MAX_JTI_LENGTH } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nconst zOpenidCredentialAuthorizationDetails = z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n});\n\nconst zItL2DocumentProofAuthorizationDetails = z.object({\n challenge_method: z.literal(\"mrtd+ias\"),\n challenge_redirect_uri: z.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 {\n CONTENT_TYPES,\n type CallbackContext,\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n RequestLike,\n decodeJwt,\n dispatchByVersion,\n formatZodError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\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 type { CallbackContext } from \"@pagopa/io-wallet-utils\";\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 { zJwtHeader, zJwtPayload } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n Jwk,\n RequestLike,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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 { 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: BaseAuthorizationServerMetadata;\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 { JwtSigner, decodeJwt } from \"@pagopa/io-wallet-utils\";\n\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 {\n type CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n decodeJwt,\n parseWithErrorHandling,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport {\n JarRequestObjectPayload,\n jwtAuthorizationRequestJwtHeaderTyp,\n signedAuthorizationRequestJwtHeaderTyp,\n zJarRequestObjectPayload,\n} from \"./z-jar\";\n\nexport interface VerifyJarRequestOptions {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jarRequestParams: {\n client_id?: string;\n };\n jwtSigner: JwtSigner;\n now?: Date;\n}\n\nexport interface VerifiedJarRequest {\n authorizationRequestPayload: JarRequestObjectPayload;\n jwt: {\n payload: JarRequestObjectPayload;\n } & Omit<ReturnType<typeof decodeJwt>, \"payload\">;\n signer: JwtSignerWithJwk;\n}\n\n/**\n * Verifies a JAR (JWT Secured Authorization Request) request by validating and verifying signatures.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns The verified authorization request parameters and metadata\n */\nexport async function verifyJarRequest(\n options: VerifyJarRequestOptions,\n): Promise<VerifiedJarRequest> {\n const { authorizationRequestJwt, callbacks, jarRequestParams, jwtSigner } =\n options;\n\n /* Encryption is not supported */\n const requestObjectIsEncrypted = zCompactJwe.safeParse(\n authorizationRequestJwt,\n ).success;\n if (requestObjectIsEncrypted) {\n throw new Oauth2Error(\"Encrypted JWE request objects are not supported.\");\n }\n\n const requestIsSigned = zCompactJwt.safeParse(\n authorizationRequestJwt,\n ).success;\n if (!requestIsSigned) {\n throw new Oauth2Error(\"JAR request object is not a valid JWT.\");\n }\n\n const { authorizationRequestPayload, jwt, signer } =\n await verifyJarRequestObject({\n authorizationRequestJwt,\n callbacks,\n jwtSigner,\n });\n\n if (!authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n 'Jar Request Object is missing the required \"client_id\" field.',\n );\n }\n\n // Expect the client_id from the jar request to match the payload\n if (jarRequestParams.client_id !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n \"client_id does not match the request object client_id.\",\n );\n }\n\n if (jwt.payload.iss !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\"iss claim in request JWT does not match client_id\");\n }\n\n // RFC 9101 §4: exp claim MUST be present and not in the past\n if (jwt.payload.exp === undefined) {\n throw new Oauth2Error(\"exp claim in request JWT is missing\");\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (nowSeconds > jwt.payload.exp) {\n throw new Oauth2Error(\"exp claim in request JWT is expired\");\n }\n\n // IT-Wallet requirement: iat MUST be present\n if (jwt.payload.iat === undefined) {\n throw new Oauth2Error(\"iat claim in request JWT is missing\");\n }\n\n // IT-Wallet requirement: iat MUST not be more than 5 minutes in the past\n const MAX_IAT_AGE_SECONDS = 5 * 60;\n if (nowSeconds - jwt.payload.iat > MAX_IAT_AGE_SECONDS) {\n throw new Oauth2Error(\n \"iat claim in request JWT is too old (must be within 5 minutes)\",\n );\n }\n\n // IT-Wallet requirement: iat MUST not be more than clock-skew tolerance in the future\n const CLOCK_SKEW_TOLERANCE_SECONDS = 60;\n if (jwt.payload.iat - nowSeconds > CLOCK_SKEW_TOLERANCE_SECONDS) {\n throw new Oauth2Error(\"iat claim in request JWT is too far in the future\");\n }\n\n return {\n authorizationRequestPayload,\n jwt,\n signer,\n };\n}\n\nasync function verifyJarRequestObject(options: {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jwtSigner: JwtSigner;\n}) {\n const { authorizationRequestJwt, callbacks, jwtSigner } = options;\n\n const jwt = decodeJwt({\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n type ClientAuthenticationCallback as UtilsClientAuthenticationCallback,\n type ClientAuthenticationCallbackOptions as UtilsClientAuthenticationCallbackOptions,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata;\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\nexport type ClientAuthenticationCallbackOptions =\n UtilsClientAuthenticationCallbackOptions<BaseAuthorizationServerMetadata>;\n\nexport type ClientAuthenticationCallback =\n UtilsClientAuthenticationCallback<ClientAuthenticationCallbackOptions>;\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 Jwk,\n calculateJwkThumbprint,\n} from \"@pagopa/io-wallet-utils\";\n\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { ClientAttestationError } from \"../../errors\";\nimport { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n} from \"./z-wallet-attestation\";\n\nconst DEFAULT_EXPIRATION_SECONDS = 3600;\n\nconst MAX_EXPIRATION_SECONDS = 86400;\n\nexport interface WalletAttestationOptionsV1_4 extends Omit<\n BaseWalletAttestationOptions,\n \"walletLink\" | \"walletName\"\n> {\n nbf?: Date;\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]];\n x5c: [string, ...string[]];\n };\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 =\n options.expiresAt ?? addSecondsToDate(iat, DEFAULT_EXPIRATION_SECONDS);\n\n if (exp <= iat) {\n throw new ValidationError(\"exp must be after iat\");\n }\n\n if (exp > addSecondsToDate(iat, MAX_EXPIRATION_SECONDS)) {\n throw new ValidationError(\"exp must not be more than 24 hours after iat\");\n }\n\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 wallet_link: options.walletLink,\n wallet_name: options.walletName,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\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 {\n type CallbackContext,\n type JweEncryptor,\n type Jwk,\n type JwtSigner,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\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 { DecodeJwtResult, decodeJwt } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\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 {\n type CallbackContext,\n JwtSignerJwk,\n dateToSeconds,\n parseWithErrorHandling,\n} 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 CONTENT_TYPES,\n type CallbackContext,\n HEADERS,\n JwtSigner,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n decodeJwt,\n hasStatusOrThrow,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n CONTENT_TYPES,\n type CallbackContext,\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 { decodeJwt, zCompactJwt } from \"@pagopa/io-wallet-utils\";\n\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 type CallbackContext,\n JwtPayload,\n JwtSigner,\n decodeJwt,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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":";AA8CO,IAAM,qBAAqB,OAChC,aAEC;AAAA,EACC,GAAG,QAAQ;AAAA,EACX,MAAM,QAAQ;AAAA,EACd,eAAe,QAAQ;AAAA,EACvB,YAAY;AAAA,EACZ,cAAc,QAAQ;AACxB;;;ACvDF;AAAA,EAGE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACRA,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EACT,YACE,SACA,SACA;AACA,UAAM,eAAe,WAAW;AAChC,UAAM,eACJ,SAAS,iBAAiB,QACtB,IAAI,QAAQ,MAAM,OAAO,KACzB,SAAS,QACP,IAAI,OAAO,QAAQ,KAAK,CAAC,KACzB;AAER,UAAM,GAAG,YAAY,GAAG,YAAY,IAAI,OAAO;AAC/C,SAAK,OAAO;AACZ,SAAK,aAAa,SAAS;AAAA,EAC7B;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AA,IACZ;AAAA,IAEA,QAAQ,QAAQ,UAAUC,kBAAiB,EAAE,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AAAA,IAC1E,mBAAmB,UAAU;AAAA,EAC/B,CAAC;AAED,SAAO,EAAE,QAAQ,IAAI,QAAQ,SAAS,IAAI,SAAS,OAAO;AAC5D;","names":["parseWithErrorHandling","parseWithErrorHandling","z","zJwtHeader","zJwtPayload","z","zJwk","zJwtHeader","zJwtPayload","zTrustChain","z","verifyWalletAttestationJwt","zCertificateChain","zJwk","zJwtHeader","zJwtPayload","zTrustChain","z","verifyWalletAttestationJwt","verifyWalletAttestationJwt","HashAlgorithm","ValidationError","dateToSeconds","parseWithErrorHandling","zCompactJwt","MAX_JTI_LENGTH","zJwk","zJwtHeader","zJwtPayload","z","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","zCompactJwt","z","HashAlgorithm","calculateJwkThumbprint","ItWalletSpecsVersion","addSecondsToDate","dateToSeconds","decodeJwt","encodeToBase64Url","parseWithErrorHandling","verifyJwt","MAX_JTI_LENGTH","zJwtHeader","zJwtPayload","z","decodeJwt","verifyJwt","encodeToBase64Url","parseWithErrorHandling","dateToSeconds","ItWalletSpecsVersion","addSecondsToDate","verifyWalletAttestationJwt","calculateJwkThumbprint","HashAlgorithm","HashAlgorithm","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","HashAlgorithm","calculateJwkThumbprint","decodeJwt","decodeUtf8String","encodeToBase64Url","verifyJwt","decodeJwt","encodeToBase64Url","decodeUtf8String","HashAlgorithm","calculateJwkThumbprint","verifyJwt","ItWalletSpecsVersion","addSecondsToDate","dateToSeconds","encodeToBase64Url","MAX_JTI_LENGTH","z","encodeToBase64Url","addSecondsToDate","dateToSeconds","ItWalletSpecsVersion","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","toURLSearchParams","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","ItWalletSpecsVersion","decodeJwt","dispatchByVersion","formatZodError","parseWithErrorHandling","z","UnexpectedStatusCodeError","createFetcher","hasStatusOrThrow","createFetcher","hasStatusOrThrow","UnexpectedStatusCodeError","zJwtHeader","zJwtPayload","z","parseWithErrorHandling","z","decodeJwt","formatZodError","dispatchByVersion","ItWalletSpecsVersion","decodeJwt","decodeJwt","parseWithErrorHandling","verifyJwt","zCompactJwt","zCompactJwt","decodeJwt","parseWithErrorHandling","verifyJwt","decodeJwt","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","HashAlgorithm","calculateJwkThumbprint","calculateJwkThumbprint","HashAlgorithm","addSecondsToDate","dateToSeconds","decodeJwt","ValidationError","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","decodeJwt","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","decodeJwt","addSecondsToDate","dateToSeconds","dateToSeconds","addSecondsToDate","decodeJwt","decodeJwt","dateToSeconds","parseWithErrorHandling","z","JWT_EXPIRY_SECONDS","dateToSeconds","parseWithErrorHandling","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","decodeJwt","hasStatusOrThrow","jwtSignerFromJwt","verifyJwt","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","decodeJwt","verifyJwt","jwtSignerFromJwt","ValidationError","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","parseWithErrorHandling","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","parseWithErrorHandling","ValidationError","decodeJwt","zCompactJwt","zCompactJwt","decodeJwt","decodeJwt","jwtSignerFromJwt","verifyJwt","decodeJwt","verifyJwt","jwtSignerFromJwt"]}
|
|
1
|
+
{"version":3,"sources":["../src/access-token/create-token-request.ts","../src/access-token/z-grant-type.ts","../src/access-token/create-token-response.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/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/verify-access-token-request.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/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/authorization-request/verify-pushed-authorization-request.ts","../src/jar/verify-jar-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/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":["import {\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n createVersionDispatcher,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n AuthorizationCodeGrantIdentifier,\n PreAuthorizedCodeGrantIdentifier,\n RefreshTokenGrantIdentifier,\n authorizationCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n refreshTokenGrantIdentifier,\n} from \"./z-grant-type\";\nimport {\n AuthorizationCodeGrantType,\n PreAuthorizedCodeGrantType,\n RefreshTokenGrantType,\n} from \"./z-token\";\n\nexport interface BaseRetrieveAccessTokenOptions {\n /**\n * Additional payload to include in the access token request. Items are encoded and sent\n * using x-www-form-urlencoded format. Nested items (JSON) are stringified and url encoded.\n * Can be used to include form fields such as client_id or authorization_details.\n */\n additionalRequestPayload?: Record<string, unknown>;\n\n config: IoWalletSdkConfig;\n}\n\nexport interface RetrieveAccessTokenOptionsAuthCode<\n V extends ItWalletSpecsVersion,\n> extends BaseRetrieveAccessTokenOptions {\n /**\n * The authorization code\n */\n authorizationCode: string;\n\n config: IoWalletSdkConfig<V>;\n\n /** The authorization_code grant type. */\n grantType: AuthorizationCodeGrantIdentifier;\n\n /**\n * PKCE Code verifier that was used in the authorization request.\n */\n pkceCodeVerifier: string;\n\n /**\n * Redirect uri to include in the access token request.\n * It MUST be set as in the Request Object.\n */\n redirectUri: string;\n}\n\nexport interface RetrieveAccessTokenOptionsPreAuthorizedCode extends BaseRetrieveAccessTokenOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.APTITUDE>;\n\n /** The pre_authorized_code grant type. */\n grantType: PreAuthorizedCodeGrantIdentifier;\n\n /** The pre-authorized code received in the credential offer. */\n preAuthorizedCode: string;\n\n /** Required when the credential offer contains a tx_code object. */\n txCode?: string;\n}\n\nexport interface RetrieveAccessTokenOptionsRefreshToken<\n V extends ItWalletSpecsVersion,\n> extends BaseRetrieveAccessTokenOptions {\n config: IoWalletSdkConfig<V>;\n\n /** The refresh_token grant type. */\n grantType: RefreshTokenGrantIdentifier;\n\n /** The refresh token received in the credential offer. */\n refreshToken: string;\n\n /** The refresh token OPTIONAL scope. */\n scope?: string;\n}\n\nexport type RetrieveAccessTokenOptionsShared<V extends ItWalletSpecsVersion> =\n | RetrieveAccessTokenOptionsAuthCode<V>\n | RetrieveAccessTokenOptionsRefreshToken<V>;\n\nexport type RetrieveAccessTokenOptions = RetrieveAccessTokenOptionsShared<\n | ItWalletSpecsVersion.V1_0\n | ItWalletSpecsVersion.V1_3\n | ItWalletSpecsVersion.V1_4\n>;\n\nexport type RetrieveAccessTokenOptionsAPTITUDE =\n | RetrieveAccessTokenOptionsPreAuthorizedCode\n | RetrieveAccessTokenOptionsShared<ItWalletSpecsVersion.APTITUDE>;\n\nexport type CreateTokenRequestOptions =\n | RetrieveAccessTokenOptions\n | RetrieveAccessTokenOptionsAPTITUDE;\n\nexport type CreateTokenRequestReturnType =\n | AuthorizationCodeGrantType\n | PreAuthorizedCodeGrantType\n | RefreshTokenGrantType;\n\nexport const createTokenRequestV1_4 = <V extends ItWalletSpecsVersion>(\n options: RetrieveAccessTokenOptionsShared<V>,\n) => {\n if (options.grantType === refreshTokenGrantIdentifier) {\n return {\n ...options.additionalRequestPayload,\n grant_type: refreshTokenGrantIdentifier,\n refresh_token: options.refreshToken,\n scope: options.scope,\n };\n }\n\n return {\n ...options.additionalRequestPayload,\n code: options.authorizationCode,\n code_verifier: options.pkceCodeVerifier,\n grant_type: authorizationCodeGrantIdentifier,\n redirect_uri: options.redirectUri,\n };\n};\n\nexport function createTokenRequestAPTITUDE(\n options: RetrieveAccessTokenOptionsAPTITUDE,\n): CreateTokenRequestReturnType {\n if (options.grantType === preAuthorizedCodeGrantIdentifier) {\n return {\n ...options.additionalRequestPayload,\n grant_type: preAuthorizedCodeGrantIdentifier,\n \"pre-authorized_code\": options.preAuthorizedCode,\n tx_code: options.txCode,\n };\n }\n\n return createTokenRequestV1_4(options);\n}\n\nconst dispatchCreateTokenRequest = createVersionDispatcher<\n CreateTokenRequestOptions,\n CreateTokenRequestReturnType\n>({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n createTokenRequestAPTITUDE(o as RetrieveAccessTokenOptionsAPTITUDE),\n [ItWalletSpecsVersion.V1_0]: (o) =>\n createTokenRequestV1_4(o as RetrieveAccessTokenOptions),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n createTokenRequestV1_4(o as RetrieveAccessTokenOptions),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n createTokenRequestV1_4(o as RetrieveAccessTokenOptions),\n});\n\n/**\n * Creates an authorization-code or pre-authorized_code access token request body.\n *\n * Authorization-code requests retain the existing default grant and require PKCE\n * and a redirect URI.\n *\n * * * Version Differences:\n * - v1.4: only support authorization_code grant type.\n * - APTITUDE: add support for pre-authorized_code grant type. Pre Authorized\n * requests use preAuthorizedCode and optional txCode, without PKCE or a redirect URI.\n *\n * @param options - Access token request inputs and version config.\n * @param options.config - The IoWalletSdkConfig instance to use.\n * @param options.grantType - The grant type to use.\n * @param options.additionalRequestPayload - Extra form fields to include in the token request.\n *\n * **authorization_code grant type parameters:**\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 *\n * **refresh_token grant type parameters (APTITUDE only):**\n * @param options.refreshToken - Refresh token.\n * @param options.scope - The refresh token OPTIONAL scope.\n *\n * **pre-authorized_code grant type parameters (APTITUDE only):**\n * @param options.preAuthorizedCode - Pre-authorized code received in the credential offer.\n * @param options.txCode - Transaction code required when the credential offer contains a `tx_code` object.\n *\n * @returns URL-form-encodable grant request data.\n */\nexport function createTokenRequest(\n options: RetrieveAccessTokenOptions,\n): AuthorizationCodeGrantType | RefreshTokenGrantType;\n\nexport function createTokenRequest(\n options: RetrieveAccessTokenOptionsAPTITUDE,\n):\n | AuthorizationCodeGrantType\n | PreAuthorizedCodeGrantType\n | RefreshTokenGrantType;\n\nexport function createTokenRequest(\n options: CreateTokenRequestOptions,\n): CreateTokenRequestReturnType;\n\nexport function createTokenRequest(\n options: CreateTokenRequestOptions,\n): CreateTokenRequestReturnType {\n return dispatchCreateTokenRequest(options);\n}\n","import { z } from \"zod\";\n\nexport const zAuthorizationCodeGrantIdentifier =\n z.literal(\"authorization_code\");\nexport const authorizationCodeGrantIdentifier =\n zAuthorizationCodeGrantIdentifier.value;\nexport type AuthorizationCodeGrantIdentifier = z.infer<\n typeof zAuthorizationCodeGrantIdentifier\n>;\nexport const zPreAuthorizedCodeGrantIdentifier = z.literal(\n \"urn:ietf:params:oauth:grant-type:pre-authorized_code\",\n);\nexport const preAuthorizedCodeGrantIdentifier =\n zPreAuthorizedCodeGrantIdentifier.value;\nexport type PreAuthorizedCodeGrantIdentifier = z.infer<\n typeof zPreAuthorizedCodeGrantIdentifier\n>;\n\nexport const zRefreshTokenGrantIdentifier = z.literal(\"refresh_token\");\nexport const refreshTokenGrantIdentifier = zRefreshTokenGrantIdentifier.value;\nexport type RefreshTokenGrantIdentifier = z.infer<\n typeof zRefreshTokenGrantIdentifier\n>;\n","import {\n type CallbackContext,\n type GenerateRandomCallback,\n HashAlgorithm,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n Jwk,\n JwtSigner,\n addSecondsToDate,\n calculateJwkThumbprint,\n createVersionDispatcher,\n dateToSeconds,\n jwtHeaderFromJwtSigner,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { CreateTokenResponseError } from \"../errors\";\nimport {\n AccessTokenProfileJwtHeader,\n AccessTokenProfileJwtPayload,\n AccessTokenResponse,\n RefreshTokenProfileJwtHeader,\n RefreshTokenProfileJwtPayload,\n zAccessTokenProfileJwtHeader,\n zAccessTokenProfileJwtPayload,\n zAccessTokenResponse,\n zRefreshTokenProfileJwtHeader,\n zRefreshTokenProfileJwtPayload,\n} from \"./z-token\";\n\nconst UUID_BYTE_LENGTH = 16;\n\n/**\n * Generates an RFC 4122 version 4 UUID using 16 random bytes obtained through\n * the supplied `generateRandom` callback.\n *\n * @param generateRandom - Callback used to source cryptographically secure random bytes.\n * @returns Canonical lowercase UUID v4 string.\n */\nasync function generateUuidV4(\n generateRandom: GenerateRandomCallback,\n): Promise<string> {\n const bytes = await generateRandom(UUID_BYTE_LENGTH);\n // RFC 4122 requires setting the version (0100) and variant (10) bits directly.\n // eslint-disable-next-line no-bitwise\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n // eslint-disable-next-line no-bitwise\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\"))\n .join(\"\")\n .match(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/);\n\n if (!hex) {\n throw new CreateTokenResponseError(\n \"Unable to generate a valid UUID v4 from the provided random bytes.\",\n );\n }\n\n return `${hex[1]}-${hex[2]}-${hex[3]}-${hex[4]}-${hex[5]}`;\n}\n\n/**\n * Resolves the `kid` to include in the Refresh Token JOSE header.\n *\n * @param signer - Signer descriptor used to sign the Refresh Token.\n * @returns The signer's key identifier, or `undefined` if none can be resolved.\n */\nfunction resolveRefreshTokenKid(signer: JwtSigner): string | undefined {\n if (signer.kid) {\n return signer.kid;\n }\n if (signer.method === \"did\") {\n return signer.didUrl;\n }\n if (signer.method === \"jwk\") {\n return signer.publicJwk.kid;\n }\n return undefined;\n}\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 * 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 config: IoWalletSdkConfig;\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 * Requests issuance of a DPoP-bound Refresh Token JWT by specifying its\n * lifetime in seconds. The Refresh Token `exp` is set to `now +\n * refreshTokenExpiresInSeconds` and must be later than the Access Token\n * `exp` (`nbf` of the Refresh Token).\n *\n * Requires `tokenType` to be `DPoP` and `dpop` to be provided. Omit this\n * option to keep the specification's optional Refresh Token behavior\n * (e.g. Bearer-only PDND responses).\n */\n refreshTokenExpiresInSeconds?: number;\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\nasync function createAccessTokenResponseV1_4(\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 if (\n options.refreshTokenExpiresInSeconds !== undefined &&\n (options.tokenType !== \"DPoP\" || !options.dpop)\n ) {\n throw new CreateTokenResponseError(\n \"refreshTokenExpiresInSeconds was provided but Refresh Token issuance requires tokenType to be 'DPoP' with a dpop public key.\",\n );\n }\n\n if (\n options.refreshTokenExpiresInSeconds !== undefined &&\n options.refreshTokenExpiresInSeconds <= options.expiresInSeconds\n ) {\n throw new CreateTokenResponseError(\n `refreshTokenExpiresInSeconds (${options.refreshTokenExpiresInSeconds}) must be greater than expiresInSeconds (${options.expiresInSeconds}) so the Refresh Token remains usable after the Access Token expires.`,\n );\n }\n\n const dpopJkt = options.dpop\n ? await calculateJwkThumbprint({\n hashAlgorithm: HashAlgorithm.Sha256,\n hashCallback: options.callbacks.hash,\n jwk: options.dpop.jwk,\n })\n : undefined;\n\n const accessTokenExpiresAt = addSecondsToDate(\n now,\n options.expiresInSeconds,\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: dpopJkt ? { jkt: dpopJkt } : undefined,\n exp: dateToSeconds(accessTokenExpiresAt),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: await generateUuidV4(options.callbacks.generateRandom),\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 let refreshToken: string | undefined;\n\n if (options.refreshTokenExpiresInSeconds !== undefined && dpopJkt) {\n const kid = resolveRefreshTokenKid(options.signer);\n if (!kid) {\n throw new CreateTokenResponseError(\n \"Unable to resolve a kid for the Refresh Token JOSE header. Provide signer.kid or a publicJwk.kid.\",\n );\n }\n\n const refreshTokenHeader = parseWithErrorHandling(\n zRefreshTokenProfileJwtHeader,\n {\n alg: options.signer.alg,\n kid,\n typ: \"rt+jwt\",\n } satisfies RefreshTokenProfileJwtHeader,\n );\n\n const refreshTokenPayload = parseWithErrorHandling(\n zRefreshTokenProfileJwtPayload,\n {\n aud: options.authorizationServer,\n client_id: options.clientId,\n cnf: { jkt: dpopJkt },\n exp: dateToSeconds(\n addSecondsToDate(now, options.refreshTokenExpiresInSeconds),\n ),\n iat: dateToSeconds(now),\n iss: options.authorizationServer,\n jti: await generateUuidV4(options.callbacks.generateRandom),\n nbf: dateToSeconds(accessTokenExpiresAt),\n sub: options.subject,\n } satisfies RefreshTokenProfileJwtPayload,\n );\n\n const refreshTokenSignResult = await options.callbacks.signJwt(\n options.signer,\n {\n header: refreshTokenHeader,\n payload: refreshTokenPayload,\n },\n );\n\n refreshToken = refreshTokenSignResult.jwt;\n }\n\n const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n ...options.additionalPayload,\n access_token: jwt,\n expires_in: options.expiresInSeconds,\n refresh_token: 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\nconst dispatchCreateAccessTokenResponse = createVersionDispatcher({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n createAccessTokenResponseV1_4(o as CreateAccessTokenResponseOptions),\n [ItWalletSpecsVersion.V1_0]: (o) =>\n createAccessTokenResponseV1_4(o as CreateAccessTokenResponseOptions),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n createAccessTokenResponseV1_4(o as CreateAccessTokenResponseOptions),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n createAccessTokenResponseV1_4(o as CreateAccessTokenResponseOptions),\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 * When `refreshTokenExpiresInSeconds` is provided, a DPoP-bound Refresh Token\n * JWT (`typ=rt+jwt`) is generated, signed, and returned as `refresh_token`.\n * Refresh Token issuance requires `tokenType` to be `DPoP` with a `dpop`\n * public key, and results in `nbf` equal to the Access Token `exp` and `exp`\n * later than that.\n *\n * @param options - Access token response creation options and version config.\n * @returns OAuth token response with a signed access token JWT, and a signed Refresh Token JWT when requested.\n * @throws {CreateTokenResponseError} If DPoP binding is required but missing, if Refresh Token issuance is requested without a valid DPoP configuration or lifetime, if the signer has no resolvable `kid` for the Refresh Token, or if response creation otherwise fails, including validation failures from the generated JWT headers or payloads.\n * @throws {ValidationError} If the generated JWT header or payload fails validation.\n */\n\nexport function createAccessTokenResponse(\n options: CreateAccessTokenResponseOptions,\n) {\n return dispatchCreateAccessTokenResponse(options);\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 const errorMessage = message ?? \"Unknown error occurred.\";\n const causeMessage =\n options?.cause instanceof Error\n ? ` ${options.cause.message}`\n : options?.cause\n ? ` ${String(options.cause)}`\n : \"\";\n\n super(`${errorMessage}${causeMessage}`, 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 {\n MAX_JTI_LENGTH,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nimport {\n zAuthorizationCodeGrantIdentifier,\n zPreAuthorizedCodeGrantIdentifier,\n zRefreshTokenGrantIdentifier,\n} from \"./z-grant-type\";\n\nexport const zPreAuthorizedCodeTokenRequest = z.object({\n grant_type: zPreAuthorizedCodeGrantIdentifier,\n \"pre-authorized_code\": z.string().nonempty(),\n tx_code: z.string().optional(),\n});\n\nexport const zAuthorizationCodeTokenRequest = z.object({\n code: z.string().nonempty(),\n code_verifier: z.string().nonempty(),\n grant_type: zAuthorizationCodeGrantIdentifier,\n redirect_uri: z.string().nonempty(),\n});\n\nexport const zRefreshTokenTokenRequest = z.object({\n grant_type: zRefreshTokenGrantIdentifier,\n refresh_token: z.string().nonempty(),\n scope: z.string().optional(),\n});\n\nexport const zAccessTokenRequest = z.discriminatedUnion(\"grant_type\", [\n zAuthorizationCodeTokenRequest,\n zRefreshTokenTokenRequest,\n]);\n\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>;\n\nexport const zAccessTokenRequestAPTITUDE = z.discriminatedUnion(\"grant_type\", [\n zAuthorizationCodeTokenRequest,\n zRefreshTokenTokenRequest,\n zPreAuthorizedCodeTokenRequest,\n]);\n\nexport type AccessTokenRequestAPTITUDE = z.infer<\n typeof zAccessTokenRequestAPTITUDE\n>;\n\nexport type AuthorizationCodeGrantType = Extract<\n AccessTokenRequest,\n { grant_type: \"authorization_code\" }\n>;\n\nexport type PreAuthorizedCodeGrantType = Extract<\n AccessTokenRequestAPTITUDE,\n { grant_type: \"urn:ietf:params:oauth:grant-type:pre-authorized_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\nexport const zRefreshTokenProfileJwtHeader = z.looseObject({\n ...zJwtHeader.shape,\n kid: z.string(),\n typ: z.literal(\"rt+jwt\"),\n});\n\nexport type RefreshTokenProfileJwtHeader = z.infer<\n typeof zRefreshTokenProfileJwtHeader\n>;\n\nexport const zRefreshTokenProfileJwtPayload = z.looseObject({\n ...zJwtPayload.shape,\n aud: z.string(),\n client_id: z.string(),\n cnf: z.object({\n jkt: z.string(),\n }),\n exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n jti: z.string().max(MAX_JTI_LENGTH),\n nbf: z.number().int(),\n sub: z.string(),\n});\n\nexport type RefreshTokenProfileJwtPayload = z.infer<\n typeof zRefreshTokenProfileJwtPayload\n>;\n","import {\n CONTENT_TYPES,\n type CallbackContext,\n HEADERS,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n createVersionDispatcher,\n hasStatusOrThrow,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { FetchTokenResponseError } from \"../errors\";\nimport {\n AccessTokenRequest,\n AccessTokenRequestAPTITUDE,\n AccessTokenResponse,\n zAccessTokenResponse,\n} from \"./z-token\";\n\nexport interface BaseFetchTokenResponseOptions {\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 * 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 config: IoWalletSdkConfig;\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\nexport interface FetchTokenResponseOptionsShared<\n V extends ItWalletSpecsVersion =\n | ItWalletSpecsVersion.V1_0\n | ItWalletSpecsVersion.V1_3\n | ItWalletSpecsVersion.V1_4,\n> extends BaseFetchTokenResponseOptions {\n /**\n * The authorization-code or refresh-token request payload.\n */\n accessTokenRequest: AccessTokenRequest;\n\n config: IoWalletSdkConfig<V>;\n}\n\nexport interface FetchTokenResponseOptionsAPTITUDE extends BaseFetchTokenResponseOptions {\n /**\n * The authorization-code, pre-authorized-code or refresh-token request payload.\n */\n accessTokenRequest: AccessTokenRequestAPTITUDE;\n\n config: IoWalletSdkConfig<ItWalletSpecsVersion.APTITUDE>;\n}\n\nexport type FetchTokenResponseOptions =\n | FetchTokenResponseOptionsAPTITUDE\n | FetchTokenResponseOptionsShared;\n\nasync function fetchTokenResponseV1_4(\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 * Version Differences:\n * - APTITUDE: extracts `authorization_server` (OPTIONAL), `pre-authorized_code` (REQUIRED), and `tx_code` (OPTIONAL)\n *\n * @param data - Access token request payload.\n * @returns URLSearchParams containing all defined request fields.\n */\nexport function toURLSearchParams(\n data: FetchTokenResponseOptions[\"accessTokenRequest\"],\n): 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\nconst dispatchFetchTokenResponse = createVersionDispatcher<\n FetchTokenResponseOptions,\n Promise<AccessTokenResponse>\n>({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n fetchTokenResponseV1_4(o as FetchTokenResponseOptionsAPTITUDE),\n [ItWalletSpecsVersion.V1_0]: (o) =>\n fetchTokenResponseV1_4(\n o as FetchTokenResponseOptionsShared<ItWalletSpecsVersion.V1_0>,\n ),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n fetchTokenResponseV1_4(\n o as FetchTokenResponseOptionsShared<ItWalletSpecsVersion.V1_3>,\n ),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n fetchTokenResponseV1_4(\n o as FetchTokenResponseOptionsShared<ItWalletSpecsVersion.V1_4>,\n ),\n});\n\n/**\n * Sends an access token request to the authorization server and returns the response\n *\n * * Version Differences:\n * - APTITUDE: add support for pre-authorized-code grant type.\n *\n * @param options - Configuration options for the access token request and version config.\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 function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse>;\n\n/**\n * Additional overloads have been omitted due to redundancy of the signature. If any signature diverges in\nthe future, new overloads should be added to support the new signature.\n */\nexport function fetchTokenResponse(\n options: FetchTokenResponseOptions,\n): Promise<AccessTokenResponse> {\n return dispatchFetchTokenResponse(options);\n}\n","import {\n FetchHeaders,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n RequestLike,\n createVersionDispatcher,\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 PreAuthorizedCodeGrantIdentifier,\n RefreshTokenGrantIdentifier,\n authorizationCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n refreshTokenGrantIdentifier,\n} from \"./z-grant-type\";\nimport {\n AccessTokenRequest,\n AccessTokenRequestAPTITUDE,\n zAccessTokenRequest,\n zAccessTokenRequestAPTITUDE,\n} 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\nexport interface ParsedAccessTokenPreAuthorizedCodeRequestGrant {\n grantType: PreAuthorizedCodeGrantIdentifier;\n preAuthorizedCode: string;\n txCode?: string;\n}\n\nexport type ParsedAccessTokenRequestGrantV1_4 =\n | ParsedAccessTokenAuthorizationCodeRequestGrant\n | ParsedAccessTokenRefreshTokenRequestGrant;\n\nexport type ParsedAccessTokenRequestGrantAPTITUDE =\n | ParsedAccessTokenAuthorizationCodeRequestGrant\n | ParsedAccessTokenPreAuthorizedCodeRequestGrant\n | ParsedAccessTokenRefreshTokenRequestGrant;\n\nexport interface BaseParseAccessTokenRequestResult {\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\nexport interface ParseAccessTokenRequestResultV1_4 extends BaseParseAccessTokenRequestResult {\n accessTokenRequest: AccessTokenRequest;\n\n grant: ParsedAccessTokenRequestGrantV1_4;\n\n /**\n * The pkce code verifier from the access token request\n */\n pkceCodeVerifier?: string;\n}\n\nexport interface ParseAccessTokenRequestResultAPTITUDE extends BaseParseAccessTokenRequestResult {\n accessTokenRequest: AccessTokenRequestAPTITUDE;\n\n grant: ParsedAccessTokenRequestGrantAPTITUDE;\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 config: IoWalletSdkConfig;\n\n request: RequestLike;\n}\n\nexport interface ParseAccessTokenRequestOptionsShared<\n V extends ItWalletSpecsVersion =\n | ItWalletSpecsVersion.V1_0\n | ItWalletSpecsVersion.V1_3\n | ItWalletSpecsVersion.V1_4,\n> extends ParseAccessTokenRequestOptions {\n /**\n * The IT-Wallet specs version to use for parsing the access token request.\n */\n config: IoWalletSdkConfig<V>;\n}\n\nexport interface ParseAccessTokenRequestOptionsAPTITUDE extends ParseAccessTokenRequestOptions {\n /**\n * The IT-Wallet specs version to use for parsing the access token request.\n */\n config: IoWalletSdkConfig<ItWalletSpecsVersion.APTITUDE>;\n}\n\nexport type ParseAccessTokenRequestResult =\n | ParseAccessTokenRequestResultAPTITUDE\n | ParseAccessTokenRequestResultV1_4;\n\nfunction parseAccessTokenRequestV1_4<V extends ItWalletSpecsVersion>(\n options: ParseAccessTokenRequestOptionsShared<V>,\n): ParseAccessTokenRequestResultV1_4 {\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\nfunction parseAccessTokenRequestAPTITUDE(\n options: ParseAccessTokenRequestOptionsAPTITUDE,\n): ParseAccessTokenRequestResultAPTITUDE {\n const validationResult = zAccessTokenRequestAPTITUDE.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 = parseGrantParametersAPTITUDE(accessTokenRequest);\n const securityHeaders = parseSecurityHeaders(options.request.headers);\n\n return {\n accessTokenRequest,\n grant,\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): ParsedAccessTokenRequestGrantV1_4 {\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 * 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 parseGrantParametersAPTITUDE(\n accessTokenRequest: AccessTokenRequestAPTITUDE,\n): ParsedAccessTokenRequestGrantAPTITUDE {\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 if (accessTokenRequest.grant_type === preAuthorizedCodeGrantIdentifier) {\n return {\n grantType: preAuthorizedCodeGrantIdentifier,\n preAuthorizedCode: accessTokenRequest[\"pre-authorized_code\"],\n txCode: accessTokenRequest.tx_code,\n };\n }\n\n throw new Oauth2Error(\n `Unsupported grant type. Supported types are: '${authorizationCodeGrantIdentifier}', '${refreshTokenGrantIdentifier}', '${preAuthorizedCodeGrantIdentifier}'`,\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\nconst dispatchParseTokenRequest = createVersionDispatcher<\n ParseAccessTokenRequestOptions,\n ParseAccessTokenRequestResult\n>({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n parseAccessTokenRequestAPTITUDE(\n o as ParseAccessTokenRequestOptionsAPTITUDE,\n ),\n [ItWalletSpecsVersion.V1_0]: (o) =>\n parseAccessTokenRequestV1_4(\n o as ParseAccessTokenRequestOptionsShared<ItWalletSpecsVersion.V1_0>,\n ),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n parseAccessTokenRequestV1_4(\n o as ParseAccessTokenRequestOptionsShared<ItWalletSpecsVersion.V1_3>,\n ),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n parseAccessTokenRequestV1_4(\n o as ParseAccessTokenRequestOptionsShared<ItWalletSpecsVersion.V1_4>,\n ),\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 grant parameters for authorization code, pre-authorized code or refresh token\n * 3. Parses security headers (DPoP and Client Attestation JWTs)\n * 4. Extracts PKCE code verifier if present (V1_4 only)\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 * * * Version Differences:\n * - APTITUDE: add support for pre-authorized-code grant type.\n *\n * @param options - Configuration object containing the access token request body and HTTP request, and version config\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 V extends ItWalletSpecsVersion =\n | ItWalletSpecsVersion.V1_0\n | ItWalletSpecsVersion.V1_3\n | ItWalletSpecsVersion.V1_4,\n>(\n options: ParseAccessTokenRequestOptionsShared<V>,\n): ParseAccessTokenRequestResultV1_4;\n\nexport function parseAccessTokenRequest(\n options: ParseAccessTokenRequestOptionsAPTITUDE,\n): ParseAccessTokenRequestResultAPTITUDE;\n\nexport function parseAccessTokenRequest(\n options: ParseAccessTokenRequestOptions,\n): ParseAccessTokenRequestResult;\n\nexport function parseAccessTokenRequest(\n options: ParseAccessTokenRequestOptions,\n): ParseAccessTokenRequestResult {\n return dispatchParseTokenRequest(options);\n}\n","import {\n FetchHeaders,\n ItWalletSpecsVersion,\n createVersionDispatcher,\n zCompactJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport {\n oauthClientAttestationHeader,\n oauthClientAttestationPopHeader,\n} from \"./types\";\nimport {\n type VerifiedWalletAttestationJwtV1_0,\n type VerifyWalletAttestationJwtOptionsV1_0,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_0,\n} from \"./v1.0/verify-wallet-attestation-jwt\";\nimport {\n type VerifiedWalletAttestationJwtV1_3,\n type VerifyWalletAttestationJwtOptionsV1_3,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_3,\n} from \"./v1.3/verify-wallet-attestation-jwt\";\nimport {\n type VerifiedWalletAttestationJwtV1_4,\n type VerifyWalletAttestationJwtOptionsV1_4,\n verifyWalletAttestationJwt as verifyWalletAttestationJwtV1_4,\n} from \"./v1.4/verify-wallet-attestation-jwt\";\n\nconst dispatchVerifyWalletAttestationJwt = createVersionDispatcher<\n VerifyWalletAttestationJwtOptions,\n Promise<VerifiedWalletAttestationJwt>\n>({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n verifyWalletAttestationJwtV1_4(o as VerifyWalletAttestationJwtOptionsV1_4),\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 {JwtParseError} 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 { type CallbackContext, JwtPayload } from \"@pagopa/io-wallet-utils\";\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: NonNullable<NonNullable<JwtPayload[\"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 {\n type JwtHeader,\n type JwtPayload,\n decodeJwt,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseVerifyWalletAttestationJwtOptions } from \"./types\";\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 {\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\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 {JwtParseError} 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 {\n zCertificateChain,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\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 {JwtParseError} 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 {\n zCertificateChain,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n zTrustChain,\n} from \"@pagopa/io-wallet-utils\";\nimport { z } from \"zod\";\n\nexport const zWalletAttestationJwtHeaderV1_4 = z.looseObject({\n ...zJwtHeader.shape,\n kid: z.string(),\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 exp: z.number().int(),\n iat: z.number().int(),\n iss: z.string(),\n nbf: z.number().optional(),\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 {JwtParseError} 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 type CallbackContext,\n FetchHeaders,\n HashAlgorithm,\n HttpMethod,\n type JwtSignerJwk,\n ValidationError,\n dateToSeconds,\n decodeUtf8String,\n encodeToBase64Url,\n parseWithErrorHandling,\n zCompactJwt,\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 {\n MAX_JTI_LENGTH,\n zHttpMethod,\n zJwk,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n Jwk,\n RequestLike,\n createVersionDispatcher,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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 { Oauth2Error } from \"../errors\";\nimport { PkceCodeChallengeMethod, verifyPkce } from \"../pkce\";\nimport { verifyTokenDPoP } from \"../token-dpop/verify-token-dpop\";\nimport {\n ParsedAccessTokenAuthorizationCodeRequestGrant,\n ParsedAccessTokenPreAuthorizedCodeRequestGrant,\n} from \"./parse-token-request\";\nimport {\n authorizationCodeGrantIdentifier,\n preAuthorizedCodeGrantIdentifier,\n} from \"./z-grant-type\";\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 BaseVerifyAccessTokenRequestOptions {\n /**\n * The authorization server metadata\n */\n authorizationServerMetadata: BaseAuthorizationServerMetadata;\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 config: IoWalletSdkConfig;\n\n /**\n * The dpop verification options\n */\n dpop: VerifyAccessTokenRequestDpop;\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 HTTP request information\n */\n request: RequestLike;\n}\n\nexport interface VerifyAccessTokenRequestOptions<\n V extends ItWalletSpecsVersion = ItWalletSpecsVersion.V1_0,\n> extends BaseVerifyAccessTokenRequestOptions {\n /**\n * The expiration date of the authorization code\n */\n codeExpiresAt?: Date;\n\n config: IoWalletSdkConfig<V>;\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 pkce options including code verifier, challenge and method\n */\n pkce: VerifyAccessTokenRequestPkce;\n}\n\nexport interface VerifyPreAuthorizedCodeAccessTokenRequestOptions extends BaseVerifyAccessTokenRequestOptions {\n config: IoWalletSdkConfig<ItWalletSpecsVersion.APTITUDE>;\n\n /** The pre-authorized code stored by the authorization server. */\n expectedPreAuthorizedCode: string;\n\n /** The stored transaction code, if one was required by the credential offer. */\n expectedTxCode?: string;\n\n /** The parsed pre-authorized code grant */\n grant: ParsedAccessTokenPreAuthorizedCodeRequestGrant;\n\n /** The expiration date stored with the pre-authorized code. */\n preAuthorizedCodeExpiresAt?: Date;\n}\n\nexport type SupportedAccessTokenVerificationOptionsV1_4 =\n VerifyAccessTokenRequestOptions<\n | ItWalletSpecsVersion.V1_0\n | ItWalletSpecsVersion.V1_3\n | ItWalletSpecsVersion.V1_4\n >;\n\nexport type SupportedAccessTokenVerificationOptionsAPTITUDE =\n | VerifyAccessTokenRequestOptions<ItWalletSpecsVersion.APTITUDE>\n | VerifyPreAuthorizedCodeAccessTokenRequestOptions;\n\nexport type SupportedAccessTokenVerificationOptions =\n | SupportedAccessTokenVerificationOptionsAPTITUDE\n | SupportedAccessTokenVerificationOptionsV1_4;\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\nasync function verifyAccessTokenRequestV1_4<V extends ItWalletSpecsVersion>(\n options: VerifyAccessTokenRequestOptions<V>,\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 verifyCodeExpiration(options.codeExpiresAt, options.now, \"code\");\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\nasync function verifyAccessTokenRequestAPTITUDE(\n options: SupportedAccessTokenVerificationOptionsAPTITUDE,\n): Promise<VerifyAccessTokenRequestResult> {\n if (options.dpop.expectedNonce === \"\") {\n throw new Oauth2Error(`Invalid 'dpop.expectedNonce' provided`);\n }\n\n if (!isPreAuthorizedCodeVerification(options)) {\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\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 verifyGrantParameters(options);\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\nfunction isPreAuthorizedCodeVerification(\n options: SupportedAccessTokenVerificationOptionsAPTITUDE,\n): options is VerifyPreAuthorizedCodeAccessTokenRequestOptions {\n return options.grant.grantType === preAuthorizedCodeGrantIdentifier;\n}\n\nfunction verifyGrantParameters(\n options: SupportedAccessTokenVerificationOptionsAPTITUDE,\n) {\n if (isPreAuthorizedCodeVerification(options)) {\n if (options.grant.preAuthorizedCode !== options.expectedPreAuthorizedCode) {\n throw new Oauth2Error(`Invalid 'pre-authorized_code' provided`);\n }\n\n verifyTransactionCode(options.grant.txCode, options.expectedTxCode);\n\n verifyCodeExpiration(\n options.preAuthorizedCodeExpiresAt,\n options.now,\n \"pre-authorized_code\",\n );\n\n return;\n }\n\n if (options.grant.grantType !== authorizationCodeGrantIdentifier) {\n throw new Oauth2Error(\n \"Only authorization_code and pre-authorized_code grants can be verified\",\n );\n }\n\n if (options.grant.code !== options.expectedCode) {\n throw new Oauth2Error(`Invalid 'code' provided`);\n }\n verifyCodeExpiration(options.codeExpiresAt, options.now, \"code\");\n}\n\nfunction verifyTransactionCode(\n txCode: string | undefined,\n expectedTxCode: string | undefined,\n) {\n if (txCode === expectedTxCode) return;\n\n if (expectedTxCode === undefined) {\n throw new Oauth2Error(\"Request contains 'tx_code' that was not expected\");\n }\n\n if (txCode === undefined) {\n throw new Oauth2Error(\"Missing required 'tx_code' in request\");\n }\n\n throw new Oauth2Error(\"Invalid 'tx_code' provided\");\n}\n\nfunction verifyCodeExpiration(\n expiresAt: Date | undefined,\n date: Date | undefined,\n codeParameter: string,\n) {\n if (!expiresAt) return;\n\n if (Number.isNaN(expiresAt.getTime())) {\n throw new Oauth2Error(`Invalid expiration date for '${codeParameter}'`);\n }\n\n const now = date ?? new Date();\n\n if (now.getTime() > expiresAt.getTime()) {\n throw new Oauth2Error(`Expired '${codeParameter}' provided`);\n }\n}\n\nconst dispatchVerifyAccessTokenRequest = createVersionDispatcher<\n SupportedAccessTokenVerificationOptions,\n Promise<VerifyAccessTokenRequestResult>\n>({\n [ItWalletSpecsVersion.APTITUDE]: (o) =>\n verifyAccessTokenRequestAPTITUDE(\n o as SupportedAccessTokenVerificationOptionsAPTITUDE,\n ),\n [ItWalletSpecsVersion.V1_0]: (o) =>\n verifyAccessTokenRequestV1_4(\n o as VerifyAccessTokenRequestOptions<ItWalletSpecsVersion.V1_0>,\n ),\n [ItWalletSpecsVersion.V1_3]: (o) =>\n verifyAccessTokenRequestV1_4(\n o as VerifyAccessTokenRequestOptions<ItWalletSpecsVersion.V1_3>,\n ),\n [ItWalletSpecsVersion.V1_4]: (o) =>\n verifyAccessTokenRequestV1_4(\n o as VerifyAccessTokenRequestOptions<ItWalletSpecsVersion.V1_4>,\n ),\n});\n\n/**\n * Verifies an authorization-code or pre-authorized-code token request.\n *\n * Both grants retain the SDK's IT-Wallet DPoP and client attestation requirements:\n * - PKCE verification against the stored code challenge for authorization-code requests only\n * - DPoP proof JWT verification and JWK thumbprint extraction\n * - Client attestation JWT and attestation PoP JWT verification\n * - Authorization code or pre-authorized code validity and expiration checks\n * - Transaction code verification when required by the credential offer\n *\n * The caller must enforce single-use redemption of codes atomically when issuing\n * the token, and limit transaction-code attempts. This verifier does not store state.\n * The upstream verifier allows optional DPoP and client attestation; the local\n * implementation retains the SDK's required security checks and error types.\n *\n * * Version Differences:\n * - APTITUDE: add support for pre-authorized-code grant type.\n * *\n * @param options - Configuration options for token request verification and version config\n * @returns A promise that resolves with verified client attestation and DPoP information\n * @throws {Oauth2Error} If the grant code is invalid or expired, or the transaction code is missing, unexpected or invalid\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 function verifyAccessTokenRequest(\n options:\n | SupportedAccessTokenVerificationOptionsAPTITUDE\n | SupportedAccessTokenVerificationOptionsV1_4,\n): Promise<VerifyAccessTokenRequestResult>;\n\nexport function verifyAccessTokenRequest(\n options: SupportedAccessTokenVerificationOptions,\n): Promise<VerifyAccessTokenRequestResult> {\n return dispatchVerifyAccessTokenRequest(options);\n}\n","import {\n type CallbackContext,\n HashAlgorithm,\n IoWalletSdkConfig,\n calculateJwkThumbprint,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata;\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 {\n CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n Jwk,\n JwtSignerJwk,\n addSecondsToDate,\n dateToSeconds,\n decodeJwt,\n encodeToBase64Url,\n parseWithErrorHandling,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n MAX_JTI_LENGTH,\n zJwtHeader,\n zJwtPayload,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 type CallbackContext,\n HashAlgorithm,\n type HashCallback,\n decodeUtf8String,\n encodeToBase64Url,\n} 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 type CallbackContext,\n HashAlgorithm,\n RequestLike,\n calculateJwkThumbprint,\n decodeJwt,\n decodeUtf8String,\n encodeToBase64Url,\n verifyJwt,\n verifyJwtIatOrThrow,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n type RequestDpopOptions,\n addSecondsToDate,\n dateToSeconds,\n dispatchByVersion,\n encodeToBase64Url,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata[\"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.APTITUDE]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\n [ItWalletSpecsVersion.V1_0]: () =>\n zAuthorizationRequestV1_0.parse({\n ...baseAuthorizationRequest,\n response_mode: (options as CreatePushedAuthorizationRequestOptionsV1_0)\n .responseMode,\n }) satisfies AuthorizationRequestV1_0,\n // V1_4 reuses V1_3 authorization request schema — no breaking changes between versions.\n [ItWalletSpecsVersion.V1_3]: () =>\n zAuthorizationRequestV1_3.parse(\n baseAuthorizationRequest,\n ) satisfies AuthorizationRequestV1_3,\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 { MAX_JTI_LENGTH } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\nconst zOpenidCredentialAuthorizationDetails = z.object({\n credential_configuration_id: z.string(),\n type: z.literal(\"openid_credential\"),\n});\n\nconst zItL2DocumentProofAuthorizationDetails = z.object({\n challenge_method: z.literal(\"mrtd+ias\"),\n challenge_redirect_uri: z.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 {\n CONTENT_TYPES,\n type CallbackContext,\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n RequestLike,\n decodeJwt,\n dispatchByVersion,\n formatZodError,\n parseWithErrorHandling,\n} from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\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.APTITUDE]: () => zAuthorizationRequestV1_3,\n [ItWalletSpecsVersion.V1_0]: () => zAuthorizationRequestV1_0,\n // V1_4 reuses V1_3 PAR schema — no breaking changes between versions.\n [ItWalletSpecsVersion.V1_3]: () => zAuthorizationRequestV1_3,\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 type { CallbackContext } from \"@pagopa/io-wallet-utils\";\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 { zJwtHeader, zJwtPayload } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n Jwk,\n RequestLike,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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 { 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: BaseAuthorizationServerMetadata;\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 { JwtSigner, decodeJwt } from \"@pagopa/io-wallet-utils\";\n\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 {\n type CallbackContext,\n JwtSigner,\n JwtSignerWithJwk,\n decodeJwt,\n parseWithErrorHandling,\n verifyJwt,\n zCompactJwe,\n zCompactJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { Oauth2Error } from \"../errors\";\nimport {\n JarRequestObjectPayload,\n jwtAuthorizationRequestJwtHeaderTyp,\n signedAuthorizationRequestJwtHeaderTyp,\n zJarRequestObjectPayload,\n} from \"./z-jar\";\n\nexport interface VerifyJarRequestOptions {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jarRequestParams: {\n client_id?: string;\n };\n jwtSigner: JwtSigner;\n now?: Date;\n}\n\nexport interface VerifiedJarRequest {\n authorizationRequestPayload: JarRequestObjectPayload;\n jwt: {\n payload: JarRequestObjectPayload;\n } & Omit<ReturnType<typeof decodeJwt>, \"payload\">;\n signer: JwtSignerWithJwk;\n}\n\n/**\n * Verifies a JAR (JWT Secured Authorization Request) request by validating and verifying signatures.\n *\n * @param options - The input parameters\n * @param options.jarRequestParams - The JAR authorization request parameters\n * @param options.callbacks - Context containing the relevant Jose crypto operations\n * @returns The verified authorization request parameters and metadata\n */\nexport async function verifyJarRequest(\n options: VerifyJarRequestOptions,\n): Promise<VerifiedJarRequest> {\n const { authorizationRequestJwt, callbacks, jarRequestParams, jwtSigner } =\n options;\n\n /* Encryption is not supported */\n const requestObjectIsEncrypted = zCompactJwe.safeParse(\n authorizationRequestJwt,\n ).success;\n if (requestObjectIsEncrypted) {\n throw new Oauth2Error(\"Encrypted JWE request objects are not supported.\");\n }\n\n const requestIsSigned = zCompactJwt.safeParse(\n authorizationRequestJwt,\n ).success;\n if (!requestIsSigned) {\n throw new Oauth2Error(\"JAR request object is not a valid JWT.\");\n }\n\n const { authorizationRequestPayload, jwt, signer } =\n await verifyJarRequestObject({\n authorizationRequestJwt,\n callbacks,\n jwtSigner,\n });\n\n if (!authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n 'Jar Request Object is missing the required \"client_id\" field.',\n );\n }\n\n // Expect the client_id from the jar request to match the payload\n if (jarRequestParams.client_id !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\n \"client_id does not match the request object client_id.\",\n );\n }\n\n if (jwt.payload.iss !== authorizationRequestPayload.client_id) {\n throw new Oauth2Error(\"iss claim in request JWT does not match client_id\");\n }\n\n // RFC 9101 §4: exp claim MUST be present and not in the past\n if (jwt.payload.exp === undefined) {\n throw new Oauth2Error(\"exp claim in request JWT is missing\");\n }\n\n const now = options.now ?? new Date();\n const nowSeconds = Math.floor(now.getTime() / 1000);\n if (nowSeconds > jwt.payload.exp) {\n throw new Oauth2Error(\"exp claim in request JWT is expired\");\n }\n\n // IT-Wallet requirement: iat MUST be present\n if (jwt.payload.iat === undefined) {\n throw new Oauth2Error(\"iat claim in request JWT is missing\");\n }\n\n // IT-Wallet requirement: iat MUST not be more than 5 minutes in the past\n const MAX_IAT_AGE_SECONDS = 5 * 60;\n if (nowSeconds - jwt.payload.iat > MAX_IAT_AGE_SECONDS) {\n throw new Oauth2Error(\n \"iat claim in request JWT is too old (must be within 5 minutes)\",\n );\n }\n\n // IT-Wallet requirement: iat MUST not be more than clock-skew tolerance in the future\n const CLOCK_SKEW_TOLERANCE_SECONDS = 60;\n if (jwt.payload.iat - nowSeconds > CLOCK_SKEW_TOLERANCE_SECONDS) {\n throw new Oauth2Error(\"iat claim in request JWT is too far in the future\");\n }\n\n return {\n authorizationRequestPayload,\n jwt,\n signer,\n };\n}\n\nasync function verifyJarRequestObject(options: {\n authorizationRequestJwt: string;\n callbacks: Pick<CallbackContext, \"verifyJwt\">;\n jwtSigner: JwtSigner;\n}) {\n const { authorizationRequestJwt, callbacks, jwtSigner } = options;\n\n const jwt = decodeJwt({\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 {\n type CallbackContext,\n IoWalletSdkConfig,\n ItWalletSpecsVersion,\n type ClientAuthenticationCallback as UtilsClientAuthenticationCallback,\n type ClientAuthenticationCallbackOptions as UtilsClientAuthenticationCallbackOptions,\n} from \"@pagopa/io-wallet-utils\";\n\nimport type { BaseAuthorizationServerMetadata } from \"../authorization-server-metadata\";\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: BaseAuthorizationServerMetadata;\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\nexport type ClientAuthenticationCallbackOptions =\n UtilsClientAuthenticationCallbackOptions<BaseAuthorizationServerMetadata>;\n\nexport type ClientAuthenticationCallback =\n UtilsClientAuthenticationCallback<ClientAuthenticationCallbackOptions>;\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 Jwk,\n calculateJwkThumbprint,\n} from \"@pagopa/io-wallet-utils\";\n\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 decodeJwt,\n} from \"@pagopa/io-wallet-utils\";\n\nimport { ClientAttestationError } from \"../../errors\";\nimport { calculateDpopJwkThumbprint } from \"../jwk-thumbprint\";\nimport { BaseWalletAttestationOptions } from \"../types\";\nimport {\n WalletAttestationJwtV1_4,\n zWalletAttestationJwtHeaderV1_4,\n zWalletAttestationJwtPayloadV1_4,\n} from \"./z-wallet-attestation\";\n\nconst DEFAULT_EXPIRATION_SECONDS = 3600;\n\nconst MAX_EXPIRATION_SECONDS = 86400;\n\nexport interface WalletAttestationOptionsV1_4 extends Omit<\n BaseWalletAttestationOptions,\n \"walletLink\" | \"walletName\"\n> {\n nbf?: Date;\n signer: {\n alg: string;\n kid: string;\n method: \"x5c\";\n trustChain?: [string, ...string[]];\n x5c: [string, ...string[]];\n };\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 =\n options.expiresAt ?? addSecondsToDate(iat, DEFAULT_EXPIRATION_SECONDS);\n\n if (exp <= iat) {\n throw new ValidationError(\"exp must be after iat\");\n }\n\n if (exp > addSecondsToDate(iat, MAX_EXPIRATION_SECONDS)) {\n throw new ValidationError(\"exp must not be more than 24 hours after iat\");\n }\n\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 wallet_link: options.walletLink,\n wallet_name: options.walletName,\n ...(options.nbf && { nbf: dateToSeconds(options.nbf) }),\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 {\n type CallbackContext,\n type JweEncryptor,\n type Jwk,\n type JwtSigner,\n addSecondsToDate,\n dateToSeconds,\n} from \"@pagopa/io-wallet-utils\";\n\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 { DecodeJwtResult, decodeJwt } from \"@pagopa/io-wallet-utils\";\nimport z from \"zod\";\n\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 {\n type CallbackContext,\n JwtSignerJwk,\n dateToSeconds,\n parseWithErrorHandling,\n} 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 CONTENT_TYPES,\n type CallbackContext,\n HEADERS,\n JwtSigner,\n UnexpectedStatusCodeError,\n ValidationError,\n createFetcher,\n decodeJwt,\n hasStatusOrThrow,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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 {\n CONTENT_TYPES,\n type CallbackContext,\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 { decodeJwt, zCompactJwt } from \"@pagopa/io-wallet-utils\";\n\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 type CallbackContext,\n JwtPayload,\n JwtSigner,\n decodeJwt,\n jwtSignerFromJwt,\n verifyJwt,\n} from \"@pagopa/io-wallet-utils\";\n\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,EAEE;AAAA,EACA;AAAA,OACK;;;ACJP,SAAS,SAAS;AAEX,IAAM,oCACX,EAAE,QAAQ,oBAAoB;AACzB,IAAM,mCACX,kCAAkC;AAI7B,IAAM,oCAAoC,EAAE;AAAA,EACjD;AACF;AACO,IAAM,mCACX,kCAAkC;AAK7B,IAAM,+BAA+B,EAAE,QAAQ,eAAe;AAC9D,IAAM,8BAA8B,6BAA6B;;;ADwFjE,IAAM,yBAAyB,CACpC,YACG;AACH,MAAI,QAAQ,cAAc,6BAA6B;AACrD,WAAO;AAAA,MAC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AUC,kBAAiB,EAAE,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AAAA,IAC1E,mBAAmB,UAAU;AAAA,EAC/B,CAAC;AAED,SAAO,EAAE,QAAQ,IAAI,QAAQ,SAAS,IAAI,SAAS,OAAO;AAC5D;","names":["ItWalletSpecsVersion","createVersionDispatcher","z","z","createVersionDispatcher","ItWalletSpecsVersion","ItWalletSpecsVersion","createVersionDispatcher","parseWithErrorHandling","parseWithErrorHandling","createVersionDispatcher","ItWalletSpecsVersion","ItWalletSpecsVersion","createVersionDispatcher","ItWalletSpecsVersion","createVersionDispatcher","z","zJwtHeader","zJwtPayload","z","zJwk","zJwtHeader","zJwtPayload","zTrustChain","z","verifyWalletAttestationJwt","zCertificateChain","zJwk","zJwtHeader","zJwtPayload","zTrustChain","z","verifyWalletAttestationJwt","createVersionDispatcher","ItWalletSpecsVersion","verifyWalletAttestationJwt","HashAlgorithm","ValidationError","dateToSeconds","parseWithErrorHandling","zCompactJwt","MAX_JTI_LENGTH","zJwk","zJwtHeader","zJwtPayload","z","HashAlgorithm","parseWithErrorHandling","dateToSeconds","ValidationError","zCompactJwt","createVersionDispatcher","ItWalletSpecsVersion","ItWalletSpecsVersion","createVersionDispatcher","HashAlgorithm","calculateJwkThumbprint","ItWalletSpecsVersion","addSecondsToDate","dateToSeconds","decodeJwt","encodeToBase64Url","parseWithErrorHandling","verifyJwt","MAX_JTI_LENGTH","zJwtHeader","zJwtPayload","z","decodeJwt","verifyJwt","encodeToBase64Url","parseWithErrorHandling","dateToSeconds","ItWalletSpecsVersion","addSecondsToDate","verifyWalletAttestationJwt","calculateJwkThumbprint","HashAlgorithm","HashAlgorithm","decodeUtf8String","encodeToBase64Url","encodeToBase64Url","decodeUtf8String","HashAlgorithm","HashAlgorithm","calculateJwkThumbprint","decodeJwt","decodeUtf8String","encodeToBase64Url","verifyJwt","decodeJwt","encodeToBase64Url","decodeUtf8String","HashAlgorithm","calculateJwkThumbprint","verifyJwt","createVersionDispatcher","ItWalletSpecsVersion","ItWalletSpecsVersion","addSecondsToDate","dateToSeconds","encodeToBase64Url","MAX_JTI_LENGTH","z","encodeToBase64Url","addSecondsToDate","dateToSeconds","ItWalletSpecsVersion","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","createFetcher","toURLSearchParams","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","ValidationError","ItWalletSpecsVersion","decodeJwt","dispatchByVersion","formatZodError","parseWithErrorHandling","z","UnexpectedStatusCodeError","createFetcher","hasStatusOrThrow","createFetcher","hasStatusOrThrow","UnexpectedStatusCodeError","zJwtHeader","zJwtPayload","z","parseWithErrorHandling","z","decodeJwt","formatZodError","dispatchByVersion","ItWalletSpecsVersion","decodeJwt","decodeJwt","parseWithErrorHandling","verifyJwt","zCompactJwt","zCompactJwt","decodeJwt","parseWithErrorHandling","verifyJwt","decodeJwt","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","HashAlgorithm","calculateJwkThumbprint","calculateJwkThumbprint","HashAlgorithm","addSecondsToDate","dateToSeconds","decodeJwt","ValidationError","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","decodeJwt","ValidationError","addSecondsToDate","dateToSeconds","decodeJwt","createWalletAttestationJwt","addSecondsToDate","ValidationError","dateToSeconds","decodeJwt","addSecondsToDate","dateToSeconds","dateToSeconds","addSecondsToDate","decodeJwt","decodeJwt","dateToSeconds","parseWithErrorHandling","z","JWT_EXPIRY_SECONDS","dateToSeconds","parseWithErrorHandling","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","decodeJwt","hasStatusOrThrow","jwtSignerFromJwt","verifyJwt","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","decodeJwt","verifyJwt","jwtSignerFromJwt","ValidationError","CONTENT_TYPES","HEADERS","UnexpectedStatusCodeError","ValidationError","createFetcher","hasStatusOrThrow","parseWithErrorHandling","createFetcher","HEADERS","CONTENT_TYPES","hasStatusOrThrow","UnexpectedStatusCodeError","parseWithErrorHandling","ValidationError","decodeJwt","zCompactJwt","zCompactJwt","decodeJwt","decodeJwt","jwtSignerFromJwt","verifyJwt","decodeJwt","verifyJwt","jwtSignerFromJwt"]}
|