@openid4vc/oauth2 0.4.5-alpha-20260126081433 → 0.4.5-alpha-20260201123930
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +24 -3
- package/dist/index.mjs +45 -17
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["z","z","z","z","ValidationError","z","formatZodError","OpenId4VcBaseError","ValidationError","OpenId4VcBaseError","formatZodError","InvalidFetchResponseError","ValidationError","z","z","z","z","z","z","z","z","z","z","InvalidFetchResponseError","ValidationError","z","authorizationServerMetadata","z","z","InvalidFetchResponseError","ValidationError","InvalidFetchResponseError","dpop","InvalidFetchResponseError","ValidationError","z","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.3.5/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/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/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/authorization-request/z-authorization-request.ts","../src/authorization-request/parse-pushed-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/z-grant-type.ts","../src/client-authentication.ts","../src/common/algorithm/algorithm-transform.ts","../src/error/Oauth2ClientErrorResponseError.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-request/verify-authorization-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/dpop/dpop-retry.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 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 * 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 { zInteger } 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: zInteger.optional(),\n exp: zInteger.optional(),\n nbf: zInteger.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 if (payload.iss && header.kid?.startsWith('did:') && !header.kid.startsWith(payload.iss)) {\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> = 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 verifiying 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 { zInteger } 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: zInteger,\n iat: zInteger,\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 // 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 // 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 { 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: { jarRequestParams: JarAuthorizationRequest }) {\n const { jarRequestParams } = 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 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, zInteger } 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 iss: z.string(),\n sub: z.string(),\n exp: zInteger,\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\nexport const zClientAttestationPopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n iss: z.string(),\n exp: zInteger,\n aud: z.union([zHttpsUrl, z.array(zHttpsUrl)]),\n\n jti: 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 { addSecondsToDate, 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 * Dpop nonce to use for constructing the client attestation pop jwt\n */\n nonce?: string\n\n /**\n * Expiration time of the client attestation pop jwt.\n *\n * @default 5 minutes after issuance date\n */\n expiresAt?: Date\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 expiresAt: options.clientAttestation.expiresAt,\n signer: options.clientAttestation.signer,\n // TODO: support dynamic fetching of the nonce\n nonce: 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 * Expected nonce in the payload. If not provided the nonce won't be validated.\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 * 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 if (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 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 expectedNonce: options.expectedNonce,\n payload,\n expectedAudience: options.authorizationServer,\n compact: options.clientAttestationPopJwt,\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'client attestation pop jwt verification failed',\n })\n\n return {\n header,\n payload,\n signer,\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * Client attestation Pop nonce value\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 * Expiration time of the JWT. If not proided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: 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 const expiresAt = options.expiresAt ?? addSecondsToDate(options.issuedAt ?? new Date(), 1 * 60)\n\n const payload = parseWithErrorHandling(zClientAttestationPopJwtPayload, {\n aud: options.authorizationServer,\n iss: clientAttestation.payload.sub,\n iat: dateToSeconds(options.issuedAt),\n exp: dateToSeconds(expiresAt),\n jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n nonce: 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 * 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 identifier of the client backend\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: 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 if (!clientAttestationHeader || !clientAttestationPopHeader) {\n return { valid: false }\n }\n\n if (\n !zCompactJwt.safeParse(clientAttestationHeader).success ||\n !zCompactJwt.safeParse(clientAttestationPopHeader).success\n ) {\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\nexport async function verifyClientAttestation({\n authorizationServer,\n clientAttestationJwt,\n clientAttestationPopJwt,\n callbacks,\n now,\n}: VerifyClientAttestationOptions) {\n try {\n const clientAttestation = await verifyClientAttestationJwt({\n callbacks,\n clientAttestationJwt,\n now,\n })\n\n const clientAttestationPop = await verifyClientAttestationPopJwt({\n callbacks: callbacks,\n authorizationServer,\n clientAttestation,\n clientAttestationPopJwt,\n now,\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, zInteger } 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: zInteger,\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 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 { 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, { type ZodSafeParseResult } 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 parsedAuthorizationRequest: ZodSafeParseResult<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 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 authorizationRequestJwt = parsedJar.authorizationRequestJwt\n } else {\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(options.authorizationRequest)\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2ServerErrorResponseError({\n error: Oauth2ErrorCodes.InvalidRequest,\n error_description: `Error occurred during validation of pushed authorization request.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n })\n }\n }\n\n const authorizationRequest = parsedAuthorizationRequest.data\n const { clientAttestation, dpop } = parseAuthorizationRequest({\n 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 { 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 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","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} from './client-attestation/z-client-attestation'\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 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/**\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/**\n * Client authentication using `attest_jwt_client_auth` option.\n */\nexport function clientAuthenticationClientAttestationJwt(\n options: ClientAuthenticationClientAttestationJwtOptions\n): ClientAuthenticationCallback {\n return async ({ headers, authorizationServerMetadata }) => {\n const clientAttestationPop = await createClientAttestationPopJwt({\n authorizationServer: authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestationJwt,\n\n // TODO: support client attestation nonce\n // We can fetch it before making the request if we don't have a nonce\n // https://www.ietf.org/archive/id/draft-ietf-oauth-attestation-based-client-auth-05.html\n // https://github.com/oauth-wg/draft-ietf-oauth-attestation-based-client-auth/issues/101\n // nonce:\n })\n\n headers.set(oauthClientAttestationHeader, options.clientAttestationJwt)\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop)\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 { 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 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 { zInteger } 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: zInteger,\n iat: zInteger,\n auth_time: zInteger.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: zInteger.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 '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 // From OpenID4VCI specification\n 'pre-authorized_grant_anonymous_access_supported': z.optional(z.boolean()),\n\n // Attestation Based Client Auth (draft 5)\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\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 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 // 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 {\n type AuthorizationCodeGrantIdentifier,\n authorizationCodeGrantIdentifier,\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 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/**\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 (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 { 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 { 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\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 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 || !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 access token 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 (\n options.expectedClientId &&\n options.expectedClientId !== verifiedClientAttestation.clientAttestation.payload.sub\n ) {\n // Ensure the client id matches with the client id from the session\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidClient,\n error_description: `The client id '${verifiedClientAttestation.clientAttestation.payload.sub}' in the client attestation does not match the client id for the authorization.`,\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 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 })\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 { 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 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 {\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 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 {\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 { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { authorizationServerRequestWithDpopRetry } from '../dpop/dpop-retry'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport {\n authorizationCodeGrantIdentifier,\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\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\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 // 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 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 })\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 accessTokenResponse: result.data,\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 RetrievePreAuthorizedCodeAccessTokenOptions,\n type RetrieveRefreshTokenAccessTokenOptions,\n retrieveAuthorizationCodeAccessToken,\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 { 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 ||\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,\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 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 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 { zInteger } 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(zInteger),\n iat: z.optional(zInteger),\n nbf: z.optional(zInteger),\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,0DAAL;AACL;AACA;AACA;;;;;;ACTF,IAAa,cAAb,cAAiC,MAAM;CAGrC,AAAO,YAAY,SAAkB,SAA8B;EACjE,MAAM,eAAe,WAAW;EAChC,MAAM,eACJ,SAAS,iBAAiB,QAAQ,IAAI,QAAQ,MAAM,YAAY,SAAS,QAAQ,IAAI,SAAS,UAAU;AAE1G,QAAM,GAAG,eAAe,eAAe;AACvC,OAAK,QAAQ,SAAS;;;;;;ACR1B,MAAa,2BAA2BA,IACrC,mBAAmB,OAAO;CACzBA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,KAAK;EACpB,KAAKA,IAAE,QAAQ;EACf,GAAGA,IAAE,QAAQ;EACb,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,MAAM;EACrB,KAAKA,IAAE,QAAQ;EACf,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,MAAM;EACrB,GAAGA,IAAE,QAAQ;EACb,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,O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;IACA,KAAK,QAAQ;IACb,uBAAuB,aAAa,KAAK;IACzC,oBAAoB,oBAAoB;IACzC,CAAC,EACuB,OAAO;WACzB,OAAO;GACd,MAAM,eAAe,iBAAiB,cAAc,MAAM,UAAU;AACpE,SAAM,IAAI,gCACR,mEAAmE,iBAAiB,QAAQ,MAAM,UAAU,SAC5G;IACE;IACA,OAAO,iBAAiB;IACxB,mBAAmB;IACpB,CACF;;;AAIL,QAAO;EACL;EACA,MAAM,UAAU,EAAE,KAAK,SAAS,GAAG;EACnC;EACA;EACA,qBAAqB,oBAAoB;EAC1C"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["z","z","z","z","ValidationError","z","formatZodError","OpenId4VcBaseError","ValidationError","OpenId4VcBaseError","formatZodError","InvalidFetchResponseError","ValidationError","z","z","z","z","z","z","z","z","z","z","InvalidFetchResponseError","ValidationError","z","authorizationServerMetadata","z","z","InvalidFetchResponseError","ValidationError","InvalidFetchResponseError","dpop","InvalidFetchResponseError","ValidationError","z","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.3.5/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/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/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/authorization-request/z-authorization-request.ts","../src/authorization-request/parse-pushed-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/z-grant-type.ts","../src/client-authentication.ts","../src/common/algorithm/algorithm-transform.ts","../src/error/Oauth2ClientErrorResponseError.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-request/verify-authorization-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/dpop/dpop-retry.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 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 * 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 if (payload.iss && header.kid?.startsWith('did:') && !header.kid.startsWith(payload.iss)) {\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> = 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 verifiying 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 // 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 // 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 { 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: { jarRequestParams: JarAuthorizationRequest }) {\n const { jarRequestParams } = 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 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, 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 iss: z.string(),\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\nexport const zClientAttestationPopJwtPayload = z\n .object({\n ...zJwtPayload.shape,\n iss: z.string(),\n exp: zNumericDate,\n aud: z.union([zHttpsUrl, z.array(zHttpsUrl)]),\n\n jti: 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 { addSecondsToDate, 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 * Dpop nonce to use for constructing the client attestation pop jwt\n */\n nonce?: string\n\n /**\n * Expiration time of the client attestation pop jwt.\n *\n * @default 5 minutes after issuance date\n */\n expiresAt?: Date\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 expiresAt: options.clientAttestation.expiresAt,\n signer: options.clientAttestation.signer,\n // TODO: support dynamic fetching of the nonce\n nonce: 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 * Expected nonce in the payload. If not provided the nonce won't be validated.\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 * 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 if (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 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 expectedNonce: options.expectedNonce,\n payload,\n expectedAudience: options.authorizationServer,\n compact: options.clientAttestationPopJwt,\n verifyJwtCallback: options.callbacks.verifyJwt,\n errorMessage: 'client attestation pop jwt verification failed',\n })\n\n return {\n header,\n payload,\n signer,\n }\n}\n\nexport interface CreateClientAttestationPopJwtOptions {\n /**\n * Client attestation Pop nonce value\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 * Expiration time of the JWT. If not proided 1 minute will be added to the `issuedAt`\n */\n expiresAt?: 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 const expiresAt = options.expiresAt ?? addSecondsToDate(options.issuedAt ?? new Date(), 1 * 60)\n\n const payload = parseWithErrorHandling(zClientAttestationPopJwtPayload, {\n aud: options.authorizationServer,\n iss: clientAttestation.payload.sub,\n iat: dateToSeconds(options.issuedAt),\n exp: dateToSeconds(expiresAt),\n jti: encodeToBase64Url(await options.callbacks.generateRandom(32)),\n nonce: 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 * 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 identifier of the client backend\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: 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 if (!clientAttestationHeader || !clientAttestationPopHeader) {\n return { valid: false }\n }\n\n if (\n !zCompactJwt.safeParse(clientAttestationHeader).success ||\n !zCompactJwt.safeParse(clientAttestationPopHeader).success\n ) {\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\nexport async function verifyClientAttestation({\n authorizationServer,\n clientAttestationJwt,\n clientAttestationPopJwt,\n callbacks,\n now,\n}: VerifyClientAttestationOptions) {\n try {\n const clientAttestation = await verifyClientAttestationJwt({\n callbacks,\n clientAttestationJwt,\n now,\n })\n\n const clientAttestationPop = await verifyClientAttestationPopJwt({\n callbacks: callbacks,\n authorizationServer,\n clientAttestation,\n clientAttestationPopJwt,\n now,\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 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 { 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, { type ZodSafeParseResult } 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 parsedAuthorizationRequest: ZodSafeParseResult<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 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 authorizationRequestJwt = parsedJar.authorizationRequestJwt\n } else {\n parsedAuthorizationRequest = zAuthorizationRequest.safeParse(options.authorizationRequest)\n if (!parsedAuthorizationRequest.success) {\n throw new Oauth2ServerErrorResponseError({\n error: Oauth2ErrorCodes.InvalidRequest,\n error_description: `Error occurred during validation of pushed authorization request.\\n${formatZodError(parsedAuthorizationRequest.error)}`,\n })\n }\n }\n\n const authorizationRequest = parsedAuthorizationRequest.data\n const { clientAttestation, dpop } = parseAuthorizationRequest({\n 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 { 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 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\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} from './client-attestation/z-client-attestation'\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 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/**\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/**\n * Client authentication using `attest_jwt_client_auth` option.\n */\nexport function clientAuthenticationClientAttestationJwt(\n options: ClientAuthenticationClientAttestationJwtOptions\n): ClientAuthenticationCallback {\n return async ({ headers, authorizationServerMetadata }) => {\n const clientAttestationPop = await createClientAttestationPopJwt({\n authorizationServer: authorizationServerMetadata.issuer,\n callbacks: options.callbacks,\n clientAttestation: options.clientAttestationJwt,\n\n // TODO: support client attestation nonce\n // We can fetch it before making the request if we don't have a nonce\n // https://www.ietf.org/archive/id/draft-ietf-oauth-attestation-based-client-auth-05.html\n // https://github.com/oauth-wg/draft-ietf-oauth-attestation-based-client-auth/issues/101\n // nonce:\n })\n\n headers.set(oauthClientAttestationHeader, options.clientAttestationJwt)\n headers.set(oauthClientAttestationPopHeader, clientAttestationPop)\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 { 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 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 '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 // From OpenID4VCI specification\n 'pre-authorized_grant_anonymous_access_supported': z.optional(z.boolean()),\n\n // Attestation Based Client Auth (draft 5)\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\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 {\n type AuthorizationCodeGrantIdentifier,\n authorizationCodeGrantIdentifier,\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 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/**\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 (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 { 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 { 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\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 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 || !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 access token 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 (\n options.expectedClientId &&\n options.expectedClientId !== verifiedClientAttestation.clientAttestation.payload.sub\n ) {\n // Ensure the client id matches with the client id from the session\n throw new Oauth2ServerErrorResponseError(\n {\n error: Oauth2ErrorCodes.InvalidClient,\n error_description: `The client id '${verifiedClientAttestation.clientAttestation.payload.sub}' in the client attestation does not match the client id for the authorization.`,\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 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 })\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 { 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 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 {\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 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 {\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 { createDpopHeadersForRequest, extractDpopNonceFromHeaders, type RequestDpopOptions } from '../dpop/dpop'\nimport { authorizationServerRequestWithDpopRetry } from '../dpop/dpop-retry'\nimport { Oauth2ClientErrorResponseError } from '../error/Oauth2ClientErrorResponseError'\nimport type { AuthorizationServerMetadata } from '../metadata/authorization-server/z-authorization-server-metadata'\nimport {\n authorizationCodeGrantIdentifier,\n clientCredentialsGrantIdentifier,\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\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 // 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 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 })\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 accessTokenResponse: result.data,\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 { 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 ||\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,\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 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,0DAAL;AACL;AACA;AACA;;;;;;ACTF,IAAa,cAAb,cAAiC,MAAM;CAGrC,AAAO,YAAY,SAAkB,SAA8B;EACjE,MAAM,eAAe,WAAW;EAChC,MAAM,eACJ,SAAS,iBAAiB,QAAQ,IAAI,QAAQ,MAAM,YAAY,SAAS,QAAQ,IAAI,SAAS,UAAU;AAE1G,QAAM,GAAG,eAAe,eAAe;AACvC,OAAK,QAAQ,SAAS;;;;;;ACR1B,MAAa,2BAA2BA,IACrC,mBAAmB,OAAO;CACzBA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,KAAK;EACpB,KAAKA,IAAE,QAAQ;EACf,GAAGA,IAAE,QAAQ;EACb,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,MAAM;EACrB,KAAKA,IAAE,QAAQ;EACf,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,MAAM;EACrB,GAAGA,IAAE,QAAQ;EACb,GAAGA,IAAE,QAAQ;EACd,CAAC;CACFA,IAAE,OAAO;EACP,KAAKA,IAAE,QAAQ,MAAM;EACrB,GAAGA,IAAE,QAAQ;EACd,CAAC;CACH,C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