{"version":3,"file":"index.mjs","names":["ValidationError","formatZodError","OpenId4VcBaseError","ValidationError","OpenId4VcBaseError","formatZodError","InvalidFetchResponseError","ValidationError","z","z","z","InvalidFetchResponseError","InvalidFetchResponseError","ValidationError","InvalidFetchResponseError","ValidationError","InvalidFetchResponseError","InvalidFetchResponseError","ValidationError","InvalidFetchResponseError"],"sources":["../src/callbacks.ts","../src/error/Oauth2Error.ts","../src/common/jwk/jwk-thumbprint.ts","../src/common/jwk/jwks.ts","../src/error/Oauth2JwtParseError.ts","../src/common/jwk/z-jwk.ts","../src/common/z-common.ts","../src/common/jwt/z-jwt.ts","../src/common/jwt/decode-jwt-header.ts","../src/common/jwt/decode-jwt.ts","../src/error/Oauth2JwtVerificationError.ts","../src/common/jwt/verify-jwt.ts","../../../node_modules/.pnpm/zod-validation-error@5.0.0_zod@4.4.3/node_modules/zod-validation-error/v4/index.mjs","../../utils/src/zod-error.ts","../../utils/src/error/OpenId4VcBaseError.ts","../../utils/src/error/ValidationError.ts","../src/metadata/fetch-jwks-uri.ts","../src/access-token/z-access-token-jwt.ts","../src/access-token/verify-access-token.ts","../src/common/z-oauth2-error.ts","../src/error/Oauth2ServerErrorResponseError.ts","../src/client-attestation/z-client-attestation.ts","../src/client-attestation/client-attestation-pop.ts","../src/client-attestation/client-attestation.ts","../src/dpop/z-dpop.ts","../src/dpop/dpop.ts","../src/authorization-request/parse-authorization-request.ts","../src/common/jwt/z-jwe.ts","../src/jar/z-jar-authorization-request.ts","../src/jar/z-jar-request-object.ts","../src/jar/handle-jar-request/verify-jar-request.ts","../src/authorization-request/z-authorization-request.ts","../src/authorization-request/parse-pushed-authorization-request.ts","../src/authorization-request/verify-authorization-request.ts","../src/authorization-response/z-authorization-response.ts","../src/authorization-response/parse-authorization-response.ts","../src/authorization-response/verify-authorization-response.ts","../src/error/Oauth2ClientErrorResponseError.ts","../src/client-attestation/client-attestation-challenge.ts","../src/z-grant-type.ts","../src/client-authentication.ts","../src/common/algorithm/algorithm-transform.ts","../src/dpop/dpop-retry.ts","../src/error/Oauth2ClientAuthorizationChallengeError.ts","../src/error/Oauth2ResourceUnauthorizedError.ts","../src/id-token/z-id-token-jwt.ts","../src/id-token/verify-id-token.ts","../src/jar/create-jar-authorization-request.ts","../src/metadata/fetch-well-known-metadata.ts","../src/metadata/authorization-server/z-authorization-server-metadata.ts","../src/metadata/authorization-server/authorization-server-metadata.ts","../src/access-token/create-access-token.ts","../src/access-token/z-access-token.ts","../src/access-token/create-access-token-response.ts","../src/access-token/parse-access-token-request.ts","../src/pkce.ts","../src/access-token/verify-access-token-request.ts","../src/authorization-challenge/z-authorization-challenge.ts","../src/authorization-challenge/create-authorization-challenge-response.ts","../src/authorization-challenge/parse-authorization-challenge-request.ts","../src/authorization-challenge/verify-authorization-challenge-request.ts","../src/authorization-request/create-pushed-authorization-response.ts","../src/authorization-request/verify-pushed-authorization-request.ts","../src/Oauth2AuthorizationServer.ts","../src/access-token/retrieve-access-token.ts","../src/authorization-challenge/send-authorization-challenge.ts","../src/authorization-request/create-authorization-request.ts","../src/resource-request/make-resource-request.ts","../src/Oauth2Client.ts","../src/Oauth2ResourceServer.ts","../src/access-token/z-token-introspection.ts","../src/access-token/introspect-token.ts","../src/resource-request/verify-resource-request.ts"],"sourcesContent":["import type { Fetch, OrPromise } from '@openid4vc/utils'\nimport type { ClientAuthenticationCallback } from './client-authentication'\nimport type { Jwk } from './common/jwk/z-jwk'\nimport type { JweEncryptor, JwtHeader, JwtPayload, JwtSigner } from './common/jwt/z-jwt'\n\n/**\n * Supported hashing algorithms\n *\n * Based on https://www.iana.org/assignments/named-information/named-information.xhtml\n */\nexport enum HashAlgorithm {\n  Sha256 = 'sha-256',\n  Sha384 = 'sha-384',\n  Sha512 = 'sha-512',\n}\n\n/**\n * Callback used for operations that require hashing\n */\nexport type HashCallback = (data: Uint8Array, alg: HashAlgorithm) => OrPromise<Uint8Array>\n\nexport type GenerateRandomCallback = (byteLength: number) => OrPromise<Uint8Array>\n\nexport type SignJwtCallback = (\n  jwtSigner: JwtSigner,\n  jwt: { header: JwtHeader; payload: JwtPayload }\n) => OrPromise<{\n  jwt: string\n  signerJwk: Jwk\n}>\n\nexport type VerifyJwtCallback = (\n  jwtSigner: JwtSigner,\n  jwt: { header: JwtHeader; payload: JwtPayload; compact: string }\n) => OrPromise<\n  | {\n      verified: true\n      signerJwk: Jwk\n    }\n  | {\n      verified: false\n      signerJwk?: Jwk\n    }\n>\n\nexport type VerifyDataIntegrityProofCallback = (\n  dataIntegrityProof: Record<string, unknown>,\n  document: Record<string, unknown>\n) => OrPromise<\n  | {\n      verified: true\n      signerJwk: Jwk\n    }\n  | {\n      verified: false\n      signerJwk?: Jwk\n    }\n>\n\nexport interface DecryptJweCallbackOptions {\n  jwk?: Jwk\n}\n\nexport type DecryptJweCallback = (\n  jwe: string,\n  options?: DecryptJweCallbackOptions\n) => OrPromise<\n  | {\n      decrypted: true\n      decryptionJwk: Jwk\n      payload: string\n    }\n  | {\n      decrypted: false\n      decryptionJwk?: Jwk\n      payload?: string\n    }\n>\n\nexport type EncryptJweCallback = (\n  jweEncryptor: JweEncryptor,\n  data: string\n) => OrPromise<{\n  encryptionJwk: Jwk\n  jwe: string\n}>\n\n/**\n * Callback context provides the callbacks that are required for the openid4vc library\n */\nexport interface CallbackContext {\n  /**\n   * Custom fetch implementation to use\n   */\n  fetch?: Fetch\n\n  /**\n   * Hash callback used for e.g. dpop and pkce\n   */\n  hash: HashCallback\n\n  /**\n   * Sign jwt callback for signing of Json Web Tokens\n   */\n  signJwt: SignJwtCallback\n\n  /**\n   * Decrypt jwe callback for decrypting of Json Web Encryptions\n   */\n  decryptJwe: DecryptJweCallback\n\n  /**\n   * Encrypt jwt callback for encrypting of Json Web Encryptions\n   */\n  encryptJwe: EncryptJweCallback\n\n  /**\n   * Verify jwt callback for verification of Json Web Tokens\n   */\n  verifyJwt: VerifyJwtCallback\n\n  /**\n   * Verify a Data Integrity proof (e.g. the `proof` of a `di_vp` key proof's Verifiable\n   * Presentation). Optional because most issuers won't support the `di_vp` proof type.\n   */\n  verifyDataIntegrityProof?: VerifyDataIntegrityProofCallback\n\n  /**\n   * Generate random callback to generate random bytes. Used for\n   * e.g. the 'jti' value in a dpop jwt, and 'code_verifier' in pkce.\n   */\n  generateRandom: GenerateRandomCallback\n\n  /**\n   * Extend a request to the authorization server with client authentication\n   * parameters. If you're not using client authentication, you can set this\n   * to `clientAuthenticationNone()`\n   *\n   * There are three default client authentication methods provided:\n   * - `clientAuthenticationClientSecretPost`\n   * - `clientAuthenticationClientSecretBasic`\n   * - `clientAuthenticationClientAttestationJwt`\n   * - `clientAuthenticationNone`\n   * - `clientAuthenticationAnonymous`\n   *\n   * A custom implementation can be made for other methods, or allowing complex\n   * scenarios where multiple authorization servers are supported.\n   */\n  clientAuthentication: ClientAuthenticationCallback\n\n  /**\n   * Get the DNS names and URI names from a X.509 certificate\n   */\n  getX509CertificateMetadata?: (certificate: string) => {\n    sanDnsNames: string[]\n    sanUriNames: string[]\n  }\n}\n","export interface Oauth2ErrorOptions {\n  cause?: unknown\n}\n\nexport class Oauth2Error extends Error {\n  public readonly cause?: unknown\n\n  public constructor(message?: string, options?: Oauth2ErrorOptions) {\n    const errorMessage = message ?? 'Unknown error occurred.'\n    const causeMessage =\n      options?.cause instanceof Error ? ` ${options.cause.message}` : options?.cause ? ` ${options?.cause}` : ''\n\n    super(`${errorMessage}${causeMessage}`)\n    this.cause = options?.cause\n  }\n}\n","import { decodeUtf8String, encodeToBase64Url, parseWithErrorHandling } from '@openid4vc/utils'\nimport z from 'zod'\nimport type { HashAlgorithm, HashCallback } from '../../callbacks'\nimport type { Jwk } from './z-jwk'\n\nexport const zJwkThumbprintComponents = z\n  .discriminatedUnion('kty', [\n    z.object({\n      kty: z.literal('EC'),\n      crv: z.string(),\n      x: z.string(),\n      y: z.string(),\n    }),\n    z.object({\n      kty: z.literal('OKP'),\n      crv: z.string(),\n      x: z.string(),\n    }),\n    z.object({\n      kty: z.literal('RSA'),\n      e: z.string(),\n      n: z.string(),\n    }),\n    z.object({\n      kty: z.literal('oct'),\n      k: z.string(),\n    }),\n  ])\n  .transform((data) => {\n    if (data.kty === 'EC') {\n      return { crv: data.crv, kty: data.kty, x: data.x, y: data.y }\n    }\n\n    if (data.kty === 'OKP') {\n      return { crv: data.crv, kty: data.kty, x: data.x }\n    }\n\n    if (data.kty === 'RSA') {\n      return { e: data.e, kty: data.kty, n: data.n }\n    }\n\n    if (data.kty === 'oct') {\n      return { k: data.k, kty: data.kty }\n    }\n\n    throw new Error('Unsupported kty')\n  })\n\nexport interface CalculateJwkThumbprintOptions {\n  /**\n   * The jwk to calcualte the thumbprint for.\n   */\n  jwk: Jwk\n\n  /**\n   * The hashing algorithm to use for calculating the thumbprint\n   */\n  hashAlgorithm: HashAlgorithm\n\n  /**\n   * The hash callback to calculate the digest\n   */\n  hashCallback: HashCallback\n}\n\nexport async function calculateJwkThumbprint(options: CalculateJwkThumbprintOptions): Promise<string> {\n  const jwkThumbprintComponents = parseWithErrorHandling(\n    zJwkThumbprintComponents,\n    options.jwk,\n    `Provided jwk does not match a supported jwk structure. Either the 'kty' is not supported, or required values are missing.`\n  )\n\n  const thumbprint = encodeToBase64Url(\n    await options.hashCallback(decodeUtf8String(JSON.stringify(jwkThumbprintComponents)), options.hashAlgorithm)\n  )\n  return thumbprint\n}\n","import { type CallbackContext, HashAlgorithm } from '../../callbacks'\nimport { Oauth2Error } from '../../error/Oauth2Error'\nimport { calculateJwkThumbprint } from './jwk-thumbprint'\nimport type { Jwk, JwkSet } from './z-jwk'\n\ninterface ExtractJwkFromJwksForJwtOptions {\n  kid?: string\n  use: 'enc' | 'sig'\n\n  /**\n   * The JWKs\n   */\n  jwks: JwkSet\n}\n\n/**\n *\n * @param header\n * @param jwks\n */\nexport function extractJwkFromJwksForJwt(options: ExtractJwkFromJwksForJwtOptions) {\n  const jwksForUse = options.jwks.keys.filter(({ use }) => !use || use === options.use)\n  const jwkForKid = options.kid ? jwksForUse.find(({ kid }) => kid === options.kid) : undefined\n\n  if (jwkForKid) {\n    return jwkForKid\n  }\n\n  if (jwksForUse.length === 1) {\n    return jwksForUse[0]\n  }\n\n  throw new Oauth2Error(\n    `Unable to extract jwk from jwks for use '${options.use}'${options.kid ? `with kid '${options.kid}'.` : '. No kid provided and more than jwk.'}`\n  )\n}\n\nexport async function isJwkInSet({\n  jwk,\n  jwks,\n  callbacks,\n}: {\n  jwk: Jwk\n  jwks: Jwk[]\n  callbacks: Pick<CallbackContext, 'hash'>\n}) {\n  const jwkThumbprint = await calculateJwkThumbprint({\n    hashAlgorithm: HashAlgorithm.Sha256,\n    hashCallback: callbacks.hash,\n    jwk,\n  })\n\n  for (const jwkFromSet of jwks) {\n    const jwkFromSetThumbprint = await calculateJwkThumbprint({\n      hashAlgorithm: HashAlgorithm.Sha256,\n      hashCallback: callbacks.hash,\n      jwk: jwkFromSet,\n    })\n\n    if (jwkFromSetThumbprint === jwkThumbprint) return true\n  }\n\n  return false\n}\n","import { Oauth2Error } from './Oauth2Error'\n\nexport class Oauth2JwtParseError extends Oauth2Error {\n  public constructor(message?: string) {\n    const errorMessage = message ?? 'Error parsing jwt'\n\n    super(errorMessage)\n  }\n}\n","import z from 'zod'\n\nexport const zJwk = z\n  .object({\n    kty: z.string(),\n    crv: z.optional(z.string()),\n    x: z.optional(z.string()),\n    y: z.optional(z.string()),\n    e: z.optional(z.string()),\n    n: z.optional(z.string()),\n    alg: z.optional(z.string()),\n    d: z.optional(z.string()),\n    dp: z.optional(z.string()),\n    dq: z.optional(z.string()),\n    ext: z.optional(z.boolean()),\n    k: z.optional(z.string()),\n    key_ops: z.optional(z.array(z.string())),\n    kid: z.optional(z.string()),\n    oth: z.optional(\n      z.array(\n        z\n          .object({\n            d: z.optional(z.string()),\n            r: z.optional(z.string()),\n            t: z.optional(z.string()),\n          })\n          .loose()\n      )\n    ),\n    p: z.optional(z.string()),\n    q: z.optional(z.string()),\n    qi: z.optional(z.string()),\n    use: z.optional(z.string()),\n    x5c: z.optional(z.array(z.string())),\n    x5t: z.optional(z.string()),\n    'x5t#S256': z.optional(z.string()),\n    x5u: z.optional(z.string()),\n  })\n  .loose()\n\nexport type Jwk = z.infer<typeof zJwk>\n\nexport const zJwkSet = z.object({ keys: z.array(zJwk) }).loose()\n\nexport type JwkSet = z.infer<typeof zJwkSet>\n","import type { FetchHeaders, HttpMethod } from '@openid4vc/utils'\nimport z from 'zod'\n\nexport const zAlgValueNotNone = z.string().refine((alg) => alg !== 'none', { message: `alg value may not be 'none'` })\n\nexport interface RequestLike {\n  headers: FetchHeaders\n  method: HttpMethod\n  url: string\n}\n","import { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { type Jwk, zJwk } from '../jwk/z-jwk'\nimport { zAlgValueNotNone } from '../z-common'\n\nexport type JwtSignerDid = {\n  method: 'did'\n  didUrl: string\n  alg: string\n\n  /**\n   * The key id that should be used for signing. You need to make sure the kid actuall matches\n   * with the key associated with the didUrl.\n   */\n  kid?: string\n}\n\nexport type JwtSignerJwk = {\n  method: 'jwk'\n  publicJwk: Jwk\n  alg: string\n\n  /**\n   * The key id that should be used for signing. You need to make sure the kid actuall matches\n   * with the key associated with the jwk.\n   *\n   * If not provided the kid can also be extracted from the `publicJwk`. Providing it here means the `kid` won't\n   * be included in the JWT header.\n   */\n  kid?: string\n}\n\nexport type JwtSignerX5c = {\n  method: 'x5c'\n  x5c: string[]\n  alg: string\n\n  /**\n   * The key id that should be used for signing. You need to make sure the kid actuall matches\n   * with the key associated with the leaf certificate.\n   */\n  kid?: string\n}\n\nexport type JwtSignerFederation = {\n  method: 'federation'\n  trustChain?: [string, ...string[]]\n  alg: string\n\n  /**\n   * The key id that should be used for signing. You need to make sure the kid actuall matches\n   * with a key present in the federation.\n   */\n  kid: string\n}\n\n// In case of custom nothing will be added to the header\nexport type JwtSignerCustom = {\n  method: 'custom'\n  alg: string\n\n  /**\n   * The key id that should be used for signing.\n   */\n  kid?: string\n}\n\nexport type JwtSigner = JwtSignerDid | JwtSignerJwk | JwtSignerX5c | JwtSignerFederation | JwtSignerCustom\n\nexport type JwtSignerWithJwk = JwtSigner & { publicJwk: Jwk }\n\nexport type JweEncryptor = JwtSignerJwk & {\n  enc: string\n\n  /**\n   * base64-url encoded apu\n   */\n  apu?: string\n\n  /**\n   * base64-url encoded apv\n   */\n  apv?: string\n}\n\nexport const zCompactJwt = z.string().regex(/^([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)$/, {\n  message: 'Not a valid compact jwt',\n})\n\nexport const zJwtConfirmationPayload = z\n  .object({\n    jwk: zJwk.optional(),\n\n    // RFC9449. jwk thumbprint of the dpop public key to which the access token is bound\n    jkt: z.string().optional(),\n  })\n  .loose()\n\nexport const zJwtPayload = z\n  .object({\n    iss: z.string().optional(),\n    aud: z.union([z.string(), z.array(z.string())]).optional(),\n    iat: zNumericDate.optional(),\n    exp: zNumericDate.optional(),\n    nbf: zNumericDate.optional(),\n    nonce: z.string().optional(),\n    jti: z.string().optional(),\n    sub: z.string().optional(),\n\n    cnf: zJwtConfirmationPayload.optional(),\n\n    // Reserved for status parameters\n    status: z.record(z.string(), z.any()).optional(),\n\n    // Reserved for OpenID Federation\n    trust_chain: z.tuple([z.string()], z.string()).optional(),\n  })\n  .loose()\n\nexport type JwtPayload = z.infer<typeof zJwtPayload>\n\nexport const zJwtHeader = z\n  .object({\n    alg: zAlgValueNotNone,\n    typ: z.string().optional(),\n\n    kid: z.string().optional(),\n    jwk: zJwk.optional(),\n    x5c: z.array(z.string()).optional(),\n\n    // Reserved for OpenID Federation\n    trust_chain: z.tuple([z.string()], z.string()).optional(),\n  })\n  .loose()\n\nexport type JwtHeader = z.infer<typeof zJwtHeader>\n","import {\n  type BaseSchema,\n  decodeBase64,\n  encodeToUtf8String,\n  parseWithErrorHandling,\n  stringToJsonWithErrorHandling,\n} from '@openid4vc/utils'\nimport { Oauth2JwtParseError } from '../../error/Oauth2JwtParseError'\nimport type { InferSchemaOrDefaultOutput } from './decode-jwt'\nimport { zJwtHeader } from './z-jwt'\n\nexport interface DecodeJwtHeaderOptions<HeaderSchema extends BaseSchema | undefined> {\n  /**\n   * The comapct encoded jwt\n   */\n  jwt: string\n\n  /**\n   * Schema to use for validating the header. If not provided the\n   * default `vJwtHeader` schema will be used\n   */\n  headerSchema?: HeaderSchema\n}\n\nexport type DecodeJwtHeaderResult<HeaderSchema extends BaseSchema | undefined = undefined> = {\n  header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n}\n\nexport function decodeJwtHeader<HeaderSchema extends BaseSchema | undefined = undefined>(\n  options: DecodeJwtHeaderOptions<HeaderSchema>\n): DecodeJwtHeaderResult<HeaderSchema> {\n  const jwtParts = options.jwt.split('.')\n  if (jwtParts.length <= 2) {\n    throw new Oauth2JwtParseError('Jwt is not a valid jwt, unable to decode')\n  }\n\n  let headerJson: Record<string, unknown>\n  try {\n    headerJson = stringToJsonWithErrorHandling(\n      encodeToUtf8String(decodeBase64(jwtParts[0])),\n      'Unable to parse jwt header to JSON'\n    )\n  } catch (error) {\n    throw new Oauth2JwtParseError(`Error parsing JWT. ${error instanceof Error ? error.message : ''}`)\n  }\n\n  const header = parseWithErrorHandling(options.headerSchema ?? zJwtHeader, headerJson) as InferSchemaOrDefaultOutput<\n    HeaderSchema,\n    typeof zJwtHeader\n  >\n\n  return {\n    header,\n  }\n}\n","import {\n  type BaseSchema,\n  decodeBase64,\n  encodeToUtf8String,\n  parseWithErrorHandling,\n  stringToJsonWithErrorHandling,\n} from '@openid4vc/utils'\nimport type z from 'zod'\nimport { Oauth2Error } from '../../error/Oauth2Error'\nimport { Oauth2JwtParseError } from '../../error/Oauth2JwtParseError'\nimport { decodeJwtHeader } from './decode-jwt-header'\nimport { type JwtSigner, type zJwtHeader, zJwtPayload } from './z-jwt'\nexport interface DecodeJwtOptions<\n  HeaderSchema extends BaseSchema | undefined,\n  PayloadSchema extends BaseSchema | undefined,\n> {\n  /**\n   * The comapct encoded jwt\n   */\n  jwt: string\n\n  /**\n   * Schema to use for validating the header. If not provided the\n   * default `zJwtHeader` schema will be used\n   */\n  headerSchema?: HeaderSchema\n\n  /**\n   * Schema to use for validating the payload. If not provided the\n   * default `zJwtPayload` schema will be used\n   */\n  payloadSchema?: PayloadSchema\n}\n\nexport type DecodeJwtResult<\n  HeaderSchema extends BaseSchema | undefined = undefined,\n  PayloadSchema extends BaseSchema | undefined = undefined,\n> = {\n  header: InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>\n  payload: InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>\n  signature: string\n  compact: string\n}\n\nexport function decodeJwt<\n  HeaderSchema extends BaseSchema | undefined = undefined,\n  PayloadSchema extends BaseSchema | undefined = undefined,\n>(options: DecodeJwtOptions<HeaderSchema, PayloadSchema>): DecodeJwtResult<HeaderSchema, PayloadSchema> {\n  const jwtParts = options.jwt.split('.')\n  if (jwtParts.length !== 3) {\n    throw new Oauth2JwtParseError('Jwt is not a valid jwt, unable to decode')\n  }\n\n  let payloadJson: Record<string, unknown>\n  try {\n    payloadJson = stringToJsonWithErrorHandling(\n      encodeToUtf8String(decodeBase64(jwtParts[1])),\n      'Unable to parse jwt payload to JSON'\n    )\n  } catch (error) {\n    throw new Oauth2JwtParseError(`Error parsing JWT. ${error instanceof Error ? error.message : ''}`)\n  }\n\n  const { header } = decodeJwtHeader({ jwt: options.jwt, headerSchema: options.headerSchema })\n  const payload = parseWithErrorHandling(options.payloadSchema ?? zJwtPayload, payloadJson)\n\n  return {\n    header: header as InferSchemaOrDefaultOutput<HeaderSchema, typeof zJwtHeader>,\n    payload: payload as InferSchemaOrDefaultOutput<PayloadSchema, typeof zJwtPayload>,\n    signature: jwtParts[2],\n    compact: options.jwt,\n  }\n}\n\nexport function jwtHeaderFromJwtSigner(signer: JwtSigner) {\n  if (signer.method === 'did') {\n    return {\n      alg: signer.alg,\n      kid: signer.didUrl,\n    } as const\n  }\n\n  if (signer.method === 'federation') {\n    return {\n      alg: signer.alg,\n      kid: signer.kid,\n      trust_chain: signer.trustChain,\n    } as const\n  }\n\n  if (signer.method === 'jwk') {\n    return {\n      alg: signer.alg,\n      jwk: signer.publicJwk,\n    } as const\n  }\n\n  if (signer.method === 'x5c') {\n    return {\n      alg: signer.alg,\n      x5c: signer.x5c,\n    } as const\n  }\n\n  return {\n    alg: signer.alg,\n  }\n}\n\nexport function jwtSignerFromJwt({\n  header,\n  payload,\n  allowedSignerMethods,\n}: Pick<DecodeJwtResult, 'header' | 'payload'> & { allowedSignerMethods?: JwtSigner['method'][] }): JwtSigner {\n  const found: Array<\n    | { method: JwtSigner['method']; signer: JwtSigner; valid: true }\n    | { method: JwtSigner['method']; error: string; valid: false }\n  > = []\n\n  if (header.x5c) {\n    found.push({\n      method: 'x5c',\n      valid: true,\n      signer: {\n        alg: header.alg,\n        method: 'x5c',\n        x5c: header.x5c,\n        kid: header.kid,\n      },\n    })\n  }\n\n  if (header.trust_chain) {\n    if (!header.kid) {\n      found.push({\n        method: 'federation',\n        valid: false,\n        error: `When 'trust_chain' is used in jwt header, the 'kid' parameter is required.`,\n      })\n    } else {\n      found.push({\n        method: 'federation',\n        valid: true,\n        signer: {\n          alg: header.alg,\n          trustChain: header.trust_chain,\n          kid: header.kid,\n          method: 'federation',\n        },\n      })\n    }\n  }\n\n  if (header.kid?.startsWith('did:') || payload.iss?.startsWith('did:')) {\n    // NOTE: special exclusion for openid4vci-proof+jwt type as it requires the `iss` to be set to the `client_id` in case\n    // of authorization code flow.\n    if (\n      payload.iss &&\n      header.kid?.startsWith('did:') &&\n      !header.kid.startsWith(payload.iss) &&\n      header.typ !== 'openid4vci-proof+jwt'\n    ) {\n      found.push({\n        method: 'did',\n        valid: false,\n        error: `kid in header starts with did that is different from did value in 'iss'`,\n      })\n    } else if (!header.kid?.startsWith('did:') && !header.kid?.startsWith('#')) {\n      found.push({\n        method: 'did',\n        valid: false,\n        error: `kid in header must start with either 'did:' or '#' when 'iss' value is a did`,\n      })\n    } else {\n      found.push({\n        method: 'did',\n        valid: true,\n        signer: {\n          method: 'did',\n          alg: header.alg,\n          didUrl: header.kid.startsWith('did:') ? header.kid : `${payload.iss}${header.kid}`,\n        },\n      })\n    }\n  }\n\n  if (header.jwk) {\n    found.push({\n      method: 'jwk',\n      signer: { alg: header.alg, method: 'jwk', publicJwk: header.jwk },\n      valid: true,\n    })\n  }\n\n  const allowedFoundMethods = found.filter((f) => !allowedSignerMethods || allowedSignerMethods?.includes(f.method))\n  const allowedValidMethods = allowedFoundMethods.filter((f) => f.valid)\n\n  if (allowedValidMethods.length > 0) {\n    // We found a valid method\n    return allowedValidMethods[0].signer\n  }\n\n  if (allowedFoundMethods.length > 0) {\n    throw new Oauth2Error(\n      `Unable to extract signer method from jwt. Found ${allowedFoundMethods.length} allowed signer method(s) but contained invalid configuration:\\n${allowedFoundMethods.map((m) => (m.valid ? '' : `FAILED: method ${m.method} - ${m.error}`)).join('\\n')}`\n    )\n  }\n\n  // Found x5c, allowed jwk\n  if (found.length > 0) {\n    throw new Oauth2Error(\n      `Unable to extract signer method from jwt. Found ${found.length} signer method(s) that are not allowed:\\n${found.map((m) => (m.valid ? `SUCCEEDED: method ${m.method}` : `FAILED: method ${m.method} - ${m.error}`)).join('\\n')}`\n    )\n  }\n\n  if (!allowedSignerMethods || allowedSignerMethods.includes('custom')) {\n    return {\n      method: 'custom',\n      alg: header.alg,\n      kid: header.kid,\n    }\n  }\n\n  throw new Oauth2Error(\n    `Unable to extract signer method from jwt. Found no signer methods and 'custom' signer method is not allowed.`\n  )\n}\n\n// Helper type to check if a schema is provided\ntype IsSchemaProvided<T> = T extends undefined ? false : true\n\n// Helper type to infer the output type based on whether a schema is provided\nexport type InferSchemaOrDefaultOutput<\n  ProvidedSchema extends BaseSchema | undefined,\n  DefaultSchema extends BaseSchema,\n> =\n  IsSchemaProvided<ProvidedSchema> extends true\n    ? ProvidedSchema extends BaseSchema\n      ? z.infer<ProvidedSchema>\n      : never\n    : z.infer<DefaultSchema>\n","import { Oauth2Error, type Oauth2ErrorOptions } from './Oauth2Error'\n\nexport class Oauth2JwtVerificationError extends Oauth2Error {\n  public constructor(message?: string, options?: Oauth2ErrorOptions) {\n    const errorMessage = message ?? 'Error verifying jwt.'\n\n    super(errorMessage, options)\n  }\n}\n","import { dateToSeconds } from '@openid4vc/utils'\nimport type { VerifyJwtCallback } from '../../callbacks'\nimport { Oauth2JwtVerificationError } from '../../error/Oauth2JwtVerificationError'\nimport type { Jwk } from '../jwk/z-jwk'\nimport type { JwtHeader, JwtPayload, JwtSigner, JwtSignerWithJwk } from './z-jwt'\n\nexport interface VerifyJwtOptions {\n  /**\n   * Compact jwt\n   */\n  compact: string\n\n  /**\n   * Header of the jwt\n   */\n  header: JwtHeader\n\n  /**\n   * Payload of the jwt.\n   */\n  payload: JwtPayload\n\n  /**\n   * If not provided current time will be used.\n   *\n   * @default new Date()\n   */\n  now?: Date\n\n  /**\n   * Whether to skip time based validation of `nbf` and `exp`.\n   * @default false\n   */\n  skipTimeBasedValidation?: boolean\n\n  /**\n   * Callback to verify jwt signature\n   */\n  verifyJwtCallback: VerifyJwtCallback\n\n  /**\n   * Signer of the jwt\n   */\n  signer: JwtSigner\n\n  /**\n   * Custom error message\n   */\n  errorMessage?: string\n\n  /**\n   * Allowed skew time in seconds for validity of token. Used for `exp` and `nbf`\n   * verification.\n   *\n   * @default 0\n   */\n  allowedSkewInSeconds?: number\n\n  /**\n   * Expected value for the 'aud' claim\n   */\n  expectedAudience?: string\n\n  /**\n   * Expected value for the 'iss' claim\n   */\n  expectedIssuer?: string\n\n  /**\n   * Expected value for the 'nonce' claim\n   */\n  expectedNonce?: string\n\n  /**\n   * Expected value for the 'sub' claim\n   */\n  expectedSubject?: string\n\n  /**\n   * The claims that are required to be present in the jwt.\n   */\n  requiredClaims?: string[]\n}\n\nexport interface VerifyJwtReturn {\n  signer: JwtSignerWithJwk\n}\n\nexport async function verifyJwt(options: VerifyJwtOptions): Promise<VerifyJwtReturn> {\n  const errorMessage = options.errorMessage ?? 'Error during verification of jwt.'\n\n  let signerJwk: Jwk\n  try {\n    const result = await options.verifyJwtCallback(options.signer, {\n      header: options.header,\n      payload: options.payload,\n      compact: options.compact,\n    })\n\n    if (!result.verified) throw new Oauth2JwtVerificationError(errorMessage)\n    signerJwk = result.signerJwk\n  } catch (error) {\n    if (error instanceof Oauth2JwtVerificationError) throw error\n    throw new Oauth2JwtVerificationError(errorMessage, { cause: error })\n  }\n\n  const nowInSeconds = dateToSeconds(options.now ?? new Date())\n  const skewInSeconds = options.allowedSkewInSeconds ?? 0\n  const timeBasedValidation = options.skipTimeBasedValidation !== undefined ? !options.skipTimeBasedValidation : true\n\n  if (timeBasedValidation && options.payload.nbf && nowInSeconds < options.payload.nbf - skewInSeconds) {\n    throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'nbf' is in the future`)\n  }\n\n  if (timeBasedValidation && options.payload.exp && nowInSeconds > options.payload.exp + skewInSeconds) {\n    throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'exp' is in the past`)\n  }\n\n  if (options.expectedAudience) {\n    if (\n      (Array.isArray(options.payload.aud) && !options.payload.aud.includes(options.expectedAudience)) ||\n      (typeof options.payload.aud === 'string' && options.payload.aud !== options.expectedAudience)\n    ) {\n      throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'aud' does not match expected value.`)\n    }\n  }\n\n  if (options.expectedIssuer && options.expectedIssuer !== options.payload.iss) {\n    throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'iss' does not match expected value.`)\n  }\n\n  if (options.expectedNonce && options.expectedNonce !== options.payload.nonce) {\n    throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'nonce' does not match expected value.`)\n  }\n\n  if (options.expectedSubject && options.expectedSubject !== options.payload.sub) {\n    throw new Oauth2JwtVerificationError(`${errorMessage} jwt 'sub' does not match expected value.`)\n  }\n\n  if (options.requiredClaims) {\n    for (const claim of options.requiredClaims) {\n      if (!options.payload[claim]) {\n        throw new Oauth2JwtVerificationError(`${errorMessage} jwt '${claim}' is missing.`)\n      }\n    }\n  }\n\n  return {\n    signer: {\n      ...options.signer,\n      publicJwk: signerJwk,\n    },\n  }\n}\n","// lib/v4/isZodErrorLike.ts\nfunction isZodErrorLike(err) {\n  return err instanceof Object && \"name\" in err && (err.name === \"ZodError\" || err.name === \"$ZodError\") && \"issues\" in err && Array.isArray(err.issues);\n}\n\n// lib/v4/ValidationError.ts\nvar ZOD_VALIDATION_ERROR_NAME = \"ZodValidationError\";\nvar ValidationError = class extends Error {\n  name;\n  details;\n  constructor(message, options) {\n    super(message, options);\n    this.name = ZOD_VALIDATION_ERROR_NAME;\n    this.details = getIssuesFromErrorOptions(options);\n  }\n  toString() {\n    return this.message;\n  }\n};\nfunction getIssuesFromErrorOptions(options) {\n  if (options) {\n    const cause = options.cause;\n    if (isZodErrorLike(cause)) {\n      return cause.issues;\n    }\n  }\n  return [];\n}\n\n// lib/v4/isValidationError.ts\nfunction isValidationError(err) {\n  return err instanceof ValidationError;\n}\n\n// lib/v4/isValidationErrorLike.ts\nfunction isValidationErrorLike(err) {\n  return err instanceof Error && err.name === ZOD_VALIDATION_ERROR_NAME;\n}\n\n// lib/v4/errorMap/custom.ts\nfunction parseCustomIssue(issue) {\n  return {\n    type: issue.code,\n    path: issue.path,\n    message: issue.message ?? \"Invalid input\"\n  };\n}\n\n// lib/v4/errorMap/invalidElement.ts\nfunction parseInvalidElementIssue(issue) {\n  return {\n    type: issue.code,\n    path: issue.path,\n    message: `unexpected element in ${issue.origin}`\n  };\n}\n\n// lib/v4/errorMap/invalidKey.ts\nfunction parseInvalidKeyIssue(issue) {\n  return {\n    type: issue.code,\n    path: issue.path,\n    message: `unexpected key in ${issue.origin}`\n  };\n}\n\n// lib/utils/prependWithAOrAn.ts\nvar vowelSoundCharSet = /* @__PURE__ */ new Set([\"a\", \"e\", \"i\", \"o\", \"u\", \"h\"]);\nfunction prependWithAOrAn(value) {\n  const firstLetter = value.charAt(0).toLowerCase();\n  const prefix = vowelSoundCharSet.has(firstLetter) ? \"an\" : \"a\";\n  return [prefix, value].join(\" \");\n}\n\n// lib/utils/stringify.ts\nfunction stringifySymbol(symbol) {\n  return symbol.description ?? \"\";\n}\nfunction stringify(value, options = {}) {\n  switch (typeof value) {\n    case \"symbol\":\n      return stringifySymbol(value);\n    case \"bigint\":\n    case \"number\": {\n      switch (options.localization) {\n        case true:\n          return value.toLocaleString();\n        case false:\n          return value.toString();\n        default:\n          return value.toLocaleString(options.localization);\n      }\n    }\n    case \"string\": {\n      if (options.wrapStringValueInQuote) {\n        return `\"${value}\"`;\n      }\n      return value;\n    }\n    default: {\n      if (value instanceof Date) {\n        switch (options.localization) {\n          case true:\n            return value.toLocaleString();\n          case false:\n            return value.toISOString();\n          default:\n            return value.toLocaleString(options.localization);\n        }\n      }\n      return String(value);\n    }\n  }\n}\n\n// lib/v4/errorMap/invalidStringFormat.ts\nfunction parseInvalidStringFormatIssue(issue, options) {\n  let message = \"\";\n  switch (issue.format) {\n    case \"lowercase\":\n    case \"uppercase\":\n      message += `expected ${issue.format} string`;\n      break;\n    case \"starts_with\": {\n      message += `expected string to start with \"${issue.prefix}\"`;\n      break;\n    }\n    case \"ends_with\": {\n      message += `expected string to end with \"${issue.suffix}\"`;\n      break;\n    }\n    case \"includes\": {\n      message += `expected string to include \"${issue.includes}\"`;\n      break;\n    }\n    case \"regex\": {\n      message += \"expected string to match pattern\";\n      if (options.displayInvalidFormatDetails) {\n        message += ` \"${issue.pattern}\"`;\n      }\n      break;\n    }\n    case \"jwt\": {\n      message += \"expected a jwt\";\n      if (options.displayInvalidFormatDetails && issue.inst && \"alg\" in issue.inst._zod.def) {\n        message += `/${issue.inst._zod.def.alg}`;\n      }\n      message += \" token\";\n      break;\n    }\n    case \"email\": {\n      message += \"expected an email address\";\n      break;\n    }\n    case \"url\":\n    case \"uuid\":\n    case \"guid\":\n    case \"cuid\":\n    case \"cuid2\":\n    case \"ulid\":\n    case \"xid\":\n    case \"ksuid\": {\n      message += `expected a ${issue.format.toUpperCase()}`;\n      if (issue.inst && \"version\" in issue.inst._zod.def) {\n        message += ` ${issue.inst._zod.def.version}`;\n      }\n      break;\n    }\n    case \"date\":\n    case \"datetime\":\n    case \"time\":\n    case \"duration\": {\n      message += `expected an ISO ${issue.format}`;\n      break;\n    }\n    case \"ipv4\":\n    case \"ipv6\": {\n      message += `expected an ${issue.format.slice(0, 2).toUpperCase()}${issue.format.slice(2)} address`;\n      break;\n    }\n    case \"cidrv4\":\n    case \"cidrv6\": {\n      message += `expected a ${issue.format.slice(0, 4).toUpperCase()}${issue.format.slice(4)} address range`;\n      break;\n    }\n    case \"base64\":\n    case \"base64url\": {\n      message += `expected a ${issue.format} encoded string`;\n      break;\n    }\n    case \"e164\": {\n      message += \"expected an E.164 formatted phone number\";\n      break;\n    }\n    default: {\n      if (issue.format.startsWith(\"sha\") || issue.format.startsWith(\"md5\")) {\n        const [alg, encoding] = issue.format.split(\"_\");\n        message += `expected a ${alg.toUpperCase()}`;\n        if (encoding) {\n          message += ` ${encoding}-encoded`;\n        }\n        message += ` hash`;\n        break;\n      }\n      message += `expected ${prependWithAOrAn(issue.format)}`;\n    }\n  }\n  if (\"input\" in issue && options.reportInput === \"typeAndValue\") {\n    const valueStr = stringify(issue.input, {\n      wrapStringValueInQuote: true,\n      localization: options.numberLocalization\n    });\n    message += `, received ${valueStr}`;\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\n\n// lib/utils/isPrimitive.ts\nfunction isPrimitive(value) {\n  if (value === null) {\n    return true;\n  }\n  switch (typeof value) {\n    case \"string\":\n    case \"number\":\n    case \"bigint\":\n    case \"boolean\":\n    case \"symbol\":\n    case \"undefined\":\n      return true;\n    default:\n      return false;\n  }\n}\n\n// lib/v4/errorMap/invalidType.ts\nfunction parseInvalidTypeIssue(issue, options) {\n  let message = `expected ${issue.expected}`;\n  if (\"input\" in issue && options.reportInput !== false) {\n    const value = issue.input;\n    message += `, received ${getTypeName(value)}`;\n    if (options.reportInput === \"typeAndValue\") {\n      if (isPrimitive(value)) {\n        const valueStr = stringify(value, {\n          wrapStringValueInQuote: true,\n          localization: options.numberLocalization\n        });\n        message += ` (${valueStr})`;\n      } else if (value instanceof Date) {\n        const valueStr = stringify(value, {\n          localization: options.dateLocalization\n        });\n        message += ` (${valueStr})`;\n      }\n    }\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\nfunction getTypeName(value) {\n  if (typeof value === \"object\") {\n    if (value === null) {\n      return \"null\";\n    }\n    if (value === void 0) {\n      return \"undefined\";\n    }\n    if (Array.isArray(value)) {\n      return \"array\";\n    }\n    if (value instanceof Date) {\n      return \"date\";\n    }\n    if (value instanceof RegExp) {\n      return \"regexp\";\n    }\n    if (value instanceof Map) {\n      return \"map\";\n    }\n    if (value instanceof Set) {\n      return \"set\";\n    }\n    if (value instanceof Error) {\n      return \"error\";\n    }\n    if (value instanceof Function) {\n      return \"function\";\n    }\n    return \"object\";\n  }\n  return typeof value;\n}\n\n// lib/v4/errorMap/invalidUnion.ts\nfunction parseInvalidUnionIssue(issue) {\n  return {\n    type: issue.code,\n    path: issue.path,\n    message: issue.message ?? \"Invalid input\"\n  };\n}\n\n// lib/utils/joinValues.ts\nfunction joinValues(values, options) {\n  const valuesToDisplay = (options.maxValuesToDisplay ? values.slice(0, options.maxValuesToDisplay) : values).map((value) => {\n    return stringify(value, {\n      wrapStringValueInQuote: options.wrapStringValuesInQuote\n    });\n  });\n  if (valuesToDisplay.length < values.length) {\n    valuesToDisplay.push(\n      `${values.length - valuesToDisplay.length} more value(s)`\n    );\n  }\n  return valuesToDisplay.reduce((acc, value, index) => {\n    if (index > 0) {\n      if (index === valuesToDisplay.length - 1 && options.lastSeparator) {\n        acc += options.lastSeparator;\n      } else {\n        acc += options.separator;\n      }\n    }\n    acc += value;\n    return acc;\n  }, \"\");\n}\n\n// lib/v4/errorMap/invalidValue.ts\nfunction parseInvalidValueIssue(issue, options) {\n  let message;\n  if (issue.expected === \"stringbool\") {\n    message = \"expected boolean as string\";\n  } else if (issue.values.length === 0) {\n    message = \"invalid value\";\n  } else if (issue.values.length === 1) {\n    const valueStr = stringify(issue.values[0], {\n      wrapStringValueInQuote: true\n    });\n    message = `expected value to be ${valueStr}`;\n  } else {\n    const valuesStr = joinValues(issue.values, {\n      separator: options.allowedValuesSeparator,\n      lastSeparator: options.allowedValuesLastSeparator,\n      wrapStringValuesInQuote: options.wrapAllowedValuesInQuote,\n      maxValuesToDisplay: options.maxAllowedValuesToDisplay\n    });\n    message = `expected value to be one of ${valuesStr}`;\n  }\n  if (\"input\" in issue && options.reportInput === \"typeAndValue\") {\n    if (isPrimitive(issue.input)) {\n      const valueStr = stringify(issue.input, {\n        wrapStringValueInQuote: true,\n        localization: options.numberLocalization\n      });\n      message += `, received ${valueStr}`;\n    } else if (issue.input instanceof Date) {\n      const valueStr = stringify(issue.input, {\n        localization: options.dateLocalization\n      });\n      message += `, received ${valueStr}`;\n    }\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\n\n// lib/v4/errorMap/notMultipleOf.ts\nfunction parseNotMultipleOfIssue(issue, options) {\n  let message = `expected multiple of ${issue.divisor}`;\n  if (\"input\" in issue && options.reportInput === \"typeAndValue\") {\n    const valueStr = stringify(issue.input, {\n      wrapStringValueInQuote: true,\n      localization: options.numberLocalization\n    });\n    message += `, received ${valueStr}`;\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\n\n// lib/v4/errorMap/tooBig.ts\nfunction parseTooBigIssue(issue, options) {\n  const maxValueStr = issue.origin === \"date\" ? stringify(new Date(issue.maximum), {\n    localization: options.dateLocalization\n  }) : stringify(issue.maximum, {\n    localization: options.numberLocalization\n  });\n  let message = \"\";\n  switch (issue.origin) {\n    case \"number\":\n    case \"int\":\n    case \"bigint\": {\n      message += `expected number to be less than${issue.inclusive ? \" or equal to\" : \"\"} ${maxValueStr}`;\n      break;\n    }\n    case \"string\": {\n      message += `expected string to contain at most ${maxValueStr} character(s)`;\n      break;\n    }\n    case \"date\": {\n      message += `expected date to be prior ${issue.inclusive ? \"or equal to\" : \"to\"} \"${maxValueStr}\"`;\n      break;\n    }\n    case \"array\": {\n      message += `expected array to contain at most ${maxValueStr} item(s)`;\n      break;\n    }\n    case \"set\": {\n      message += `expected set to contain at most ${maxValueStr} item(s)`;\n      break;\n    }\n    case \"file\": {\n      message += `expected file to not exceed ${maxValueStr} byte(s) in size`;\n      break;\n    }\n    default: {\n      message += `expected value to be less than${issue.inclusive ? \" or equal to\" : \"\"} ${maxValueStr}`;\n    }\n  }\n  if (\"input\" in issue && options.reportInput === \"typeAndValue\") {\n    const value = issue.input;\n    if (isPrimitive(value)) {\n      const valueStr = stringify(value, {\n        wrapStringValueInQuote: true,\n        localization: options.numberLocalization\n      });\n      message += `, received ${valueStr}`;\n    } else if (value instanceof Date) {\n      const valueStr = stringify(value, {\n        localization: options.dateLocalization\n      });\n      message += `, received ${valueStr}`;\n    }\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\n\n// lib/v4/errorMap/tooSmall.ts\nfunction parseTooSmallIssue(issue, options) {\n  const minValueStr = issue.origin === \"date\" ? stringify(new Date(issue.minimum), {\n    localization: options.dateLocalization\n  }) : stringify(issue.minimum, {\n    localization: options.numberLocalization\n  });\n  let message = \"\";\n  switch (issue.origin) {\n    case \"number\":\n    case \"int\":\n    case \"bigint\": {\n      message += `expected number to be greater than${issue.inclusive ? \" or equal to\" : \"\"} ${minValueStr}`;\n      break;\n    }\n    case \"date\": {\n      message += `expected date to be ${issue.inclusive ? \"later or equal to\" : \"later to\"} \"${minValueStr}\"`;\n      break;\n    }\n    case \"string\": {\n      message += `expected string to contain at least ${minValueStr} character(s)`;\n      break;\n    }\n    case \"array\": {\n      message += `expected array to contain at least ${minValueStr} item(s)`;\n      break;\n    }\n    case \"set\": {\n      message += `expected set to contain at least ${minValueStr} item(s)`;\n      break;\n    }\n    case \"file\": {\n      message += `expected file to be at least ${minValueStr} byte(s) in size`;\n      break;\n    }\n    default:\n      message += `expected value to be greater than${issue.inclusive ? \" or equal to\" : \"\"} ${minValueStr}`;\n  }\n  if (\"input\" in issue && options.reportInput === \"typeAndValue\") {\n    const value = issue.input;\n    if (isPrimitive(value)) {\n      const valueStr = stringify(value, {\n        wrapStringValueInQuote: true,\n        localization: options.numberLocalization\n      });\n      message += `, received ${valueStr}`;\n    } else if (value instanceof Date) {\n      const valueStr = stringify(value, {\n        localization: options.dateLocalization\n      });\n      message += `, received ${valueStr}`;\n    }\n  }\n  return {\n    type: issue.code,\n    path: issue.path,\n    message\n  };\n}\n\n// lib/v4/errorMap/unrecognizedKeys.ts\nfunction parseUnrecognizedKeysIssue(issue, options) {\n  const keysStr = joinValues(issue.keys, {\n    separator: options.unrecognizedKeysSeparator,\n    lastSeparator: options.unrecognizedKeysLastSeparator,\n    wrapStringValuesInQuote: options.wrapUnrecognizedKeysInQuote,\n    maxValuesToDisplay: options.maxUnrecognizedKeysToDisplay\n  });\n  return {\n    type: issue.code,\n    path: issue.path,\n    message: `unrecognized key(s) ${keysStr} in object`\n  };\n}\n\n// lib/v4/errorMap/errorMap.ts\nvar issueParsers = {\n  invalid_type: parseInvalidTypeIssue,\n  too_big: parseTooBigIssue,\n  too_small: parseTooSmallIssue,\n  invalid_format: parseInvalidStringFormatIssue,\n  invalid_value: parseInvalidValueIssue,\n  invalid_element: parseInvalidElementIssue,\n  not_multiple_of: parseNotMultipleOfIssue,\n  unrecognized_keys: parseUnrecognizedKeysIssue,\n  invalid_key: parseInvalidKeyIssue,\n  custom: parseCustomIssue,\n  invalid_union: parseInvalidUnionIssue\n};\nvar defaultErrorMapOptions = {\n  reportInput: \"type\",\n  displayInvalidFormatDetails: false,\n  allowedValuesSeparator: \", \",\n  allowedValuesLastSeparator: \" or \",\n  wrapAllowedValuesInQuote: true,\n  maxAllowedValuesToDisplay: 10,\n  unrecognizedKeysSeparator: \", \",\n  unrecognizedKeysLastSeparator: \" and \",\n  wrapUnrecognizedKeysInQuote: true,\n  maxUnrecognizedKeysToDisplay: 5,\n  dateLocalization: true,\n  numberLocalization: true\n};\nfunction createErrorMap(partialOptions = {}) {\n  const options = {\n    ...defaultErrorMapOptions,\n    ...partialOptions\n  };\n  const errorMap = (issue) => {\n    if (issue.code === void 0) {\n      return \"Not supported issue type\";\n    }\n    const parseFunc = issueParsers[issue.code];\n    const ast = parseFunc(issue, options);\n    return ast.message;\n  };\n  return errorMap;\n}\n\n// lib/utils/NonEmptyArray.ts\nfunction isNonEmptyArray(value) {\n  return value.length !== 0;\n}\n\n// lib/utils/joinPath.ts\nvar identifierRegex = /[$_\\p{ID_Start}][$\\u200c\\u200d\\p{ID_Continue}]*/u;\nfunction joinPath(path) {\n  if (path.length === 1) {\n    let propertyKey = path[0];\n    if (typeof propertyKey === \"symbol\") {\n      propertyKey = stringifySymbol(propertyKey);\n    }\n    return propertyKey.toString() || '\"\"';\n  }\n  return path.reduce((acc, propertyKey) => {\n    if (typeof propertyKey === \"number\") {\n      return acc + \"[\" + propertyKey.toString() + \"]\";\n    }\n    if (typeof propertyKey === \"symbol\") {\n      propertyKey = stringifySymbol(propertyKey);\n    }\n    if (propertyKey.includes('\"')) {\n      return acc + '[\"' + escapeQuotes(propertyKey) + '\"]';\n    }\n    if (!identifierRegex.test(propertyKey)) {\n      return acc + '[\"' + propertyKey + '\"]';\n    }\n    const separator = acc.length === 0 ? \"\" : \".\";\n    return acc + separator + propertyKey;\n  }, \"\");\n}\nfunction escapeQuotes(str) {\n  return str.replace(/\"/g, '\\\\\"');\n}\n\n// lib/utils/titleCase.ts\nfunction titleCase(value) {\n  if (value.length === 0) {\n    return value;\n  }\n  return value.charAt(0).toUpperCase() + value.slice(1);\n}\n\n// lib/v4/MessageBuilder.ts\nvar defaultMessageBuilderOptions = {\n  prefix: \"Validation error\",\n  prefixSeparator: \": \",\n  maxIssuesInMessage: 99,\n  // I've got 99 problems but the b$tch ain't one\n  unionSeparator: \" or \",\n  issueSeparator: \"; \",\n  includePath: true,\n  forceTitleCase: true\n};\nfunction createMessageBuilder(partialOptions = {}) {\n  const options = {\n    ...defaultMessageBuilderOptions,\n    ...partialOptions\n  };\n  return function messageBuilder(issues) {\n    const message = issues.slice(0, options.maxIssuesInMessage).map((issue) => mapIssue(issue, options)).join(options.issueSeparator);\n    return conditionallyPrefixMessage(message, options);\n  };\n}\nfunction mapIssue(issue, options) {\n  if (issue.code === \"invalid_union\" && isNonEmptyArray(issue.errors)) {\n    const individualMessages = issue.errors.map(\n      (issues) => issues.map(\n        (subIssue) => mapIssue(\n          {\n            ...subIssue,\n            path: issue.path.concat(subIssue.path)\n          },\n          options\n        )\n      ).join(options.issueSeparator)\n    );\n    return Array.from(new Set(individualMessages)).join(options.unionSeparator);\n  }\n  const buf = [];\n  if (options.forceTitleCase) {\n    buf.push(titleCase(issue.message));\n  } else {\n    buf.push(issue.message);\n  }\n  pathCondition: if (options.includePath && issue.path !== void 0 && isNonEmptyArray(issue.path)) {\n    if (issue.path.length === 1) {\n      const identifier = issue.path[0];\n      if (typeof identifier === \"number\") {\n        buf.push(` at index ${identifier}`);\n        break pathCondition;\n      }\n    }\n    buf.push(` at \"${joinPath(issue.path)}\"`);\n  }\n  return buf.join(\"\");\n}\nfunction conditionallyPrefixMessage(message, options) {\n  if (options.prefix != null) {\n    if (message.length > 0) {\n      return [options.prefix, message].join(options.prefixSeparator);\n    }\n    return options.prefix;\n  }\n  if (message.length > 0) {\n    return message;\n  }\n  return defaultMessageBuilderOptions.prefix;\n}\n\n// lib/v4/fromZodError.ts\nfunction fromZodError(zodError, options = {}) {\n  if (!isZodErrorLike(zodError)) {\n    throw new TypeError(\n      `Invalid zodError param; expected instance of ZodError. Did you mean to use the \"${fromError.name}\" method instead?`\n    );\n  }\n  return fromZodErrorWithoutRuntimeCheck(zodError, options);\n}\nfunction fromZodErrorWithoutRuntimeCheck(zodError, options = {}) {\n  const zodIssues = zodError.issues;\n  let message;\n  if (isNonEmptyArray(zodIssues)) {\n    const messageBuilder = createMessageBuilderFromOptions(options);\n    message = messageBuilder(zodIssues);\n  } else {\n    message = zodError.message;\n  }\n  return new ValidationError(message, { cause: zodError });\n}\nfunction createMessageBuilderFromOptions(options) {\n  if (\"messageBuilder\" in options) {\n    return options.messageBuilder;\n  }\n  return createMessageBuilder(options);\n}\n\n// lib/v4/toValidationError.ts\nvar toValidationError = (options = {}) => (err) => {\n  if (isZodErrorLike(err)) {\n    return fromZodErrorWithoutRuntimeCheck(err, options);\n  }\n  if (err instanceof Error) {\n    return new ValidationError(err.message, { cause: err });\n  }\n  return new ValidationError(\"Unknown error\");\n};\n\n// lib/v4/fromError.ts\nfunction fromError(err, options = {}) {\n  return toValidationError(options)(err);\n}\n\n// lib/v4/fromZodIssue.ts\nimport * as zod from \"zod/v4/core\";\nfunction fromZodIssue(issue, options = {}) {\n  const messageBuilder = createMessageBuilderFromOptions2(options);\n  const message = messageBuilder([issue]);\n  return new ValidationError(message, {\n    cause: new zod.$ZodRealError([issue])\n  });\n}\nfunction createMessageBuilderFromOptions2(options) {\n  if (\"messageBuilder\" in options) {\n    return options.messageBuilder;\n  }\n  return createMessageBuilder(options);\n}\nexport {\n  ValidationError,\n  createErrorMap,\n  createMessageBuilder,\n  fromError,\n  fromZodError,\n  fromZodIssue,\n  isValidationError,\n  isValidationErrorLike,\n  isZodErrorLike,\n  toValidationError\n};\n//# sourceMappingURL=index.mjs.map","import z from 'zod'\nimport { createErrorMap, fromError } from 'zod-validation-error'\n\nz.config({\n  customError: createErrorMap(),\n})\n\nexport function formatZodError(error?: z.ZodError): string {\n  if (!error) return ''\n\n  return fromError(error, { prefix: '', prefixSeparator: '✖ ', issueSeparator: '\\n✖ ' }).toString()\n}\n","export abstract class OpenId4VcBaseError extends Error {}\n","import type { ZodError } from 'zod'\nimport { formatZodError } from '../zod-error'\nimport { OpenId4VcBaseError } from './OpenId4VcBaseError'\n\nexport class ValidationError extends OpenId4VcBaseError {\n  public zodError: ZodError | undefined\n\n  constructor(message: string, zodError?: ZodError) {\n    super(message)\n\n    const formattedError = zodError ? formatZodError(zodError) : ''\n    this.message = `${message}\\n${formattedError}`\n\n    Object.defineProperty(this, 'zodError', {\n      value: zodError,\n      writable: false,\n      enumerable: false,\n    })\n  }\n}\n","import { ContentType, createZodFetcher, type Fetch, InvalidFetchResponseError } from '@openid4vc/utils'\nimport { ValidationError } from '../../../utils/src/error/ValidationError'\nimport { type JwkSet, zJwkSet } from '../common/jwk/z-jwk'\n\n/**\n * Fetch JWKs from a provided JWKs URI.\n *\n * Returns validated metadata if successful response\n * Throws error otherwise\n *\n * @throws {ValidationError} if successful response but validation of response failed\n * @throws {InvalidFetchResponseError} if unsuccesful response\n */\nexport async function fetchJwks(jwksUrl: string, fetch?: Fetch): Promise<JwkSet> {\n  const fetcher = createZodFetcher(fetch)\n\n  const { result, response } = await fetcher(zJwkSet, [ContentType.JwkSet, ContentType.Json], jwksUrl)\n  if (!response.ok) {\n    throw new InvalidFetchResponseError(\n      `Fetching JWKs from jwks_uri '${jwksUrl}' resulted in an unsuccessful response with status code '${response.status}'.`,\n      await response.clone().text(),\n      response\n    )\n  }\n\n  if (!result?.success) {\n    throw new ValidationError(`Validation of JWKs from jwks_uri '${jwksUrl}' failed`, result?.error)\n  }\n\n  return result.data\n}\n","import { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zJwtHeader, zJwtPayload } from '../common/jwt/z-jwt'\n\nexport const zAccessTokenProfileJwtHeader = z\n  .object({\n    ...zJwtHeader.shape,\n    typ: z.enum(['application/at+jwt', 'at+jwt']),\n  })\n  .loose()\nexport type AccessTokenProfileJwtHeader = z.infer<typeof zAccessTokenProfileJwtHeader>\n\nexport const zAccessTokenProfileJwtPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    iss: z.string(),\n    exp: zNumericDate,\n    iat: zNumericDate,\n    aud: z.union([z.string(), z.array(z.string())]),\n    sub: z.string(),\n\n    // REQUIRED according to RFC 9068, but OpenID4VCI allows anonymous access\n    client_id: z.optional(z.string()),\n    jti: z.string(),\n\n    // SHOULD be included in the authorization request contained it\n    scope: z.optional(z.string()),\n  })\n  .loose()\n\nexport type AccessTokenProfileJwtPayload = z.infer<typeof zAccessTokenProfileJwtPayload>\n","import type { CallbackContext } from '../callbacks'\nimport { extractJwkFromJwksForJwt } from '../common/jwk/jwks'\nimport { decodeJwt } from '../common/jwt/decode-jwt'\nimport { verifyJwt } from '../common/jwt/verify-jwt'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { fetchJwks } from '../metadata/fetch-jwks-uri'\nimport { zAccessTokenProfileJwtHeader, zAccessTokenProfileJwtPayload } from './z-access-token-jwt'\n\nexport enum SupportedAuthenticationScheme {\n  Bearer = 'Bearer',\n  DPoP = 'DPoP',\n}\n\nexport interface VerifyJwtProfileAccessTokenOptions {\n  /**\n   * The access token\n   */\n  accessToken: string\n\n  /**\n   * Callbacks used for verifying the access token\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'fetch'>\n\n  /**\n   * If not provided current time will be used\n   */\n  now?: Date\n\n  /**\n   * Identifier of the resource server\n   */\n  resourceServer: string\n\n  /**\n   * List of authorization servers that this resource endpoint supports\n   */\n  authorizationServers: AuthorizationServerMetadata[]\n}\n\n/**\n * Verify an access token as a JWT Profile access token.\n *\n * @throws {@link ValidationError} if the JWT header or payload does not align with JWT Profile rules\n * @throws {@link Oauth2JwtParseError} if the jwt is not a valid jwt format, or the jwt header/payload cannot be parsed as JSON\n * @throws {@link Oauth2JwtVerificationError} if the JWT verification fails (signature or nbf/exp)\n * @throws {@link Oauth2JwtVerificationError} if the JWT verification fails (signature or nbf/exp)\n */\nexport async function verifyJwtProfileAccessToken(options: VerifyJwtProfileAccessTokenOptions) {\n  const decodedJwt = decodeJwt({\n    jwt: options.accessToken,\n    headerSchema: zAccessTokenProfileJwtHeader,\n    payloadSchema: zAccessTokenProfileJwtPayload,\n  })\n\n  const authorizationServer = options.authorizationServers.find(({ issuer }) => decodedJwt.payload.iss === issuer)\n  if (!authorizationServer) {\n    // Authorization server not found\n    throw new Oauth2Error(\n      `Access token jwt contains unrecognized authorization server 'iss' value of '${decodedJwt.payload.iss}'`\n    )\n  }\n\n  const jwksUrl = authorizationServer.jwks_uri\n  if (!jwksUrl) {\n    throw new Oauth2Error(\n      `Authorization server '${authorizationServer.issuer}' does not have a 'jwks_uri' parameter to fetch JWKs.`\n    )\n  }\n\n  const jwks = await fetchJwks(jwksUrl, options.callbacks.fetch)\n  const publicJwk = extractJwkFromJwksForJwt({\n    kid: decodedJwt.header.kid,\n    jwks,\n    use: 'sig',\n  })\n\n  await verifyJwt({\n    compact: options.accessToken,\n    header: decodedJwt.header,\n    payload: decodedJwt.payload,\n    signer: { method: 'jwk', publicJwk, alg: decodedJwt.header.alg },\n    verifyJwtCallback: options.callbacks.verifyJwt,\n    errorMessage: 'Error during verification of access token jwt.',\n    now: options.now,\n    expectedAudience: options.resourceServer,\n  })\n\n  return {\n    header: decodedJwt.header,\n    payload: decodedJwt.payload,\n    authorizationServer,\n  }\n}\n","import z from 'zod'\n\nexport enum Oauth2ErrorCodes {\n  ServerError = 'server_error',\n\n  // Resource Indicators\n  InvalidTarget = 'invalid_target',\n\n  // Oauth2\n  InvalidRequest = 'invalid_request',\n  InvalidToken = 'invalid_token',\n  InsufficientScope = 'insufficient_scope',\n  InvalidGrant = 'invalid_grant',\n  InvalidClient = 'invalid_client',\n  UnauthorizedClient = 'unauthorized_client',\n  UnsupportedGrantType = 'unsupported_grant_type',\n  InvalidScope = 'invalid_scope',\n\n  // DPoP\n  InvalidDpopProof = 'invalid_dpop_proof',\n  UseDpopNonce = 'use_dpop_nonce',\n\n  // Client Attestation (draft 09)\n  UseAttestationChallenge = 'use_attestation_challenge',\n\n  // FiPA\n  RedirectToWeb = 'redirect_to_web',\n  InvalidSession = 'invalid_session',\n  InsufficientAuthorization = 'insufficient_authorization',\n\n  // OpenID4VCI\n  InvalidCredentialRequest = 'invalid_credential_request',\n  CredentialRequestDenied = 'credential_request_denied',\n  InvalidProof = 'invalid_proof',\n  InvalidNonce = 'invalid_nonce',\n  InvalidEncryptionParameters = 'invalid_encryption_parameters',\n  UnknownCredentialConfiguration = 'unknown_credential_configuration',\n  UnknownCredentialIdentifier = 'unknown_credential_identifier',\n  InvalidTransactionId = 'invalid_transaction_id',\n  // Removed from Draft 16+\n  UnsupportedCredentialType = 'unsupported_credential_type',\n  UnsupportedCredentialFormat = 'unsupported_credential_format',\n\n  // OpenID4VCI Interactive Authorization\n  MissingInteractionType = 'missing_interaction_type',\n\n  // Jar\n  InvalidRequestUri = 'invalid_request_uri',\n  InvalidRequestObject = 'invalid_request_object',\n  RequestNotSupported = 'request_not_supported',\n  RequestUriNotSupported = 'request_uri_not_supported',\n\n  // OpenID4VP\n  VpFormatsNotSupported = 'vp_formats_not_supported',\n  AccessDenied = 'access_denied',\n  InvalidPresentationDefinitionUri = 'invalid_presentation_definition_uri',\n  InvalidPresentationDefinitionReference = 'invalid_presentation_definition_reference',\n  InvalidRequestUriMethod = 'invalid_request_uri_method',\n  InvalidTransactionData = 'invalid_transaction_data',\n  WalletUnavailable = 'wallet_unavailable',\n}\n\nexport const zOauth2ErrorResponse = z\n  .object({\n    error: z.union([z.enum(Oauth2ErrorCodes), z.string()]),\n    error_description: z.string().optional(),\n    error_uri: z.string().optional(),\n  })\n  .loose()\n\nexport type Oauth2ErrorResponse = z.infer<typeof zOauth2ErrorResponse>\n","import type { Oauth2ErrorResponse } from '../common/z-oauth2-error'\nimport type { Oauth2ErrorOptions } from '../error/Oauth2Error'\nimport { Oauth2Error } from './Oauth2Error'\n\ninterface Oauth2ServerErrorResponseErrorOptions extends Oauth2ErrorOptions {\n  internalMessage?: string\n\n  /**\n   * @default 400\n   */\n  status?: number\n}\n\nexport class Oauth2ServerErrorResponseError extends Oauth2Error {\n  public readonly status: number\n\n  public constructor(\n    public readonly errorResponse: Oauth2ErrorResponse,\n    options?: Oauth2ServerErrorResponseErrorOptions\n  ) {\n    super(\n      `${options?.internalMessage ?? errorResponse.error_description}\\n${JSON.stringify(errorResponse, null, 2)}`,\n      options\n    )\n    this.status = options?.status ?? 400\n  }\n}\n","import { zHttpsUrl, zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zJwk } from '../common/jwk/z-jwk'\nimport { zJwtHeader, zJwtPayload } from '../common/jwt/z-jwt'\n\nexport const zOauthClientAttestationHeader = z.literal('OAuth-Client-Attestation')\nexport const oauthClientAttestationHeader = zOauthClientAttestationHeader.value\n\nexport const zClientAttestationJwtPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    sub: z.string(),\n    exp: zNumericDate,\n    cnf: z\n      .object({\n        jwk: zJwk,\n      })\n      .loose(),\n\n    // OID4VCI Wallet Attestation Extensions\n    wallet_name: z.string().optional(),\n    wallet_link: z.url().optional(),\n  })\n  .loose()\nexport type ClientAttestationJwtPayload = z.infer<typeof zClientAttestationJwtPayload>\n\nexport const zClientAttestationJwtHeader = z\n  .object({\n    ...zJwtHeader.shape,\n    typ: z.literal('oauth-client-attestation+jwt'),\n  })\n  .loose()\n\nexport type ClientAttestationJwtHeader = z.infer<typeof zClientAttestationJwtHeader>\n\nexport const zOauthClientAttestationPopHeader = z.literal('OAuth-Client-Attestation-PoP')\nexport const oauthClientAttestationPopHeader = zOauthClientAttestationPopHeader.value\n\n// draft 09: header used by the authorization/resource server to provide a fresh challenge.\nexport const zOauthClientAttestationChallengeHeader = z.literal('OAuth-Client-Attestation-Challenge')\nexport const oauthClientAttestationChallengeHeader = zOauthClientAttestationChallengeHeader.value\n\n// draft 09 §6.1: response body of the authorization server's `challenge_endpoint`.\nexport const zClientAttestationChallengeResponse = z.object({ attestation_challenge: z.string() }).loose()\nexport type ClientAttestationChallengeResponse = z.infer<typeof zClientAttestationChallengeResponse>\n\nexport const zClientAttestationPopJwtPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    aud: z.union([zHttpsUrl, z.array(zHttpsUrl)]),\n\n    jti: z.string(),\n\n    // `challenge` (draft 06+) replaced `nonce`. Both are accepted on verification; `nonce`\n    // is retained only for backwards compatibility with <= draft 05 PoP JWTs.\n    challenge: z.optional(z.string()),\n    nonce: z.optional(z.string()),\n  })\n  .loose()\nexport type ClientAttestationPopJwtPayload = z.infer<typeof zClientAttestationPopJwtPayload>\n\nexport const zClientAttestationPopJwtHeader = z\n  .object({\n    ...zJwtHeader.shape,\n    typ: z.literal('oauth-client-attestation-pop+jwt'),\n  })\n  .loose()\nexport type ClientAttestationPopJwtHeader = z.infer<typeof zClientAttestationPopJwtHeader>\n","import { dateToSeconds, encodeToBase64Url, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { decodeJwt } from '../common/jwt/decode-jwt'\nimport { verifyJwt } from '../common/jwt/verify-jwt'\nimport type { JwtSignerJwk } from '../common/jwt/z-jwt'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport {\n  type ClientAttestationJwtHeader,\n  type ClientAttestationJwtPayload,\n  type ClientAttestationPopJwtHeader,\n  type ClientAttestationPopJwtPayload,\n  oauthClientAttestationHeader,\n  oauthClientAttestationPopHeader,\n  zClientAttestationJwtHeader,\n  zClientAttestationJwtPayload,\n  zClientAttestationPopJwtHeader,\n  zClientAttestationPopJwtPayload,\n} from './z-client-attestation'\n\nexport interface RequestClientAttestationOptions {\n  /**\n   * The challenge provided by the authorization server to include in the client attestation pop jwt.\n   */\n  challenge?: string\n\n  /**\n   * @deprecated Renamed to `challenge` in draft 06. If `challenge` is not set, this value is used.\n   */\n  nonce?: string\n\n  /**\n   * The client attestation jwt to create the pop for.\n   */\n  jwt: string\n\n  /**\n   * The signer of the client attestation pop jwt.\n   *\n   * Will be extracted from the client attestation if not provided.\n   */\n  signer?: JwtSignerJwk\n}\n\nexport async function createClientAttestationForRequest(\n  options: { clientAttestation: RequestClientAttestationOptions } & Pick<\n    CreateClientAttestationPopJwtOptions,\n    'callbacks' | 'authorizationServer'\n  >\n) {\n  const clientAttestationPopJwt = await createClientAttestationPopJwt({\n    authorizationServer: options.authorizationServer,\n    clientAttestation: options.clientAttestation.jwt,\n    callbacks: options.callbacks,\n    signer: options.clientAttestation.signer,\n    // TODO: support dynamic fetching of the challenge from the `challenge_endpoint`\n    challenge: options.clientAttestation.challenge ?? options.clientAttestation.nonce,\n  })\n\n  return {\n    headers: {\n      [oauthClientAttestationHeader]: options.clientAttestation.jwt,\n      [oauthClientAttestationPopHeader]: clientAttestationPopJwt,\n    },\n  }\n}\n\nexport interface VerifyClientAttestationPopJwtOptions {\n  /**\n   * The compact client attestation pop jwt.\n   */\n  clientAttestationPopJwt: string\n\n  /**\n   * The issuer identifier of the authorization server handling the client attestation.\n   */\n  authorizationServer: string\n\n  /**\n   * The expected value of the `aud` claim. Defaults to `authorizationServer`.\n   *\n   * draft 09 allows the audience to be a Resource Server identifier URL in addition to the\n   * authorization server issuer URL; set this when verifying a PoP JWT at a resource server.\n   */\n  expectedAudience?: string\n\n  /**\n   * Expected challenge in the payload. If not provided the challenge won't be validated.\n   *\n   * Matched against the `challenge` claim (draft 06+) and, for backwards compatibility,\n   * the legacy `nonce` claim.\n   */\n  expectedChallenge?: string\n\n  /**\n   * @deprecated Renamed to `expectedChallenge` in draft 06. If `expectedChallenge` is not set,\n   * this value is used.\n   */\n  expectedNonce?: string\n\n  /**\n   * Date to use for expiration. If not provided current date will be used.\n   */\n  now?: Date\n\n  /**\n   * Allowed skew time in seconds for validity of token. Used for `exp` and `nbf`\n   * verification.\n   *\n   * @default 0\n   */\n  allowedSkewInSeconds?: number\n\n  /**\n   * Callbacks used for verifying client attestation pop jwt.\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt'>\n\n  /**\n   * The parsed and verified client attestation jwt\n   */\n  clientAttestation: {\n    header: ClientAttestationJwtHeader\n    payload: ClientAttestationJwtPayload\n  }\n}\n\nexport type VerifiedClientAttestationPopJwt = Awaited<ReturnType<typeof verifyClientAttestationPopJwt>>\nexport async function verifyClientAttestationPopJwt(options: VerifyClientAttestationPopJwtOptions) {\n  const { header, payload } = decodeJwt({\n    jwt: options.clientAttestationPopJwt,\n    headerSchema: zClientAttestationPopJwtHeader,\n    payloadSchema: zClientAttestationPopJwtPayload,\n  })\n\n  // `iss` was removed from the Client Attestation PoP JWT in draft 08. Only validate it against\n  // the client attestation `sub` when a legacy (<= draft 07) PoP JWT still includes it.\n  if (payload.iss !== undefined && payload.iss !== options.clientAttestation.payload.sub) {\n    throw new Oauth2Error(\n      `Client Attestation Pop jwt contains 'iss' (client_id) value '${payload.iss}', but expected 'sub' value from client attestation '${options.clientAttestation.payload.sub}'`\n    )\n  }\n\n  // `challenge` (draft 06+) replaced `nonce`. Accept either claim for backwards compatibility.\n  const expectedChallenge = options.expectedChallenge ?? options.expectedNonce\n  if (expectedChallenge !== undefined && expectedChallenge !== (payload.challenge ?? payload.nonce)) {\n    throw new Oauth2Error(\"Client Attestation Pop jwt 'challenge' does not match expected value.\")\n  }\n\n  const { signer } = await verifyJwt({\n    signer: {\n      alg: header.alg,\n      method: 'jwk',\n      publicJwk: options.clientAttestation.payload.cnf.jwk,\n    },\n    now: options.now,\n    header,\n    payload,\n    expectedAudience: options.expectedAudience ?? options.authorizationServer,\n    compact: options.clientAttestationPopJwt,\n    verifyJwtCallback: options.callbacks.verifyJwt,\n    errorMessage: 'client attestation pop jwt verification failed',\n    allowedSkewInSeconds: options.allowedSkewInSeconds,\n  })\n\n  return {\n    header,\n    payload,\n    signer,\n  }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n  /**\n   * The challenge provided by the authorization server to include in the client attestation pop jwt.\n   */\n  challenge?: string\n\n  /**\n   * @deprecated Renamed to `challenge` in draft 06. If `challenge` is not set, this value is used.\n   */\n  nonce?: string\n\n  /**\n   * The audience authorization server identifier\n   */\n  authorizationServer: string\n\n  /**\n   * Creation time of the JWT. If not provided the current date will be used\n   */\n  issuedAt?: Date\n\n  /**\n   * The client attestation to create the Pop for\n   */\n  clientAttestation: string\n\n  /**\n   * Additional payload to include in the client attestation pop jwt payload. Will be applied after\n   * any default claims that are included, so add claims with caution.\n   */\n  additionalPayload?: Record<string, unknown>\n\n  /**\n   * Callback used for dpop\n   */\n  callbacks: Pick<CallbackContext, 'generateRandom' | 'signJwt'>\n\n  /**\n   * The signer of jwt. Only jwk signer allowed.\n   *\n   * If not provided, the signer will be derived based on the\n   * `cnf.jwk` and `alg` in the client attestation.\n   */\n  signer?: JwtSignerJwk\n}\n\nexport async function createClientAttestationPopJwt(options: CreateClientAttestationPopJwtOptions) {\n  const clientAttestation = decodeJwt({\n    jwt: options.clientAttestation,\n    headerSchema: zClientAttestationJwtHeader,\n    payloadSchema: zClientAttestationJwtPayload,\n  })\n\n  const signer = options.signer ?? {\n    method: 'jwk',\n    alg: clientAttestation.header.alg,\n    publicJwk: clientAttestation.payload.cnf.jwk,\n  }\n\n  const header = parseWithErrorHandling(zClientAttestationPopJwtHeader, {\n    typ: 'oauth-client-attestation-pop+jwt',\n    alg: signer.alg,\n  } satisfies ClientAttestationPopJwtHeader)\n\n  // `iss` (removed in draft 08) and `exp` (removed in draft 06) are no longer part of the\n  // Client Attestation PoP JWT. `challenge` (draft 06+) replaces the legacy `nonce`.\n  const payload = parseWithErrorHandling(zClientAttestationPopJwtPayload, {\n    aud: options.authorizationServer,\n    iat: dateToSeconds(options.issuedAt ?? new Date()),\n    jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n    challenge: options.challenge ?? options.nonce,\n    ...options.additionalPayload,\n  } satisfies ClientAttestationPopJwtPayload)\n\n  const { jwt } = await options.callbacks.signJwt(signer, {\n    header,\n    payload,\n  })\n\n  return jwt\n}\n","import { dateToSeconds, type FetchHeaders, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { decodeJwt, jwtHeaderFromJwtSigner, jwtSignerFromJwt } from '../common/jwt/decode-jwt'\nimport { verifyJwt } from '../common/jwt/verify-jwt'\nimport { type JwtSigner, zCompactJwt } from '../common/jwt/z-jwt'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport { verifyClientAttestationPopJwt } from './client-attestation-pop'\nimport {\n  type ClientAttestationJwtHeader,\n  type ClientAttestationJwtPayload,\n  oauthClientAttestationHeader,\n  oauthClientAttestationPopHeader,\n  zClientAttestationJwtHeader,\n  zClientAttestationJwtPayload,\n} from './z-client-attestation'\n\nexport interface VerifyClientAttestationJwtOptions {\n  /**\n   * The compact client attestation jwt.\n   */\n  clientAttestationJwt: string\n\n  /**\n   * Date to use for expiration. If not provided current date will be used.\n   */\n  now?: Date\n\n  /**\n   * Allowed skew time in seconds for validity of token. Used for `exp` and `nbf`\n   * verification.\n   *\n   * @default 0\n   */\n  allowedSkewInSeconds?: number\n\n  /**\n   * Callbacks used for verifying client attestation pop jwt.\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt'>\n\n  // TODO: expectedClientId? expectedIssuer?\n}\n\nexport type VerifiedClientAttestationJwt = Awaited<ReturnType<typeof verifyClientAttestationJwt>>\nexport async function verifyClientAttestationJwt(options: VerifyClientAttestationJwtOptions) {\n  const { header, payload } = decodeJwt({\n    jwt: options.clientAttestationJwt,\n    headerSchema: zClientAttestationJwtHeader,\n    payloadSchema: zClientAttestationJwtPayload,\n  })\n\n  const { signer } = await verifyJwt({\n    signer: jwtSignerFromJwt({ header, payload }),\n    now: options.now,\n    header,\n    payload,\n    compact: options.clientAttestationJwt,\n    verifyJwtCallback: options.callbacks.verifyJwt,\n    errorMessage: 'client attestation jwt verification failed.',\n  })\n\n  return {\n    header,\n    payload,\n    signer,\n  }\n}\n\nexport interface CreateClientAttestationJwtOptions {\n  /**\n   * Creation time of the JWT. If not provided the current date will be used\n   */\n  issuedAt?: Date\n\n  /**\n   * Expiration time of the JWT.\n   */\n  expiresAt: Date\n\n  /**\n   * Issuer of the client attestation, usually the identifier of the client backend (attester).\n   *\n   * The `iss` claim was removed from the Client Attestation JWT in draft 08, so it is only\n   * included in the payload when this option is provided. It is also useful for interoperability\n   * with <= draft 07 verifiers and when the KID is a relative DID URL to the issuer.\n   */\n  issuer?: string\n\n  /**\n   * The client id of the client instance.\n   */\n  clientId: string\n\n  /**\n   * The confirmation payload for the client, attesting the `jwk`, `key_type` and `user_authentication`\n   */\n  confirmation: ClientAttestationJwtPayload['cnf']\n\n  /**\n   * Additional payload to include in the client attestation jwt payload. Will be applied after\n   * any default claims that are included, so add claims with caution.\n   */\n  additionalPayload?: Record<string, unknown>\n\n  /**\n   * Callback used for client attestation\n   */\n  callbacks: Pick<CallbackContext, 'signJwt'>\n\n  /**\n   * The signer of the client attestation jwt.\n   */\n  signer: JwtSigner\n}\n\nexport async function createClientAttestationJwt(options: CreateClientAttestationJwtOptions) {\n  const header = parseWithErrorHandling(zClientAttestationJwtHeader, {\n    typ: 'oauth-client-attestation+jwt',\n    ...jwtHeaderFromJwtSigner(options.signer),\n  } satisfies ClientAttestationJwtHeader)\n\n  const payload = parseWithErrorHandling(zClientAttestationJwtPayload, {\n    // `iss` was removed from the Client Attestation JWT in draft 08. Only include it when a\n    // legacy `issuer` is explicitly provided.\n    ...(options.issuer ? { iss: options.issuer } : {}),\n    iat: dateToSeconds(options.issuedAt),\n    exp: dateToSeconds(options.expiresAt),\n    sub: options.clientId,\n    cnf: options.confirmation,\n    ...options.additionalPayload,\n  } satisfies ClientAttestationJwtPayload)\n\n  const { jwt } = await options.callbacks.signJwt(options.signer, {\n    header,\n    payload,\n  })\n\n  return jwt\n}\n\nexport function extractClientAttestationJwtsFromHeaders(\n  headers: FetchHeaders\n):\n  | { valid: false }\n  | { valid: true; clientAttestationHeader?: undefined; clientAttestationPopHeader?: undefined }\n  | { valid: true; clientAttestationHeader: string; clientAttestationPopHeader?: string } {\n  const clientAttestationHeader = headers.get(oauthClientAttestationHeader)\n  const clientAttestationPopHeader = headers.get(oauthClientAttestationPopHeader)\n\n  if (!clientAttestationHeader && !clientAttestationPopHeader) {\n    return { valid: true }\n  }\n\n  // A Client Attestation PoP header without a Client Attestation header is always invalid.\n  if (!clientAttestationHeader) {\n    return { valid: false }\n  }\n\n  if (!zCompactJwt.safeParse(clientAttestationHeader).success) {\n    return { valid: false } as const\n  }\n\n  // draft 09 `attest_jwt_client_auth_dpop`: the attestation header is present without a separate PoP\n  // header (the DPoP proof serves as the PoP). This is only accepted later if a matching DPoP proof\n  // is present.\n  if (!clientAttestationPopHeader) {\n    return { valid: true, clientAttestationHeader } as const\n  }\n\n  if (!zCompactJwt.safeParse(clientAttestationPopHeader).success) {\n    return { valid: false } as const\n  }\n\n  return {\n    valid: true,\n    clientAttestationPopHeader,\n    clientAttestationHeader,\n  } as const\n}\n\nexport interface VerifyClientAttestationOptions {\n  authorizationServer: string\n  clientAttestationJwt: string\n  clientAttestationPopJwt: string\n  callbacks: Pick<CallbackContext, 'verifyJwt'>\n\n  /**\n   * Date to use for expiration. If not provided current date will be used.\n   */\n  now?: Date\n\n  /**\n   * Allowed skew time in seconds for validity of token. Used for `exp` and `nbf`\n   * verification.\n   *\n   * @default 0\n   */\n  allowedSkewInSeconds?: number\n}\n\nexport async function verifyClientAttestation({\n  authorizationServer,\n  clientAttestationJwt,\n  clientAttestationPopJwt,\n  callbacks,\n  now,\n  allowedSkewInSeconds,\n}: VerifyClientAttestationOptions) {\n  try {\n    const clientAttestation = await verifyClientAttestationJwt({\n      callbacks,\n      clientAttestationJwt,\n      now,\n      allowedSkewInSeconds,\n    })\n\n    const clientAttestationPop = await verifyClientAttestationPopJwt({\n      callbacks: callbacks,\n      authorizationServer,\n      clientAttestation,\n      clientAttestationPopJwt,\n      now,\n      allowedSkewInSeconds,\n    })\n\n    return {\n      clientAttestation,\n      clientAttestationPop,\n    }\n  } catch (error) {\n    if (error instanceof Oauth2Error) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidClient,\n          error_description: `Error verifying client attestation. ${error.message}`,\n        },\n        {\n          status: 401,\n          cause: error,\n        }\n      )\n    }\n\n    throw new Oauth2ServerErrorResponseError(\n      {\n        error: Oauth2ErrorCodes.ServerError,\n        error_description: 'Error during verification of client attestation jwt',\n      },\n      {\n        status: 500,\n        cause: error,\n        internalMessage: 'Unknown error thrown during verification of client attestation jwt',\n      }\n    )\n  }\n}\n","import { zHttpMethod, zHttpsUrl, zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zJwk } from '../common/jwk/z-jwk'\nimport { zJwtHeader, zJwtPayload } from '../common/jwt/z-jwt'\n\nexport const zDpopJwtPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    iat: zNumericDate,\n    htu: zHttpsUrl,\n    htm: zHttpMethod,\n    jti: z.string(),\n\n    // Only required when presenting in combination with access token\n    ath: z.optional(z.string()),\n  })\n  .loose()\nexport type DpopJwtPayload = z.infer<typeof zDpopJwtPayload>\n\nexport const zDpopJwtHeader = z\n  .object({\n    ...zJwtHeader.shape,\n    typ: z.literal('dpop+jwt'),\n    jwk: zJwk,\n  })\n  .loose()\nexport type DpopJwtHeader = z.infer<typeof zDpopJwtHeader>\n","import {\n  dateToSeconds,\n  decodeUtf8String,\n  encodeToBase64Url,\n  type FetchHeaders,\n  parseWithErrorHandling,\n  URL,\n} from '@openid4vc/utils'\nimport { type CallbackContext, HashAlgorithm } from '../callbacks'\nimport { calculateJwkThumbprint } from '../common/jwk/jwk-thumbprint'\nimport { decodeJwt } from '../common/jwt/decode-jwt'\nimport { verifyJwt } from '../common/jwt/verify-jwt'\nimport { type JwtSignerJwk, zCompactJwt } from '../common/jwt/z-jwt'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport { type DpopJwtHeader, type DpopJwtPayload, zDpopJwtHeader, zDpopJwtPayload } from './z-dpop'\n\nexport interface RequestDpopOptions {\n  /**\n   * Dpop nonce to use for constructing the dpop jwt\n   */\n  nonce?: string\n\n  /**\n   * The signer of the dpop jwt\n   */\n  signer: JwtSignerJwk\n}\n\nexport async function createDpopHeadersForRequest(options: CreateDpopJwtOptions) {\n  const dpopJwt = await createDpopJwt(options)\n\n  return {\n    DPoP: dpopJwt,\n  }\n}\n\nexport interface CreateDpopJwtOptions {\n  request: Omit<RequestLike, 'headers'>\n\n  /**\n   * Dpop nonce value\n   */\n  nonce?: string\n\n  /**\n   * Creation time of the JWT. If not provided the current date will be used\n   */\n  issuedAt?: Date\n\n  /**\n   * Additional payload to include in the dpop jwt payload. Will be applied after\n   * any default claims that are included, so add claims with caution.\n   */\n  additionalPayload?: Record<string, unknown>\n\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   * If provided, the `hashCallback` parameter also needs to be provided\n   */\n  accessToken?: string\n\n  /**\n   * Callback used for dpop\n   */\n  callbacks: Pick<CallbackContext, 'generateRandom' | 'hash' | 'signJwt'>\n\n  /**\n   * The signer of the dpop jwt. Only jwk signer allowed.\n   */\n  signer: JwtSignerJwk\n}\n\nexport async function createDpopJwt(options: CreateDpopJwtOptions) {\n  // Calculate access token hash\n  let ath: string | undefined\n  if (options.accessToken) {\n    ath = encodeToBase64Url(await options.callbacks.hash(decodeUtf8String(options.accessToken), HashAlgorithm.Sha256))\n  }\n\n  const header = parseWithErrorHandling(zDpopJwtHeader, {\n    typ: 'dpop+jwt',\n    jwk: options.signer.publicJwk,\n    alg: options.signer.alg,\n  } satisfies DpopJwtHeader)\n\n  const payload = parseWithErrorHandling(zDpopJwtPayload, {\n    htu: htuFromRequestUrl(options.request.url),\n    iat: dateToSeconds(options.issuedAt),\n    htm: options.request.method,\n    jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n    ath,\n    nonce: options.nonce,\n    ...options.additionalPayload,\n  } satisfies DpopJwtPayload)\n\n  const { jwt } = await options.callbacks.signJwt(options.signer, {\n    header,\n    payload,\n  })\n\n  return jwt\n}\n\nexport interface VerifyDpopJwtOptions {\n  /**\n   * The compact dpop jwt.\n   */\n  dpopJwt: string\n\n  /**\n   * The requet for which to verify the dpop jwt\n   */\n  request: RequestLike\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   * Expected nonce in the payload. If not provided the nonce won't be validated.\n   */\n  expectedNonce?: string\n\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   * 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   * Callbacks used for verifying dpop jwt\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>\n\n  now?: Date\n}\n\nexport async function verifyDpopJwt(options: VerifyDpopJwtOptions) {\n  try {\n    const { header, payload } = decodeJwt({\n      jwt: options.dpopJwt,\n      headerSchema: zDpopJwtHeader,\n      payloadSchema: zDpopJwtPayload,\n    })\n\n    if (options.allowedSigningAlgs && !options.allowedSigningAlgs.includes(header.alg)) {\n      throw new Oauth2Error(\n        `dpop jwt uses alg value '${header.alg}' but allowed dpop signging alg values are ${options.allowedSigningAlgs.join(', ')}.`\n      )\n    }\n\n    if (options.expectedNonce) {\n      if (!payload.nonce) {\n        throw new Oauth2Error(\n          `Dpop jwt does not have a nonce value, but expected nonce value '${options.expectedNonce}'`\n        )\n      }\n\n      if (payload.nonce !== options.expectedNonce) {\n        throw new Oauth2Error(\n          `Dpop jwt contains nonce value '${payload.nonce}', but expected nonce value '${options.expectedNonce}'`\n        )\n      }\n    }\n\n    if (options.request.method !== payload.htm) {\n      throw new Oauth2Error(\n        `Dpop jwt contains htm value '${payload.htm}', but expected htm value '${options.request.method}'`\n      )\n    }\n\n    const expectedHtu = htuFromRequestUrl(options.request.url)\n    if (expectedHtu !== payload.htu) {\n      throw new Oauth2Error(`Dpop jwt contains htu value '${payload.htu}', but expected htu value '${expectedHtu}'.`)\n    }\n\n    if (options.accessToken) {\n      const expectedAth = encodeToBase64Url(\n        await options.callbacks.hash(decodeUtf8String(options.accessToken), HashAlgorithm.Sha256)\n      )\n\n      if (!payload.ath) {\n        throw new Oauth2Error(`Dpop jwt does not have a ath value, but expected ath value '${expectedAth}'.`)\n      }\n\n      if (payload.ath !== expectedAth) {\n        throw new Oauth2Error(`Dpop jwt contains ath value '${payload.ath}', but expected ath value '${expectedAth}'.`)\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 (options.expectedJwkThumbprint && options.expectedJwkThumbprint !== jwkThumbprint) {\n      throw new Oauth2Error(\n        `Dpop is signed with jwk with thumbprint value '${jwkThumbprint}', but expect jwk thumbprint value '${options.expectedJwkThumbprint}'`\n      )\n    }\n\n    await verifyJwt({\n      signer: {\n        alg: header.alg,\n        method: 'jwk',\n        publicJwk: header.jwk,\n      },\n      now: options.now,\n      header,\n      payload,\n      compact: options.dpopJwt,\n      verifyJwtCallback: options.callbacks.verifyJwt,\n      errorMessage: 'dpop jwt verification failed',\n    })\n\n    return {\n      header,\n      payload,\n      jwkThumbprint,\n    }\n  } catch (error) {\n    if (error instanceof Oauth2Error) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidDpopProof,\n        error_description: error.message,\n      })\n    }\n\n    throw error\n  }\n}\n\nfunction htuFromRequestUrl(requestUrl: string) {\n  const htu = new URL(requestUrl)\n  htu.search = ''\n  htu.hash = ''\n\n  return htu.toString()\n}\n\nexport function extractDpopNonceFromHeaders(headers: FetchHeaders) {\n  return headers.get('DPoP-Nonce')\n}\n\nexport function extractDpopJwtFromHeaders(headers: FetchHeaders): { valid: true; dpopJwt?: string } | { 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 { valid: true, dpopJwt }\n}\n","import { extractClientAttestationJwtsFromHeaders } from '../client-attestation/client-attestation'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { extractDpopJwtFromHeaders } from '../dpop/dpop'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\n\nexport interface ParseAuthorizationRequestOptions {\n  request: RequestLike\n\n  authorizationRequest: {\n    dpop_jkt?: string\n  }\n}\n\nexport interface ParseAuthorizationRequestResult {\n  /**\n   * The dpop params from the authorization request.\n   *\n   * Both `dpop_jkt` and DPoP header can be included in the request.\n   *\n   * The jkt and the signer of the jwt have not been verified against\n   * each other yet, this only happens during verification\n   */\n  dpop?:\n    | {\n        jwkThumbprint: string\n        jwt?: string\n      }\n    | {\n        jwkThumbprint?: string\n        jwt: string\n      }\n\n  // TODO: we should revampt this to generic client authentication so we can suppor other\n  // method as well. We should also create a generic verify client authentication method.\n  /**\n   * The client attestation jwts from the authorization request headers.\n   * These have not been verified yet.\n   */\n  clientAttestation?: {\n    clientAttestationJwt: string\n\n    /**\n     * Absent for the DPoP-bound `attest_jwt_client_auth_dpop` method (draft 09), where the DPoP proof\n     * serves as the Client Attestation PoP.\n     */\n    clientAttestationPopJwt?: string\n  }\n}\n\n/**\n * Parse an authorization request.\n *\n * @throws {Oauth2ServerErrorResponseError}\n */\nexport function parseAuthorizationRequest(options: ParseAuthorizationRequestOptions): 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 Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidDpopProof,\n      error_description: `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 = extractClientAttestationJwtsFromHeaders(options.request.headers)\n  if (!extractedClientAttestationJwts.valid) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description:\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    dpop: extractedDpopJwt.dpopJwt\n      ? {\n          jwt: extractedDpopJwt.dpopJwt,\n          jwkThumbprint: options.authorizationRequest.dpop_jkt,\n        }\n      : // Basically the same as above, but with correct TS type hinting\n        options.authorizationRequest.dpop_jkt\n        ? {\n            jwt: extractedDpopJwt.dpopJwt,\n            jwkThumbprint: options.authorizationRequest.dpop_jkt,\n          }\n        : undefined,\n    clientAttestation: extractedClientAttestationJwts.clientAttestationHeader\n      ? {\n          clientAttestationJwt: extractedClientAttestationJwts.clientAttestationHeader,\n          clientAttestationPopJwt: extractedClientAttestationJwts.clientAttestationPopHeader,\n        }\n      : undefined,\n  }\n}\n","import { z } from 'zod'\n\nexport const zCompactJwe = z\n  .string()\n  .regex(/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, {\n    message: 'Not a valid compact jwe',\n  })\n","import { zHttpsUrl } from '@openid4vc/utils'\nimport { z } from 'zod'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\n\nexport const zJarAuthorizationRequest = z\n  .object({\n    request: z.optional(z.string()),\n    request_uri: z.optional(zHttpsUrl),\n    client_id: z.optional(z.string()),\n  })\n  .loose()\nexport type JarAuthorizationRequest = z.infer<typeof zJarAuthorizationRequest>\n\nexport function validateJarRequestParams(options: {\n  jarRequestParams: JarAuthorizationRequest\n  allowRequestUri?: boolean\n}) {\n  const { jarRequestParams, allowRequestUri = true } = options\n\n  if (jarRequestParams.request && jarRequestParams.request_uri) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: '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 Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: 'request or request_uri must be present',\n    })\n  }\n\n  if (jarRequestParams.request_uri && !allowRequestUri) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: 'request_uri is not allowed',\n    })\n  }\n\n  return jarRequestParams as JarAuthorizationRequest &\n    ({ request_uri: string; request?: never } | { request: string; request_uri?: never })\n}\n\nexport function isJarAuthorizationRequest(request: JarAuthorizationRequest): request is JarAuthorizationRequest {\n  return 'request' in request || 'request_uri' in request\n}\n","import { z } from 'zod'\nimport { zJwtPayload } from '../common/jwt/z-jwt'\n\nexport const zJarRequestObjectPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    client_id: z.string(),\n  })\n  .loose()\nexport type JarRequestObjectPayload = z.infer<typeof zJarRequestObjectPayload>\n\nconst zSignedAuthorizationRequestJwtHeaderTyp = z.literal('oauth-authz-req+jwt')\nexport const signedAuthorizationRequestJwtHeaderTyp = zSignedAuthorizationRequestJwtHeaderTyp.value\n\nconst zJwtAuthorizationRequestJwtHeaderTyp = z.literal('jwt')\nexport const jwtAuthorizationRequestJwtHeaderTyp = zJwtAuthorizationRequestJwtHeaderTyp.value\n","import { ContentType, createFetcher, type Fetch } from '@openid4vc/utils'\nimport type { CallbackContext } from '../../callbacks'\nimport { decodeJwt } from '../../common/jwt/decode-jwt'\nimport { verifyJwt } from '../../common/jwt/verify-jwt'\nimport { zCompactJwe } from '../../common/jwt/z-jwe'\nimport { type JwtSigner, type JwtSignerWithJwk, zCompactJwt } from '../../common/jwt/z-jwt'\nimport { Oauth2ErrorCodes } from '../../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../../error/Oauth2ServerErrorResponseError'\nimport { type JarAuthorizationRequest, validateJarRequestParams } from '../z-jar-authorization-request'\nimport {\n  type JarRequestObjectPayload,\n  jwtAuthorizationRequestJwtHeaderTyp,\n  signedAuthorizationRequestJwtHeaderTyp,\n  zJarRequestObjectPayload,\n} from '../z-jar-request-object'\n\nexport interface ParsedJarRequestOptions {\n  jarRequestParams: JarAuthorizationRequest\n  callbacks: Pick<CallbackContext, 'fetch'>\n}\n\nexport interface VerifyJarRequestOptions {\n  jarRequestParams: {\n    client_id?: string\n  }\n  authorizationRequestJwt: string\n  callbacks: Pick<CallbackContext, 'verifyJwt'>\n  jwtSigner: JwtSigner\n}\n\nexport interface ParsedJarRequest {\n  authorizationRequestJwt: string\n  sendBy: 'value' | 'reference'\n}\n\nexport interface VerifiedJarRequest {\n  authorizationRequestPayload: JarRequestObjectPayload\n  signer: JwtSignerWithJwk\n  jwt: ReturnType<typeof decodeJwt<undefined, typeof zJarRequestObjectPayload>>\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(options: ParsedJarRequestOptions): 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      requestUri: jarRequestParams.request_uri,\n      fetch: callbacks.fetch,\n    }))\n\n  return { sendBy, authorizationRequestJwt }\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(options: VerifyJarRequestOptions): Promise<VerifiedJarRequest> {\n  const { jarRequestParams, authorizationRequestJwt, callbacks, jwtSigner } = options\n\n  /* Encryption is not supported */\n  const requestObjectIsEncrypted = zCompactJwe.safeParse(authorizationRequestJwt).success\n  if (requestObjectIsEncrypted) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: 'Encrypted JWE request objects are not supported.',\n    })\n  }\n\n  const requestIsSigned = zCompactJwt.safeParse(authorizationRequestJwt).success\n  if (!requestIsSigned) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: 'JAR request object is not a valid JWT.',\n    })\n  }\n\n  const { authorizationRequestPayload, signer, jwt } = await verifyJarRequestObject({\n    authorizationRequestJwt,\n    callbacks,\n    jwtSigner,\n  })\n  if (!authorizationRequestPayload.client_id) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: '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 Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: 'client_id does not match the request object client_id.',\n    })\n  }\n\n  return {\n    jwt,\n    authorizationRequestPayload,\n    signer,\n  }\n}\n\nasync function fetchJarRequestObject(options: { requestUri: string; fetch?: Fetch }): Promise<string> {\n  const { requestUri, fetch } = options\n\n  const response = await createFetcher(fetch)(requestUri, {\n    method: 'get',\n    headers: {\n      Accept: `${ContentType.OAuthAuthorizationRequestJwt}, ${ContentType.Jwt};q=0.9, text/plain`,\n      'Content-Type': ContentType.XWwwFormUrlencoded,\n    },\n  }).catch(() => {\n    throw new Oauth2ServerErrorResponseError({\n      error_description: `Fetching request_object from request_uri '${requestUri}' failed`,\n      error: Oauth2ErrorCodes.InvalidRequestUri,\n    })\n  })\n\n  if (!response.ok) {\n    throw new Oauth2ServerErrorResponseError({\n      error_description: `Fetching request_object from request_uri '${requestUri}' failed with status code '${response.status}'.`,\n      error: Oauth2ErrorCodes.InvalidRequestUri,\n    })\n  }\n\n  return await response.text()\n}\n\nasync function verifyJarRequestObject(options: {\n  authorizationRequestJwt: string\n  callbacks: Pick<CallbackContext, 'verifyJwt'>\n  jwtSigner: JwtSigner\n}) {\n  const { authorizationRequestJwt, callbacks, jwtSigner } = options\n\n  const jwt = decodeJwt({ jwt: authorizationRequestJwt, payloadSchema: zJarRequestObjectPayload })\n\n  const { signer } = await verifyJwt({\n    verifyJwtCallback: callbacks.verifyJwt,\n    compact: authorizationRequestJwt,\n    header: jwt.header,\n    payload: jwt.payload,\n\n    signer: jwtSigner,\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 Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequestObject,\n      error_description: `Invalid Jar Request Object typ header. Expected \"oauth-authz-req+jwt\" or \"jwt\", received \"${jwt.header.typ}\".`,\n    })\n  }\n\n  return {\n    signer,\n    jwt,\n    authorizationRequestPayload: jwt.payload,\n  }\n}\n","import { zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zOauth2ErrorResponse } from '../common/z-oauth2-error'\n\nexport const zPushedAuthorizationRequestUriPrefix = z.literal('urn:ietf:params:oauth:request_uri:')\nexport const pushedAuthorizationRequestUriPrefix = zPushedAuthorizationRequestUriPrefix.value\nexport type PushedAuthorizationRequestUriPrefix = z.infer<typeof zPushedAuthorizationRequestUriPrefix>\n\n// TODO: should create different request validations for different\n// response types. Currently we basically only support `code`\nexport const zAuthorizationRequest = z\n  .object({\n    response_type: z.string(),\n    client_id: z.string(),\n\n    issuer_state: z.optional(z.string()),\n    redirect_uri: z.url().optional(),\n    resource: z.optional(zHttpsUrl),\n    scope: z.optional(z.string()),\n    state: z.optional(z.string()),\n\n    // DPoP jwk thumbprint\n    dpop_jkt: z.optional(z.base64url()),\n\n    code_challenge: z.optional(z.string()),\n    code_challenge_method: z.optional(z.string()),\n  })\n  .loose()\nexport type AuthorizationRequest = z.infer<typeof zAuthorizationRequest>\n\nexport const zPushedAuthorizationRequest = z\n  .object({\n    request_uri: z.string(),\n    client_id: z.string(),\n  })\n  .loose()\nexport type PushedAuthorizationRequest = z.infer<typeof zPushedAuthorizationRequest>\n\nexport const zPushedAuthorizationResponse = z\n  .object({\n    request_uri: z.string(),\n    expires_in: z.number().int(),\n  })\n  .loose()\nexport type PushedAuthorizationResponse = z.infer<typeof zPushedAuthorizationResponse>\n\nexport const zPushedAuthorizationErrorResponse = zOauth2ErrorResponse\nexport type PushedAuthorizationErrorResponse = z.infer<typeof zPushedAuthorizationErrorResponse>\n","import { formatZodError, parseWithErrorHandling } from '@openid4vc/utils'\nimport z from 'zod'\nimport type { CallbackContext } from '../callbacks'\nimport { decodeJwt } from '../common/jwt/decode-jwt'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport { parseJarRequest } from '../jar/handle-jar-request/verify-jar-request'\nimport { isJarAuthorizationRequest, zJarAuthorizationRequest } from '../jar/z-jar-authorization-request'\nimport { type ParseAuthorizationRequestResult, parseAuthorizationRequest } from './parse-authorization-request'\nimport {\n  type AuthorizationRequest,\n  pushedAuthorizationRequestUriPrefix,\n  zAuthorizationRequest,\n} from './z-authorization-request'\n\nexport interface ParsePushedAuthorizationRequestOptions {\n  request: RequestLike\n  authorizationRequest: unknown\n  callbacks: Pick<CallbackContext, 'fetch'>\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 * Parse an pushed authorization request.\n *\n * @throws {Oauth2ServerErrorResponseError}\n */\nexport async function parsePushedAuthorizationRequest(\n  options: ParsePushedAuthorizationRequestOptions\n): Promise<ParsePushedAuthorizationRequestResult> {\n  const parsed = parseWithErrorHandling(\n    z.union([zAuthorizationRequest, zJarAuthorizationRequest]),\n    options.authorizationRequest,\n    'Invalid authorization request. Could not parse authorization request or jar.'\n  )\n\n  let authorizationRequest: AuthorizationRequest\n  let authorizationRequestJwt: string | undefined\n  if (isJarAuthorizationRequest(parsed)) {\n    const parsedJar = await parseJarRequest({ jarRequestParams: parsed, callbacks: options.callbacks })\n    const jwt = decodeJwt({ jwt: parsedJar.authorizationRequestJwt })\n\n    const parsedAuthorizationRequest = zAuthorizationRequest.safeParse(jwt.payload)\n    if (!parsedAuthorizationRequest.success) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Invalid authorization request. Could not parse jar request payload.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n      })\n    }\n\n    authorizationRequest = parsedAuthorizationRequest.data\n    authorizationRequestJwt = parsedJar.authorizationRequestJwt\n  } else {\n    authorizationRequest = parsed\n  }\n\n  const { clientAttestation, dpop } = parseAuthorizationRequest({\n    authorizationRequest,\n    request: options.request,\n  })\n\n  return {\n    authorizationRequest,\n    authorizationRequestJwt,\n    dpop,\n    clientAttestation,\n  }\n}\n\nexport interface ParsePushedAuthorizationRequestUriReferenceValueOptions {\n  uri: string\n}\n\n/**\n * Parse a pushed authorization request URI prefixed with `urn:ietf:params:oauth:request_uri:`\n * and returns the identifier, without the prefix.\n *\n * @throws {Oauth2ServerErrorResponseError}\n */\nexport function parsePushedAuthorizationRequestUriReferenceValue(\n  options: ParsePushedAuthorizationRequestUriReferenceValueOptions\n): string {\n  if (!options.uri.startsWith(pushedAuthorizationRequestUriPrefix)) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: `The 'request_uri' must start with the prefix \"${pushedAuthorizationRequestUriPrefix}\".`,\n    })\n  }\n\n  return options.uri.substring(pushedAuthorizationRequestUriPrefix.length)\n}\n","import { type CallbackContext, HashAlgorithm } from '../callbacks'\nimport { type VerifiedClientAttestationJwt, verifyClientAttestation } from '../client-attestation/client-attestation'\nimport type { VerifiedClientAttestationPopJwt } from '../client-attestation/client-attestation-pop'\nimport {\n  oauthClientAttestationHeader,\n  oauthClientAttestationPopHeader,\n} from '../client-attestation/z-client-attestation'\nimport { calculateJwkThumbprint } from '../common/jwk/jwk-thumbprint'\nimport type { Jwk } from '../common/jwk/z-jwk'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { verifyDpopJwt } from '../dpop/dpop'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\n\nexport interface VerifyAuthorizationRequestDpop {\n  /**\n   * Whether dpop is required.\n   */\n  required?: boolean\n\n  /**\n   * The dpop jwt from the pushed or interactive authorization request.\n   *\n   * If dpop is required, at least one of `jwt` or `jwkThumbprint` MUST\n   * be provided. If both are provided, the jwk thumbprints are matched\n   */\n  jwt?: string\n\n  /**\n   * The jwk thumbprint as provided in the `dpop_jkt` parameter.\n   *\n   * If dpop is required, at least one of `jwt` or `jwkThumbprint` MUST\n   * be provided. If both are provided, the jwk thumbprints are matched\n   */\n  jwkThumbprint?: 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\nexport interface VerifyAuthorizationRequestClientAttestation {\n  /**\n   * Whether client attestation is required.\n   */\n  required?: boolean\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  clientAttestationJwt?: string\n  clientAttestationPopJwt?: string\n}\n\nexport interface VerifyAuthorizationRequestReturn {\n  dpop?: {\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     * The JWK will be returned if a DPoP proof was provided in the header.\n     */\n    jwk?: Jwk\n  }\n\n  /**\n   * The verified client attestation if any were provided.\n   */\n  clientAttestation?: {\n    clientAttestation: VerifiedClientAttestationJwt\n    clientAttestationPop: VerifiedClientAttestationPopJwt\n  }\n}\n\nexport interface VerifyAuthorizationRequestOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  authorizationRequest: {\n    client_id?: string\n  }\n  request: RequestLike\n\n  dpop?: VerifyAuthorizationRequestDpop\n  clientAttestation?: VerifyAuthorizationRequestClientAttestation\n\n  /**\n   * Date to use for expiration. If not provided current date will be used.\n   */\n  now?: Date\n\n  callbacks: Pick<CallbackContext, 'hash' | 'verifyJwt'>\n}\n\n// TODO: verify the request against the metadata\nexport async function verifyAuthorizationRequest(\n  options: VerifyAuthorizationRequestOptions\n): Promise<VerifyAuthorizationRequestReturn> {\n  const dpopResult = options.dpop\n    ? await verifyAuthorizationRequestDpop(options.dpop, options.request, options.callbacks, options.now)\n    : undefined\n\n  const clientAttestationResult = options.clientAttestation\n    ? await verifyAuthorizationRequestClientAttestation(\n        options.clientAttestation,\n        options.authorizationServerMetadata,\n        options.callbacks,\n        dpopResult?.jwkThumbprint,\n        options.now,\n        options.authorizationRequest.client_id\n      )\n    : undefined\n\n  return {\n    dpop: dpopResult?.jwkThumbprint\n      ? {\n          jwkThumbprint: dpopResult.jwkThumbprint,\n          jwk: dpopResult.jwk,\n        }\n      : undefined,\n    clientAttestation: clientAttestationResult,\n  }\n}\n\nasync function verifyAuthorizationRequestClientAttestation(\n  options: VerifyAuthorizationRequestClientAttestation,\n  authorizationServerMetadata: AuthorizationServerMetadata,\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>,\n  dpopJwkThumbprint?: string,\n  now?: Date,\n  requestClientId?: string\n) {\n  if (!options.clientAttestationJwt || !options.clientAttestationPopJwt) {\n    if (!options.required && !options.clientAttestationJwt && !options.clientAttestationPopJwt) {\n      return undefined\n    }\n\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description: `Missing required client attestation parameters in pushed authorization request. Make sure to provide the '${oauthClientAttestationHeader}' and '${oauthClientAttestationPopHeader}' header values.`,\n    })\n  }\n\n  const verifiedClientAttestation = await verifyClientAttestation({\n    authorizationServer: authorizationServerMetadata.issuer,\n    callbacks,\n    clientAttestationJwt: options.clientAttestationJwt,\n    clientAttestationPopJwt: options.clientAttestationPopJwt,\n    now,\n  })\n\n  if (requestClientId && requestClientId !== verifiedClientAttestation.clientAttestation.payload.sub) {\n    // Ensure the client id matches with the client id provided in the authorization request\n    throw new Oauth2ServerErrorResponseError(\n      {\n        error: Oauth2ErrorCodes.InvalidClient,\n        error_description: `The client_id '${requestClientId}' in the request does not match the client id '${verifiedClientAttestation.clientAttestation.payload.sub}' in the client attestation`,\n      },\n      {\n        status: 401,\n      }\n    )\n  }\n\n  if (options.ensureConfirmationKeyMatchesDpopKey && dpopJwkThumbprint) {\n    const clientAttestationJkt = await calculateJwkThumbprint({\n      hashAlgorithm: HashAlgorithm.Sha256,\n      hashCallback: callbacks.hash,\n      jwk: verifiedClientAttestation.clientAttestation.payload.cnf.jwk,\n    })\n\n    if (clientAttestationJkt !== dpopJwkThumbprint) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidRequest,\n          error_description:\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          status: 401,\n        }\n      )\n    }\n  }\n\n  return verifiedClientAttestation\n}\n\nasync function verifyAuthorizationRequestDpop(\n  options: VerifyAuthorizationRequestDpop,\n  request: RequestLike,\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>,\n  now?: Date\n) {\n  if (options.required && !options.jwt && !options.jwkThumbprint) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidDpopProof,\n      error_description: `Missing required DPoP parameters in authorization request. Either DPoP header or 'dpop_jkt' is required.`,\n    })\n  }\n\n  const verifyDpopResult = options.jwt\n    ? await verifyDpopJwt({\n        callbacks,\n        dpopJwt: options.jwt,\n        request,\n        allowedSigningAlgs: options.allowedSigningAlgs,\n        now,\n      })\n    : undefined\n\n  if (options.jwkThumbprint && verifyDpopResult && options.jwkThumbprint !== verifyDpopResult.jwkThumbprint) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidDpopProof,\n      error_description: `DPoP jwk thumbprint does not match with 'dpop_jkt' provided in authorization request`,\n    })\n  }\n\n  return {\n    jwk: verifyDpopResult?.header.jwk,\n    jwkThumbprint: verifyDpopResult?.jwkThumbprint ?? options.jwkThumbprint,\n  }\n}\n","import { URL, zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zOauth2ErrorResponse } from '../common/z-oauth2-error'\n\nexport const zAuthorizationResponse = z\n  .object({\n    state: z.string().optional(),\n    code: z.string().nonempty(),\n    iss: zHttpsUrl.optional(), // RFC 9207\n\n    // This allows for discriminating between error and success responses.\n    error: z.optional(z.never()),\n  })\n  .loose()\n\nexport const zAuthorizationResponseFromUriParams = z\n  .url()\n  .transform((url): unknown => Object.fromEntries(new URL(url).searchParams))\n  .pipe(zAuthorizationResponse)\n\nexport type AuthorizationResponse = z.infer<typeof zAuthorizationResponse>\n\nexport const zAuthorizationErrorResponse = z\n  .object({\n    ...zOauth2ErrorResponse.shape,\n    state: z.string().optional(),\n    iss: zHttpsUrl.optional(), // RFC 9207\n\n    // This allows for discriminating between error and success responses.\n    code: z.optional(z.never()),\n  })\n  .loose()\nexport type AuthorizationErrorResponse = z.infer<typeof zAuthorizationErrorResponse>\n","import { formatZodError, URL } from '@openid4vc/utils'\nimport z from 'zod'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport {\n  type AuthorizationErrorResponse,\n  type AuthorizationResponse,\n  zAuthorizationErrorResponse,\n  zAuthorizationResponse,\n} from './z-authorization-response'\n\nexport interface ParseAuthorizationResponseOptions {\n  url: string\n}\n\n/**\n * Parse an authorization response redirect URL.\n *\n * @throws {Oauth2ServerErrorResponseError}\n */\nexport function parseAuthorizationResponseRedirectUrl(\n  options: ParseAuthorizationResponseOptions\n): AuthorizationResponse | AuthorizationErrorResponse {\n  const searchParams = Object.fromEntries(new URL(options.url).searchParams)\n\n  const parsedAuthorizationResponse = z\n    .union([zAuthorizationErrorResponse, zAuthorizationResponse])\n    .safeParse(searchParams)\n\n  if (!parsedAuthorizationResponse.success) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: `Error occurred during validation of authorization response redirect URL.\\n${formatZodError(parsedAuthorizationResponse.error)}`,\n    })\n  }\n\n  return parsedAuthorizationResponse.data\n}\n","import { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport type { AuthorizationErrorResponse, AuthorizationResponse } from './z-authorization-response'\n\nexport interface VerifyAuthorizationResponseOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n  authorizationResponse: AuthorizationResponse | AuthorizationErrorResponse\n}\n\n/**\n * Verifies an authorization (error) response.\n *\n * Currently it only verifies that the 'iss' value in an authorization (error) response matches the 'issuer' value of the authorization server metadata\n * according to RFC 9207.\n *\n * You can call this method after calling `parseAuthorizationResponse` and having fetched the associated session/authorization server\n * for the authorization response, to be able to verify the issuer\n */\nexport function verifyAuthorizationResponse({\n  authorizationResponse,\n  authorizationServerMetadata,\n}: VerifyAuthorizationResponseOptions) {\n  const expectedIssuer = authorizationServerMetadata.issuer\n  const responseIssuer = authorizationResponse.iss\n\n  if (authorizationServerMetadata.authorization_response_iss_parameter_supported && !responseIssuer) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description:\n        \"Authorization server requires 'iss' parameter in authorization response (authorization_response_iss_parameter_supported), but no 'iss' parameter is present in the authorization response.\",\n    })\n  }\n\n  if (responseIssuer && responseIssuer !== expectedIssuer) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description:\n        \"The 'iss' value in the authorization response does not match the expected 'issuer' value from the authorization server metadata.\",\n    })\n  }\n}\n","import type { FetchResponse } from '@openid4vc/utils'\nimport type { Oauth2ErrorResponse } from '../common/z-oauth2-error'\nimport { Oauth2Error } from './Oauth2Error'\n\nexport class Oauth2ClientErrorResponseError extends Oauth2Error {\n  public readonly response: FetchResponse\n\n  public constructor(\n    message: string,\n    public readonly errorResponse: Oauth2ErrorResponse,\n    response: FetchResponse\n  ) {\n    super(`${message}\\n${JSON.stringify(errorResponse, null, 2)}`)\n    this.response = response.clone()\n  }\n}\n","import {\n  ContentType,\n  createZodFetcher,\n  type FetchHeaders,\n  InvalidFetchResponseError,\n  ValidationError,\n} from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { Oauth2ErrorCodes, type Oauth2ErrorResponse } from '../common/z-oauth2-error'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { oauthClientAttestationChallengeHeader, zClientAttestationChallengeResponse } from './z-client-attestation'\n\nexport interface RequestClientAttestationChallengeOptions {\n  /**\n   * Metadata of the authorization server from which to request the challenge.\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * Callback context\n   */\n  callbacks: Pick<CallbackContext, 'fetch'>\n}\n\n/**\n * Request a fresh Client Attestation challenge from the authorization server's `challenge_endpoint`.\n *\n * @see https://www.ietf.org/archive/id/draft-ietf-oauth-attestation-based-client-auth-09.html#section-6.1\n *\n * @throws {Oauth2Error} if the authorization server has no `challenge_endpoint`\n * @throws {InvalidFetchResponseError} if the request failed\n * @throws {ValidationError} if the response could not be validated\n */\nexport async function requestClientAttestationChallenge(options: RequestClientAttestationChallengeOptions) {\n  const fetchWithZod = createZodFetcher(options.callbacks.fetch)\n\n  const { authorizationServerMetadata } = options\n  const challengeEndpoint = authorizationServerMetadata.challenge_endpoint\n  if (!challengeEndpoint) {\n    throw new Oauth2Error(\n      `Unable to request client attestation challenge. Authorization server '${authorizationServerMetadata.issuer}' has no 'challenge_endpoint'`\n    )\n  }\n\n  const { response, result } = await fetchWithZod(\n    zClientAttestationChallengeResponse,\n    ContentType.Json,\n    challengeEndpoint,\n    {\n      method: 'POST',\n    }\n  )\n\n  if (!response.ok || !result) {\n    throw new InvalidFetchResponseError(\n      `Unable to request client attestation challenge from challenge endpoint '${challengeEndpoint}'. Received response with status ${response.status}`,\n      await response.clone().text(),\n      response\n    )\n  }\n\n  if (!result.success) {\n    throw new ValidationError('Error validating client attestation challenge response', result.error)\n  }\n\n  return {\n    challenge: result.data.attestation_challenge,\n  }\n}\n\n/**\n * Extract the Client Attestation challenge from the `OAuth-Client-Attestation-Challenge` response header.\n */\nexport function extractClientAttestationChallengeFromHeaders(headers: FetchHeaders) {\n  return headers.get(oauthClientAttestationChallengeHeader)\n}\n\nexport interface ShouldRetryAuthorizationServerRequestWithClientAttestationChallengeOptions {\n  /**\n   * The error response that will be evaluated for the 'use_attestation_challenge' error to determine\n   * whether the request should be retried using a fresh client attestation challenge.\n   */\n  errorResponse: Oauth2ErrorResponse\n\n  /**\n   * The headers returned in the response. The 'OAuth-Client-Attestation-Challenge' header will be\n   * extracted if the error response indicates so. Will throw an error if the 'error' in the response is\n   * 'use_attestation_challenge' but the headers do not contain the 'OAuth-Client-Attestation-Challenge'\n   * header value.\n   */\n  responseHeaders: FetchHeaders\n}\n\nexport function shouldRetryAuthorizationServerRequestWithClientAttestationChallenge(\n  options: ShouldRetryAuthorizationServerRequestWithClientAttestationChallengeOptions\n) {\n  if (options.errorResponse.error !== Oauth2ErrorCodes.UseAttestationChallenge) {\n    return {\n      retry: false,\n    } as const\n  }\n\n  const attestationChallenge = extractClientAttestationChallengeFromHeaders(options.responseHeaders)\n  if (!attestationChallenge) {\n    throw new Oauth2Error(\n      `Error response error contains error '${Oauth2ErrorCodes.UseAttestationChallenge}' but the response headers do not include a valid '${oauthClientAttestationChallengeHeader}' header value.`\n    )\n  }\n\n  return {\n    retry: true,\n    attestationChallenge,\n  } as const\n}\n\n/**\n * Wraps an authorization server request so that it is retried once with a fresh Client Attestation\n * challenge when the server responds with the 'use_attestation_challenge' error and provides a\n * challenge in the 'OAuth-Client-Attestation-Challenge' response header.\n *\n * Mirrors {@link authorizationServerRequestWithDpopRetry} for DPoP nonces.\n */\nexport async function authorizationServerRequestWithClientAttestationChallengeRetry<T>(options: {\n  request: (attestationChallenge?: string) => Promise<T>\n}): Promise<T> {\n  try {\n    return await options.request()\n  } catch (error) {\n    if (error instanceof Oauth2ClientErrorResponseError) {\n      const challengeRetry = shouldRetryAuthorizationServerRequestWithClientAttestationChallenge({\n        responseHeaders: error.response.headers,\n        errorResponse: error.errorResponse,\n      })\n\n      // Retry with the fresh challenge\n      if (challengeRetry.retry) {\n        return options.request(challengeRetry.attestationChallenge)\n      }\n    }\n\n    throw error\n  }\n}\n","import z from 'zod'\n\nexport const zPreAuthorizedCodeGrantIdentifier = z.literal('urn:ietf:params:oauth:grant-type:pre-authorized_code')\nexport const preAuthorizedCodeGrantIdentifier = zPreAuthorizedCodeGrantIdentifier.value\nexport type PreAuthorizedCodeGrantIdentifier = z.infer<typeof zPreAuthorizedCodeGrantIdentifier>\n\nexport const zAuthorizationCodeGrantIdentifier = z.literal('authorization_code')\nexport const authorizationCodeGrantIdentifier = zAuthorizationCodeGrantIdentifier.value\nexport type AuthorizationCodeGrantIdentifier = z.infer<typeof zAuthorizationCodeGrantIdentifier>\n\nexport const zRefreshTokenGrantIdentifier = z.literal('refresh_token')\nexport const refreshTokenGrantIdentifier = zRefreshTokenGrantIdentifier.value\nexport type RefreshTokenGrantIdentifier = z.infer<typeof zRefreshTokenGrantIdentifier>\n\n/**\n * Default value for `grant_types_supported` per RFC 8414 Section 2\n * when not explicitly provided in authorization server metadata.\n */\nexport const defaultGrantTypesSupported = [authorizationCodeGrantIdentifier, 'implicit'] as const\n\n/**\n * Get the supported grant types from authorization server metadata,\n * falling back to the RFC 8414 default of `[\"authorization_code\", \"implicit\"]`.\n */\nexport function getGrantTypesSupported(grantTypesSupported: string[] | undefined): readonly string[] {\n  return grantTypesSupported ?? defaultGrantTypesSupported\n}\n\nexport const zClientCredentialsGrantIdentifier = z.literal('client_credentials')\nexport const clientCredentialsGrantIdentifier = zClientCredentialsGrantIdentifier.value\nexport type ClientCredentialsGrantIdentifier = z.infer<typeof zClientCredentialsGrantIdentifier>\n","import type { ContentType, FetchHeaders, HttpMethod } from '@openid4vc/utils'\nimport { decodeUtf8String, encodeToBase64Url } from '@openid4vc/utils'\nimport type { CallbackContext } from './callbacks'\nimport { createClientAttestationPopJwt } from './client-attestation/client-attestation-pop'\nimport {\n  oauthClientAttestationHeader,\n  oauthClientAttestationPopHeader,\n  zClientAttestationJwtHeader,\n  zClientAttestationJwtPayload,\n} from './client-attestation/z-client-attestation'\nimport { decodeJwt } from './common/jwt/decode-jwt'\nimport type { JwtSignerJwk } from './common/jwt/z-jwt'\nimport { createDpopJwt } from './dpop/dpop'\nimport { Oauth2Error } from './error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from './metadata/authorization-server/z-authorization-server-metadata'\nimport { preAuthorizedCodeGrantIdentifier } from './z-grant-type'\n\nexport enum SupportedClientAuthenticationMethod {\n  ClientSecretBasic = 'client_secret_basic',\n  ClientSecretPost = 'client_secret_post',\n  ClientAttestationJwt = 'attest_jwt_client_auth',\n  // DPoP-bound variant introduced in draft 09.\n  ClientAttestationJwtDpop = 'attest_jwt_client_auth_dpop',\n  None = 'none',\n}\n\ntype ClientAuthenticationEndpointType = 'endpoint' | 'token' | 'introspection'\n\n/**\n * Determine the supported client authentication method based on authorization\n * server metadata\n */\nexport function getSupportedClientAuthenticationMethod(\n  authorizationServer: AuthorizationServerMetadata,\n  endpointType: ClientAuthenticationEndpointType\n): SupportedClientAuthenticationMethod {\n  if (endpointType === 'introspection' && authorizationServer.introspection_endpoint_auth_methods_supported) {\n    const supportedMethod = authorizationServer.introspection_endpoint_auth_methods_supported.find(\n      (m): m is SupportedClientAuthenticationMethod =>\n        Object.values(SupportedClientAuthenticationMethod).includes(m as SupportedClientAuthenticationMethod)\n    )\n\n    if (!supportedMethod) {\n      throw new Oauth2Error(\n        `Authorization server metadata for issuer '${\n          authorizationServer.issuer\n        }' has 'introspection_endpoint_auth_methods_supported' metadata, but does not contain a supported value. Supported values are '${Object.values(\n          SupportedClientAuthenticationMethod\n        ).join(\n          ', '\n        )}', found values are '${authorizationServer.introspection_endpoint_auth_methods_supported.join(', ')}'`\n      )\n    }\n\n    return supportedMethod\n  }\n\n  // We allow the introspection endpoint to fallback on the token endpoint metadata if the introspection\n  // metadata is not defined\n  if (authorizationServer.token_endpoint_auth_methods_supported) {\n    const supportedMethod = authorizationServer.token_endpoint_auth_methods_supported.find(\n      (m): m is SupportedClientAuthenticationMethod =>\n        Object.values(SupportedClientAuthenticationMethod).includes(m as SupportedClientAuthenticationMethod)\n    )\n\n    if (!supportedMethod) {\n      throw new Oauth2Error(\n        `Authorization server metadata for issuer '${\n          authorizationServer.issuer\n        }' has 'token_endpoint_auth_methods_supported' metadata, but does not contain a supported value. Supported values are '${Object.values(\n          SupportedClientAuthenticationMethod\n        ).join(', ')}', found values are '${authorizationServer.token_endpoint_auth_methods_supported.join(', ')}'`\n      )\n    }\n\n    return supportedMethod\n  }\n\n  // If omitted from metadata, the default is \"client_secret_basic\" according to rfc8414\n  return SupportedClientAuthenticationMethod.ClientSecretBasic\n}\n\nexport interface ClientAuthenticationDynamicOptions {\n  clientId: string\n  clientSecret: string\n}\n\n/**\n * Dynamicaly get the client authentication method based on endpoint type and authorization server.\n * Only `client_secret_post`, `client_secret_basic`, and `none` supported.\n *\n * It also supports anonymous access to the token endpoint for pre-authorized code flow\n * if the authorization server has enabled `pre-authorized_grant_anonymous_access_supported`\n */\nexport function clientAuthenticationDynamic(options: ClientAuthenticationDynamicOptions): ClientAuthenticationCallback {\n  return (callbackOptions) => {\n    const { url, authorizationServerMetadata, body } = callbackOptions\n    const endpointType: ClientAuthenticationEndpointType =\n      url === authorizationServerMetadata.introspection_endpoint\n        ? 'introspection'\n        : url === authorizationServerMetadata.token_endpoint\n          ? 'token'\n          : 'endpoint'\n    const method = getSupportedClientAuthenticationMethod(authorizationServerMetadata, endpointType)\n\n    // Special case for pre-auth flow where we can use anonymous client\n    if (\n      endpointType === 'token' &&\n      body.grant_type === preAuthorizedCodeGrantIdentifier &&\n      authorizationServerMetadata['pre-authorized_grant_anonymous_access_supported']\n    ) {\n      return clientAuthenticationAnonymous()(callbackOptions)\n    }\n\n    if (method === SupportedClientAuthenticationMethod.ClientSecretBasic) {\n      return clientAuthenticationClientSecretBasic(options)(callbackOptions)\n    }\n\n    if (method === SupportedClientAuthenticationMethod.ClientSecretPost) {\n      return clientAuthenticationClientSecretPost(options)(callbackOptions)\n    }\n\n    if (method === SupportedClientAuthenticationMethod.None) {\n      return clientAuthenticationNone(options)(callbackOptions)\n    }\n\n    throw new Oauth2Error(\n      `Unsupported client auth method ${method}. Supported values are ${Object.values(\n        SupportedClientAuthenticationMethod\n      ).join(', ')}`\n    )\n  }\n}\n\n/**\n * Options for client authentication\n */\nexport interface ClientAuthenticationCallbackOptions {\n  /**\n   * Metadata of the authorization server\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * URL to which the request will be made\n   */\n  url: string\n\n  /**\n   * http method that will be used\n   */\n  method: HttpMethod\n\n  /**\n   * Headers for the request. You can modify this object\n   */\n  headers: FetchHeaders\n\n  contentType: ContentType\n\n  /**\n   * The body as a JSON object. If content type `x-www-form-urlencoded`\n   * is used, it will be encoded after this call.\n   *\n   * You can modify this object\n   */\n  body: Record<string, unknown>\n\n  /**\n   * A fresh Client Attestation challenge provided by the authorization server (draft 09), e.g.\n   * obtained from the `OAuth-Client-Attestation-Challenge` response header when retrying after a\n   * `use_attestation_challenge` error. When set it takes precedence over any statically configured\n   * challenge for methods that include a Client Attestation PoP.\n   */\n  attestationChallenge?: string\n}\n\n/**\n * Callback method to determine the client authentication for a request.\n */\nexport type ClientAuthenticationCallback = (options: ClientAuthenticationCallbackOptions) => Promise<void> | void\n\nexport interface ClientAuthenticationClientSecretPostOptions {\n  clientId: string\n  clientSecret: string\n}\n\n/**\n * Client authentication using `client_secret_post` option\n */\nexport function clientAuthenticationClientSecretPost(\n  options: ClientAuthenticationClientSecretPostOptions\n): ClientAuthenticationCallback {\n  return ({ body }) => {\n    body.client_id = options.clientId\n    body.client_secret = options.clientSecret\n  }\n}\n\nexport interface ClientAuthenticationClientSecretBasicOptions {\n  clientId: string\n  clientSecret: string\n}\n\n/**\n * Client authentication using `client_secret_basic` option\n */\nexport function clientAuthenticationClientSecretBasic(\n  options: ClientAuthenticationClientSecretBasicOptions\n): ClientAuthenticationCallback {\n  return ({ headers }) => {\n    const authorization = encodeToBase64Url(decodeUtf8String(`${options.clientId}:${options.clientSecret}`))\n    headers.set('Authorization', `Basic ${authorization}`)\n  }\n}\n\nexport interface ClientAuthenticationNoneOptions {\n  clientId: string\n}\n\n/**\n * Client authentication using `none` option\n */\nexport function clientAuthenticationNone(options: ClientAuthenticationNoneOptions): ClientAuthenticationCallback {\n  return ({ body }) => {\n    body.client_id = options.clientId\n  }\n}\n\n/**\n * Anonymous client authentication\n */\nexport function clientAuthenticationAnonymous(): ClientAuthenticationCallback {\n  return () => {}\n}\n\nexport interface ClientAuthenticationClientAttestationJwtOptions {\n  clientAttestationJwt: string\n  callbacks: Pick<CallbackContext, 'signJwt' | 'generateRandom'>\n\n  /**\n   * Challenge provided by the authorization server (e.g. obtained from its `challenge_endpoint`)\n   * to include in the Client Attestation PoP JWT.\n   */\n  challenge?: string\n}\n\n/**\n * Client authentication using `attest_jwt_client_auth` option.\n */\nexport function clientAuthenticationClientAttestationJwt(\n  options: ClientAuthenticationClientAttestationJwtOptions\n): ClientAuthenticationCallback {\n  return async ({ headers, authorizationServerMetadata, attestationChallenge }) => {\n    const clientAttestationPop = await createClientAttestationPopJwt({\n      authorizationServer: authorizationServerMetadata.issuer,\n      callbacks: options.callbacks,\n      clientAttestation: options.clientAttestationJwt,\n\n      // A server-provided challenge (draft 09, e.g. from the `OAuth-Client-Attestation-Challenge`\n      // response header on retry) takes precedence over a statically configured challenge.\n      challenge: attestationChallenge ?? options.challenge,\n    })\n\n    headers.set(oauthClientAttestationHeader, options.clientAttestationJwt)\n    headers.set(oauthClientAttestationPopHeader, clientAttestationPop)\n  }\n}\n\nexport interface ClientAuthenticationClientAttestationJwtDpopOptions {\n  clientAttestationJwt: string\n  callbacks: Pick<CallbackContext, 'signJwt' | 'generateRandom' | 'hash'>\n\n  /**\n   * The DPoP (client instance) key signer. In the DPoP-bound method the client instance key and the\n   * DPoP key are the same key. If not provided, the signer is derived from the `cnf.jwk` of the client\n   * attestation.\n   */\n  signer?: JwtSignerJwk\n\n  /**\n   * Challenge provided by the authorization server (e.g. obtained from its `challenge_endpoint`) to\n   * include in the DPoP proof. A server-provided challenge threaded through the client authentication\n   * callback takes precedence. The challenge is placed in the DPoP `nonce` claim.\n   */\n  challenge?: string\n}\n\n/**\n * Client authentication using the `attest_jwt_client_auth_dpop` option (draft 09 §5.2).\n *\n * In this DPoP-bound variant the client instance key and the DPoP key are the same key, and a single\n * DPoP proof serves as both the DPoP proof and the Client Attestation PoP. The request carries the\n * `OAuth-Client-Attestation` and `DPoP` headers, but no separate `OAuth-Client-Attestation-PoP` header.\n */\nexport function clientAuthenticationClientAttestationJwtDpop(\n  options: ClientAuthenticationClientAttestationJwtDpopOptions\n): ClientAuthenticationCallback {\n  return async ({ headers, url, method, attestationChallenge }) => {\n    const clientAttestation = decodeJwt({\n      jwt: options.clientAttestationJwt,\n      headerSchema: zClientAttestationJwtHeader,\n      payloadSchema: zClientAttestationJwtPayload,\n    })\n\n    const signer = options.signer ?? {\n      method: 'jwk',\n      alg: clientAttestation.header.alg,\n      publicJwk: clientAttestation.payload.cnf.jwk,\n    }\n\n    const dpopJwt = await createDpopJwt({\n      request: { url, method },\n      signer,\n      // A server-provided challenge (draft 09, e.g. from the `OAuth-Client-Attestation-Challenge`\n      // response header on retry) takes precedence over a statically configured challenge. In the\n      // DPoP-bound method the challenge is carried in the DPoP `nonce` claim.\n      nonce: attestationChallenge ?? options.challenge,\n      callbacks: options.callbacks,\n    })\n\n    headers.set(oauthClientAttestationHeader, options.clientAttestationJwt)\n    headers.set('DPoP', dpopJwt)\n  }\n}\n","/**\n * Algorithm transformation utilities for JWA and COSE\n *\n * This module provides utilities to transform between JWA (JSON Web Algorithms)\n * signature algorithm identifiers and fully-specified COSE (CBOR Object Signing and Encryption)\n * algorithm identifiers.\n *\n * Based on RFC 9864: Fully-Specified Algorithms for JOSE and COSE\n * https://www.rfc-editor.org/rfc/rfc9864.html\n */\n\nimport { Oauth2Error } from '../../error/Oauth2Error'\n\n/**\n * JWA (JSON Web Algorithms) signature algorithm identifiers\n *\n * From RFC 7518 (JWA) and RFC 9864 (Fully-Specified Algorithms)\n */\nenum JwaSignatureAlgorithm {\n  // EdDSA algorithms - RFC 9864 Section 2.2\n  Ed25519 = 'Ed25519',\n  Ed448 = 'Ed448',\n\n  // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2\n  // Maps to Ed25519 as it's the most common use case (similar to WebAuthn's approach)\n  EdDSA = 'EdDSA',\n\n  // ECDSA algorithms - RFC 9864 Section 2.1\n  // JWA ECDSA algorithms are already fully-specified\n  ES256 = 'ES256',\n  ES384 = 'ES384',\n  ES512 = 'ES512',\n  ES256K = 'ES256K',\n\n  // RSA algorithms - RFC 7518\n  RS256 = 'RS256',\n  RS384 = 'RS384',\n  RS512 = 'RS512',\n  PS256 = 'PS256',\n  PS384 = 'PS384',\n  PS512 = 'PS512',\n}\n\n/**\n * Mapping of JWA signature algorithm identifiers to fully-specified COSE algorithm identifiers\n *\n * From RFC 9864:\n * - EdDSA algorithms (Section 2.2)\n * - ECDSA algorithms (Section 2.1) - JWA ECDSA algorithms are already fully-specified\n *\n * Note: JWA ECDSA algorithms (ES256, ES384, ES512) are already fully-specified,\n * while COSE ECDSA algorithms with the same names are polymorphic and deprecated.\n * The fully-specified COSE equivalents use different names (ESP256, ESP384, ESP512).\n */\nconst JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP = {\n  // EdDSA algorithms - RFC 9864 Section 2.2\n  [JwaSignatureAlgorithm.Ed25519]: -19,\n  [JwaSignatureAlgorithm.Ed448]: -53,\n\n  // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2\n  // Maps to Ed25519 as it's the most common use case (similar to WebAuthn's approach)\n  [JwaSignatureAlgorithm.EdDSA]: -19,\n\n  // ECDSA algorithms - RFC 9864 Section 2.1\n  // JOSE ES256/ES384/ES512 map to fully-specified COSE ESP256/ESP384/ESP512\n  [JwaSignatureAlgorithm.ES256]: -9, // COSE ESP256 (ECDSA using P-256 curve and SHA-256)\n  [JwaSignatureAlgorithm.ES384]: -51, // COSE ESP384 (ECDSA using P-384 curve and SHA-384)\n  [JwaSignatureAlgorithm.ES512]: -52, // COSE ESP512 (ECDSA using P-521 curve and SHA-512)\n  [JwaSignatureAlgorithm.ES256K]: -47, // ECDSA using secp256k1 curve and SHA-256\n\n  // RSA algorithms - RFC 7518\n  [JwaSignatureAlgorithm.RS256]: -257, // RSASSA-PKCS1-v1_5 using SHA-256\n  [JwaSignatureAlgorithm.RS384]: -258, // RSASSA-PKCS1-v1_5 using SHA-384\n  [JwaSignatureAlgorithm.RS512]: -259, // RSASSA-PKCS1-v1_5 using SHA-512\n  [JwaSignatureAlgorithm.PS256]: -37, // RSASSA-PSS using SHA-256 and MGF1 with SHA-256\n  [JwaSignatureAlgorithm.PS384]: -38, // RSASSA-PSS using SHA-384 and MGF1 with SHA-384\n  [JwaSignatureAlgorithm.PS512]: -39, // RSASSA-PSS using SHA-512 and MGF1 with SHA-512\n} as const\n\n/**\n * Mapping of COSE algorithm identifiers to JWA signature algorithm identifiers\n *\n * This is the inverse of JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP, with additional entries\n * for deprecated polymorphic COSE algorithms that should be avoided.\n */\nconst COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP = {\n  // EdDSA algorithms - RFC 9864 Section 2.2\n  [-19]: JwaSignatureAlgorithm.Ed25519,\n  [-53]: JwaSignatureAlgorithm.Ed448,\n\n  // Deprecated polymorphic EdDSA - RFC 9864 Section 4.1.2 & 4.2.2\n  // Maps to Ed25519 as it's the most common use case (similar to WebAuthn's approach)\n  [-8]: JwaSignatureAlgorithm.Ed25519,\n\n  // ECDSA algorithms - RFC 9864 Section 2.1\n  // Fully-specified COSE algorithms\n  [-9]: JwaSignatureAlgorithm.ES256, // ESP256 -> ES256\n  [-51]: JwaSignatureAlgorithm.ES384, // ESP384 -> ES384\n  [-52]: JwaSignatureAlgorithm.ES512, // ESP512 -> ES512\n  [-47]: JwaSignatureAlgorithm.ES256K, // ECDSA using secp256k1\n\n  // Deprecated polymorphic COSE ECDSA algorithms - RFC 9864 Section 4.2.2\n  // These are included for backwards compatibility but should be avoided\n  [-7]: JwaSignatureAlgorithm.ES256, // Deprecated COSE ES256 (polymorphic)\n  [-35]: JwaSignatureAlgorithm.ES384, // Deprecated COSE ES384 (polymorphic)\n  [-36]: JwaSignatureAlgorithm.ES512, // Deprecated COSE ES512 (polymorphic)\n\n  // RSA algorithms\n  [-257]: JwaSignatureAlgorithm.RS256,\n  [-258]: JwaSignatureAlgorithm.RS384,\n  [-259]: JwaSignatureAlgorithm.RS512,\n  [-37]: JwaSignatureAlgorithm.PS256,\n  [-38]: JwaSignatureAlgorithm.PS384,\n  [-39]: JwaSignatureAlgorithm.PS512,\n} as const\n\nexport type CoseAlgorithmIdentifier = keyof typeof COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP\nexport type JwaSignatureAlgorithmIdentifier = `${JwaSignatureAlgorithm}`\n\n/**\n * Transform a JWA signature algorithm identifier to an RFC 9864 fully-specified COSE algorithm identifier\n *\n * @param jwaAlg - JWA signature algorithm identifier (e.g., 'Ed25519', 'ES256')\n * @returns Fully-specified COSE algorithm identifier (e.g., -19, -9) or undefined if not mappable\n *\n * @example\n * ```typescript\n * const coseAlg = jwaSignatureAlgorithmToFullySpecifiedCoseAlgorithm('Ed25519') // Returns -19\n * const coseAlg = jwaSignatureAlgorithmToFullySpecifiedCoseAlgorithm('ES256')   // Returns -9 (ESP256)\n * ```\n */\nexport function jwaSignatureAlgorithmToFullySpecifiedCoseAlgorithm(\n  jwaAlg: string\n): CoseAlgorithmIdentifier | undefined {\n  return JWA_SIGNATURE_TO_COSE_ALGORITHM_MAP[jwaAlg as JwaSignatureAlgorithm]\n}\n\n/**\n * Transform a COSE algorithm identifier (either RFC 9864 fully-specified, or polymorphic) to a JWA signature algorithm identifier\n *\n * @param coseAlg - COSE algorithm identifier (e.g., -19, -9)\n * @returns JWA signature algorithm identifier (e.g., 'Ed25519', 'ES256') or undefined if not mappable\n *\n * @example\n * ```typescript\n * const jwaAlg = fullySpecifiedCoseAlgorithmToJwaSignatureAlgorithm(-19) // Returns 'Ed25519'\n * const jwaAlg = fullySpecifiedCoseAlgorithmToJwaSignatureAlgorithm(-9)  // Returns 'ES256'\n * const jwaAlg = fullySpecifiedCoseAlgorithmToJwaSignatureAlgorithm(-7)  // Returns 'ES256' (deprecated polymorphic COSE ES256)\n * ```\n */\nexport function fullySpecifiedCoseAlgorithmToJwaSignatureAlgorithm(\n  coseAlg: number\n): JwaSignatureAlgorithmIdentifier | undefined {\n  return COSE_TO_JWA_SIGNATURE_ALGORITHM_MAP[coseAlg as CoseAlgorithmIdentifier]\n}\n\n/**\n * Transform an array of JWA signature algorithm identifiers to RFC 9864 fully-specified COSE algorithm identifiers.\n *\n * By default it filters out unmappable algorithms. You can also choose to throw an error when an unknown\n * algorithm is detected.\n *\n * @param jwaAlgs - Array of JWA signature algorithm identifiers\n * @returns Array of fully-specified COSE algorithm identifiers\n *\n * @example\n * ```typescript\n * const coseAlgs = jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray(['Ed25519', 'ES256', 'Unknown'])\n * // Returns [-19, -9]\n * ```\n */\nexport function jwaSignatureAlgorithmArrayToFullySpecifiedCoseAlgorithmArray(\n  jwaAlgs: string[],\n  throwOnUnknownValue = false\n): CoseAlgorithmIdentifier[] {\n  return jwaAlgs\n    .map((jwaAlg) => {\n      const coseAlg = jwaSignatureAlgorithmToFullySpecifiedCoseAlgorithm(jwaAlg)\n      if (coseAlg || !throwOnUnknownValue) return coseAlg\n      throw new Oauth2Error(`Found unknown JWA signature algorithm '${jwaAlg}'. Unable to map to COSE algorithm.`)\n    })\n    .filter((coseAlg): coseAlg is CoseAlgorithmIdentifier => coseAlg !== undefined)\n}\n\n/**\n * Transform an array of COSE algorithm identifiers (either RFC 9864 fully-specified or polymorphic) to JWA signature algorithm identifiers\n *\n * By default it filters out unmappable algorithms. You can also choose to throw an error when an unknown\n * algorithm is detected.\n *\n * @param coseAlgs - Array of COSE algorithm identifiers\n * @returns Array of JWA signature algorithm identifiers\n *\n * @example\n * ```typescript\n * const jwaAlgs = fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray([-19, -9, 999])\n * // Returns ['Ed25519', 'ES256']\n * ```\n */\nexport function fullySpecifiedCoseAlgorithmArrayToJwaSignatureAlgorithmArray(\n  coseAlgs: number[],\n  throwOnUnknownValue = false\n): JwaSignatureAlgorithmIdentifier[] {\n  return coseAlgs\n    .map((coseAlg) => {\n      const jwaAlg = fullySpecifiedCoseAlgorithmToJwaSignatureAlgorithm(coseAlg)\n      if (jwaAlg || !throwOnUnknownValue) return jwaAlg\n      throw new Oauth2Error(\n        `Found unknown COSE algorithm identifier '${coseAlg}'. Unable to map to JWA signature algorithm.`\n      )\n    })\n    .filter((alg): alg is JwaSignatureAlgorithmIdentifier => alg !== undefined)\n}\n","import type { FetchHeaders } from '@openid4vc/utils'\nimport { SupportedAuthenticationScheme } from '../access-token/verify-access-token'\nimport { Oauth2ErrorCodes, type Oauth2ErrorResponse } from '../common/z-oauth2-error'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { Oauth2ResourceUnauthorizedError } from '../error/Oauth2ResourceUnauthorizedError'\nimport { extractDpopNonceFromHeaders, type RequestDpopOptions } from './dpop'\n\nexport async function authorizationServerRequestWithDpopRetry<T>(options: {\n  dpop?: RequestDpopOptions\n  request: (dpop?: RequestDpopOptions) => Promise<T>\n}): Promise<T> {\n  try {\n    return await options.request(options.dpop)\n  } catch (error) {\n    if (options.dpop && error instanceof Oauth2ClientErrorResponseError) {\n      const dpopRetry = shouldRetryAuthorizationServerRequestWithDPoPNonce({\n        responseHeaders: error.response.headers,\n        errorResponse: error.errorResponse,\n      })\n\n      // Retry with the dpop nonce\n      if (dpopRetry.retry) {\n        return options.request({\n          ...options.dpop,\n          nonce: dpopRetry.dpopNonce,\n        })\n      }\n    }\n\n    throw error\n  }\n}\n\nexport interface ShouldRetryAuthorizationServerRequestWithDpopNonceOptions {\n  /**\n   * The error response that will be evaluated for the\n   * 'use_dpop_nonce' error to determine whether the request\n   * should be retried using a dpop nonce.\n   */\n  errorResponse: Oauth2ErrorResponse\n\n  /**\n   * The headers returned in the response. The 'DPoP-Nonce'\n   * header will be extracted if the access token error response indicates so.\n   * Will throw an error if the 'error' in the response is 'use_dpop_nonce' but the\n   * headers does not contain the 'DPoP-Nonce' header value.\n   */\n  responseHeaders: FetchHeaders\n}\n\nexport function shouldRetryAuthorizationServerRequestWithDPoPNonce(\n  options: ShouldRetryAuthorizationServerRequestWithDpopNonceOptions\n) {\n  if (options.errorResponse.error !== 'use_dpop_nonce') {\n    return {\n      retry: false,\n    } as const\n  }\n\n  const dpopNonce = extractDpopNonceFromHeaders(options.responseHeaders)\n  if (!dpopNonce) {\n    throw new Oauth2Error(\n      `Error response error contains error 'use_dpop_nonce' but the response headers do not include a valid 'DPoP-Nonce' header value.`\n    )\n  }\n\n  return {\n    retry: true,\n    dpopNonce,\n  } as const\n}\n\nexport interface ShouldRetryResourceRequestWithDpopNonceOptions {\n  resourceUnauthorizedError: Oauth2ResourceUnauthorizedError\n\n  /**\n   * The headers returned in the resource request response. If the\n   * headeres contain a 'WWW-Authenticate' header containing error value\n   * of 'use_dpop_nonce', the 'DPoP-Nonce' header will be extracted.\n   * Will throw an error if the 'error' in the 'WWW-Authenticate' header is 'use_dpop_nonce'\n   * but the headers does not contain the 'DPoP-Nonce' header value.\n   */\n  responseHeaders: FetchHeaders\n}\n\nexport function shouldRetryResourceRequestWithDPoPNonce(options: ShouldRetryResourceRequestWithDpopNonceOptions) {\n  const useDpopNonceChallenge = options.resourceUnauthorizedError.wwwAuthenticateHeaders.find(\n    (challenge) =>\n      challenge.scheme === SupportedAuthenticationScheme.DPoP && challenge.error === Oauth2ErrorCodes.UseDpopNonce\n  )\n\n  if (!useDpopNonceChallenge) {\n    return { retry: false } as const\n  }\n\n  const dpopNonce = extractDpopNonceFromHeaders(options.responseHeaders)\n  if (!dpopNonce || typeof dpopNonce !== 'string') {\n    throw new Oauth2Error(\n      `Resource request error in 'WWW-Authenticate' response header contains error 'use_dpop_nonce' but the response headers do not include a valid 'DPoP-Nonce' value.`\n    )\n  }\n\n  return {\n    retry: true,\n    dpopNonce,\n  } as const\n}\n","import type { FetchResponse } from '@openid4vc/utils'\nimport type { AuthorizationChallengeErrorResponse } from '../authorization-challenge/z-authorization-challenge'\nimport { Oauth2ClientErrorResponseError } from './Oauth2ClientErrorResponseError'\n\nexport class Oauth2ClientAuthorizationChallengeError extends Oauth2ClientErrorResponseError {\n  public constructor(\n    message: string,\n    public readonly errorResponse: AuthorizationChallengeErrorResponse,\n    response: FetchResponse\n  ) {\n    super(message, errorResponse, response)\n  }\n}\n","import { encodeWwwAuthenticateHeader, parseWwwAuthenticateHeader } from '@openid4vc/utils'\nimport type { SupportedAuthenticationScheme } from '../access-token/verify-access-token'\nimport type { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2Error } from './Oauth2Error'\n\nexport interface WwwAuthenticateHeaderChallenge {\n  scheme: SupportedAuthenticationScheme | (string & {})\n\n  /**\n   * Space delimited scope value that lists scopes required\n   * to access this resource.\n   */\n  scope?: string\n\n  /**\n   * Error should only be undefined if no access token was provided at all\n   */\n  error?: Oauth2ErrorCodes | string\n  error_description?: string\n\n  /**\n   * Additional payload items to include in the Www-Authenticate\n   * header response.\n   */\n  additionalPayload?: Record<string, string>\n}\n\nexport class Oauth2ResourceUnauthorizedError extends Oauth2Error {\n  public readonly wwwAuthenticateHeaders: WwwAuthenticateHeaderChallenge[]\n\n  public constructor(\n    internalMessage: string | undefined,\n    wwwAuthenticateHeaders: WwwAuthenticateHeaderChallenge | Array<WwwAuthenticateHeaderChallenge>\n  ) {\n    super(`${internalMessage}\\n${JSON.stringify(wwwAuthenticateHeaders, null, 2)}`)\n    this.wwwAuthenticateHeaders = Array.isArray(wwwAuthenticateHeaders)\n      ? wwwAuthenticateHeaders\n      : [wwwAuthenticateHeaders]\n  }\n\n  static fromHeaderValue(value: string) {\n    const headers = parseWwwAuthenticateHeader(value)\n    return new Oauth2ResourceUnauthorizedError(\n      undefined,\n      headers.map(\n        ({ scheme, payload: { error, error_description, scope, ...additionalPayload } }) =>\n          ({\n            scheme,\n            error: Array.isArray(error) ? error.join(',') : (error ?? undefined),\n            error_description: Array.isArray(error_description)\n              ? error_description.join(',')\n              : (error_description ?? undefined),\n            scope: Array.isArray(scope) ? scope.join(',') : (scope ?? undefined),\n            ...additionalPayload,\n          }) satisfies WwwAuthenticateHeaderChallenge\n      )\n    )\n  }\n\n  public toHeaderValue() {\n    return encodeWwwAuthenticateHeader(\n      this.wwwAuthenticateHeaders.map((header) => ({\n        scheme: header.scheme,\n        payload: {\n          error: header.error ?? null,\n          error_description: header.error_description ?? null,\n          scope: header.scope ?? null,\n          ...header.additionalPayload,\n        },\n      }))\n    )\n  }\n}\n","import { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zJwtHeader, zJwtPayload } from '../common/jwt/z-jwt'\n\nexport const zIdTokenJwtHeader = z\n  .object({\n    ...zJwtHeader.shape,\n  })\n  .loose()\nexport type IdTokenJwtHeader = z.infer<typeof zIdTokenJwtHeader>\n\nexport const zIdTokenJwtPayload = z\n  .object({\n    ...zJwtPayload.shape,\n    iss: z.string(),\n    sub: z.string(),\n    aud: z.union([z.string(), z.array(z.string())]),\n    exp: zNumericDate,\n    iat: zNumericDate,\n    auth_time: zNumericDate.optional(),\n    acr: z.string().optional(),\n    amr: z.array(z.string()).optional(),\n    azp: z.string().optional(),\n\n    // Standard Profile Claims\n    // https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims\n    name: z.string().optional(),\n    given_name: z.string().optional(),\n    family_name: z.string().optional(),\n    middle_name: z.string().optional(),\n    nickname: z.string().optional(),\n    preferred_username: z.string().optional(),\n    profile: z.url().optional(),\n    picture: z.url().optional(),\n    website: z.url().optional(),\n    email: z.email().optional(),\n    email_verified: z.boolean().optional(),\n    gender: z.enum(['male', 'female']).or(z.string()).optional(),\n    birthdate: z.iso.date().optional(),\n    zoneinfo: z.string().optional(),\n    locale: z.string().optional(),\n    phone_number: z.string().optional(),\n    phone_number_verified: z.boolean().optional(),\n    address: z\n      .object({\n        formatted: z.string().optional(),\n        street_address: z.string().optional(),\n        locality: z.string().optional(),\n        region: z.string().optional(),\n        postal_code: z.string().optional(),\n        country: z.string().optional(),\n      })\n      .loose()\n      .optional(),\n    updated_at: zNumericDate.optional(),\n  })\n  .loose()\n\nexport type IdTokenJwtPayload = z.infer<typeof zIdTokenJwtPayload>\n","import type { CallbackContext } from '../callbacks'\nimport { extractJwkFromJwksForJwt } from '../common/jwk/jwks'\nimport { decodeJwt } from '../common/jwt/decode-jwt'\nimport { verifyJwt } from '../common/jwt/verify-jwt'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { fetchJwks } from '../metadata/fetch-jwks-uri'\nimport { zIdTokenJwtHeader, zIdTokenJwtPayload } from './z-id-token-jwt'\n\nexport interface VerifyIdTokenJwtOptions {\n  /**\n   * The compact id token.\n   */\n  idToken: string\n\n  /**\n   * Callbacks used for verifying the id token\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'fetch'>\n\n  /**\n   * If not provided current time will be used\n   */\n  now?: Date\n\n  /**\n   * Authorization server metadata\n   */\n  authorizationServer: AuthorizationServerMetadata\n\n  /**\n   * The client_id of the Relying Party for which the token was issued.\n   */\n  clientId: 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/**\n * Verify an ID Token JWT.\n */\nexport async function verifyIdTokenJwt(options: VerifyIdTokenJwtOptions) {\n  const { header, payload } = decodeJwt({\n    jwt: options.idToken,\n    headerSchema: zIdTokenJwtHeader,\n    payloadSchema: zIdTokenJwtPayload,\n  })\n\n  const jwksUrl = options.authorizationServer.jwks_uri\n  if (!jwksUrl) {\n    throw new Oauth2Error(\n      `Authorization server '${options.authorizationServer.issuer}' does not have a 'jwks_uri' parameter to fetch JWKs.`\n    )\n  }\n\n  if (payload.iss !== options.authorizationServer.issuer) {\n    throw new Oauth2Error(\n      `Invalid 'iss' claim in id token jwt. Expected '${options.authorizationServer.issuer}', got '${payload.iss}'.`\n    )\n  }\n\n  if (payload.azp && payload.azp !== options.clientId) {\n    throw new Oauth2Error(`Invalid 'azp' claim in id token jwt. Expected '${options.clientId}', got '${payload.azp}'.`)\n  }\n\n  const jwks = await fetchJwks(jwksUrl, options.callbacks.fetch)\n  const publicJwk = extractJwkFromJwksForJwt({\n    kid: header.kid,\n    jwks,\n    use: 'sig',\n  })\n\n  await verifyJwt({\n    compact: options.idToken,\n    header,\n    payload,\n    signer: { method: 'jwk', publicJwk, alg: header.alg },\n    verifyJwtCallback: options.callbacks.verifyJwt,\n    errorMessage: 'Error during verification of id token jwt.',\n    now: options.now,\n    expectedAudience: options.clientId,\n    expectedIssuer: options.authorizationServer.issuer,\n    expectedNonce: options.expectedNonce,\n  })\n\n  return {\n    header,\n    payload,\n  }\n}\n","import { addSecondsToDate, dateToSeconds } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport type { Jwk } from '../common/jwk/z-jwk'\nimport { jwtHeaderFromJwtSigner } from '../common/jwt/decode-jwt'\nimport type { JweEncryptor, JwtPayload, JwtSigner } from '../common/jwt/z-jwt'\nimport type { JarAuthorizationRequest } from './z-jar-authorization-request'\n\nexport interface CreateJarAuthorizationRequestOptions {\n  authorizationRequestPayload: JwtPayload & { client_id?: string }\n  requestUri?: string\n\n  jwtSigner: JwtSigner\n  jweEncryptor?: JweEncryptor\n\n  callbacks: Pick<CallbackContext, 'signJwt' | 'encryptJwe'>\n\n  /**\n   * Number of seconds after which the signed authorization request will expire\n   */\n  expiresInSeconds: number\n\n  /**\n   * Date that should be used as now. If not provided current date will be used.\n   */\n  now?: Date\n\n  additionalJwtPayload?: Record<string, unknown>\n}\n\n/**\n * Creates a JAR (JWT Authorization Request) request object.\n *\n * @param options - The input parameters\n * @param options.authorizationRequestPayload - The authorization request parameters\n * @param options.jwtSigner - The JWT signer\n * @param options.jweEncryptor - The JWE encryptor (optional) if provided, the request object will be encrypted\n * @param options.requestUri - The request URI (optional) if provided, the request object needs to be fetched from the URI\n * @param options.callbacks - The callback context\n * @returns the requestParams, signerJwk, encryptionJwk, and requestObjectJwt\n */\nexport async function createJarAuthorizationRequest(options: CreateJarAuthorizationRequestOptions) {\n  const { jwtSigner, jweEncryptor, authorizationRequestPayload, requestUri, callbacks } = 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: { ...jwtHeaderFromJwtSigner(jwtSigner), typ: 'oauth-authz-req+jwt' },\n    payload: {\n      iat: dateToSeconds(now),\n      exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n      ...options.additionalJwtPayload,\n      ...authorizationRequestPayload,\n    },\n  })\n  authorizationRequestJwt = jwt\n\n  if (jweEncryptor) {\n    const encryptionResult = await callbacks.encryptJwe(jweEncryptor, authorizationRequestJwt)\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 { jarAuthorizationRequest, signerJwk, encryptionJwk, authorizationRequestJwt }\n}\n","import { type BaseSchema, ContentType, createZodFetcher, type Fetch, InvalidFetchResponseError } from '@openid4vc/utils'\nimport type z from 'zod'\nimport { ValidationError } from '../../../utils/src/error/ValidationError'\n\nexport interface FetchWellKnownMetadataOptions {\n  /**\n   * Custom fetch implementation to use for fetching the metadata\n   */\n  fetch?: Fetch\n\n  /**\n   * The accepted content types. If not provided a default of `ContentType.Json`\n   * will be used. This will be used for the `Accept` header, as well as verified\n   * against the `Content-Type` response header.\n   */\n  acceptedContentType?: [ContentType, ...ContentType[]]\n}\n\n/**\n * Fetch well known metadata and validate the response.\n *\n * Returns null if 404 is returned\n * Returns validated metadata if successful response\n * Throws error otherwise\n *\n * @throws {ValidationError} if successful response but validation of response failed\n * @throws {InvalidFetchResponseError} if no successful or 404 response\n * @throws {Error} if parsing json from response fails\n */\nexport async function fetchWellKnownMetadata<Schema extends BaseSchema>(\n  wellKnownMetadataUrl: string,\n  schema: Schema,\n  options?: FetchWellKnownMetadataOptions\n): Promise<z.infer<Schema> | null> {\n  const fetcher = createZodFetcher(options?.fetch)\n\n  const acceptedContentType = options?.acceptedContentType ?? [ContentType.Json]\n\n  const { result, response } = await fetcher(schema, acceptedContentType, wellKnownMetadataUrl)\n  if (response.status === 404) {\n    return null\n  }\n\n  if (!response.ok) {\n    throw new InvalidFetchResponseError(\n      `Fetching well known metadata from '${wellKnownMetadataUrl}' resulted in an unsuccessful response with status '${response.status}'.`,\n      await response.clone().text(),\n      response\n    )\n  }\n\n  if (!result?.success) {\n    throw new ValidationError(`Validation of metadata from '${wellKnownMetadataUrl}' failed`, result?.error)\n  }\n\n  return result.data\n}\n","import { zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zAlgValueNotNone } from '../../common/z-common'\n\nconst knownClientAuthenticationMethod = z.enum([\n  'client_secret_basic',\n  'client_secret_post',\n  'attest_jwt_client_auth',\n  'attest_jwt_client_auth_dpop',\n  'client_secret_jwt',\n  'private_key_jwt',\n])\n\nexport const zAuthorizationServerMetadata = z\n  .object({\n    issuer: zHttpsUrl,\n    token_endpoint: zHttpsUrl,\n    token_endpoint_auth_methods_supported: z.optional(z.array(z.union([knownClientAuthenticationMethod, z.string()]))),\n    authorization_endpoint: z.optional(zHttpsUrl),\n    jwks_uri: z.optional(zHttpsUrl),\n    grant_types_supported: z.optional(z.array(z.string())),\n\n    // RFC7636\n    code_challenge_methods_supported: z.optional(z.array(z.string())),\n\n    // RFC9449\n    dpop_signing_alg_values_supported: z.optional(z.array(z.string())),\n\n    // RFC9126\n    require_pushed_authorization_requests: z.optional(z.boolean()),\n    pushed_authorization_request_endpoint: z.optional(zHttpsUrl),\n\n    // RFC9068\n    introspection_endpoint: z.optional(zHttpsUrl),\n    introspection_endpoint_auth_methods_supported: z.optional(\n      z.array(z.union([knownClientAuthenticationMethod, z.string()]))\n    ),\n    introspection_endpoint_auth_signing_alg_values_supported: z.optional(z.array(zAlgValueNotNone)),\n\n    // FiPA (no RFC yet)\n    authorization_challenge_endpoint: z.optional(zHttpsUrl),\n\n    // OpenID4VCI 1.1 - Interactive Authorization Endpoint\n    interactive_authorization_endpoint: z.optional(zHttpsUrl),\n    require_interactive_authorization_request: z.optional(z.boolean()),\n\n    // From OpenID4VCI specification\n    'pre-authorized_grant_anonymous_access_supported': z.optional(z.boolean()),\n\n    // OAuth 2.0 Attestation-Based Client Authentication (draft 09)\n    client_attestation_signing_alg_values_supported: z.optional(z.array(zAlgValueNotNone)),\n    client_attestation_pop_signing_alg_values_supported: z.optional(z.array(zAlgValueNotNone)),\n    // Endpoint from which the client can obtain a fresh challenge for the Client Attestation PoP JWT.\n    challenge_endpoint: z.optional(zHttpsUrl),\n\n    // Non-standard (draft 05 era); retained for backwards compatibility. Not part of draft 06+.\n    client_attestation_pop_nonce_required: z.boolean().optional(),\n\n    // RFC9207\n    authorization_response_iss_parameter_supported: z.boolean().optional(),\n  })\n  .loose()\n  .refine(\n    ({\n      introspection_endpoint_auth_methods_supported: methodsSupported,\n      introspection_endpoint_auth_signing_alg_values_supported: algValuesSupported,\n    }) => {\n      if (!methodsSupported) return true\n      if (!methodsSupported.includes('private_key_jwt') && !methodsSupported.includes('client_secret_jwt')) return true\n\n      return algValuesSupported !== undefined && algValuesSupported.length > 0\n    },\n    `Metadata value 'introspection_endpoint_auth_signing_alg_values_supported' must be defined if metadata 'introspection_endpoint_auth_methods_supported' value contains values 'private_key_jwt' or 'client_secret_jwt'`\n  )\n  .refine(\n    // OpenID4VCI 1.1: require_interactive_authorization_request MUST NOT be present if interactive_authorization_endpoint is omitted\n    ({ require_interactive_authorization_request, interactive_authorization_endpoint }) =>\n      !require_interactive_authorization_request || interactive_authorization_endpoint !== undefined,\n    `Metadata value 'require_interactive_authorization_request' MUST NOT be present if 'interactive_authorization_endpoint' is omitted`\n  )\n\nexport type AuthorizationServerMetadata = z.infer<typeof zAuthorizationServerMetadata>\n","import { type Fetch, joinUriParts, OpenId4VcBaseError, URL } from '@openid4vc/utils'\nimport { Oauth2Error } from '../../error/Oauth2Error'\nimport { fetchWellKnownMetadata } from '../fetch-well-known-metadata'\nimport { type AuthorizationServerMetadata, zAuthorizationServerMetadata } from './z-authorization-server-metadata'\n\nconst wellKnownAuthorizationServerSuffix = '.well-known/oauth-authorization-server'\nconst wellKnownOpenIdConfigurationServerSuffix = '.well-known/openid-configuration'\n\n/**\n * fetch authorization server metadata. It first tries to fetch the oauth-authorization-server metadata. If that returns\n *  a 404, the openid-configuration metadata will be fetched.\n */\nexport async function fetchAuthorizationServerMetadata(\n  issuer: string,\n  fetch?: Fetch\n): Promise<AuthorizationServerMetadata | null> {\n  const parsedIssuerUrl = new URL(issuer)\n\n  const openIdConfigurationWellKnownMetadataUrl = joinUriParts(issuer, [wellKnownOpenIdConfigurationServerSuffix])\n  const authorizationServerWellKnownMetadataUrl = joinUriParts(parsedIssuerUrl.origin, [\n    wellKnownAuthorizationServerSuffix,\n    parsedIssuerUrl.pathname,\n  ])\n\n  // NOTE: there is a difference in how to construct well-known OAuth2 and well-known openid\n  // url. For OAuth you place `.well-known/oauth-authorization-server` between the origin and\n  // the path. Historically we used the same method as OpenID (which a lot of servers seems to\n  // host as well), and thus we use this as a last fallback if it's different for now (in case of subpath).\n  const nonCompliantAuthorizationServerWellKnownMetadataUrl = joinUriParts(issuer, [wellKnownAuthorizationServerSuffix])\n\n  let firstError: Error | null = null\n\n  // First try oauth-authorization-server\n  let authorizationServerResult = await fetchWellKnownMetadata(\n    authorizationServerWellKnownMetadataUrl,\n    zAuthorizationServerMetadata,\n    {\n      fetch,\n    }\n  ).catch((error) => {\n    if (error instanceof OpenId4VcBaseError) throw error\n\n    // An exception occurs if a CORS-policy blocks the request, i.e. because the URL is invalid due to the legacy path being used\n    // The legacy path should still be tried therefore we store the first error to rethrow it later if needed\n    firstError = error\n  })\n\n  if (\n    !authorizationServerResult &&\n    nonCompliantAuthorizationServerWellKnownMetadataUrl !== authorizationServerWellKnownMetadataUrl\n  ) {\n    authorizationServerResult = await fetchWellKnownMetadata(\n      nonCompliantAuthorizationServerWellKnownMetadataUrl,\n      zAuthorizationServerMetadata,\n      {\n        fetch,\n      }\n    ).catch((error) => {\n      // Similar to above, if there was a library error, we throw it.\n      // However in other cases we swallow it, we only keep the first error\n      if (error instanceof OpenId4VcBaseError) throw error\n    })\n  }\n\n  if (!authorizationServerResult) {\n    authorizationServerResult = await fetchWellKnownMetadata(\n      openIdConfigurationWellKnownMetadataUrl,\n      zAuthorizationServerMetadata,\n      {\n        fetch,\n      }\n    ).catch((error) => {\n      throw firstError ?? error\n    })\n  }\n\n  if (!authorizationServerResult && firstError) {\n    throw firstError\n  }\n\n  if (authorizationServerResult && authorizationServerResult.issuer !== issuer) {\n    // issuer param MUST match\n    throw new Oauth2Error(\n      `The 'issuer' parameter '${authorizationServerResult.issuer}' in the well known authorization server metadata at '${authorizationServerWellKnownMetadataUrl}' does not match the provided issuer '${issuer}'.`\n    )\n  }\n\n  return authorizationServerResult\n}\n\nexport function getAuthorizationServerMetadataFromList(\n  authorizationServersMetadata: AuthorizationServerMetadata[],\n  issuer: string\n) {\n  const authorizationServerMetadata = authorizationServersMetadata.find(\n    (authorizationServerMetadata) => authorizationServerMetadata.issuer === issuer\n  )\n\n  if (!authorizationServerMetadata) {\n    throw new Oauth2Error(\n      `Authorization server '${issuer}' not found in list of authorization servers. Available authorization servers are ${authorizationServersMetadata\n        .map((as) => `'${as.issuer}'`)\n        .join(', ')}`\n    )\n  }\n\n  return authorizationServerMetadata\n}\n","import { addSecondsToDate, dateToSeconds, encodeToBase64Url, parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { HashAlgorithm } from '../callbacks'\nimport { calculateJwkThumbprint } from '../common/jwk/jwk-thumbprint'\nimport type { Jwk } from '../common/jwk/z-jwk'\nimport { jwtHeaderFromJwtSigner } from '../common/jwt/decode-jwt'\nimport type { JwtSigner } from '../common/jwt/z-jwt'\nimport {\n  type AccessTokenProfileJwtHeader,\n  type AccessTokenProfileJwtPayload,\n  zAccessTokenProfileJwtHeader,\n  zAccessTokenProfileJwtPayload,\n} from './z-access-token-jwt'\n\nexport interface CreateAccessTokenOptions {\n  callbacks: Pick<CallbackContext, 'signJwt' | 'generateRandom' | 'hash'>\n\n  /**\n   * public dpop jwk key. Will be encoded as jwk thumbprint in the `cnf.jkt` claim.\n   */\n  dpop?: {\n    jwk: Jwk\n  }\n\n  /**\n   * scope of the access token. If the authorization request included scopes\n   * they should be added to the access token as well\n   */\n  scope?: string\n\n  /**\n   * Client id to which the access token is bound.\n   * Can be undefined in case of anonymous access using pre authorized code flow\n   */\n  clientId?: string\n\n  /**\n   * The authorization server that issues the access token\n   */\n  authorizationServer: string\n\n  /**\n   * Signer of the access token\n   */\n  signer: JwtSigner\n\n  /**\n   * Number of seconds after which the token will expire\n   */\n  expiresInSeconds: number\n\n  /**\n   * The audience of the access token. Should be the `resource` if included in the authorization request\n   */\n  audience: string\n\n  /**\n   * The subject of the access token. When a resource owner is involved,\n   * it should be an identifier for the resource owner.\n   */\n  subject: string\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   * Additional payload claims to include in the access token JWT.\n   * Will override existing claims so you can override default behaviour, but be careful.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\n/**\n * Create an oauth2 access token conformant with \"JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens\"\n * @see https://datatracker.ietf.org/doc/html/rfc9068\n */\nexport async function createAccessTokenJwt(options: CreateAccessTokenOptions) {\n  const header = parseWithErrorHandling(zAccessTokenProfileJwtHeader, {\n    ...jwtHeaderFromJwtSigner(options.signer),\n    typ: 'at+jwt',\n  } satisfies AccessTokenProfileJwtHeader)\n\n  const now = options.now ?? new Date()\n\n  const payload = parseWithErrorHandling(zAccessTokenProfileJwtPayload, {\n    iat: dateToSeconds(now),\n    exp: dateToSeconds(addSecondsToDate(now, options.expiresInSeconds)),\n    aud: options.audience,\n    iss: options.authorizationServer,\n    jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n    client_id: options.clientId,\n    sub: options.subject,\n    scope: options.scope,\n    cnf: options.dpop\n      ? {\n          jkt: await calculateJwkThumbprint({\n            hashAlgorithm: HashAlgorithm.Sha256,\n            hashCallback: options.callbacks.hash,\n            jwk: options.dpop.jwk,\n          }),\n        }\n      : undefined,\n    ...options.additionalPayload,\n  } satisfies AccessTokenProfileJwtPayload)\n\n  const { jwt } = await options.callbacks.signJwt(options.signer, {\n    header,\n    payload,\n  })\n\n  return {\n    jwt,\n  }\n}\n","import { zHttpsUrl } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zOauth2ErrorResponse } from '../common/z-oauth2-error'\nimport {\n  zAuthorizationCodeGrantIdentifier,\n  zClientCredentialsGrantIdentifier,\n  zPreAuthorizedCodeGrantIdentifier,\n  zRefreshTokenGrantIdentifier,\n} from '../z-grant-type'\n\nexport const zAccessTokenRequest = z.intersection(\n  z\n    .object({\n      // Pre authorized code flow\n      'pre-authorized_code': z.optional(z.string()),\n\n      // Authorization code flow\n      code: z.optional(z.string()),\n      redirect_uri: z.url().optional(),\n\n      // Refresh token grant\n      refresh_token: z.optional(z.string()),\n\n      resource: z.optional(zHttpsUrl),\n      code_verifier: z.optional(z.string()),\n\n      grant_type: z.union([\n        zPreAuthorizedCodeGrantIdentifier,\n        zAuthorizationCodeGrantIdentifier,\n        zRefreshTokenGrantIdentifier,\n        zClientCredentialsGrantIdentifier,\n        // string makes the previous ones unnecessary, but it does help with error messages\n        z.string(),\n      ]),\n    })\n    .loose(),\n  z\n    .object({\n      tx_code: z.optional(z.string()),\n      // user_pin is from OpenID4VCI draft 11\n      user_pin: z.optional(z.string()),\n    })\n    .loose()\n    .refine(({ tx_code, user_pin }) => !tx_code || !user_pin || user_pin === tx_code, {\n      message: `If both 'tx_code' and 'user_pin' are present they must match`,\n    })\n    .transform(({ tx_code, user_pin, ...rest }) => {\n      return {\n        ...rest,\n        ...((tx_code ?? user_pin) ? { tx_code: tx_code ?? user_pin } : {}),\n      }\n    })\n)\nexport type AccessTokenRequest = z.infer<typeof zAccessTokenRequest>\n\nexport const zAccessTokenResponse = z\n  .object({\n    access_token: z.string(),\n    token_type: z.string(),\n\n    expires_in: z.optional(z.number().int()),\n    scope: z.optional(z.string()),\n    state: z.optional(z.string()),\n\n    refresh_token: z.optional(z.string()),\n\n    // OpenID4VCI specific parameters\n    c_nonce: z.optional(z.string()),\n    c_nonce_expires_in: z.optional(z.number().int()),\n\n    // TODO: add additional params\n    authorization_details: z\n      .array(\n        z\n          .object({\n            // required when type is openid_credential (so we probably need a discriminator)\n            // credential_identifiers: z.array(z.string()),\n          })\n          .loose()\n      )\n      .optional(),\n  })\n  .loose()\n\nexport type AccessTokenResponse = z.infer<typeof zAccessTokenResponse>\n\nexport const zAccessTokenErrorResponse = zOauth2ErrorResponse\nexport type AccessTokenErrorResponse = z.infer<typeof zAccessTokenErrorResponse>\n","import { parseWithErrorHandling } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { type AccessTokenResponse, zAccessTokenResponse } from './z-access-token'\n\nexport interface CreateAccessTokenResponseOptions {\n  callbacks: Pick<CallbackContext, 'signJwt' | 'generateRandom' | 'hash'>\n\n  /**\n   * The access token\n   */\n  accessToken: string\n\n  /**\n   * The type of token. Should be DPoP if the access token\n   * is bound to a dpop key\n   */\n  tokenType: 'DPoP' | 'Bearer' | (string & {})\n\n  /**\n   * Number of seconds after which the access tokens expires.\n   */\n  expiresInSeconds: number\n\n  /**\n   * The refresh token\n   */\n  refreshToken?: string\n\n  /**\n   * New cNonce value\n   */\n  cNonce?: string\n  cNonceExpiresIn?: number\n\n  /**\n   * Additional payload to include in the access token response.\n   *\n   * Will be applied after default payload to allow overriding over values, but be careful.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\nexport async function createAccessTokenResponse(options: CreateAccessTokenResponseOptions) {\n  const accessTokenResponse = parseWithErrorHandling(zAccessTokenResponse, {\n    access_token: options.accessToken,\n    refresh_token: options.refreshToken,\n    token_type: options.tokenType,\n    expires_in: options.expiresInSeconds,\n    c_nonce: options.cNonce,\n    c_nonce_expires_in: options.cNonceExpiresIn,\n    ...options.additionalPayload,\n  } satisfies AccessTokenResponse)\n\n  return accessTokenResponse\n}\n","import { formatZodError } from '@openid4vc/utils'\nimport { extractClientAttestationJwtsFromHeaders } from '../client-attestation/client-attestation'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { extractDpopJwtFromHeaders } from '../dpop/dpop'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport {\n  type AuthorizationCodeGrantIdentifier,\n  authorizationCodeGrantIdentifier,\n  getGrantTypesSupported,\n  type PreAuthorizedCodeGrantIdentifier,\n  preAuthorizedCodeGrantIdentifier,\n  type RefreshTokenGrantIdentifier,\n  refreshTokenGrantIdentifier,\n} from '../z-grant-type'\nimport { type AccessTokenRequest, zAccessTokenRequest } from './z-access-token'\n\nexport interface ParsedAccessTokenPreAuthorizedCodeRequestGrant {\n  grantType: PreAuthorizedCodeGrantIdentifier\n  preAuthorizedCode: string\n  txCode?: string\n}\n\nexport interface ParsedAccessTokenAuthorizationCodeRequestGrant {\n  grantType: AuthorizationCodeGrantIdentifier\n  code: string\n}\n\nexport interface ParsedAccessTokenRefreshTokenRequestGrant {\n  grantType: RefreshTokenGrantIdentifier\n  refreshToken: string\n}\n\ntype ParsedAccessTokenRequestGrant =\n  | ParsedAccessTokenPreAuthorizedCodeRequestGrant\n  | ParsedAccessTokenAuthorizationCodeRequestGrant\n  | ParsedAccessTokenRefreshTokenRequestGrant\n\nexport interface ParseAccessTokenRequestResult {\n  accessTokenRequest: AccessTokenRequest\n  grant: ParsedAccessTokenRequestGrant\n\n  /**\n   * The dpop jwt from the access token request headers\n   */\n  dpop?: {\n    jwt: string\n  }\n\n  /**\n   * The client attestation jwts from the access token request headers\n   */\n  clientAttestation?: {\n    clientAttestationJwt: string\n\n    /**\n     * Absent for the DPoP-bound `attest_jwt_client_auth_dpop` method (draft 09), where the DPoP proof\n     * serves as the Client Attestation PoP.\n     */\n    clientAttestationPopJwt?: string\n  }\n\n  /**\n   * The pkce code verifier from the access token request\n   */\n  pkceCodeVerifier?: string\n}\n\nexport interface ParseAccessTokenRequestOptions {\n  request: RequestLike\n\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  /**\n   * Authorization server metadata. When provided, the grant type will be validated\n   * against `grant_types_supported`. If `grant_types_supported` is not set in the metadata,\n   * the default per RFC 8414 is `[\"authorization_code\", \"implicit\"]`.\n   */\n  authorizationServerMetadata?: AuthorizationServerMetadata\n}\n\n/**\n * Parse access token request and extract the grant specific properties.\n *\n * If something goes wrong, such as the grant is not supported, missing parameters, etc,\n * it will throw `Oauth2ServerErrorResponseError` containing an error response object\n * that can be returned to the client.\n */\nexport function parseAccessTokenRequest(options: ParseAccessTokenRequestOptions): ParseAccessTokenRequestResult {\n  const parsedAccessTokenRequest = zAccessTokenRequest.safeParse(options.accessTokenRequest)\n  if (!parsedAccessTokenRequest.success) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: `Error occurred during validation of authorization request.\\n${formatZodError(parsedAccessTokenRequest.error)}`,\n    })\n  }\n\n  const accessTokenRequest = parsedAccessTokenRequest.data\n  let grant: ParsedAccessTokenRequestGrant\n\n  if (options.authorizationServerMetadata) {\n    const supportedGrantTypes = getGrantTypesSupported(options.authorizationServerMetadata.grant_types_supported)\n    if (!supportedGrantTypes.includes(accessTokenRequest.grant_type)) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.UnsupportedGrantType,\n        error_description: `The grant type '${accessTokenRequest.grant_type}' is not supported by the authorization server. Supported grant types are: ${supportedGrantTypes.join(', ')}`,\n      })\n    }\n  }\n\n  if (accessTokenRequest.grant_type === preAuthorizedCodeGrantIdentifier) {\n    if (!accessTokenRequest['pre-authorized_code']) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Missing required 'pre-authorized_code' for grant type '${preAuthorizedCodeGrantIdentifier}'`,\n      })\n    }\n\n    grant = {\n      grantType: preAuthorizedCodeGrantIdentifier,\n      preAuthorizedCode: accessTokenRequest['pre-authorized_code'],\n      txCode: accessTokenRequest.tx_code,\n    }\n  } else if (accessTokenRequest.grant_type === authorizationCodeGrantIdentifier) {\n    if (!accessTokenRequest.code) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Missing required 'code' for grant type '${authorizationCodeGrantIdentifier}'`,\n      })\n    }\n\n    grant = {\n      grantType: authorizationCodeGrantIdentifier,\n      code: accessTokenRequest.code,\n    }\n  } else if (accessTokenRequest.grant_type === refreshTokenGrantIdentifier) {\n    if (!accessTokenRequest.refresh_token) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Missing required 'refresh_token' for grant type '${refreshTokenGrantIdentifier}'`,\n      })\n    }\n\n    grant = {\n      grantType: refreshTokenGrantIdentifier,\n      refreshToken: accessTokenRequest.refresh_token,\n    }\n  } else {\n    // Unsupported grant type\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.UnsupportedGrantType,\n      error_description: `The grant type '${accessTokenRequest.grant_type}' is not supported`,\n    })\n  }\n\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 Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidDpopProof,\n      error_description: `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 = extractClientAttestationJwtsFromHeaders(options.request.headers)\n  if (!extractedClientAttestationJwts.valid) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description:\n        'Request contains client attestation header, but the values are not valid client attestation and client attestation PoP header.',\n    })\n  }\n\n  const pkceCodeVerifier = accessTokenRequest.code_verifier\n\n  return {\n    accessTokenRequest,\n    grant,\n\n    dpop: extractedDpopJwt.dpopJwt\n      ? {\n          jwt: extractedDpopJwt.dpopJwt,\n        }\n      : undefined,\n    clientAttestation: extractedClientAttestationJwts.clientAttestationHeader\n      ? {\n          clientAttestationJwt: extractedClientAttestationJwts.clientAttestationHeader,\n          clientAttestationPopJwt: extractedClientAttestationJwts.clientAttestationPopHeader,\n        }\n      : undefined,\n    pkceCodeVerifier,\n  }\n}\n","import { decodeUtf8String, encodeToBase64Url } from '@openid4vc/utils'\nimport { type CallbackContext, HashAlgorithm, type HashCallback } from './callbacks'\nimport { Oauth2Error } from './error/Oauth2Error'\n\nexport enum PkceCodeChallengeMethod {\n  Plain = 'plain',\n  S256 = 'S256',\n}\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?: Array<string | PkceCodeChallengeMethod>\n\n  /**\n   * Code verifier to use. If not provided a value will be generated.\n   */\n  codeVerifier?: string\n\n  callbacks: Pick<CallbackContext, 'hash' | 'generateRandom'>\n}\n\nexport interface CreatePkceReturn {\n  codeVerifier: string\n  codeChallenge: string\n  codeChallengeMethod: PkceCodeChallengeMethod\n}\n\nexport async function createPkce(options: CreatePkceOptions): Promise<CreatePkceReturn> {\n  const allowedCodeChallengeMethods = options.allowedCodeChallengeMethods ?? [\n    PkceCodeChallengeMethod.S256,\n    PkceCodeChallengeMethod.Plain,\n  ]\n\n  if (allowedCodeChallengeMethods.length === 0) {\n    throw new Oauth2Error(`Unable to create PKCE code verifier. 'allowedCodeChallengeMethods' is an empty array.`)\n  }\n\n  const codeChallengeMethod = allowedCodeChallengeMethods.includes(PkceCodeChallengeMethod.S256)\n    ? PkceCodeChallengeMethod.S256\n    : PkceCodeChallengeMethod.Plain\n\n  const codeVerifier = options.codeVerifier ?? encodeToBase64Url(await options.callbacks.generateRandom(64))\n  return {\n    codeVerifier,\n    codeChallenge: await calculateCodeChallenge({\n      codeChallengeMethod,\n      codeVerifier,\n      hashCallback: options.callbacks.hash,\n    }),\n    codeChallengeMethod,\n  }\n}\n\nexport interface VerifyPkceOptions {\n  /**\n   * secure random code verifier\n   */\n  codeVerifier: string\n\n  codeChallenge: string\n  codeChallengeMethod: PkceCodeChallengeMethod\n\n  callbacks: Pick<CallbackContext, 'hash'>\n}\n\nexport async function verifyPkce(options: VerifyPkceOptions) {\n  const calculatedCodeChallenge = await calculateCodeChallenge({\n    codeChallengeMethod: options.codeChallengeMethod,\n    codeVerifier: options.codeVerifier,\n    hashCallback: options.callbacks.hash,\n  })\n\n  if (options.codeChallenge !== calculatedCodeChallenge) {\n    throw new Oauth2Error(\n      `Derived code challenge '${calculatedCodeChallenge}' from code_verifier '${options.codeVerifier}' using code challenge method '${options.codeChallengeMethod}' does not match the expected code challenge.`\n    )\n  }\n}\n\nasync function calculateCodeChallenge(options: {\n  codeVerifier: string\n  codeChallengeMethod: PkceCodeChallengeMethod\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(await options.hashCallback(decodeUtf8String(options.codeVerifier), HashAlgorithm.Sha256))\n  }\n\n  throw new Oauth2Error(`Unsupported code challenge method ${options.codeChallengeMethod}`)\n}\n","import { type CallbackContext, HashAlgorithm } from '../callbacks'\nimport {\n  type VerifiedClientAttestationJwt,\n  verifyClientAttestation,\n  verifyClientAttestationJwt,\n} from '../client-attestation/client-attestation'\nimport type { VerifiedClientAttestationPopJwt } from '../client-attestation/client-attestation-pop'\nimport {\n  oauthClientAttestationHeader,\n  oauthClientAttestationPopHeader,\n} from '../client-attestation/z-client-attestation'\nimport { SupportedClientAuthenticationMethod } from '../client-authentication'\nimport { calculateJwkThumbprint } from '../common/jwk/jwk-thumbprint'\nimport type { Jwk } from '../common/jwk/z-jwk'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { verifyDpopJwt } from '../dpop/dpop'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { type PkceCodeChallengeMethod, verifyPkce } from '../pkce'\nimport type {\n  ParsedAccessTokenAuthorizationCodeRequestGrant,\n  ParsedAccessTokenPreAuthorizedCodeRequestGrant,\n  ParsedAccessTokenRefreshTokenRequestGrant,\n} from './parse-access-token-request'\nimport type { AccessTokenRequest } from './z-access-token'\n\nexport interface VerifyAccessTokenRequestDpop {\n  /**\n   * Whether dpop is required\n   */\n  required?: boolean\n\n  /**\n   * The dpop jwt from the access token request\n   */\n  jwt?: string\n\n  /**\n   * The expected jwk thumbprint, and can be used to match a dpop provided in the authorization\n   * request to the dpop key used for the access token request.\n   */\n  expectedJwkThumbprint?: 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   * Expected nonce in the dpop proof. If not provided the nonce won't be validated.\n   *\n   * For the DPoP-bound `attest_jwt_client_auth_dpop` method (draft 09) the server-provided client\n   * attestation challenge is carried in the dpop `nonce` claim, so this can be set to the issued\n   * challenge to enforce it.\n   */\n  expectedNonce?: string\n}\n\nexport interface VerifyAccessTokenRequestClientAttestation {\n  /**\n   * Whether client attestation is required.\n   */\n  required?: boolean\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  clientAttestationJwt?: string\n  clientAttestationPopJwt?: string\n\n  /**\n   * The expected client id that is bound to the authorization session, and can be used to match the client id\n   * provided in the authorization request to the client used for the access token request.\n   */\n  expectedClientId?: string\n}\n\nexport interface VerifyAccessTokenRequestPkce {\n  codeVerifier?: string\n\n  codeChallenge: string\n  codeChallengeMethod: PkceCodeChallengeMethod\n}\n\nexport interface VerifyAccessTokenRequestReturn {\n  dpop?: {\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    jwk: Jwk\n  }\n\n  clientAttestation?: {\n    clientAttestation: VerifiedClientAttestationJwt\n    /**\n     * Absent for the DPoP-bound `attest_jwt_client_auth_dpop` method (draft 09), where the verified\n     * DPoP proof serves as the Client Attestation PoP.\n     */\n    clientAttestationPop?: VerifiedClientAttestationPopJwt\n  }\n}\n\nexport interface VerifyPreAuthorizedCodeAccessTokenRequestOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  grant: ParsedAccessTokenPreAuthorizedCodeRequestGrant\n  accessTokenRequest: AccessTokenRequest\n  request: RequestLike\n\n  expectedPreAuthorizedCode: string\n  expectedTxCode?: string\n\n  clientAttestation?: VerifyAccessTokenRequestClientAttestation\n  dpop?: VerifyAccessTokenRequestDpop\n  pkce?: VerifyAccessTokenRequestPkce\n\n  preAuthorizedCodeExpiresAt?: Date\n  now?: Date\n\n  callbacks: Pick<CallbackContext, 'hash' | 'verifyJwt'>\n}\n\nexport async function verifyPreAuthorizedCodeAccessTokenRequest(\n  options: VerifyPreAuthorizedCodeAccessTokenRequestOptions\n): Promise<VerifyAccessTokenRequestReturn> {\n  if (options.pkce) {\n    await verifyAccessTokenRequestPkce(options.pkce, options.callbacks)\n  }\n\n  const dpopResult = options.dpop\n    ? await verifyAccessTokenRequestDpop(options.dpop, options.request, options.callbacks)\n    : undefined\n\n  const clientAttestationResult = options.clientAttestation\n    ? await verifyAccessTokenRequestClientAttestation(\n        options.clientAttestation,\n        options.authorizationServerMetadata,\n        options.callbacks,\n        dpopResult?.jwkThumbprint,\n        options.now\n      )\n    : undefined\n\n  if (options.grant.preAuthorizedCode !== options.expectedPreAuthorizedCode) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidGrant,\n      error_description: `Invalid 'pre-authorized_code' provided`,\n    })\n  }\n\n  if (options.grant.txCode !== options.expectedTxCode) {\n    // If they do not match there is an error\n    // No tx_code was expected, but it was in the request\n    if (!options.expectedTxCode) {\n      // not expected but provided\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Request contains 'tx_code' that was not expected`,\n      })\n    }\n\n    // tx_code was expected but not provided\n    if (!options.grant.txCode) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description: `Missing required 'tx_code' in request`,\n      })\n    }\n\n    // tx_code was expected and provided, but wrong\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidGrant,\n      error_description: `Invalid 'tx_code' provided`,\n    })\n  }\n\n  if (options.preAuthorizedCodeExpiresAt) {\n    const now = options.now ?? new Date()\n\n    if (now.getTime() > options.preAuthorizedCodeExpiresAt.getTime()) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidGrant,\n          error_description: `Expired 'pre-authorized_code' provided`,\n        },\n        {\n          internalMessage: `The provided 'pre-authorized_code' in the request expired at '${options.preAuthorizedCodeExpiresAt.getTime()}', now is '${now.getTime()}'`,\n        }\n      )\n    }\n  }\n\n  return { dpop: dpopResult, clientAttestation: clientAttestationResult }\n}\n\nexport interface VerifyAuthorizationCodeAccessTokenRequestOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  grant: ParsedAccessTokenAuthorizationCodeRequestGrant\n  accessTokenRequest: AccessTokenRequest\n  request: RequestLike\n\n  expectedCode: string\n\n  clientAttestation?: VerifyAccessTokenRequestClientAttestation\n  dpop?: VerifyAccessTokenRequestDpop\n  pkce?: VerifyAccessTokenRequestPkce\n\n  codeExpiresAt?: Date\n  now?: Date\n\n  callbacks: Pick<CallbackContext, 'hash' | 'verifyJwt'>\n}\n\nexport async function verifyAuthorizationCodeAccessTokenRequest(\n  options: VerifyAuthorizationCodeAccessTokenRequestOptions\n): Promise<VerifyAccessTokenRequestReturn> {\n  if (options.pkce) {\n    await verifyAccessTokenRequestPkce(options.pkce, options.callbacks)\n  }\n\n  const dpopResult = options.dpop\n    ? await verifyAccessTokenRequestDpop(options.dpop, options.request, options.callbacks)\n    : undefined\n\n  const clientAttestationResult = options.clientAttestation\n    ? await verifyAccessTokenRequestClientAttestation(\n        options.clientAttestation,\n        options.authorizationServerMetadata,\n        options.callbacks,\n        dpopResult?.jwkThumbprint,\n        options.now\n      )\n    : undefined\n\n  if (options.grant.code !== options.expectedCode) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidGrant,\n      error_description: `Invalid 'code' provided`,\n    })\n  }\n\n  if (options.codeExpiresAt) {\n    const now = options.now ?? new Date()\n\n    if (now.getTime() > options.codeExpiresAt.getTime()) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidGrant,\n          error_description: `Expired 'code' provided`,\n        },\n        {\n          internalMessage: `The provided 'code' in the request expired at '${options.codeExpiresAt.getTime()}', now is '${now.getTime()}'`,\n        }\n      )\n    }\n  }\n\n  return { dpop: dpopResult, clientAttestation: clientAttestationResult }\n}\n\nexport interface VerifyRefreshTokenAccessTokenRequestOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  grant: ParsedAccessTokenRefreshTokenRequestGrant\n  accessTokenRequest: AccessTokenRequest\n  request: RequestLike\n\n  expectedRefreshToken: string\n\n  clientAttestation?: VerifyAccessTokenRequestClientAttestation\n  dpop?: VerifyAccessTokenRequestDpop\n  pkce?: VerifyAccessTokenRequestPkce\n\n  refreshTokenExpiresAt?: Date\n  now?: Date\n\n  callbacks: Pick<CallbackContext, 'hash' | 'verifyJwt'>\n}\n\nexport async function verifyRefreshTokenAccessTokenRequest(\n  options: VerifyRefreshTokenAccessTokenRequestOptions\n): Promise<VerifyAccessTokenRequestReturn> {\n  if (options.pkce) {\n    await verifyAccessTokenRequestPkce(options.pkce, options.callbacks)\n  }\n\n  const dpopResult = options.dpop\n    ? await verifyAccessTokenRequestDpop(options.dpop, options.request, options.callbacks)\n    : undefined\n\n  const clientAttestationResult = options.clientAttestation\n    ? await verifyAccessTokenRequestClientAttestation(\n        options.clientAttestation,\n        options.authorizationServerMetadata,\n        options.callbacks,\n        dpopResult?.jwkThumbprint,\n        options.now\n      )\n    : undefined\n\n  if (options.grant.refreshToken !== options.expectedRefreshToken) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidGrant,\n      error_description: `Invalid 'refresh_token' provided`,\n    })\n  }\n\n  if (options.refreshTokenExpiresAt) {\n    const now = options.now ?? new Date()\n\n    if (now.getTime() > options.refreshTokenExpiresAt.getTime()) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidGrant,\n          error_description: `Expired 'refresh_token' provided`,\n        },\n        {\n          internalMessage: `The provided 'refresh_token' in the request expired at '${options.refreshTokenExpiresAt.getTime()}', now is '${now.getTime()}'`,\n        }\n      )\n    }\n  }\n\n  return { dpop: dpopResult, clientAttestation: clientAttestationResult }\n}\n\nasync function verifyAccessTokenRequestClientAttestation(\n  options: VerifyAccessTokenRequestClientAttestation,\n  authorizationServerMetadata: AuthorizationServerMetadata,\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>,\n  dpopJwkThumbprint?: string,\n  now?: Date\n) {\n  if (!options.clientAttestationJwt) {\n    if (!options.required && !options.clientAttestationPopJwt) {\n      return undefined\n    }\n\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description: `Missing required client attestation parameters in access token request. Make sure to provide the '${oauthClientAttestationHeader}' and '${oauthClientAttestationPopHeader}' header values.`,\n    })\n  }\n\n  // DPoP-bound method (`attest_jwt_client_auth_dpop`, draft 09 §5.2): the client attestation is present\n  // without a separate PoP header; the DPoP proof serves as the Client Attestation PoP.\n  if (!options.clientAttestationPopJwt) {\n    return verifyAccessTokenRequestClientAttestationDpop(\n      { ...options, clientAttestationJwt: options.clientAttestationJwt },\n      authorizationServerMetadata,\n      callbacks,\n      dpopJwkThumbprint,\n      now\n    )\n  }\n\n  const verifiedClientAttestation = await verifyClientAttestation({\n    authorizationServer: authorizationServerMetadata.issuer,\n    callbacks,\n    clientAttestationJwt: options.clientAttestationJwt,\n    clientAttestationPopJwt: options.clientAttestationPopJwt,\n    now,\n  })\n\n  // Ensure the client id matches with the client id from the session\n  assertExpectedClientId(options.expectedClientId, verifiedClientAttestation.clientAttestation.payload.sub)\n\n  if (options.ensureConfirmationKeyMatchesDpopKey && dpopJwkThumbprint) {\n    await assertConfirmationKeyMatchesDpopKey(\n      verifiedClientAttestation.clientAttestation.payload.cnf.jwk,\n      dpopJwkThumbprint,\n      callbacks\n    )\n  }\n\n  return verifiedClientAttestation\n}\n\nasync function verifyAccessTokenRequestClientAttestationDpop(\n  options: VerifyAccessTokenRequestClientAttestation & { clientAttestationJwt: string },\n  authorizationServerMetadata: AuthorizationServerMetadata,\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>,\n  dpopJwkThumbprint?: string,\n  now?: Date\n) {\n  // Hardening: if the authorization server advertises client authentication methods but not the\n  // DPoP-bound method, reject. Advertising is only SHOULD in draft 09 §8, so an absent list is allowed.\n  const supportedMethods = authorizationServerMetadata.token_endpoint_auth_methods_supported\n  if (supportedMethods && !supportedMethods.includes(SupportedClientAuthenticationMethod.ClientAttestationJwtDpop)) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description: `The authorization server does not support the '${SupportedClientAuthenticationMethod.ClientAttestationJwtDpop}' client authentication method.`,\n    })\n  }\n\n  // The DPoP proof is the Client Attestation PoP in this method, so a valid DPoP proof is required.\n  if (!dpopJwkThumbprint) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidClient,\n      error_description: `Client attestation provided without an '${oauthClientAttestationPopHeader}' header, but no valid DPoP proof is present. The '${SupportedClientAuthenticationMethod.ClientAttestationJwtDpop}' method requires a DPoP proof.`,\n    })\n  }\n\n  let clientAttestation: VerifiedClientAttestationJwt\n  try {\n    clientAttestation = await verifyClientAttestationJwt({\n      callbacks,\n      clientAttestationJwt: options.clientAttestationJwt,\n      now,\n    })\n  } catch (error) {\n    if (error instanceof Oauth2Error) {\n      throw new Oauth2ServerErrorResponseError(\n        {\n          error: Oauth2ErrorCodes.InvalidClient,\n          error_description: `Error verifying client attestation. ${error.message}`,\n        },\n        { status: 401, cause: error }\n      )\n    }\n    throw error\n  }\n\n  // Ensure the client id matches with the client id from the session\n  assertExpectedClientId(options.expectedClientId, clientAttestation.payload.sub)\n\n  // draft 09 §7.3: the DPoP public key MUST match the `cnf` JWK of the Client Attestation. This is\n  // mandatory for the DPoP-bound method (not gated on `ensureConfirmationKeyMatchesDpopKey`).\n  await assertConfirmationKeyMatchesDpopKey(clientAttestation.payload.cnf.jwk, dpopJwkThumbprint, callbacks)\n\n  return { clientAttestation }\n}\n\nfunction assertExpectedClientId(expectedClientId: string | undefined, sub: string) {\n  if (expectedClientId && expectedClientId !== sub) {\n    throw new Oauth2ServerErrorResponseError(\n      {\n        error: Oauth2ErrorCodes.InvalidClient,\n        error_description: `The client id '${sub}' in the client attestation does not match the client id for the authorization.`,\n      },\n      {\n        status: 401,\n      }\n    )\n  }\n}\n\nasync function assertConfirmationKeyMatchesDpopKey(\n  confirmationJwk: Jwk,\n  dpopJwkThumbprint: string,\n  callbacks: Pick<CallbackContext, 'hash'>\n) {\n  const clientAttestationJkt = await calculateJwkThumbprint({\n    hashAlgorithm: HashAlgorithm.Sha256,\n    hashCallback: callbacks.hash,\n    jwk: confirmationJwk,\n  })\n\n  if (clientAttestationJkt !== dpopJwkThumbprint) {\n    throw new Oauth2ServerErrorResponseError(\n      {\n        error: Oauth2ErrorCodes.InvalidRequest,\n        error_description:\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        status: 401,\n      }\n    )\n  }\n}\n\nasync function verifyAccessTokenRequestDpop(\n  options: VerifyAccessTokenRequestDpop,\n  request: RequestLike,\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash'>\n) {\n  if (options.required && !options.jwt) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidDpopProof,\n      error_description: 'Missing required DPoP proof',\n    })\n  }\n\n  if (!options.jwt) return undefined\n\n  const { header, jwkThumbprint } = await verifyDpopJwt({\n    callbacks,\n    dpopJwt: options.jwt,\n    request,\n    allowedSigningAlgs: options.allowedSigningAlgs,\n    expectedJwkThumbprint: options.expectedJwkThumbprint,\n    expectedNonce: options.expectedNonce,\n  })\n\n  return {\n    jwk: header.jwk,\n    jwkThumbprint,\n  }\n}\n\nasync function verifyAccessTokenRequestPkce(\n  options: VerifyAccessTokenRequestPkce,\n  callbacks: Pick<CallbackContext, 'hash'>\n) {\n  if (options.codeChallenge && !options.codeVerifier) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: `Missing required 'code_verifier' in access token request`,\n    })\n  }\n\n  if (!options.codeVerifier) return null\n\n  try {\n    await verifyPkce({\n      callbacks,\n      codeChallenge: options.codeChallenge,\n      codeChallengeMethod: options.codeChallengeMethod,\n      codeVerifier: options.codeVerifier,\n    })\n  } catch (error) {\n    if (error instanceof Oauth2Error) {\n      throw new Oauth2ServerErrorResponseError({\n        error: Oauth2ErrorCodes.InvalidGrant,\n        error_description: error.message,\n      })\n    }\n    throw error\n  }\n}\n","import { zInteger } from '@openid4vc/utils'\n\nimport z from 'zod'\nimport { zAuthorizationRequest } from '../authorization-request/z-authorization-request'\nimport { zOauth2ErrorResponse } from '../common/z-oauth2-error'\n\nexport const zAuthorizationChallengeRequest = z\n  .object({\n    // authorization challenge request can include same parameters as an authorization request\n    // except for response_type (always `code`), and `client_id` is optional (becase\n    // it's possible to do client authentication using different methods)\n    ...zAuthorizationRequest.omit({ response_type: true, client_id: true }).shape,\n    client_id: z.optional(zAuthorizationRequest.shape.client_id),\n\n    auth_session: z.optional(z.string()),\n\n    // DRAFT presentation during issuance\n    presentation_during_issuance_session: z.optional(z.string()),\n  })\n  .loose()\nexport type AuthorizationChallengeRequest = z.infer<typeof zAuthorizationChallengeRequest>\n\nexport const zAuthorizationChallengeResponse = z\n  .object({\n    authorization_code: z.string(),\n  })\n  .loose()\nexport type AuthorizationChallengeResponse = z.infer<typeof zAuthorizationChallengeResponse>\n\nexport const zAuthorizationChallengeErrorResponse = z\n  .object({\n    ...zOauth2ErrorResponse.shape,\n    auth_session: z.optional(z.string()),\n    request_uri: z.optional(z.string()),\n    expires_in: z.optional(zInteger),\n\n    // DRAFT: presentation during issuance\n    presentation: z.optional(z.string()),\n  })\n  .loose()\nexport type AuthorizationChallengeErrorResponse = z.infer<typeof zAuthorizationChallengeErrorResponse>\n","import { parseWithErrorHandling, type StringWithAutoCompletion } from '@openid4vc/utils'\nimport type { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport {\n  type AuthorizationChallengeErrorResponse,\n  type AuthorizationChallengeResponse,\n  zAuthorizationChallengeErrorResponse,\n  zAuthorizationChallengeResponse,\n} from './z-authorization-challenge'\n\nexport interface CreateAuthorizationChallengeResponseOptions {\n  /**\n   * The authorization code\n   */\n  authorizationCode: string\n\n  /**\n   * Additional payload to include in the authorization challenge response.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\n/**\n * Create an authorization challenge response\n *\n * @throws {ValidationError} if an error occurred during verification of the {@link AuthorizationChallengeResponse}\n */\nexport function createAuthorizationChallengeResponse(options: CreateAuthorizationChallengeResponseOptions) {\n  const authorizationChallengeResponse = parseWithErrorHandling(zAuthorizationChallengeResponse, {\n    ...options.additionalPayload,\n    authorization_code: options.authorizationCode,\n  } satisfies AuthorizationChallengeResponse)\n\n  return { authorizationChallengeResponse }\n}\n\nexport interface CreateAuthorizationChallengeErrorResponseOptions {\n  /**\n   * Auth session identifier for the authorization challenge. The client MUST include this\n   * in subsequent requests to the authorization challenge endpoint.\n   */\n  authSession?: string\n\n  /**\n   * Error codes specific to authorization challenge are:\n   *  - @see Oauth2ErrorCodes.RedirectToWeb\n   *  - @see Oauth2ErrorCodes.InvalidSession\n   *  - @see Oauth2ErrorCodes.InsufficientAuthorization\n   */\n  error: StringWithAutoCompletion<Oauth2ErrorCodes>\n\n  /**\n   * Optional error description\n   */\n  errorDescription?: string\n\n  /**\n   * OpenID4VP authorization request url that must be completed before authorization\n   * can be granted\n   *\n   * Should be combined with `error` @see Oauth2ErrorCodes.InsufficientAuthorization\n   */\n  presentation?: string\n\n  /**\n   * Optional PAR request uri, allowing the authorization challenge request to be treated\n   * as a succesfull pushed authorization request.\n   *\n   * Should be combined with `error` @see Oauth2ErrorCodes.RedirectToWeb\n   */\n  requestUri?: string\n\n  /**\n   * Duration is seconds after which the `requestUri` parameter will expire. Should only be included\n   * if the `requestUri` is also included, and has no meaning otherwise\n   */\n  expiresIn?: number\n\n  /**\n   * Additional payload to include in the authorization challenge error response.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\n/**\n * Create an authorization challenge error response\n *\n * @throws {ValidationError} if an error occurred during validation of the {@link AuthorizationChallengeErrorResponse}\n */\nexport function createAuthorizationChallengeErrorResponse(options: CreateAuthorizationChallengeErrorResponseOptions) {\n  const authorizationChallengeErrorResponse = parseWithErrorHandling(zAuthorizationChallengeErrorResponse, {\n    ...options.additionalPayload,\n\n    // General FiPA\n    error: options.error,\n    error_description: options.errorDescription,\n    auth_session: options.authSession,\n\n    // Presentation during issuance\n    presentation: options.presentation,\n\n    // PAR\n    request_uri: options.requestUri,\n    expires_in: options.expiresIn,\n  } satisfies AuthorizationChallengeErrorResponse)\n\n  return authorizationChallengeErrorResponse\n}\n","import { formatZodError } from '@openid4vc/utils'\nimport {\n  type ParseAuthorizationRequestResult,\n  parseAuthorizationRequest,\n} from '../authorization-request/parse-authorization-request'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { Oauth2ServerErrorResponseError } from '../error/Oauth2ServerErrorResponseError'\nimport { type AuthorizationChallengeRequest, zAuthorizationChallengeRequest } from './z-authorization-challenge'\n\nexport interface ParseAuthorizationChallengeRequestOptions {\n  request: RequestLike\n\n  authorizationChallengeRequest: unknown\n}\n\nexport interface ParseAuthorizationChallengeRequestResult extends ParseAuthorizationRequestResult {\n  authorizationChallengeRequest: AuthorizationChallengeRequest\n}\n\n/**\n * Parse an authorization challenge request.\n *\n * @throws {Oauth2ServerErrorResponseError}\n */\nexport function parseAuthorizationChallengeRequest(\n  options: ParseAuthorizationChallengeRequestOptions\n): ParseAuthorizationChallengeRequestResult {\n  const parsedAuthorizationChallengeRequest = zAuthorizationChallengeRequest.safeParse(\n    options.authorizationChallengeRequest\n  )\n  if (!parsedAuthorizationChallengeRequest.success) {\n    throw new Oauth2ServerErrorResponseError({\n      error: Oauth2ErrorCodes.InvalidRequest,\n      error_description: `Error occurred during validation of authorization challenge request.\\n${formatZodError(parsedAuthorizationChallengeRequest.error)}`,\n    })\n  }\n\n  const authorizationChallengeRequest = parsedAuthorizationChallengeRequest.data\n  const { clientAttestation, dpop } = parseAuthorizationRequest({\n    authorizationRequest: authorizationChallengeRequest,\n    request: options.request,\n  })\n\n  return {\n    authorizationChallengeRequest: parsedAuthorizationChallengeRequest.data,\n\n    dpop,\n    clientAttestation,\n  }\n}\n","import {\n  type VerifyAuthorizationRequestOptions,\n  type VerifyAuthorizationRequestReturn,\n  verifyAuthorizationRequest,\n} from '../authorization-request/verify-authorization-request'\nimport type { AuthorizationChallengeRequest } from './z-authorization-challenge'\n\nexport type VerifyAuthorizationChallengeRequestReturn = VerifyAuthorizationRequestReturn\nexport interface VerifyAuthorizationChallengeRequestOptions\n  extends Omit<VerifyAuthorizationRequestOptions, 'authorizationRequest'> {\n  authorizationChallengeRequest: AuthorizationChallengeRequest\n}\n\nexport async function verifyAuthorizationChallengeRequest(\n  options: VerifyAuthorizationChallengeRequestOptions\n): Promise<VerifyAuthorizationChallengeRequestReturn> {\n  const { clientAttestation, dpop } = await verifyAuthorizationRequest({\n    ...options,\n    authorizationRequest: options.authorizationChallengeRequest,\n  })\n\n  return {\n    dpop,\n    clientAttestation,\n  }\n}\n","import { parseWithErrorHandling, type StringWithAutoCompletion } from '@openid4vc/utils'\nimport { zAccessTokenErrorResponse } from '../access-token/z-access-token'\nimport type { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport {\n  type PushedAuthorizationErrorResponse,\n  type PushedAuthorizationResponse,\n  zPushedAuthorizationResponse,\n} from './z-authorization-request'\n\nexport interface CreatePushedAuthorizationResponseOptions {\n  /**\n   * The request uri where the client should redirect to\n   */\n  requestUri: string\n\n  /**\n   * Number of seconds after which the `requestUri` will expire.\n   */\n  expiresInSeconds: number\n\n  /**\n   * Additional payload to include in the pushed authorization response.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\n/**\n * Create an pushed authorization response\n *\n * @throws {ValidationError} if an error occurred during verification of the {@link PushedAuthorizationResponse}\n */\nexport function createPushedAuthorizationResponse(options: CreatePushedAuthorizationResponseOptions) {\n  const pushedAuthorizationResponse = parseWithErrorHandling(zPushedAuthorizationResponse, {\n    ...options.additionalPayload,\n    expires_in: options.expiresInSeconds,\n    request_uri: options.requestUri,\n  } satisfies PushedAuthorizationResponse)\n\n  return { pushedAuthorizationResponse }\n}\n\nexport interface CreatePushedAuthorizationErrorResponseOptions {\n  /**\n   * The pushed authorization error\n   */\n  error: StringWithAutoCompletion<Oauth2ErrorCodes>\n\n  /**\n   * Optional error description\n   */\n  errorDescription?: string\n\n  /**\n   * Additional payload to include in the pushed authorization error response.\n   */\n  additionalPayload?: Record<string, unknown>\n}\n\n/**\n * Create a pushed authorization error response\n *\n * @throws {ValidationError} if an error occurred during validation of the {@link PushedAuthorizationErrorResponse}\n */\nexport function createPushedAuthorizationErrorResponse(options: CreatePushedAuthorizationErrorResponseOptions) {\n  const pushedAuthorizationErrorResponse = parseWithErrorHandling(zAccessTokenErrorResponse, {\n    ...options.additionalPayload,\n    error: options.error,\n    error_description: options.errorDescription,\n  } satisfies PushedAuthorizationErrorResponse)\n\n  return pushedAuthorizationErrorResponse\n}\n","import type { JwtSigner } from '../common/jwt/z-jwt'\nimport { type VerifiedJarRequest, verifyJarRequest } from '../jar/handle-jar-request/verify-jar-request'\nimport {\n  type VerifyAuthorizationRequestOptions,\n  type VerifyAuthorizationRequestReturn,\n  verifyAuthorizationRequest,\n} from './verify-authorization-request'\n\nexport interface VerifyPushedAuthorizationRequestReturn extends VerifyAuthorizationRequestReturn {\n  /**\n   * The verified JAR request, if `authorizationRequestJwt` was provided\n   */\n  jar?: VerifiedJarRequest\n}\n\nexport interface VerifyPushedAuthorizationRequestOptions extends VerifyAuthorizationRequestOptions {\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\nexport async function verifyPushedAuthorizationRequest(\n  options: VerifyPushedAuthorizationRequestOptions\n): Promise<VerifyPushedAuthorizationRequestReturn> {\n  let jar: VerifiedJarRequest | undefined\n  if (options.authorizationRequestJwt) {\n    jar = await verifyJarRequest({\n      authorizationRequestJwt: options.authorizationRequestJwt.jwt,\n      jarRequestParams: options.authorizationRequest,\n      callbacks: options.callbacks,\n      jwtSigner: options.authorizationRequestJwt.signer,\n    })\n  }\n\n  const { clientAttestation, dpop } = await verifyAuthorizationRequest(options)\n\n  return {\n    dpop,\n    clientAttestation,\n    jar,\n  }\n}\n","import { encodeToBase64Url, parseWithErrorHandling } from '@openid4vc/utils'\nimport { type CreateAccessTokenOptions, createAccessTokenJwt } from './access-token/create-access-token'\nimport {\n  type CreateAccessTokenResponseOptions,\n  createAccessTokenResponse,\n} from './access-token/create-access-token-response'\nimport { type ParseAccessTokenRequestOptions, parseAccessTokenRequest } from './access-token/parse-access-token-request'\nimport {\n  type VerifyAuthorizationCodeAccessTokenRequestOptions,\n  type VerifyPreAuthorizedCodeAccessTokenRequestOptions,\n  type VerifyRefreshTokenAccessTokenRequestOptions,\n  verifyAuthorizationCodeAccessTokenRequest,\n  verifyPreAuthorizedCodeAccessTokenRequest,\n  verifyRefreshTokenAccessTokenRequest,\n} from './access-token/verify-access-token-request'\nimport {\n  type CreateAuthorizationChallengeErrorResponseOptions,\n  type CreateAuthorizationChallengeResponseOptions,\n  createAuthorizationChallengeErrorResponse,\n  createAuthorizationChallengeResponse,\n} from './authorization-challenge/create-authorization-challenge-response'\nimport {\n  type ParseAuthorizationChallengeRequestOptions,\n  parseAuthorizationChallengeRequest,\n} from './authorization-challenge/parse-authorization-challenge-request'\nimport {\n  type VerifyAuthorizationChallengeRequestOptions,\n  verifyAuthorizationChallengeRequest,\n} from './authorization-challenge/verify-authorization-challenge-request'\nimport {\n  type CreatePushedAuthorizationErrorResponseOptions,\n  type CreatePushedAuthorizationResponseOptions,\n  createPushedAuthorizationErrorResponse,\n  createPushedAuthorizationResponse,\n} from './authorization-request/create-pushed-authorization-response'\nimport {\n  type ParsePushedAuthorizationRequestOptions,\n  parsePushedAuthorizationRequest,\n} from './authorization-request/parse-pushed-authorization-request'\nimport {\n  type VerifyPushedAuthorizationRequestOptions,\n  verifyPushedAuthorizationRequest,\n} from './authorization-request/verify-pushed-authorization-request'\nimport type { CallbackContext } from './callbacks'\nimport { type VerifyClientAttestationOptions, verifyClientAttestation } from './client-attestation/client-attestation'\nimport { Oauth2ErrorCodes } from './common/z-oauth2-error'\nimport { type VerifyDpopJwtOptions, verifyDpopJwt } from './dpop/dpop'\nimport {\n  type AuthorizationServerMetadata,\n  zAuthorizationServerMetadata,\n} from './metadata/authorization-server/z-authorization-server-metadata'\n\nexport interface Oauth2AuthorizationServerOptions {\n  /**\n   * Callbacks required for the oauth2 authorization server\n   */\n  callbacks: Omit<CallbackContext, 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Oauth2AuthorizationServer {\n  public constructor(private options: Oauth2AuthorizationServerOptions) {}\n\n  public createAuthorizationServerMetadata(authorizationServerMetadata: AuthorizationServerMetadata) {\n    return parseWithErrorHandling(\n      zAuthorizationServerMetadata,\n      authorizationServerMetadata,\n      'Error validating authorization server metadata'\n    )\n  }\n\n  /**\n   * Parse access token request and extract the grant specific properties.\n   *\n   * If something goes wrong, such as the grant is not supported, missing parameters, etc,\n   * it will throw `Oauth2ServerErrorResponseError` containing an error response object\n   * that can be returned to the client.\n   */\n  public parseAccessTokenRequest(options: ParseAccessTokenRequestOptions) {\n    return parseAccessTokenRequest(options)\n  }\n\n  public verifyPreAuthorizedCodeAccessTokenRequest(\n    options: Omit<VerifyPreAuthorizedCodeAccessTokenRequestOptions, 'callbacks'>\n  ) {\n    return verifyPreAuthorizedCodeAccessTokenRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public verifyAuthorizationCodeAccessTokenRequest(\n    options: Omit<VerifyAuthorizationCodeAccessTokenRequestOptions, 'callbacks'>\n  ) {\n    return verifyAuthorizationCodeAccessTokenRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public verifyRefreshTokenAccessTokenRequest(options: Omit<VerifyRefreshTokenAccessTokenRequestOptions, 'callbacks'>) {\n    return verifyRefreshTokenAccessTokenRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  /**\n   * Create an access token response.\n   *\n   * The `sub` claim can be used to identify the resource owner is subsequent requests.\n   * For pre-auth flow this can be the pre-authorized_code but there are no requirements\n   * on the value.\n   *\n   * To generate a refresh token, set the `refreshToken` option to `true`. You can\n   * also provide a custom refresh token string.\n   */\n  public async createAccessTokenResponse(\n    options: Pick<\n      CreateAccessTokenOptions,\n      | 'expiresInSeconds'\n      | 'scope'\n      | 'clientId'\n      | 'audience'\n      | 'signer'\n      | 'dpop'\n      | 'authorizationServer'\n      | 'now'\n      | 'subject'\n    > &\n      Pick<CreateAccessTokenResponseOptions, 'cNonce' | 'cNonceExpiresIn'> & {\n        additionalAccessTokenPayload?: CreateAccessTokenOptions['additionalPayload']\n        additionalAccessTokenResponsePayload?: CreateAccessTokenResponseOptions['additionalPayload']\n        refreshToken?: boolean | string\n      }\n  ) {\n    const { jwt: accessToken } = await createAccessTokenJwt({\n      audience: options.audience,\n      authorizationServer: options.authorizationServer,\n      callbacks: this.options.callbacks,\n      expiresInSeconds: options.expiresInSeconds,\n      subject: options.subject,\n      scope: options.scope,\n      clientId: options.clientId,\n      signer: options.signer,\n      dpop: options.dpop,\n      now: options.now,\n      additionalPayload: options.additionalAccessTokenPayload,\n    })\n\n    return createAccessTokenResponse({\n      accessToken,\n      refreshToken:\n        typeof options.refreshToken === 'string'\n          ? options.refreshToken\n          : options.refreshToken\n            ? encodeToBase64Url(await this.options.callbacks.generateRandom(32))\n            : undefined,\n      callbacks: this.options.callbacks,\n      expiresInSeconds: options.expiresInSeconds,\n      tokenType: options.dpop ? 'DPoP' : 'Bearer',\n      cNonce: options.cNonce,\n      cNonceExpiresIn: options.cNonceExpiresIn,\n      additionalPayload: options.additionalAccessTokenResponsePayload,\n    })\n  }\n\n  /**\n   * Parse a pushed authorization request\n   */\n  public async parsePushedAuthorizationRequest(options: Omit<ParsePushedAuthorizationRequestOptions, 'callbacks'>) {\n    return await parsePushedAuthorizationRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  /**\n   * Verify pushed authorization request.\n   *\n   * Make sure to provide the `authorizationRequestJwt` if this was returned in the `parsePushedAuthorizationRequest`\n   */\n  public verifyPushedAuthorizationRequest(options: Omit<VerifyPushedAuthorizationRequestOptions, 'callbacks'>) {\n    return verifyPushedAuthorizationRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public createPushedAuthorizationResponse(options: CreatePushedAuthorizationResponseOptions) {\n    return createPushedAuthorizationResponse(options)\n  }\n\n  public createPushedAuthorizationErrorResponse(options: CreatePushedAuthorizationErrorResponseOptions) {\n    return createPushedAuthorizationErrorResponse(options)\n  }\n\n  /**\n   * Parse an authorization challenge request\n   */\n  public parseAuthorizationChallengeRequest(options: ParseAuthorizationChallengeRequestOptions) {\n    return parseAuthorizationChallengeRequest(options)\n  }\n\n  public verifyAuthorizationChallengeRequest(options: Omit<VerifyAuthorizationChallengeRequestOptions, 'callbacks'>) {\n    return verifyAuthorizationChallengeRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public createAuthorizationChallengeResponse(options: CreateAuthorizationChallengeResponseOptions) {\n    return createAuthorizationChallengeResponse(options)\n  }\n\n  /**\n   * Create an authorization challenge error response indicating presentation of credentials\n   * using OpenID4VP is required before authorization can be granted.\n   *\n   * The `presentation` parameter should be an OpenID4VP authorization request url.\n   * The `authSession` should be used to track the session\n   */\n  public createAuthorizationChallengePresentationErrorResponse(\n    options: Pick<CreateAuthorizationChallengeErrorResponseOptions, 'errorDescription' | 'additionalPayload'> &\n      Required<Pick<CreateAuthorizationChallengeErrorResponseOptions, 'authSession' | 'presentation'>>\n  ) {\n    return createAuthorizationChallengeErrorResponse({\n      error: Oauth2ErrorCodes.InsufficientAuthorization,\n      errorDescription: options.errorDescription,\n      additionalPayload: options.additionalPayload,\n      authSession: options.authSession,\n      presentation: options.presentation,\n    })\n  }\n\n  public createAuthorizationChallengeErrorResponse(options: CreateAuthorizationChallengeErrorResponseOptions) {\n    return createAuthorizationChallengeErrorResponse(options)\n  }\n\n  public async verifyDpopJwt(options: Omit<VerifyDpopJwtOptions, 'callbacks'>) {\n    return verifyDpopJwt({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public async verifyClientAttestation(options: Omit<VerifyClientAttestationOptions, 'callbacks'>) {\n    return verifyClientAttestation({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n}\n","import {\n  ContentType,\n  createZodFetcher,\n  Headers,\n  InvalidFetchResponseError,\n  objectToQueryParams,\n  parseWithErrorHandling,\n} from '@openid4vc/utils'\nimport { ValidationError } from '../../../utils/src/error/ValidationError'\nimport type { CallbackContext } from '../callbacks'\nimport {\n  authorizationServerRequestWithClientAttestationChallengeRetry,\n  extractClientAttestationChallengeFromHeaders,\n} from '../client-attestation/client-attestation-challenge'\nimport { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { authorizationServerRequestWithDpopRetry } from '../dpop/dpop-retry'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport {\n  authorizationCodeGrantIdentifier,\n  clientCredentialsGrantIdentifier,\n  getGrantTypesSupported,\n  preAuthorizedCodeGrantIdentifier,\n  refreshTokenGrantIdentifier,\n} from '../z-grant-type'\nimport {\n  type AccessTokenRequest,\n  type AccessTokenResponse,\n  zAccessTokenErrorResponse,\n  zAccessTokenRequest,\n  zAccessTokenResponse,\n} from './z-access-token'\n\nexport interface RetrieveAccessTokenReturn {\n  accessTokenResponse: AccessTokenResponse\n  dpop?: RequestDpopOptions\n\n  /**\n   * A fresh Client Attestation challenge provided by the authorization server in the\n   * `OAuth-Client-Attestation-Challenge` response header (draft 09 §6.2). If present, the client\n   * should use this challenge for the next Client Attestation PoP JWT.\n   */\n  attestationChallenge?: string\n}\n\ninterface RetrieveAccessTokenBaseOptions {\n  /**\n   * Authorization server to request the access token from\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * Callbacks to use for requesting access token\n   */\n  callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'hash' | 'signJwt' | 'clientAuthentication'>\n\n  /**\n   * The resource to which access is being requested. This can help the authorization\n   * server in determining the resource server to handle the authorization request for\n   */\n  resource?: string\n\n  /**\n   * Dpop parameters for including a dpop in the access token request. The request will automatically\n   * be retried if the server responds with a 'use_dpop_nonce' header.\n   *\n   * If provided but 'dpop_signing_alg_values_supported' is not available in the authorization server\n   * metadata, or the 'alg' value does not match an error will be thrown.\n   */\n  dpop?: RequestDpopOptions\n}\n\nexport interface RetrievePreAuthorizedCodeAccessTokenOptions extends RetrieveAccessTokenBaseOptions {\n  preAuthorizedCode: string\n  txCode?: string\n\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\nexport async function retrievePreAuthorizedCodeAccessToken(\n  options: RetrievePreAuthorizedCodeAccessTokenOptions\n): Promise<RetrieveAccessTokenReturn> {\n  const request = {\n    grant_type: preAuthorizedCodeGrantIdentifier,\n    'pre-authorized_code': options.preAuthorizedCode,\n    tx_code: options.txCode,\n    resource: options.resource,\n    ...options.additionalRequestPayload,\n  } satisfies AccessTokenRequest\n\n  return retrieveAccessToken({\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    request,\n    dpop: options.dpop,\n    callbacks: options.callbacks,\n    resource: options.resource,\n  })\n}\n\nexport interface RetrieveAuthorizationCodeAccessTokenOptions extends RetrieveAccessTokenBaseOptions {\n  /**\n   * PKCE Code verifier that was used in the authorization request.\n   */\n  pkceCodeVerifier?: string\n\n  /**\n   * The authorization code\n   */\n  authorizationCode: string\n\n  /**\n   * Redirect uri to include in the access token request. Only required\n   * if the redirect uri was present in the authorization request.\n   */\n  redirectUri?: string\n\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\nexport async function retrieveAuthorizationCodeAccessToken(\n  options: RetrieveAuthorizationCodeAccessTokenOptions\n): Promise<RetrieveAccessTokenReturn> {\n  const request = {\n    grant_type: authorizationCodeGrantIdentifier,\n    code: options.authorizationCode,\n    code_verifier: options.pkceCodeVerifier,\n    redirect_uri: options.redirectUri,\n    resource: options.resource,\n    ...options.additionalRequestPayload,\n  } satisfies AccessTokenRequest\n\n  return retrieveAccessToken({\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    request,\n    dpop: options.dpop,\n    resource: options.resource,\n    callbacks: options.callbacks,\n  })\n}\n\nexport interface RetrieveRefreshTokenAccessTokenOptions extends RetrieveAccessTokenBaseOptions {\n  /**\n   * The refresh token\n   */\n  refreshToken: string\n\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\nexport async function retrieveRefreshTokenAccessToken(\n  options: RetrieveRefreshTokenAccessTokenOptions\n): Promise<RetrieveAccessTokenReturn> {\n  const request = {\n    grant_type: refreshTokenGrantIdentifier,\n    refresh_token: options.refreshToken,\n    resource: options.resource,\n    ...options.additionalRequestPayload,\n  } satisfies AccessTokenRequest\n\n  return retrieveAccessToken({\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    request,\n    dpop: options.dpop,\n    callbacks: options.callbacks,\n    resource: options.resource,\n  })\n}\n\nexport interface RetrieveClientCredentialsAccessTokenOptions extends RetrieveAccessTokenBaseOptions {\n  /**\n   * The scope of the access request\n   */\n  scope?: string\n\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\nexport async function retrieveClientCredentialsAccessToken(\n  options: RetrieveClientCredentialsAccessTokenOptions\n): Promise<RetrieveAccessTokenReturn> {\n  const request = {\n    grant_type: clientCredentialsGrantIdentifier,\n    scope: options.scope,\n    resource: options.resource,\n    ...options.additionalRequestPayload,\n  } satisfies AccessTokenRequest\n\n  return retrieveAccessToken({\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    request,\n    dpop: options.dpop,\n    callbacks: options.callbacks,\n    resource: options.resource,\n  })\n}\n\ninterface RetrieveAccessTokenOptions extends RetrieveAccessTokenBaseOptions {\n  /**\n   * The access token request body\n   */\n  request: AccessTokenRequest\n}\n\n/**\n * Internal method\n */\nasync function retrieveAccessToken(options: RetrieveAccessTokenOptions): Promise<RetrieveAccessTokenReturn> {\n  const fetchWithZod = createZodFetcher(options.callbacks.fetch)\n\n  const accessTokenRequest = parseWithErrorHandling(\n    zAccessTokenRequest,\n    options.request,\n    'Error validating access token request'\n  )\n\n  const supportedGrantTypes = getGrantTypesSupported(options.authorizationServerMetadata.grant_types_supported)\n  if (!supportedGrantTypes.includes(accessTokenRequest.grant_type)) {\n    throw new Oauth2Error(\n      `The authorization server '${options.authorizationServerMetadata.issuer}' does not support the '${accessTokenRequest.grant_type}' grant type. Supported grant types are: ${supportedGrantTypes.join(', ')}`\n    )\n  }\n\n  // For backwards compat with draft 11 (we send both)\n  if (accessTokenRequest.tx_code) {\n    accessTokenRequest.user_pin = accessTokenRequest.tx_code\n  }\n\n  return await authorizationServerRequestWithClientAttestationChallengeRetry({\n    request: (attestationChallenge) =>\n      authorizationServerRequestWithDpopRetry({\n        dpop: options.dpop,\n        request: async (dpop) => {\n          const dpopHeaders = dpop\n            ? await createDpopHeadersForRequest({\n                request: {\n                  method: 'POST',\n                  url: options.authorizationServerMetadata.token_endpoint,\n                },\n                signer: dpop.signer,\n                callbacks: options.callbacks,\n                nonce: dpop.nonce,\n              })\n            : undefined\n\n          const headers = new Headers({\n            'Content-Type': ContentType.XWwwFormUrlencoded,\n            ...dpopHeaders,\n          })\n\n          // Apply client authentication\n          await options.callbacks.clientAuthentication({\n            url: options.authorizationServerMetadata.token_endpoint,\n            method: 'POST',\n            authorizationServerMetadata: options.authorizationServerMetadata,\n            body: accessTokenRequest,\n            contentType: ContentType.XWwwFormUrlencoded,\n            headers,\n            attestationChallenge,\n          })\n\n          const { response, result } = await fetchWithZod(\n            zAccessTokenResponse,\n            ContentType.Json,\n            options.authorizationServerMetadata.token_endpoint,\n            {\n              body: objectToQueryParams(accessTokenRequest).toString(),\n              method: 'POST',\n              headers,\n            }\n          )\n\n          if (!response.ok || !result) {\n            const tokenErrorResponse = zAccessTokenErrorResponse.safeParse(\n              await response\n                .clone()\n                .json()\n                .catch(() => null)\n            )\n            if (tokenErrorResponse.success) {\n              throw new Oauth2ClientErrorResponseError(\n                `Unable to retrieve access token from '${options.authorizationServerMetadata.token_endpoint}'. Received token error response with status ${response.status}`,\n                tokenErrorResponse.data,\n                response\n              )\n            }\n\n            throw new InvalidFetchResponseError(\n              `Unable to retrieve access token from '${options.authorizationServerMetadata.token_endpoint}'. Received response with status ${response.status}`,\n              await response.clone().text(),\n              response\n            )\n          }\n\n          if (!result.success) {\n            throw new ValidationError('Error validating access token response', result.error)\n          }\n\n          const dpopNonce = extractDpopNonceFromHeaders(response.headers) ?? undefined\n          return {\n            dpop: dpop\n              ? {\n                  ...dpop,\n                  nonce: dpopNonce,\n                }\n              : undefined,\n            attestationChallenge: extractClientAttestationChallengeFromHeaders(response.headers) ?? undefined,\n            accessTokenResponse: result.data,\n          }\n        },\n      }),\n  })\n}\n","import {\n  ContentType,\n  createZodFetcher,\n  Headers,\n  InvalidFetchResponseError,\n  objectToQueryParams,\n  parseWithErrorHandling,\n  ValidationError,\n} from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { authorizationServerRequestWithDpopRetry } from '../dpop/dpop-retry'\nimport { Oauth2ClientAuthorizationChallengeError } from '../error/Oauth2ClientAuthorizationChallengeError'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { createPkce } from '../pkce'\nimport {\n  type AuthorizationChallengeRequest,\n  zAuthorizationChallengeErrorResponse,\n  zAuthorizationChallengeRequest,\n  zAuthorizationChallengeResponse,\n} from './z-authorization-challenge'\n\nexport interface SendAuthorizationChallengeRequestOptions {\n  /**\n   * Callback context\n   */\n  callbacks: Pick<CallbackContext, 'fetch' | 'hash' | 'generateRandom' | 'signJwt' | 'clientAuthentication'>\n\n  /**\n   * Metadata of the authorization server where to perform the authorization challenge\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * Previously established auth session\n   */\n  authSession?: string\n\n  /**\n   * Scope to request for the authorization challenge request\n   */\n  scope?: string\n\n  /**\n   * State for the authorization challenge request\n   */\n  state?: string\n\n  /**\n   * The resource to which access is being requested. This can help the authorization\n   * server in determining the resource server to handle the authorization request for\n   */\n  resource?: string\n\n  /**\n   * Redirect uri to include in the authorization challenge request. Maybe be used by the\n   * server when falling back to a PAR request.\n   */\n  redirectUri?: string\n\n  /**\n   * Presentation during issuance session if credentials were presented\n   * as part of an issuance session\n   */\n  presentationDuringIssuanceSession?: string\n\n  /**\n   * Additional payload to include in the authorization challenge 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   * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n   */\n  pkceCodeVerifier?: string\n\n  /**\n   * DPoP options\n   */\n  dpop?: RequestDpopOptions\n}\n\n/**\n * Send an authorization challenge request.\n *\n * @throws {Oauth2ClientAuthorizationChallengeError} if the request failed and a {@link AuthorizationChallengeErrorResponse} is returned\n * @throws {InvalidFetchResponseError} if the request failed but no error response could be parsed\n * @throws {ValidationError} if a successful response was received but an error occurred during verification of the {@link AuthorizationChallengeResponse}\n */\nexport async function sendAuthorizationChallengeRequest(options: SendAuthorizationChallengeRequestOptions) {\n  const fetchWithZod = createZodFetcher(options.callbacks.fetch)\n\n  const authorizationServerMetadata = options.authorizationServerMetadata\n  const authorizationChallengeEndpoint = authorizationServerMetadata.authorization_challenge_endpoint\n  if (!authorizationChallengeEndpoint) {\n    throw new Oauth2Error(\n      `Unable to send authorization challenge. Authorization server '${authorizationServerMetadata.issuer}' has no 'authorization_challenge_endpoint'`\n    )\n  }\n\n  // PKCE\n  // If auth session is included it's likely not needed to use PKCE\n  const pkce =\n    authorizationServerMetadata.code_challenge_methods_supported && !options.authSession\n      ? await createPkce({\n          allowedCodeChallengeMethods: authorizationServerMetadata.code_challenge_methods_supported,\n          callbacks: options.callbacks,\n          codeVerifier: options.pkceCodeVerifier,\n        })\n      : undefined\n\n  const authorizationChallengeRequest = parseWithErrorHandling(zAuthorizationChallengeRequest, {\n    ...options.additionalRequestPayload,\n    auth_session: options.authSession,\n    scope: options.scope,\n    redirect_uri: options.redirectUri,\n    resource: options.resource,\n    state: options.state,\n    code_challenge: pkce?.codeChallenge,\n    code_challenge_method: pkce?.codeChallengeMethod,\n    presentation_during_issuance_session: options.presentationDuringIssuanceSession,\n  } satisfies AuthorizationChallengeRequest)\n\n  return authorizationServerRequestWithDpopRetry({\n    dpop: options.dpop,\n    request: async (dpop) => {\n      const dpopHeaders = dpop\n        ? await createDpopHeadersForRequest({\n            request: {\n              method: 'POST',\n              url: authorizationChallengeEndpoint,\n            },\n            signer: dpop.signer,\n            callbacks: options.callbacks,\n            nonce: dpop.nonce,\n          })\n        : undefined\n\n      const headers = new Headers({\n        ...dpopHeaders,\n        'Content-Type': ContentType.XWwwFormUrlencoded,\n      })\n\n      // Apply client authentication\n      await options.callbacks.clientAuthentication({\n        url: authorizationChallengeEndpoint,\n        method: 'POST',\n        authorizationServerMetadata: options.authorizationServerMetadata,\n        body: authorizationChallengeRequest,\n        contentType: ContentType.XWwwFormUrlencoded,\n        headers,\n      })\n\n      const { response, result } = await fetchWithZod(\n        zAuthorizationChallengeResponse,\n        ContentType.Json,\n        authorizationChallengeEndpoint,\n        {\n          method: 'POST',\n          body: objectToQueryParams(authorizationChallengeRequest).toString(),\n          headers,\n        }\n      )\n\n      if (!response.ok || !result) {\n        const authorizationChallengeErrorResponse = zAuthorizationChallengeErrorResponse.safeParse(\n          await response\n            .clone()\n            .json()\n            .catch(() => null)\n        )\n        if (authorizationChallengeErrorResponse.success) {\n          throw new Oauth2ClientAuthorizationChallengeError(\n            `Error requesting authorization code from authorization challenge endpoint '${authorizationServerMetadata.authorization_challenge_endpoint}'. Received response with status ${response.status}`,\n            authorizationChallengeErrorResponse.data,\n            response\n          )\n        }\n\n        throw new InvalidFetchResponseError(\n          `Error requesting authorization code from authorization challenge endpoint '${authorizationServerMetadata.authorization_challenge_endpoint}'. Received response with status ${response.status}`,\n          await response.clone().text(),\n          response\n        )\n      }\n\n      if (!result.success) {\n        throw new ValidationError('Error validating authorization challenge response', result.error)\n      }\n\n      const dpopNonce = extractDpopNonceFromHeaders(response.headers) ?? undefined\n      return {\n        pkce,\n        dpop: dpop\n          ? {\n              ...dpop,\n              nonce: dpopNonce,\n            }\n          : undefined,\n        authorizationChallengeResponse: result.data,\n      }\n    },\n  })\n}\n","import {\n  ContentType,\n  createZodFetcher,\n  Headers,\n  InvalidFetchResponseError,\n  objectToQueryParams,\n} from '@openid4vc/utils'\nimport { ValidationError } from '../../../utils/src/error/ValidationError'\nimport { type CallbackContext, HashAlgorithm } from '../callbacks'\nimport { calculateJwkThumbprint } from '../common/jwk/jwk-thumbprint'\nimport { zOauth2ErrorResponse } from '../common/z-oauth2-error'\nimport { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { authorizationServerRequestWithDpopRetry } from '../dpop/dpop-retry'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport { createPkce } from '../pkce'\nimport {\n  type AuthorizationRequest,\n  type PushedAuthorizationRequest,\n  zPushedAuthorizationResponse,\n} from './z-authorization-request'\n\nexport interface CreateAuthorizationRequestUrlOptions {\n  /**\n   * Callback context mostly for crypto related functionality\n   */\n  callbacks: Pick<CallbackContext, 'fetch' | 'hash' | 'generateRandom' | 'signJwt' | 'clientAuthentication'>\n\n  /**\n   * Metadata of the authorization server for which to create the authorization request url\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * The client id to use for the authorization request.\n   *\n   * For authorization requests the `client_id` is ALWAYS required, even if client authentication is used\n   * (which differs from the token endpoint). This should match with the client_id that will be used for\n   * client authentication\n   */\n  clientId: string\n\n  /**\n   * Scope to request for the authorization request\n   */\n  scope?: string\n\n  /**\n   * State for the authorization request\n   */\n  state?: string\n\n  /**\n   * The resource to which access is being requested. This can help the authorization\n   * server in determining the resource server to handle the authorization request for\n   */\n  resource?: string\n\n  /**\n   * Redirect uri to include in the authorization request\n   */\n  redirectUri?: string\n\n  /**\n   * Additional payload to include in the authorization 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   * Code verifier to use for pkce. If not provided a value will generated when pkce is supported\n   */\n  pkceCodeVerifier?: string\n\n  /**\n   * DPoP options\n   *\n   * If PAR is not used only the `dpop_jkt` property will be included in the request\n   */\n  dpop?: RequestDpopOptions\n}\n\n/**\n * Create an authorization request url that can be used for authorization.\n *\n * If the authorization server supports Pushed Authorization Requests (PAR) the\n * request will first be pushed to the authorization request, and a reference to\n * the authorization request will be returned (using the 'request_uri' param).\n */\nexport async function createAuthorizationRequestUrl(options: CreateAuthorizationRequestUrlOptions) {\n  const authorizationServerMetadata = options.authorizationServerMetadata\n\n  const pushedAuthorizationRequestEndpoint = authorizationServerMetadata.pushed_authorization_request_endpoint\n  if (!authorizationServerMetadata.authorization_endpoint) {\n    throw new Oauth2Error(\n      `Unable to create authorization request url. Authorization server '${authorizationServerMetadata.issuer}' has no 'authorization_endpoint'`\n    )\n  }\n\n  // PKCE\n  const pkce = authorizationServerMetadata.code_challenge_methods_supported\n    ? await createPkce({\n        allowedCodeChallengeMethods: authorizationServerMetadata.code_challenge_methods_supported,\n        callbacks: options.callbacks,\n        codeVerifier: options.pkceCodeVerifier,\n      })\n    : undefined\n\n  const authorizationRequest: AuthorizationRequest = {\n    ...options.additionalRequestPayload,\n    response_type: 'code',\n    client_id: options.clientId,\n    redirect_uri: options.redirectUri,\n    resource: options.resource,\n    scope: options.scope,\n    state: options.state,\n    code_challenge: pkce?.codeChallenge,\n    code_challenge_method: pkce?.codeChallengeMethod,\n  }\n  let pushedAuthorizationRequest: PushedAuthorizationRequest | undefined\n  let dpop: RequestDpopOptions | undefined = options.dpop\n\n  if (authorizationServerMetadata.require_pushed_authorization_requests || pushedAuthorizationRequestEndpoint) {\n    // Use PAR if supported or required\n    if (!pushedAuthorizationRequestEndpoint) {\n      throw new Oauth2Error(\n        `Authorization server '${authorizationServerMetadata.issuer}' indicated that pushed authorization requests are required, but the 'pushed_authorization_request_endpoint' is missing in the authorization server metadata.`\n      )\n    }\n\n    const { pushedAuthorizationResponse, dpopNonce } = await authorizationServerRequestWithDpopRetry({\n      dpop: options.dpop,\n      request: async (dpop) => {\n        const dpopHeaders = dpop\n          ? await createDpopHeadersForRequest({\n              request: {\n                method: 'POST',\n                url: pushedAuthorizationRequestEndpoint,\n              },\n              signer: dpop.signer,\n              callbacks: options.callbacks,\n              nonce: dpop.nonce,\n            })\n          : undefined\n\n        return await pushAuthorizationRequest({\n          authorizationServerMetadata,\n          authorizationRequest,\n          pushedAuthorizationRequestEndpoint,\n          callbacks: options.callbacks,\n          headers: dpopHeaders,\n        })\n      },\n    })\n\n    pushedAuthorizationRequest = {\n      request_uri: pushedAuthorizationResponse.request_uri,\n      client_id: authorizationRequest.client_id,\n    }\n\n    if (options.dpop && dpopNonce) {\n      dpop = {\n        ...options.dpop,\n        nonce: dpopNonce,\n      }\n    }\n  } else {\n    // If not using PAR but dpop we include the `dpop_jkt` option\n    if (options.dpop) {\n      authorizationRequest.dpop_jkt = await calculateJwkThumbprint({\n        hashAlgorithm: HashAlgorithm.Sha256,\n        hashCallback: options.callbacks.hash,\n        jwk: options.dpop.signer.publicJwk,\n      })\n    }\n  }\n\n  const authorizationRequestUrl = `${authorizationServerMetadata.authorization_endpoint}?${objectToQueryParams(pushedAuthorizationRequest ?? authorizationRequest).toString()}`\n  return {\n    authorizationRequestUrl,\n    pkce,\n    dpop,\n  }\n}\n\ninterface PushAuthorizationRequestOptions {\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  pushedAuthorizationRequestEndpoint: string\n  authorizationRequest: AuthorizationRequest\n\n  /**\n   * Headers to include in the PAR request\n   */\n  headers?: Record<string, unknown>\n\n  callbacks: Pick<CallbackContext, 'fetch' | 'clientAuthentication'>\n}\n\nasync function pushAuthorizationRequest(options: PushAuthorizationRequestOptions) {\n  const fetchWithZod = createZodFetcher(options.callbacks.fetch)\n\n  if (options.authorizationRequest.request_uri) {\n    throw new Oauth2Error(\n      `Authorization request contains 'request_uri' parameter. This is not allowed for pushed authorization requests.`\n    )\n  }\n\n  const headers = new Headers({\n    ...options.headers,\n    'Content-Type': ContentType.XWwwFormUrlencoded,\n  })\n\n  // NOTE: this will currently be called twice if we need to retry dpop.\n  // Probably have to think about caching it in some way.\n  // Apply client authentication\n  await options.callbacks.clientAuthentication({\n    url: options.pushedAuthorizationRequestEndpoint,\n    method: 'POST',\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    body: options.authorizationRequest,\n    contentType: ContentType.XWwwFormUrlencoded,\n    headers,\n  })\n\n  const { response, result } = await fetchWithZod(\n    zPushedAuthorizationResponse,\n    ContentType.Json,\n    options.pushedAuthorizationRequestEndpoint,\n    {\n      method: 'POST',\n      body: objectToQueryParams(options.authorizationRequest).toString(),\n      headers,\n    }\n  )\n\n  if (!response.ok || !result) {\n    const parErrorResponse = zOauth2ErrorResponse.safeParse(\n      await response\n        .clone()\n        .json()\n        .catch(() => null)\n    )\n    if (parErrorResponse.success) {\n      throw new Oauth2ClientErrorResponseError(\n        `Unable to push authorization request to '${options.pushedAuthorizationRequestEndpoint}'. Received response with status ${response.status}`,\n        parErrorResponse.data,\n        response\n      )\n    }\n\n    throw new InvalidFetchResponseError(\n      `Unable to push authorization request to '${options.pushedAuthorizationRequestEndpoint}'. Received response with status ${response.status}`,\n      await response.clone().text(),\n      response\n    )\n  }\n\n  if (!result.success) {\n    throw new ValidationError('Error validating pushed authorization response', result.error)\n  }\n\n  const dpopNonce = extractDpopNonceFromHeaders(response.headers)\n  return {\n    dpopNonce,\n    pushedAuthorizationResponse: result.data,\n  }\n}\n","import { createFetcher, type FetchRequestInit, type FetchResponse, type HttpMethod } from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { shouldRetryResourceRequestWithDPoPNonce } from '../dpop/dpop-retry'\nimport {\n  Oauth2ResourceUnauthorizedError,\n  type WwwAuthenticateHeaderChallenge,\n} from '../error/Oauth2ResourceUnauthorizedError'\n\nexport interface ResourceRequestOptions {\n  /**\n   * DPoP options\n   */\n  dpop?: RequestDpopOptions & {\n    /**\n     * Whether to retry the request if the server responds with an error indicating\n     * the request should be retried with a server provided dpop nonce\n     *\n     * @default true\n     */\n    retryWithNonce?: boolean\n  }\n\n  /**\n   * Callbacks\n   */\n  callbacks: Pick<CallbackContext, 'fetch' | 'generateRandom' | 'signJwt' | 'hash'>\n\n  /**\n   * Access token\n   */\n  accessToken: string\n\n  url: string\n  requestOptions: FetchRequestInit\n}\n\ninterface ResourceRequestResponseBase {\n  ok: boolean\n  response: FetchResponse\n\n  /**\n   * If the response included a dpop nonce to be used in subsequent requests\n   */\n  dpop?: {\n    nonce: string\n  }\n}\n\nexport interface ResourceRequestResponseOk extends ResourceRequestResponseBase {\n  ok: true\n}\n\nexport interface ResourceRequestResponseNotOk extends ResourceRequestResponseBase {\n  ok: false\n\n  /**\n   * If a WWW-Authenticate was included in the headers of the response\n   * they will be parsed and added here.\n   */\n  wwwAuthenticate?: WwwAuthenticateHeaderChallenge[]\n}\n\nexport async function resourceRequest(\n  options: ResourceRequestOptions\n): Promise<ResourceRequestResponseOk | ResourceRequestResponseNotOk> {\n  const dpopHeaders = options.dpop\n    ? await createDpopHeadersForRequest({\n        request: {\n          url: options.url,\n          // in fetch the default is GET if not provided\n          method: (options.requestOptions.method as HttpMethod) ?? 'GET',\n        },\n        signer: options.dpop.signer,\n        callbacks: options.callbacks,\n        nonce: options.dpop.nonce,\n        accessToken: options.accessToken,\n      })\n    : undefined\n\n  const response = await createFetcher(options.callbacks.fetch)(options.url, {\n    ...options.requestOptions,\n    headers: {\n      ...options.requestOptions.headers,\n      Authorization: `${dpopHeaders ? 'DPoP' : 'Bearer'} ${options.accessToken}`,\n      ...dpopHeaders,\n    },\n  })\n\n  const dpopNonce = extractDpopNonceFromHeaders(response.headers)\n  if (response.ok) {\n    return {\n      ok: true,\n      response,\n      dpop: dpopNonce\n        ? {\n            nonce: dpopNonce,\n          }\n        : undefined,\n    }\n  }\n\n  const wwwAuthenticateHeader = response.headers.get('WWW-Authenticate')\n  const resourceUnauthorizedError = wwwAuthenticateHeader\n    ? Oauth2ResourceUnauthorizedError.fromHeaderValue(wwwAuthenticateHeader)\n    : undefined\n\n  const shouldRetryWithNonce = options.dpop?.retryWithNonce ?? true\n  const dpopRetry = resourceUnauthorizedError\n    ? shouldRetryResourceRequestWithDPoPNonce({\n        responseHeaders: response.headers,\n        resourceUnauthorizedError: resourceUnauthorizedError,\n      })\n    : undefined\n\n  // only retry if retryWithNonce is set\n  if (shouldRetryWithNonce && dpopRetry?.retry && options.dpop) {\n    return await resourceRequest({\n      ...options,\n      dpop: {\n        ...options.dpop,\n        nonce: dpopRetry.dpopNonce,\n        // We'll never try multiple times (to prevent endless recursion)\n        retryWithNonce: false,\n      },\n    })\n  }\n\n  return {\n    ok: false,\n    response,\n    dpop: dpopNonce\n      ? {\n          nonce: dpopNonce,\n        }\n      : undefined,\n    wwwAuthenticate: resourceUnauthorizedError?.wwwAuthenticateHeaders,\n  }\n}\n","import { objectToQueryParams } from '@openid4vc/utils'\nimport {\n  type RetrieveAuthorizationCodeAccessTokenOptions,\n  type RetrieveClientCredentialsAccessTokenOptions,\n  type RetrievePreAuthorizedCodeAccessTokenOptions,\n  type RetrieveRefreshTokenAccessTokenOptions,\n  retrieveAuthorizationCodeAccessToken,\n  retrieveClientCredentialsAccessToken,\n  retrievePreAuthorizedCodeAccessToken,\n  retrieveRefreshTokenAccessToken,\n} from './access-token/retrieve-access-token'\nimport {\n  type SendAuthorizationChallengeRequestOptions,\n  sendAuthorizationChallengeRequest,\n} from './authorization-challenge/send-authorization-challenge'\nimport {\n  type CreateAuthorizationRequestUrlOptions,\n  createAuthorizationRequestUrl,\n} from './authorization-request/create-authorization-request'\nimport { type ParseAuthorizationResponseOptions, parseAuthorizationResponseRedirectUrl } from './authorization-response'\nimport {\n  type VerifyAuthorizationResponseOptions,\n  verifyAuthorizationResponse,\n} from './authorization-response/verify-authorization-response'\nimport type { CallbackContext } from './callbacks'\nimport {\n  type RequestClientAttestationChallengeOptions,\n  requestClientAttestationChallenge,\n} from './client-attestation/client-attestation-challenge'\nimport { SupportedClientAuthenticationMethod } from './client-authentication'\nimport { Oauth2ErrorCodes } from './common/z-oauth2-error'\nimport { extractDpopNonceFromHeaders } from './dpop/dpop'\nimport { Oauth2ClientAuthorizationChallengeError } from './error/Oauth2ClientAuthorizationChallengeError'\nimport { fetchAuthorizationServerMetadata } from './metadata/authorization-server/authorization-server-metadata'\nimport type { AuthorizationServerMetadata } from './metadata/authorization-server/z-authorization-server-metadata'\nimport { createPkce } from './pkce'\nimport { type ResourceRequestOptions, resourceRequest } from './resource-request/make-resource-request'\n\nexport interface Oauth2ClientOptions {\n  /**\n   * Callbacks required for the oauth2 client\n   */\n  callbacks: Omit<CallbackContext, 'verifyJwt' | 'decryptJwe' | 'encryptJwe'>\n}\n\nexport class Oauth2Client {\n  public constructor(private options: Oauth2ClientOptions) {}\n\n  // TODO: add options to provide client metadata / algs supported by the client\n  // so we can find the commonly supported algs and make it easier\n  public isDpopSupported(options: { authorizationServerMetadata: AuthorizationServerMetadata }) {\n    if (\n      !options.authorizationServerMetadata.dpop_signing_alg_values_supported ||\n      options.authorizationServerMetadata.dpop_signing_alg_values_supported.length === 0\n    ) {\n      return {\n        supported: false,\n      } as const\n    }\n\n    return {\n      supported: true,\n      dpopSigningAlgValuesSupported: options.authorizationServerMetadata.dpop_signing_alg_values_supported,\n    } as const\n  }\n\n  public isClientAttestationSupported(options: { authorizationServerMetadata: AuthorizationServerMetadata }) {\n    if (\n      !options.authorizationServerMetadata.token_endpoint_auth_methods_supported?.includes(\n        SupportedClientAuthenticationMethod.ClientAttestationJwt\n      )\n    ) {\n      return {\n        supported: false,\n      } as const\n    }\n\n    return {\n      supported: true,\n    } as const\n  }\n\n  public async fetchAuthorizationServerMetadata(issuer: string) {\n    return fetchAuthorizationServerMetadata(issuer, this.options.callbacks.fetch)\n  }\n\n  /**\n   * Initiate authorization.\n   *\n   * It will take the followings steps:\n   * - if `authorization_challenge_endpoint` is defined, send an authorization challenge request\n   * - if authorization challenge request returns a `redirect_to_web` error code with `request_uri`\n   *   then construct the authorization request url based on the `request_uri`\n   * - if the `authorization_challenge_endpoint` is not defined, or authorization challenge request reuturns a `redirect_to_web` error code without `request_uri`\n   *   then the authorization request url will be constructed as usual (optionally using PAR).\n   *\n   * @throws {Oauth2ClientAuthorizationChallengeError} in case of an error response. If `error` is\n   * `insufficient_authorization` possible extra steps can be taken.\n   */\n  public async initiateAuthorization(options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks'>) {\n    const pkce = options.authorizationServerMetadata.code_challenge_methods_supported\n      ? await createPkce({\n          allowedCodeChallengeMethods: options.authorizationServerMetadata.code_challenge_methods_supported,\n          callbacks: this.options.callbacks,\n          codeVerifier: options.pkceCodeVerifier,\n        })\n      : undefined\n\n    if (options.authorizationServerMetadata.authorization_challenge_endpoint) {\n      try {\n        await this.sendAuthorizationChallengeRequest({\n          authorizationServerMetadata: options.authorizationServerMetadata,\n          additionalRequestPayload: options.additionalRequestPayload,\n          pkceCodeVerifier: pkce?.codeVerifier,\n          redirectUri: options.redirectUri,\n          scope: options.scope,\n          resource: options.resource,\n          dpop: options.dpop,\n          state: options.state,\n        })\n      } catch (error) {\n        // In this case we resume with the normal auth flow\n        const isRecoverableError =\n          error instanceof Oauth2ClientAuthorizationChallengeError &&\n          error.errorResponse.error === Oauth2ErrorCodes.RedirectToWeb\n\n        if (!isRecoverableError) throw error\n\n        // If a request_uri was returned we can treat the response as if PAR was used\n        if (error.errorResponse.request_uri) {\n          const authorizationRequestUrl = `${options.authorizationServerMetadata.authorization_endpoint}?${objectToQueryParams(\n            {\n              request_uri: error.errorResponse.request_uri,\n              client_id: options.clientId,\n            }\n          ).toString()}`\n\n          const dpopNonce = extractDpopNonceFromHeaders(error.response.headers)\n          return {\n            dpop: options.dpop\n              ? {\n                  ...options.dpop,\n                  nonce: dpopNonce ?? undefined,\n                }\n              : undefined,\n            authorizationRequestUrl,\n            pkce,\n          }\n        }\n      }\n    }\n\n    return this.createAuthorizationRequestUrl({\n      authorizationServerMetadata: options.authorizationServerMetadata,\n      clientId: options.clientId,\n      additionalRequestPayload: options.additionalRequestPayload,\n      redirectUri: options.redirectUri,\n      scope: options.scope,\n      pkceCodeVerifier: pkce?.codeVerifier,\n      resource: options.resource,\n      dpop: options.dpop,\n      state: options.state,\n    })\n  }\n\n  public sendAuthorizationChallengeRequest(options: Omit<SendAuthorizationChallengeRequestOptions, 'callbacks'>) {\n    return sendAuthorizationChallengeRequest({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  /**\n   * Request a fresh Client Attestation challenge from the authorization server's `challenge_endpoint`\n   * (draft 09). The returned challenge can be passed to `clientAuthenticationClientAttestationJwt` so\n   * it is included in the Client Attestation PoP JWT.\n   */\n  public requestClientAttestationChallenge(options: Omit<RequestClientAttestationChallengeOptions, 'callbacks'>) {\n    return requestClientAttestationChallenge({\n      ...options,\n      callbacks: this.options.callbacks,\n    })\n  }\n\n  public async createAuthorizationRequestUrl(options: Omit<CreateAuthorizationRequestUrlOptions, 'callbacks'>) {\n    return createAuthorizationRequestUrl({\n      authorizationServerMetadata: options.authorizationServerMetadata,\n      clientId: options.clientId,\n      additionalRequestPayload: options.additionalRequestPayload,\n      redirectUri: options.redirectUri,\n      resource: options.resource,\n      scope: options.scope,\n      callbacks: this.options.callbacks,\n      pkceCodeVerifier: options.pkceCodeVerifier,\n      dpop: options.dpop,\n      state: options.state,\n    })\n  }\n\n  public async retrievePreAuthorizedCodeAccessToken({\n    authorizationServerMetadata,\n    preAuthorizedCode,\n    additionalRequestPayload,\n    txCode,\n    dpop,\n    resource,\n  }: Omit<RetrievePreAuthorizedCodeAccessTokenOptions, 'callbacks'>) {\n    const result = await retrievePreAuthorizedCodeAccessToken({\n      authorizationServerMetadata,\n      preAuthorizedCode,\n      txCode,\n      resource,\n      additionalRequestPayload: {\n        ...additionalRequestPayload,\n        tx_code: txCode,\n      },\n      callbacks: this.options.callbacks,\n      dpop,\n    })\n\n    return result\n  }\n\n  public async retrieveAuthorizationCodeAccessToken({\n    authorizationServerMetadata,\n    additionalRequestPayload,\n    authorizationCode,\n    pkceCodeVerifier,\n    redirectUri,\n    resource,\n    dpop,\n  }: Omit<RetrieveAuthorizationCodeAccessTokenOptions, 'callbacks'>) {\n    const result = await retrieveAuthorizationCodeAccessToken({\n      authorizationServerMetadata,\n      authorizationCode,\n      pkceCodeVerifier,\n      additionalRequestPayload,\n      resource,\n      callbacks: this.options.callbacks,\n      dpop,\n      redirectUri,\n    })\n\n    return result\n  }\n\n  public async retrieveRefreshTokenAccessToken({\n    authorizationServerMetadata,\n    additionalRequestPayload,\n    refreshToken,\n    resource,\n    dpop,\n  }: Omit<RetrieveRefreshTokenAccessTokenOptions, 'callbacks'>) {\n    const result = await retrieveRefreshTokenAccessToken({\n      authorizationServerMetadata,\n      refreshToken,\n      additionalRequestPayload,\n      resource,\n      callbacks: this.options.callbacks,\n      dpop,\n    })\n\n    return result\n  }\n\n  public async retrieveClientCredentialsAccessToken({\n    authorizationServerMetadata,\n    additionalRequestPayload,\n    scope,\n    resource,\n    dpop,\n  }: Omit<RetrieveClientCredentialsAccessTokenOptions, 'callbacks'>) {\n    const result = await retrieveClientCredentialsAccessToken({\n      authorizationServerMetadata,\n      scope,\n      additionalRequestPayload,\n      resource,\n      callbacks: this.options.callbacks,\n      dpop,\n    })\n\n    return result\n  }\n\n  public async resourceRequest(options: ResourceRequestOptions) {\n    return resourceRequest(options)\n  }\n\n  /**\n   * Parses an authorization response redirect URL into an authorization (error) response.\n   *\n   * Make sure to call `Oauth2Client.verifyAuthorizationResponse` after fetching the session\n   * based on the parsed response, to ensure the authorization response `iss` value is verified.\n   */\n  public parseAuthorizationResponseRedirectUrl(options: ParseAuthorizationResponseOptions) {\n    return parseAuthorizationResponseRedirectUrl(options)\n  }\n\n  public verifyAuthorizationResponse(options: VerifyAuthorizationResponseOptions) {\n    return verifyAuthorizationResponse(options)\n  }\n}\n","import { type VerifyResourceRequestOptions, verifyResourceRequest } from '.'\nimport type { CallbackContext } from './callbacks'\n\nexport interface Oauth2ResourceServerOptions {\n  /**\n   * Callbacks required for the oauth2 resource server\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash' | 'clientAuthentication' | 'fetch'>\n}\n\nexport class Oauth2ResourceServer {\n  public constructor(private options: Oauth2ResourceServerOptions) {}\n\n  public async verifyResourceRequest(options: Omit<VerifyResourceRequestOptions, 'callbacks'>) {\n    return verifyResourceRequest({\n      callbacks: this.options.callbacks,\n      ...options,\n    })\n  }\n}\n","import { zNumericDate } from '@openid4vc/utils'\nimport z from 'zod'\nimport { zJwtConfirmationPayload } from '../common/jwt/z-jwt'\n\nexport const zTokenIntrospectionRequest = z\n  .object({\n    token: z.string(),\n    token_type_hint: z.optional(z.string()),\n  })\n  .loose()\n\nexport type TokenIntrospectionRequest = z.infer<typeof zTokenIntrospectionRequest>\n\nexport const zTokenIntrospectionResponse = z\n  .object({\n    active: z.boolean(),\n    scope: z.optional(z.string()),\n    client_id: z.optional(z.string()),\n    username: z.optional(z.string()),\n    token_type: z.optional(z.string()),\n\n    exp: z.optional(zNumericDate),\n    iat: z.optional(zNumericDate),\n    nbf: z.optional(zNumericDate),\n\n    sub: z.optional(z.string()),\n    aud: z.optional(z.union([z.string(), z.array(z.string())])),\n\n    iss: z.optional(z.string()),\n    jti: z.optional(z.string()),\n\n    cnf: z.optional(zJwtConfirmationPayload),\n  })\n  .loose()\n\nexport type TokenIntrospectionResponse = z.infer<typeof zTokenIntrospectionResponse>\n","import {\n  ContentType,\n  createZodFetcher,\n  Headers,\n  InvalidFetchResponseError,\n  objectToQueryParams,\n  parseWithErrorHandling,\n} from '@openid4vc/utils'\nimport type { CallbackContext } from '../callbacks'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport {\n  type TokenIntrospectionRequest,\n  zTokenIntrospectionRequest,\n  zTokenIntrospectionResponse,\n} from './z-token-introspection'\n\nexport interface IntrospectTokenOptions {\n  /**\n   * Metadata of the authorization server. Must contain an `introspection_endpoint`\n   */\n  authorizationServerMetadata: AuthorizationServerMetadata\n\n  /**\n   * The provided access token\n   */\n  token: string\n\n  /**\n   * The scheme of the access token, will be sent along with the token\n   * as a hint.\n   */\n  tokenTypeHint?: string\n\n  /**\n   * Additional payload to include in the introspection 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  additionalPayload?: Record<string, unknown>\n\n  callbacks: Pick<CallbackContext, 'fetch' | 'clientAuthentication'>\n}\n\nexport async function introspectToken(options: IntrospectTokenOptions) {\n  const fetchWithZod = createZodFetcher(options.callbacks.fetch)\n\n  const introspectionRequest = parseWithErrorHandling(zTokenIntrospectionRequest, {\n    token: options.token,\n    token_type_hint: options.tokenTypeHint,\n    ...options.additionalPayload,\n  } satisfies TokenIntrospectionRequest)\n\n  const introspectionEndpoint = options.authorizationServerMetadata.introspection_endpoint\n  if (!introspectionEndpoint) {\n    throw new Oauth2Error(`Missing required 'introspection_endpoint' parameter in authorization server metadata`)\n  }\n\n  const headers = new Headers({\n    'Content-Type': ContentType.XWwwFormUrlencoded,\n  })\n\n  // Apply client authentication\n  await options.callbacks.clientAuthentication({\n    url: introspectionEndpoint,\n    method: 'POST',\n    authorizationServerMetadata: options.authorizationServerMetadata,\n    body: introspectionRequest,\n    contentType: ContentType.XWwwFormUrlencoded,\n    headers,\n  })\n\n  const { result, response } = await fetchWithZod(\n    zTokenIntrospectionResponse,\n    ContentType.Json,\n    introspectionEndpoint,\n    {\n      body: objectToQueryParams(introspectionRequest).toString(),\n      method: 'POST',\n      headers,\n    }\n  )\n\n  // TODO: better error handling (error response?)\n  if (!response.ok || !result?.success) {\n    throw new InvalidFetchResponseError(\n      `Unable to introspect token from '${introspectionEndpoint}'. Received response with status ${response.status}`,\n      await response.clone().text(),\n      response\n    )\n  }\n\n  return result.data\n}\n","import { ValidationError } from '@openid4vc/utils'\nimport { introspectToken } from '../access-token/introspect-token'\nimport { SupportedAuthenticationScheme, verifyJwtProfileAccessToken } from '../access-token/verify-access-token'\nimport type { AccessTokenProfileJwtPayload } from '../access-token/z-access-token-jwt'\nimport type { TokenIntrospectionResponse } from '../access-token/z-token-introspection'\nimport type { CallbackContext } from '../callbacks'\nimport type { Jwk } from '../common/jwk/z-jwk'\nimport type { RequestLike } from '../common/z-common'\nimport { Oauth2ErrorCodes } from '../common/z-oauth2-error'\nimport { extractDpopJwtFromHeaders, verifyDpopJwt } from '../dpop/dpop'\nimport { Oauth2Error } from '../error/Oauth2Error'\nimport { Oauth2JwtParseError } from '../error/Oauth2JwtParseError'\nimport { Oauth2ResourceUnauthorizedError } from '../error/Oauth2ResourceUnauthorizedError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\n\nexport interface VerifyResourceRequestOptions {\n  /**\n   * The incoming request\n   */\n  request: RequestLike\n\n  /**\n   * Identifier for the resource server, will be matched with the `aud` value of the access token.\n   */\n  resourceServer: string\n\n  /**\n   * Callbacks for verification of the access token.\n   */\n  callbacks: Pick<CallbackContext, 'verifyJwt' | 'hash' | 'clientAuthentication' | 'fetch'>\n\n  /**\n   * allowed auth schems for the access token. If not provided\n   * all supported authentication schemes are allowed.\n   */\n  allowedAuthenticationSchemes?: SupportedAuthenticationScheme[]\n\n  /**\n   * List of authorization servers that this resource endpoint supports\n   */\n  authorizationServers: AuthorizationServerMetadata[]\n\n  now?: Date\n}\n\nexport async function verifyResourceRequest(options: VerifyResourceRequestOptions) {\n  const allowedAuthenticationSchemes =\n    options.allowedAuthenticationSchemes ?? Object.values(SupportedAuthenticationScheme)\n  if (allowedAuthenticationSchemes.length === 0) {\n    throw new Oauth2Error(\n      `Emtpy array provided for 'allowedAuthenticationSchemes', provide at least one allowed authentication scheme, or remove the value to allow all supported authentication schemes`\n    )\n  }\n\n  const authorizationHeader = options.request.headers.get('Authorization')\n  if (!authorizationHeader) {\n    throw new Oauth2ResourceUnauthorizedError(\n      `No 'Authorization' header provided in request.`,\n      allowedAuthenticationSchemes.map((scheme) => ({ scheme }))\n    )\n  }\n\n  const [scheme, accessToken] = authorizationHeader.split(' ', 2)\n  if (!scheme || !accessToken) {\n    throw new Oauth2ResourceUnauthorizedError(\n      `Malformed 'Authorization' header provided in request.`,\n      allowedAuthenticationSchemes.map((scheme) => ({ scheme }))\n    )\n  }\n\n  if (\n    !allowedAuthenticationSchemes.includes(scheme as SupportedAuthenticationScheme) ||\n    (scheme !== SupportedAuthenticationScheme.Bearer && scheme !== SupportedAuthenticationScheme.DPoP)\n  ) {\n    throw new Oauth2ResourceUnauthorizedError(\n      `Provided authentication scheme '${scheme}' is not allowed. Allowed authentication schemes are ${allowedAuthenticationSchemes.map((s) => `'${s}'`).join(', ')}.`,\n      allowedAuthenticationSchemes.map((scheme) => ({ scheme }))\n    )\n  }\n\n  // We first perform the usual Bearer authentication verification\n  // Try to parse and verify it as an jwt profile access token\n  const verificationResult = await verifyJwtProfileAccessToken({\n    accessToken,\n    callbacks: options.callbacks,\n    authorizationServers: options.authorizationServers,\n    resourceServer: options.resourceServer,\n    now: options.now,\n  }).catch((error) => {\n    // It's ok if we couldn't parse it as a JWT -- it means it's probably an opaque token\n    if (error instanceof Oauth2JwtParseError || error instanceof ValidationError) return null\n\n    const errorMessage = error instanceof Oauth2Error ? error.message : 'Invalid access token'\n    throw new Oauth2ResourceUnauthorizedError(\n      `Error occurred during verification of jwt profile access token: ${error.message}`,\n      {\n        scheme,\n        error: Oauth2ErrorCodes.InvalidToken,\n        error_description: errorMessage,\n      }\n    )\n  })\n\n  let tokenPayload: AccessTokenProfileJwtPayload | TokenIntrospectionResponse | undefined = verificationResult?.payload\n  let authorizationServer = verificationResult?.authorizationServer\n  if (!tokenPayload) {\n    // If there's no verification result it means it couldn't be parsed and we will try\n    // to use token introspection on all authorization servers until we've found the correct one\n    for (const authorizationServerMetadata of options.authorizationServers) {\n      try {\n        tokenPayload = await introspectToken({\n          authorizationServerMetadata,\n          callbacks: options.callbacks,\n          token: accessToken,\n          tokenTypeHint: scheme,\n        })\n        authorizationServer = authorizationServerMetadata\n\n        // If we found the active token.\n        if (tokenPayload.active) break\n      } catch (_error) {\n        // No-op?\n      }\n    }\n  }\n\n  if (!tokenPayload || !authorizationServer) {\n    throw new Oauth2ResourceUnauthorizedError('Could not verify token as jwt or using token introspection.', {\n      scheme,\n      error: Oauth2ErrorCodes.InvalidToken,\n      error_description: 'Token is not valid',\n    })\n  }\n\n  let dpopJwk: Jwk | undefined\n  if (\n    scheme === SupportedAuthenticationScheme.DPoP ||\n    // two alternative methods to determine whether DPoP was used. As the user can\n    // choose to include `Bearer` scheme even if DPoP was used\n    tokenPayload.token_type === SupportedAuthenticationScheme.DPoP ||\n    tokenPayload.cnf?.jkt\n  ) {\n    const dpopJwtResult = extractDpopJwtFromHeaders(options.request.headers)\n    if (!dpopJwtResult.valid) {\n      throw new Oauth2ResourceUnauthorizedError(\n        `Request contains a 'DPoP' header, but the value is not a valid DPoP jwt.`,\n        {\n          scheme,\n          error: Oauth2ErrorCodes.InvalidDpopProof,\n          error_description: `Request contains a 'DPoP' header, but the value is not a valid DPoP jwt.`,\n        }\n      )\n    }\n\n    if (!dpopJwtResult.dpopJwt) {\n      throw new Oauth2ResourceUnauthorizedError(`Request is missing required 'DPoP' header.`, {\n        scheme,\n        error: Oauth2ErrorCodes.InvalidDpopProof,\n        error_description: `Request is missing required 'DPoP' header.`,\n      })\n    }\n\n    // Take the jwk thumbprint from the token / introspection result\n    if (!tokenPayload.cnf?.jkt) {\n      throw new Oauth2ResourceUnauthorizedError(\n        `Token payload is missing required 'cnf.jkt' value for DPoP verification.`,\n        {\n          scheme,\n          error: Oauth2ErrorCodes.InvalidToken,\n          error_description: `Token payload is missing required 'cnf.jkt' value for DPoP verification.`,\n        }\n      )\n    }\n\n    try {\n      const decodedDpopJwt = await verifyDpopJwt({\n        callbacks: options.callbacks,\n        dpopJwt: dpopJwtResult.dpopJwt,\n        request: options.request,\n        accessToken,\n        now: options.now,\n        expectedJwkThumbprint: tokenPayload.cnf?.jkt,\n        allowedSigningAlgs: authorizationServer.dpop_signing_alg_values_supported,\n      })\n      dpopJwk = decodedDpopJwt.header.jwk\n    } catch (error) {\n      const errorMessage = error instanceof Oauth2Error ? error.message : 'Error verifying DPoP jwt'\n      throw new Oauth2ResourceUnauthorizedError(\n        `Error occurred during verification of jwt profile access token: ${error instanceof Error ? error.message : error}`,\n        {\n          scheme,\n          error: Oauth2ErrorCodes.InvalidDpopProof,\n          error_description: errorMessage,\n        }\n      )\n    }\n  }\n\n  return {\n    tokenPayload,\n    dpop: dpopJwk ? { jwk: dpopJwk } : undefined,\n    scheme,\n    accessToken,\n    authorizationServer: authorizationServer.issuer,\n  }\n}\n"],"x_google_ignoreList":[12],"mappings":";;;;;;;;;AAUA,IAAY,gBAAL,yBAAA,eAAA;CACL,cAAA,YAAA;CACA,cAAA,YAAA;CACA,cAAA,YAAA;;AACF,EAAA,CAAA,CAAA;;;ACVA,IAAa,cAAb,cAAiC,MAAM;CAGrC,YAAmB,SAAkB,SAA8B;EACjE,MAAM,eAAe,WAAW;EAChC,MAAM,eACJ,SAAS,iBAAiB,QAAQ,IAAI,QAAQ,MAAM,YAAY,SAAS,QAAQ,IAAI,SAAS,UAAU;EAE1G,MAAM,GAAG,eAAe,cAAc;EACtC,KAAK,QAAQ,SAAS;CACxB;AACF;;;ACVA,MAAa,2BAA2B,EACrC,mBAAmB,OAAO;CACzB,EAAE,OAAO;EACP,KAAK,EAAE,QAAQ,IAAI;EACnB,KAAK,EAAE,OAAO;EACd,GAAG,EAAE,OAAO;EACZ,GAAG,EAAE,OAAO;CACd,CAAC;CACD,EA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