@sphereon/oid4vci-common 0.20.2-next.2 → 0.20.2-next.21
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.cjs +105 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +273 -11
- package/dist/index.d.ts +273 -11
- package/dist/index.js +103 -9
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_@swc+core@1.14.0_postcss@8.5.6_tsx@4.20.6_typescript@5.8.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js","../lib/functions/randomBytes.cjs","../lib/index.ts","../lib/functions/index.ts","../lib/functions/CredentialRequestUtil.ts","../lib/functions/CredentialResponseUtil.ts","../lib/functions/HttpUtils.ts","../lib/types/index.ts","../lib/types/OpenIDClient.ts","../lib/types/Authorization.types.ts","../lib/types/Generic.types.ts","../lib/types/CredentialIssuance.types.ts","../lib/types/v1_0_15.types.ts","../lib/types/ServerMetadata.ts","../lib/types/OpenID4VCIErrors.ts","../lib/types/OpenID4VCIVersions.types.ts","../lib/types/StateManager.types.ts","../lib/types/Token.types.ts","../lib/types/QRCode.types.ts","../lib/functions/CredentialOfferUtil.ts","../lib/functions/Encoding.ts","../lib/functions/TypeConversionUtils.ts","../lib/functions/IssuerMetadataUtils.ts","../lib/functions/FormatUtils.ts","../lib/functions/ProofUtil.ts","../lib/functions/AuthorizationResponseUtil.ts","../lib/functions/RandomUtils.ts","../lib/experimental/holder-vci.ts","../lib/events/index.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nconst MAX_BYTES = 65536\n\n// Node supports requesting up to this number of bytes\n// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48\nconst MAX_UINT32 = 4294967295\n\nfunction oldBrowser() {\n throw new Error('Secure random number generation is not supported by this browser.\\nUse Chrome, Firefox or Internet Explorer 11')\n}\n\n// eslint-disable-next-line no-undef\nconst _global = typeof globalThis !== 'undefined' ? globalThis : global\n\nlet crypto = _global.crypto || _global.msCrypto\nif (!crypto) {\n try {\n // eslint-disable-next-line no-undef\n crypto = require('crypto')\n } catch (err) {\n throw Error('crypto module is not available')\n }\n}\n\nfunction randomBytes(size) {\n // phantomjs needs to throw\n if (size > MAX_UINT32) throw new Error('requested too many random bytes')\n\n // eslint-disable-next-line no-undef\n const bytes = Buffer.allocUnsafe(size)\n\n if (size > 0) {\n // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) {\n // this is the max bytes crypto.getRandomValues\n // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues\n for (let generated = 0; generated < size; generated += MAX_BYTES) {\n // buffer.slice automatically checks if the end is past the end of\n // the buffer so we don't have to here\n crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n return Uint8Array.from(bytes)\n}\n\n// eslint-disable-next-line no-undef\nmodule.exports = randomBytes\n","import { Loggers } from '@sphereon/ssi-types'\n\nexport const VCI_LOGGERS = Loggers.DEFAULT\nexport const VCI_LOG_COMMON = VCI_LOGGERS.get('sphereon:oid4vci:common')\n\nexport * from './functions'\nexport * from './types'\nexport * from './experimental/holder-vci'\nexport * from './events'\n","export * from './CredentialRequestUtil'\nexport * from './CredentialResponseUtil'\nexport * from './CredentialOfferUtil'\nexport * from './Encoding'\nexport * from './TypeConversionUtils'\nexport * from './IssuerMetadataUtils'\nexport * from './FormatUtils'\nexport * from './HttpUtils'\nexport * from './ProofUtil'\nexport * from './AuthorizationResponseUtil'\nexport * from './RandomUtils'\n","//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","import { CredentialResponse, OpenIDResponse } from '../types'\n\nimport { post } from './HttpUtils'\n\nexport function isDeferredCredentialResponse(credentialResponse: OpenIDResponse<CredentialResponse>) {\n const orig = credentialResponse.successBody\n // Specs mention 202, but some implementations like EBSI return 200\n return credentialResponse.origResponse.status % 200 <= 2 && !!orig && !orig.credentials && (!!orig.acceptance_token || !!orig.transaction_id)\n}\nfunction assertNonFatalError(credentialResponse: OpenIDResponse<CredentialResponse>) {\n if (credentialResponse.origResponse.status === 400 && credentialResponse.errorBody?.error) {\n if (credentialResponse.errorBody.error === 'invalid_transaction_id' || credentialResponse.errorBody.error.includes('acceptance_token')) {\n throw Error('Invalid transaction id. Probably the deferred credential request expired')\n }\n }\n}\n\nexport function isDeferredCredentialIssuancePending(credentialResponse: OpenIDResponse<CredentialResponse>) {\n if (isDeferredCredentialResponse(credentialResponse)) {\n return credentialResponse?.successBody?.transaction_id ?? !!credentialResponse?.successBody?.acceptance_token\n }\n if (credentialResponse.origResponse.status === 400 && credentialResponse.errorBody?.error) {\n if (credentialResponse.errorBody.error === 'issuance_pending') {\n return true\n } else if (credentialResponse.errorBody.error_description?.toLowerCase().includes('not available yet')) {\n return true\n }\n }\n return false\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\nexport async function acquireDeferredCredential({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n deferredCredentialIntervalInMS,\n deferredCredentialAwait,\n}: {\n bearerToken: string\n transactionId?: string\n deferredCredentialIntervalInMS?: number\n deferredCredentialAwait?: boolean\n deferredCredentialEndpoint: string\n}): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n let credentialResponse: OpenIDResponse<CredentialResponse> & { access_token: string } = await acquireDeferredCredentialImpl({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n })\n\n const DEFAULT_SLEEP_IN_MS = 5000\n while (!credentialResponse.successBody?.credentials && deferredCredentialAwait) {\n assertNonFatalError(credentialResponse)\n const pending = isDeferredCredentialIssuancePending(credentialResponse)\n console.log(`Issuance still pending?: ${pending}`)\n if (!pending) {\n return Promise.reject(Error(`Issuance isn't pending anymore: ${credentialResponse}`))\n }\n\n await sleep(deferredCredentialIntervalInMS ?? DEFAULT_SLEEP_IN_MS)\n credentialResponse = await acquireDeferredCredentialImpl({ bearerToken, transactionId, deferredCredentialEndpoint })\n }\n return credentialResponse\n}\n\nasync function acquireDeferredCredentialImpl({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n}: {\n bearerToken: string\n transactionId?: string\n deferredCredentialEndpoint: string\n}): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n const response: OpenIDResponse<CredentialResponse> = await post(\n deferredCredentialEndpoint,\n JSON.stringify(transactionId ? { transaction_id: transactionId } : ''),\n { bearerToken },\n )\n console.log(JSON.stringify(response, null, 2))\n assertNonFatalError(response)\n\n return { ...response, access_token: bearerToken }\n}\n","import { Loggers } from '@sphereon/ssi-types'\nimport fetch from 'cross-fetch'\n\nimport { Encoding, OpenIDResponse } from '../types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:openid4vci:http')\n\nexport const getJson = async <T>(\n URL: string,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await openIdFetch(URL, undefined, { method: 'GET', ...opts })\n}\n\nexport const formPost = async <T>(\n url: string,\n body: BodyInit,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await post(url, body, opts?.contentType ? { ...opts } : { contentType: Encoding.FORM_URL_ENCODED, ...opts })\n}\n\nexport const post = async <T>(\n url: string,\n body?: BodyInit,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await openIdFetch(url, body, { method: 'POST', ...opts })\n}\n\nconst openIdFetch = async <T>(\n url: string,\n body?: BodyInit,\n opts?: {\n method?: string\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n const headers: Record<string, string> = opts?.customHeaders ?? {}\n if (opts?.bearerToken) {\n headers['Authorization'] =\n `${headers.dpop ? 'DPoP' : 'Bearer'} ${typeof opts.bearerToken === 'function' ? await opts.bearerToken() : opts.bearerToken}`\n }\n const method = opts?.method ? opts.method : body ? 'POST' : 'GET'\n const accept = opts?.accept ? opts.accept : 'application/json'\n headers['Accept'] = accept\n if (headers['Content-Type']) {\n if (opts?.contentType && opts.contentType !== headers['Content-Type']) {\n throw Error(`Mismatch in content-types from custom headers (${headers['Content-Type']}) and supplied content type option (${opts.contentType})`)\n }\n } else {\n if (opts?.contentType) {\n headers['Content-Type'] = opts.contentType\n } else if (method !== 'GET') {\n headers['Content-Type'] = 'application/json'\n }\n }\n\n const payload: RequestInit = {\n method,\n headers,\n body,\n }\n\n logger.debug(`START fetching url: ${url}`)\n if (body) {\n logger.debug(`Body:\\r\\n${typeof body == 'string' ? body : JSON.stringify(body)}`)\n }\n logger.debug(`Headers:\\r\\n${JSON.stringify(payload.headers)}`)\n const origResponse = await fetch(url, payload)\n const isJSONResponse = accept === 'application/json' || origResponse.headers.get('Content-Type') === 'application/json'\n const success = origResponse && origResponse.status >= 200 && origResponse.status < 400\n const responseText = await origResponse.text()\n const responseBody = isJSONResponse && responseText.includes('{') ? JSON.parse(responseText) : responseText\n\n logger.debug(`${success ? 'success' : 'error'} status: ${origResponse.status}, body:\\r\\n${JSON.stringify(responseBody)}`)\n if (!success && opts?.exceptionOnHttpErrorStatus) {\n const error = JSON.stringify(responseBody)\n throw new Error(error === '{}' ? '{\"error\": \"not found\"}' : error)\n }\n logger.debug(`END fetching url: ${url}`)\n\n return {\n origResponse,\n successBody: success ? responseBody : undefined,\n errorBody: !success ? responseBody : undefined,\n }\n}\n\nexport const isValidURL = (url: string): boolean => {\n const urlPattern = new RegExp(\n '^(https?:\\\\/\\\\/)' + // validate protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // validate domain name\n '((localhost))|' + // validate OR localhost\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // validate OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+:]*)*' + // validate port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // validate query string\n '(\\\\#[-a-z\\\\d_]*)?$', // validate fragment locator\n 'i',\n )\n return urlPattern.test(url)\n}\n\nexport const trimBoth = (value: string, trim: string): string => {\n return trimEnd(trimStart(value, trim), trim)\n}\n\nexport const trimEnd = (value: string, trim: string): string => {\n return value.endsWith(trim) ? value.substring(0, value.length - trim.length) : value\n}\n\nexport const trimStart = (value: string, trim: string): string => {\n return value.startsWith(trim) ? value.substring(trim.length) : value\n}\n\nexport const adjustUrl = <T extends string | URL>(\n urlOrPath: T,\n opts?: {\n stripSlashEnd?: boolean\n stripSlashStart?: boolean\n prepend?: string\n append?: string\n },\n): T => {\n let url = typeof urlOrPath === 'object' ? urlOrPath.toString() : (urlOrPath as string)\n if (opts?.append) {\n url = trimEnd(url, '/') + '/' + trimStart(opts.append, '/')\n }\n if (opts?.prepend) {\n if (opts.prepend.includes('://')) {\n // includes domain/hostname\n if (!url.startsWith(opts.prepend)) {\n url = trimEnd(opts.prepend, '/') + '/' + trimStart(url, '/')\n }\n } else {\n // path only for prepend\n let host = ''\n let path = url\n if (url.includes('://')) {\n // includes domain/hostname\n host = new URL(url).host\n path = new URL(url).pathname\n }\n if (!path.startsWith(opts.prepend)) {\n if (host && host !== '') {\n url = trimEnd(host, '/')\n }\n url += trimEnd(url, '/') + '/' + trimBoth(opts.prepend, '/') + '/' + trimStart(path, '/')\n }\n }\n }\n if (opts?.stripSlashStart) {\n url = trimStart(url, '/')\n }\n if (opts?.stripSlashEnd) {\n url = trimEnd(url, '/')\n }\n\n if (typeof urlOrPath === 'string') {\n return url as T\n }\n return new URL(url) as T\n}\n","export * from './OpenIDClient'\nexport * from './Authorization.types'\nexport * from './CredentialIssuance.types'\nexport * from './Generic.types'\nexport * from './v1_0_15.types'\nexport * from './ServerMetadata'\nexport * from './OpenID4VCIErrors'\nexport * from './OpenID4VCIVersions.types'\nexport * from './StateManager.types'\nexport * from './Token.types'\nexport * from './QRCode.types'\n","/**\n * Copied from openid-client\n */\nexport type ClientResponseType = 'code' | 'id_token' | 'code id_token' | 'none' | string\nexport type ClientAuthMethod =\n | 'client_secret_basic'\n | 'client_secret_post'\n | 'client_secret_jwt'\n | 'private_key_jwt'\n | 'tls_client_auth'\n | 'self_signed_tls_client_auth'\n | 'none'\nexport interface ClientMetadata {\n // important\n client_id: string\n id_token_signed_response_alg?: string\n token_endpoint_auth_method?: ClientAuthMethod\n client_secret?: string\n redirect_uris?: string[]\n response_types?: ClientResponseType[]\n post_logout_redirect_uris?: string[]\n default_max_age?: number\n require_auth_time?: boolean\n tls_client_certificate_bound_access_tokens?: boolean\n request_object_signing_alg?: string\n\n // less important\n id_token_encrypted_response_alg?: string\n id_token_encrypted_response_enc?: string\n introspection_endpoint_auth_method?: ClientAuthMethod\n introspection_endpoint_auth_signing_alg?: string\n request_object_encryption_alg?: string\n request_object_encryption_enc?: string\n revocation_endpoint_auth_method?: ClientAuthMethod\n revocation_endpoint_auth_signing_alg?: string\n token_endpoint_auth_signing_alg?: string\n userinfo_encrypted_response_alg?: string\n userinfo_encrypted_response_enc?: string\n userinfo_signed_response_alg?: string\n authorization_encrypted_response_alg?: string\n authorization_encrypted_response_enc?: string\n authorization_signed_response_alg?: string\n\n [key: string]: unknown\n}\n","import { CreateDPoPClientOpts } from '@sphereon/oid4vc-common'\n\nimport { Alg, CredentialOfferPayload, ProofOfPossessionCallbacks, UniformCredentialOffer } from './CredentialIssuance.types'\nimport {\n ErrorResponse,\n IssuerCredentialSubject,\n JsonLdIssuerCredentialDefinition,\n OID4VCICredentialFormat,\n PRE_AUTH_CODE_LITERAL,\n TxCode,\n} from './Generic.types'\nimport { EndpointMetadata } from './ServerMetadata'\nimport { AuthorizationDetailsV1_0_15 } from './v1_0_15.types'\n\nexport interface CommonAuthorizationRequest {\n /**\n * REQUIRED. Value MUST be set to \"code\". for Authorization Code Grant\n */\n response_type: ResponseType.AUTH_CODE\n /**\n * The authorization server issues the registered client a client\n * identifier -- a unique string representing the registration\n * information provided by the client.\n */\n client_id: string\n /**\n * If the \"code_challenge_method\" from Section 4.3 was \"S256\", the\n * received \"code_verifier\" is hashed by SHA-256, base64url-encoded, and\n * then compared to the \"code_challenge\", i.e.:\n * BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge\n *\n * If the \"code_challenge_method\" from Section 4.3 was \"plain\", they are\n * compared directly, i.e.:\n * code_verifier == code_challenge.\n */\n code_challenge: string\n /**\n * value must be set either to \"S256\" or a value defined by a cryptographically secure\n */\n code_challenge_method: CodeChallengeMethod\n /**\n * The redirection endpoint URI MUST be an absolute URI as defined by: absolute-URI = scheme \":\" hier-part [ \"?\" query ]\n */\n redirect_uri: string\n /**\n * The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings.\n */\n scope?: string\n /**\n * There are two possible ways to request issuance of a specific Credential type in an Authorization Request.\n * One way is to use of the authorization_details request parameter as defined in [I-D.ietf-oauth-rar]\n * with one or more authorization details objects of type openid_credential Section 5.1.1.\n * (The other is through the use of scopes as defined in Section 5.1.2.)\n */\n authorization_details?: AuthorizationDetailsV1_0_15[] | AuthorizationDetailsV1_0_15\n /**\n * OPTIONAL. JSON string containing the Wallet's OpenID Connect issuer URL. The Credential Issuer will use the discovery process as defined in\n * [SIOPv2] to determine the Wallet's capabilities and endpoints. RECOMMENDED in Dynamic Credential Request.\n */\n wallet_issuer?: string\n /**\n * OPTIONAL. JSON string containing an opaque user hint the Wallet MAY use in subsequent callbacks to optimize the user's experience.\n * RECOMMENDED in Dynamic Credential Request.\n */\n user_hint?: string\n /**\n * OPTIONAL. String value identifying a certain processing context at the Credential Issuer. A value for this parameter is typically passed in\n * an issuance initation request from the Credential Issuer to the Wallet (see (Section 4.1). This request parameter is used to pass the\n * issuer_state value back to the Credential Issuer.\n */\n issuer_state?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-req\nexport interface CommonAuthorizationChallengeRequest {\n /**\n * REQUIRED if the client is not authenticating with the authorization server and if no auth_session is included..\n */\n client_id?: string\n /**\n * OPTIONAL. String value identifying a certain processing context at the Credential Issuer. A value for this parameter is typically passed in\n * an issuance initation request from the Credential Issuer to the Wallet. This request parameter is used to pass the\n * issuer_state value back to the Credential Issuer.\n */\n issuer_state?: string\n /**\n * The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings.\n */\n scope?: string // TODO what we do with this\n /**\n * OPTIONAL. A random string or a JWE. The auth session allows the authorization server to associate subsequent\n * requests by this client with an ongoing authorization request sequence. The client MUST include the\n * auth_session in follow-up requests to the authorization challenge endpoint if it receives one along with\n * the error response.\n */\n auth_session?: string\n /**\n * OPTIONAL. If the \"code_challenge_method\" from Section 4.3 was \"S256\", the\n * received \"code_verifier\" is hashed by SHA-256, base64url-encoded, and\n * then compared to the \"code_challenge\", i.e.:\n * BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge\n *\n * If the \"code_challenge_method\" from Section 4.3 was \"plain\", they are\n * compared directly, i.e.:\n * code_verifier == code_challenge.\n */\n code_challenge?: string // TODO what we do with this\n /**\n * OPTIONAL. value must be set either to \"S256\" or a value defined by a cryptographically secure\n */\n code_challenge_method?: CodeChallengeMethod // TODO what we do with this\n /**\n * OPTIONAL. String containing information about the session when credential presentation is happening during issuance of another\n * credential. The content of this parameter is opaque to the wallet. When this parameter is present the Wallet MUST use this parameter in\n * the subsequent Authorization Challenge Request. This allows the Issuer to determine which it can be used by to prevent session\n * fixation attacks. The Response URI MAY return this parameter in response to successful Authorization Responses or for Error\n * Responses.\n */\n presentation_during_issuance_session?: string\n}\n\nexport interface AuthorizationChallengeRequestOpts {\n clientId?: string\n issuerState?: string\n authSession?: string\n scope?: string\n codeChallenge?: string\n codeChallengeMethod?: CodeChallengeMethod\n presentationDuringIssuanceSession?: string\n metadata?: EndpointMetadata\n credentialIssuer?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-error-response\nexport interface AuthorizationChallengeErrorResponse {\n /**\n * A single ASCII error code of type AuthorizationChallengeError.\n */\n error: AuthorizationChallengeError\n /**\n * OPTIONAL. OPTIONAL. Human-readable ASCII text providing additional information, used\n * to assist the client developer in understanding the error that occurred. Values for the error_description\n * parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E.\n */\n error_description?: string\n /**\n * OPTIONAL. A URI identifying a human-readable web page with information about the error, used\n * to provide the client developer with additional information about the error. Values for the error_uri\n * parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the\n * set %x21 / %x23-5B / %x5D-7E.\n */\n error_uri?: string\n /**\n * OPTIONAL. A random string or a JWE. The auth session allows the authorization server to associate subsequent\n * requests by this client with an ongoing authorization request sequence. The client MUST include the\n * auth_session in follow-up requests to the authorization challenge endpoint if it receives one along with\n * the error response.\n */\n auth_session?: string\n /**\n * OPTIONAL. The request URI corresponding to the authorization request posted. This URI is a single-use reference\n * to the respective request data in the subsequent authorization request.\n */\n request_uri?: string\n /**\n * OPTIONAL. A JSON number that represents the lifetime of the request URI in seconds as a positive integer.\n */\n expires_in?: number\n /**\n * String containing the OID4VP request URI. The Wallet will use this URI to start the OID4VP flow.\n */\n presentation?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-res\nexport interface AuthorizationChallengeCodeResponse {\n /**\n * The authorization code issued by the authorization server.\n */\n authorization_code: string\n state?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-error-response\nexport enum AuthorizationChallengeError {\n invalid_request = 'invalid_request',\n invalid_client = 'invalid_client',\n unauthorized_client = 'unauthorized_client',\n invalid_session = 'invalid_session',\n invalid_scope = 'invalid_scope',\n insufficient_authorization = 'insufficient_authorization',\n redirect_to_web = 'redirect_to_web',\n}\n\n/**\n * string type added for conformity with our previous code in the client\n */\nexport type credential_identifiers =\n | (CommonAuthorizationDetails &\n (AuthorizationDetailsJwtVcJson | AuthorizationDetailsJwtVcJsonLdAndLdpVc | AuthorizationDetailsSdJwtVc | AuthorizationDetailsMsoMdoc))\n | string\n\nexport type AuthorizationRequest =\n | AuthorizationRequestJwtVcJson\n | AuthorizationRequestJwtVcJsonLdAndLdpVc\n | AuthorizationRequestSdJwtVc\n | AuthorizationRequestMsoMdoc\n\nexport interface AuthorizationRequestJwtVcJson extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsJwtVcJson[]\n}\n\nexport interface AuthorizationRequestJwtVcJsonLdAndLdpVc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsJwtVcJsonLdAndLdpVc[]\n}\n\nexport interface AuthorizationRequestSdJwtVc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsSdJwtVc[]\n}\n\nexport interface AuthorizationRequestMsoMdoc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsMsoMdoc[]\n}\n\n/*\nexport interface AuthDetails {\n type: 'openid_credential' | string;\n locations?: string | string[];\n format: CredentialFormat | CredentialFormat[];\n\n [s: string]: unknown;\n}\n*/\n\nexport interface CommonAuthorizationDetails {\n /**\n * REQUIRED. JSON string that determines the authorization details type.\n * MUST be set to openid_credential for the purpose of this specification.\n */\n type: 'openid_credential'\n\n /**\n * REQUIRED when format parameter is not present. String specifying a unique identifier of the Credential being described in the credential_configurations_supported map in the Credential Issuer Metadata as defined in Section 11.2.3. The referenced object in the credential_configurations_supported map conveys the details, such as the format, for issuance of the requested Credential. This specification defines Credential Format specific Issuer Metadata in Appendix A. It MUST NOT be present if format parameter is present.\n */\n credential_configuration_id?: string // FIXME maybe split up and make this & format required again\n\n /**\n * REQUIRED. JSON string representing the format in which the Credential is requested to be issued.\n * This Credential format identifier determines further claims in the authorization details object\n * specifically used to identify the Credential type to be issued. This specification defines\n * Credential Format Profiles in Appendix E.\n */\n format?: OID4VCICredentialFormat\n /**\n * If the Credential Issuer metadata contains an authorization_server parameter,\n * the authorization detail's locations common data field MUST be set to the Credential Issuer Identifier value.\n */\n locations?: string[]\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport interface AuthorizationDetailsJwtVcJson extends CommonAuthorizationDetails {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc added for backward compat\n\n /**\n * A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential.\n * The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the\n * verifiable credential to be issued. This object indicates the claims the Wallet would like to turn up in the\n * credential to be issued.\n */\n credentialSubject?: IssuerCredentialSubject\n\n types: string[] // This claim contains the type values the Wallet requests authorization for at the issuer.\n}\n\nexport interface AuthorizationDetailsJwtVcJsonLdAndLdpVc extends CommonAuthorizationDetails {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n\n /**\n * REQUIRED. JSON object containing (and isolating) the detailed description of the credential type.\n * This object MUST be processed using full JSON-LD processing. It consists of the following sub-claims:\n * - @context: REQUIRED. JSON array as defined in Appendix E.1.3.2\n * - types: REQUIRED. JSON array as defined in Appendix E.1.3.2.\n * This claim contains the type values the Wallet shall request in the subsequent Credential Request\n */\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface AuthorizationDetailsSdJwtVc extends CommonAuthorizationDetails {\n format: 'dc+sd-jwt' | 'vc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface AuthorizationDetailsMsoMdoc extends CommonAuthorizationDetails {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport enum GrantTypes {\n AUTHORIZATION_CODE = 'authorization_code',\n PRE_AUTHORIZED_CODE = 'urn:ietf:params:oauth:grant-type:pre-authorized_code',\n PASSWORD = 'password',\n}\n\nexport enum Encoding {\n FORM_URL_ENCODED = 'application/x-www-form-urlencoded',\n UTF_8 = 'UTF-8',\n}\n\nexport enum ResponseType {\n AUTH_CODE = 'code',\n}\n\nexport enum CodeChallengeMethod {\n plain = 'plain',\n S256 = 'S256',\n}\n\nexport interface AuthorizationServerOpts {\n allowInsecureEndpoints?: boolean\n as?: string // If not provided the issuer hostname will be used!\n tokenEndpoint?: string // Allows to override the default '/token' endpoint\n clientOpts?: AuthorizationServerClientOpts\n}\n\nexport type AuthorizationServerClientOpts = {\n clientId: string\n clientAssertionType?: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n kid?: string\n alg?: Alg\n signCallbacks?: ProofOfPossessionCallbacks\n}\n\nexport interface IssuerOpts {\n issuer: string\n tokenEndpoint?: string\n fetchMetadata?: boolean\n}\n\nexport interface AccessTokenFromAuthorizationResponseOpts extends AccessTokenRequestOpts {\n authorizationResponse: AuthorizationResponse\n}\n\nexport type TxCodeAndPinRequired = { isPinRequired?: boolean; txCode?: TxCode }\n\nexport interface AccessTokenRequestOpts {\n credentialOffer?: UniformCredentialOffer\n credentialIssuer?: string\n asOpts?: AuthorizationServerOpts\n metadata?: EndpointMetadata\n codeVerifier?: string // only required for authorization flow\n code?: string // only required for authorization flow\n redirectUri?: string // only required for authorization flow\n pin?: string // Pin-number. Only used when required\n pinMetadata?: TxCodeAndPinRequired // OPTIONAL. String value containing a Transaction Code. This value MUST be present if a tx_code object was present in the Credential Offer (including if the object was empty). This parameter MUST only be used if the grant_type is urn:ietf:params:oauth:grant-type:pre-authorized_code.\n // if the CreateDPoPOpts are provided, a dPoP will be created using the provided callback,\n // if the authorization server indicates that it supports dPoP via the dpop_signing_alg_values_supported parameter.\n createDPoPOpts?: CreateDPoPClientOpts\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalParams?: Record<string, any>\n}\n\n/*export interface AuthorizationRequestOpts {\n clientId: string;\n codeChallenge: string;\n codeChallengeMethod: CodeChallengeMethod;\n authorizationDetails?: AuthorizationDetails[];\n redirectUri: string;\n scope?: string;\n}*/\n\n/**\n * Determinse whether PAR should be used when supported\n *\n * REQUIRE: Require PAR, if AS does not support it throw an error\n * AUTO: Use PAR is the AS supports it, otherwise construct a reqular URI,\n * NEVER: Do not use PAR even if the AS supports it (not recommended)\n */\nexport enum PARMode {\n REQUIRE,\n AUTO,\n NEVER,\n}\n\n/**\n * Optional options to provide PKCE params like code verifier and challenge yourself, or to disable PKCE altogether. If not provide PKCE will still be used! If individual params are not provide, they will be generated/calculated\n */\nexport interface PKCEOpts {\n /**\n * PKCE is enabled by default even if you do not provide these options. Set this to true to disable PKCE\n */\n disabled?: boolean\n\n /**\n * Provide a code_challenge, otherwise it will be calculated using the code_verifier and method\n */\n codeChallenge?: string\n\n /**\n * The code_challenge_method, should always by S256\n */\n codeChallengeMethod?: CodeChallengeMethod\n\n /**\n * Provide a code_verifier, otherwise it will be generated\n */\n codeVerifier?: string\n}\n\nexport enum CreateRequestObjectMode {\n NONE,\n REQUEST_OBJECT,\n REQUEST_URI,\n}\n\nexport type RequestObjectOpts = {\n requestObjectMode?: CreateRequestObjectMode\n signCallbacks?: ProofOfPossessionCallbacks\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clientMetadata?: Record<string, any> // TODO: Merge SIOP/OID4VP\n iss?: string\n jwksUri?: string\n kid?: string\n}\n\nexport interface AuthorizationRequestOpts {\n clientId?: string\n pkce?: PKCEOpts\n parMode?: PARMode\n authorizationDetails?: AuthorizationDetailsV1_0_15 | AuthorizationDetailsV1_0_15[]\n redirectUri?: string\n scope?: string\n requestObjectOpts?: RequestObjectOpts\n holderPreferredAuthzFlowTypeOrder?: AuthzFlowType[]\n}\n\nexport interface AuthorizationResponse {\n code: string\n scope?: string\n state?: string\n}\n\nexport interface AuthorizationGrantResponse extends AuthorizationResponse {\n grant_type: string\n}\n\nexport interface AccessTokenRequest {\n client_id?: string\n code?: string\n code_verifier?: string\n grant_type: GrantTypes\n 'pre-authorized_code': string\n redirect_uri?: string\n scope?: string\n user_pin?: string //this is for v11, not required in v13 anymore\n tx_code?: string //draft 13\n [s: string]: unknown\n}\n\nexport interface OpenIDResponse<T, P = never> {\n origResponse: Response\n successBody?: T\n errorBody?: ErrorResponse\n params?: P\n}\n\nexport interface DPoPResponseParams {\n dpop?: { dpopNonce: string }\n}\n\nexport interface AccessTokenResponse {\n access_token: string\n scope?: string\n token_type?: string\n expires_in?: number // in seconds\n c_nonce?: string\n c_nonce_expires_in?: number // in seconds\n authorization_pending?: boolean\n interval?: number // in seconds\n authorization_details?: AuthorizationDetailsV1_0_15[]\n}\n\nexport enum AuthzFlowType {\n AUTHORIZATION_CODE_FLOW = 'Authorization Code Flow',\n PRE_AUTHORIZED_CODE_FLOW = 'Pre-Authorized Code Flow',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace AuthzFlowType {\n export function valueOf(request: CredentialOfferPayload): AuthzFlowType {\n if (PRE_AUTH_CODE_LITERAL in request) {\n return AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW\n }\n return AuthzFlowType.AUTHORIZATION_CODE_FLOW\n }\n}\n\nexport interface PushedAuthorizationResponse {\n request_uri: string\n expires_in: number\n}\n","import { ICredentialContextType, IVerifiableCredential, W3CVerifiableCredential } from '@sphereon/ssi-types'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { ProofOfPossession } from './CredentialIssuance.types'\nimport { AuthorizationServerMetadata } from './ServerMetadata'\nimport { CredentialOfferSession } from './StateManager.types'\nimport {\n CredentialConfigurationSupportedV1_0_15,\n CredentialRequestV1_0_15,\n EndpointMetadataResultV1_0_15,\n IssuerMetadataV1_0_15,\n} from './v1_0_15.types'\n\nexport type InputCharSet = 'numeric' | 'text'\nexport type KeyProofType = 'jwt' | 'cwt' | 'ldp_vp'\n\nexport type PoPMode = 'pop' | 'JWT' // Proof of possession, or regular JWT\n\nexport type CredentialOfferMode = 'VALUE' | 'REFERENCE'\n\n/**\n * Important Note: please be aware that these Common interfaces are based on versions v1_0.11 and v1_0.09\n */\nexport interface ImageInfo {\n uri?: string\n alt_text?: string\n\n [key: string]: unknown\n}\n\nexport type OID4VCICredentialFormat = 'jwt_vc_json' | 'jwt_vc_json-ld' | 'ldp_vc' | 'dc+sd-jwt' | 'vc+sd-jwt' | 'jwt_vc' | 'mso_mdoc' // jwt_vc & vc+sd-jwt are added for backwards compat TODO SSISDK-36\n\nexport const supportedOID4VCICredentialFormat: readonly (OID4VCICredentialFormat | string)[] = [\n 'jwt_vc_json',\n 'jwt_vc_json-ld',\n 'ldp_vc',\n 'dc+sd-jwt',\n 'jwt_vc',\n 'mso_mdoc',\n]\n\nexport interface NameAndLocale {\n name?: string // REQUIRED. String value of a display name for the Credential.\n locale?: string // OPTIONAL. String value that identifies the language of this object represented as a language tag taken from values defined in BCP47 [RFC5646]. Multiple display objects MAY be included for separate languages. There MUST be only one object with the same language identifier.\n [key: string]: unknown\n}\n\nexport interface LogoAndColor {\n logo?: ImageInfo // OPTIONAL. A JSON object with information about the logo of the Credential with a following non-exhaustive list of parameters that MAY be included:\n description?: string // OPTIONAL. String value of a description of the Credential.\n background_color?: string //OPTIONAL. String value of a background color of the Credential represented as numerical color values defined in CSS Color Module Level 37 [CSS-Color].\n text_color?: string // OPTIONAL. String value of a text color of the Credential represented as numerical color values defined in CSS Color Module Level 37 [CSS-Color].\n}\n\nexport type CredentialsSupportedDisplay = NameAndLocale &\n LogoAndColor & {\n name: string // REQUIRED. String value of a display name for the Credential.\n background_image?: ImageInfo //OPTIONAL, NON-SPEC compliant!. URL of a background image useful for card views of credentials. Expected to an image that fills the full card-view of a wallet\n }\n\nexport type MetadataDisplay = NameAndLocale &\n LogoAndColor & {\n name?: string //OPTIONAL. String value of a display name for the Credential Issuer.\n }\n\nexport interface CredentialSupplierConfig {\n [key: string]: any // This allows additional properties for credential suppliers\n}\n\nexport interface CredentialIssuerMetadataOpts {\n credential_endpoint?: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n batch_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Batch Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. If omitted, the Credential Issuer does not support the Batch Credential Endpoint.\n credentials_supported: CredentialsSupportedLegacy[] // REQUIRED in versions below 13. A JSON array containing a list of JSON objects, each of them representing metadata about a separate credential type that the Credential Issuer can issue. The JSON objects in the array MUST conform to the structure of the Section 10.2.3.1.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n authorization_server?: string // OPTIONAL. Identifier of the OAuth 2.0 Authorization Server (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n token_endpoint?: string\n notification_endpoint?: string\n authorization_challenge_endpoint?: string // OPTIONAL URL of the Credential Issuer's Authorization Challenge Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. Described on https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-end\n display?: MetadataDisplay[] // An array of objects, where each object contains display properties of a Credential Issuer for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n credential_supplier_config?: CredentialSupplierConfig\n}\n\n//todo: investigate if these values are enough.\nexport type AlgValue = 'RS256' | 'ES256' | 'PS256' | 'HS256' | string\nexport type EncValue = 'A128GCM' | 'A256GCM' | 'A128CBC-HS256' | 'A256CBC-HS512' | string\n\nexport interface ResponseEncryption {\n /**\n * REQUIRED. Array containing a list of the JWE [RFC7516] encryption algorithms\n * (alg values) [RFC7518] supported by the Credential and Batch Credential Endpoint to encode the\n * Credential or Batch Credential Response in a JWT\n */\n alg_values_supported: AlgValue[]\n\n /**\n * REQUIRED. Array containing a list of the JWE [RFC7516] encryption algorithms\n * (enc values) [RFC7518] supported by the Credential and Batch Credential Endpoint to encode the\n * Credential or Batch Credential Response in a JWT\n */\n enc_values_supported: EncValue[]\n\n /**\n * REQUIRED. Boolean value specifying whether the Credential Issuer requires the\n * additional encryption on top of TLS for the Credential Response. If the value is true, the Credential\n * Issuer requires encryption for every Credential Response and therefore the Wallet MUST provide\n * encryption keys in the Credential Request. If the value is false, the Wallet MAY chose whether it\n * provides encryption keys or not.\n */\n encryption_required: boolean\n}\n\n// For now we extend the opts above. Only difference is that the credential endpoint is optional in the Opts, as it can come from other sources. The value is however required in the eventual Issuer Metadata\nexport interface CredentialIssuerMetadata extends CredentialIssuerMetadataOpts, Partial<AuthorizationServerMetadata> {\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n credential_configurations_supported: Record<string, CredentialConfigurationSupported> // REQUIRED. A JSON array containing a list of JSON objects, each of them representing metadata about a separate credential type that the Credential Issuer can issue. The JSON objects in the array MUST conform to the structure of the Section 10.2.3.1.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n credential_response_encryption_alg_values_supported?: string // OPTIONAL. Array containing a list of the JWE [RFC7516] encryption algorithms (alg values) [RFC7518] supported by the Credential and/or Batch Credential Endpoint to encode the Credential or Batch Credential Response in a JWT [RFC7519].\n credential_response_encryption_enc_values_supported?: string //OPTIONAL. Array containing a list of the JWE [RFC7516] encryption algorithms (enc values) [RFC7518] supported by the Credential and/or Batch Credential Endpoint to encode the Credential or Batch Credential Response in a JWT [RFC7519].\n require_credential_response_encryption?: boolean //OPTIONAL. Boolean value specifying whether the Credential Issuer requires additional encryption on top of TLS for the Credential Response and expects encryption parameters to be present in the Credential Request and/or Batch Credential Request, with true indicating support. When the value is true, credential_response_encryption_alg_values_supported parameter MUST also be provided. If omitted, the default value is false.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter in the authorization_details Token Response parameter, with true indicating support. If omitted, the default value is false.\n}\n\n// For now we extend the opts above. Only difference is that the credential endpoint is optional in the Opts, as it can come from other sources. The value is however required in the eventual Issuer Metadata\n\nexport interface CredentialSupportedBrief {\n cryptographic_binding_methods_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify how the Credential is bound to the identifier of the End-User who possesses the Credential\n cryptographic_suites_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify the cryptographic suites that are supported for the cryptographic_binding_methods_supported\n}\n\nexport interface ProofType {\n proof_signing_alg_values_supported: string[]\n}\n\nexport type ProofTypesSupported = {\n [key in KeyProofType]?: ProofType\n}\n\nexport type CommonCredentialSupported = CredentialSupportedBrief &\n ExperimentalSubjectIssuance & {\n format: OID4VCICredentialFormat | string //REQUIRED. A JSON string identifying the format of this credential, e.g. jwt_vc_json or ldp_vc.\n id?: string // OPTIONAL. A JSON string identifying the respective object. The value MUST be unique across all credentials_supported entries in the Credential Issuer Metadata\n display?: CredentialsSupportedDisplay[] // OPTIONAL. An array of objects, where each object contains the display properties of the supported credential for a certain language\n scope?: string // OPTIONAL. A JSON string identifying the scope value that this Credential Issuer supports for this particular Credential. The value can be the same across multiple credential_configurations_supported objects. The Authorization Server MUST be able to uniquely identify the Credential Issuer based on the scope value. The Wallet can use this value in the Authorization Request as defined in Section 5.1.2. Scope values in this Credential Issuer metadata MAY duplicate those in the scopes_supported parameter of the Authorization Server.\n proof_types_supported?: ProofTypesSupported\n\n /**\n * following properties are non-mso_mdoc specific and we might wanna rethink them when we're going to support mso_mdoc\n */\n }\n\nexport interface CredentialSupportedJwtVcJsonLdAndLdpVc extends CommonCredentialSupported {\n types: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n '@context': ICredentialContextType[] // REQUIRED. JSON array as defined in [VC_DATA], Section 4.1.\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n}\n\nexport interface CredentialSupportedJwtVcJson extends CommonCredentialSupported {\n types: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc added for backwards compat\n}\n\nexport interface CredentialSupportedSdJwtVc extends CommonCredentialSupported {\n format: 'dc+sd-jwt' | 'vc+sd-jwt' // TODO Separate CredentialSupportedSdJwtVc for vcdm2?\n\n vct: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialSupportedSdJwtVcV13 extends CommonCredentialSupported {\n format: 'vc+sd-jwt' // TODO SSISDK-13\n\n vct: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialSupportedMsoMdoc extends CommonCredentialSupported {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport type CredentialConfigurationSupported =\n | CredentialConfigurationSupportedV1_0_15\n | (CommonCredentialSupported &\n (CredentialSupportedJwtVcJson | CredentialSupportedJwtVcJsonLdAndLdpVc | CredentialSupportedSdJwtVc | CredentialSupportedMsoMdoc))\n\nexport type CredentialsSupportedLegacy = CommonCredentialSupported &\n (\n | CredentialSupportedJwtVcJson\n | CredentialSupportedJwtVcJsonLdAndLdpVc\n | CredentialSupportedSdJwtVc\n | CredentialSupportedSdJwtVcV13\n | CredentialSupportedMsoMdoc\n )\n\nexport interface CommonCredentialOfferFormat {\n format: OID4VCICredentialFormat | string\n}\n\nexport interface CredentialOfferFormatJwtVcJsonLdAndLdpVc extends CommonCredentialOfferFormat {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n // REQUIRED. JSON object containing (and isolating) the detailed description of the credential type. This object MUST be processed using full JSON-LD processing.\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface CredentialOfferFormatJwtVcJson extends CommonCredentialOfferFormat {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc is added for backwards compat\n types: string[] // REQUIRED. JSON array as defined in Appendix E.1.1.2. This claim contains the type values the Wallet shall request in the subsequent Credential Request.\n}\n\n// NOTE: the sd-jwt format is added to oid4vci in a later draft version than currently\n// supported, so there's no defined offer format. However, based on the request structure\n// we support sd-jwt for older drafts of oid4vci as well\nexport interface CredentialOfferFormatSdJwtVc extends CommonCredentialOfferFormat {\n format: 'dc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CredentialOfferFormatSdJwtVcv13 extends CommonCredentialOfferFormat {\n format: 'vc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\n// NOTE: the sd-jwt format is added to oid4vci in a later draft version than currently\n// supported, so there's no defined offer format. However, based on the request structure\n// we support sd-jwt for older drafts of oid4vci as well\nexport interface CredentialOfferFormatMsoMdoc extends CommonCredentialOfferFormat {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport type CredentialOfferFormatV1_0_11 = CommonCredentialOfferFormat &\n (CredentialOfferFormatJwtVcJsonLdAndLdpVc | CredentialOfferFormatJwtVcJson | CredentialOfferFormatSdJwtVcv13 | CredentialOfferFormatMsoMdoc)\n\n/**\n * Optional storage that can help the credential Data Supplier. For instance to store credential input data during offer creation, if no additional data can be supplied later on\n */\nexport type CredentialDataSupplierInput = any\n\nexport type CreateCredentialOfferURIResult = {\n uri: string\n correlationId: string\n qrCodeDataUri?: string\n session: CredentialOfferSession\n userPin?: string\n txCode?: TxCode\n}\n\nexport interface JsonLdIssuerCredentialDefinition {\n '@context': ICredentialContextType[]\n types: string[]\n credentialSubject?: IssuerCredentialSubject\n}\n\nexport interface ErrorResponse {\n error: string\n error_description?: string\n error_uri?: string\n state?: string\n}\n\nexport type CredentialRequest = CredentialRequestV1_0_15\n\nexport interface CommonCredentialRequest extends ExperimentalSubjectIssuance {\n format: OID4VCICredentialFormat /* | OID4VCICredentialFormat[];*/ // for now it seems only one is supported in the spec\n proof?: ProofOfPossession\n}\n\nexport interface CredentialRequestJwtVcJson extends CommonCredentialRequest {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc for backwards compat\n types: string[]\n credentialSubject?: IssuerCredentialSubject\n}\n\nexport interface CredentialRequestJwtVcJsonLdAndLdpVc extends CommonCredentialRequest {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface CredentialRequestSdJwtVc extends CommonCredentialRequest {\n format: 'dc+sd-jwt'\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CredentialRequestMsoMdoc extends CommonCredentialRequest {\n format: 'mso_mdoc'\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CommonCredentialResponse extends ExperimentalSubjectIssuance {\n // format: string; TODO do we still need this for previous version support?\n credential?: W3CVerifiableCredential\n acceptance_token?: string\n c_nonce?: string\n c_nonce_expires_in?: string\n}\n\nexport interface CredentialResponseLdpVc extends CommonCredentialResponse {\n // format: 'ldp_vc';\n credential: IVerifiableCredential\n}\n\nexport interface CredentialResponseJwtVc {\n // format: 'jwt_vc_json' | 'jwt_vc_json-ld'; TODO do we still need this for previous version support?\n credential: string\n}\n\nexport interface CredentialResponseSdJwtVc {\n // format: 'vc+sd-jwt'; TODO do we still need this for previous version support?\n credential: string\n}\n\n// export type CredentialSubjectDisplay = NameAndLocale[];\n\nexport type IssuerCredentialSubjectDisplay = CredentialSubjectDisplay & { [key: string]: CredentialSubjectDisplay }\n\nexport interface CredentialSubjectDisplay {\n mandatory?: boolean // OPTIONAL. Boolean which when set to true indicates the claim MUST be present in the issued Credential. If the mandatory property is omitted its default should be assumed to be false.\n value_type?: string // OPTIONAL. String value determining type of value of the claim. A non-exhaustive list of valid values defined by this specification are string, number, and image media types such as image/jpeg as defined in IANA media type registry for images\n display?: NameAndLocale[] // OPTIONAL. An array of objects, where each object contains display properties of a certain claim in the Credential for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n}\n\nexport interface IssuerCredentialSubject {\n [key: string]: IssuerCredentialSubjectDisplay\n}\n\nexport interface Grant {\n authorization_code?: GrantAuthorizationCode\n [PRE_AUTH_GRANT_LITERAL]?: GrantUrnIetf\n}\n\nexport interface GrantAuthorizationCode {\n /**\n * OPTIONAL. String value created by the Credential Issuer and opaque to the Wallet that is used to bind the subsequent\n * Authorization Request with the Credential Issuer to a context set up during previous steps.\n */\n issuer_state?: string\n\n // v12 feature\n /**\n * OPTIONAL string that the Wallet can use to identify the Authorization Server to use with this grant type when authorization_servers parameter in the Credential Issuer metadata has multiple entries. MUST NOT be used otherwise. The value of this parameter MUST match with one of the values in the authorization_servers array obtained from the Credential Issuer metadata\n */\n authorization_server?: string\n}\n\nexport interface TxCode {\n /**\n * OPTIONAL. String specifying the input character set. Possible values are numeric (only digits) and text (any characters). The default is numeric.\n */\n input_mode?: InputCharSet\n\n /**\n * OPTIONAL. Integer specifying the length of the Transaction Code. This helps the Wallet to render the input screen and improve the user experience.\n */\n length?: number\n\n /**\n * OPTIONAL. String containing guidance for the Holder of the Wallet on how to obtain the Transaction Code, e.g.,\n * describing over which communication channel it is delivered. The Wallet is RECOMMENDED to display this description\n * next to the Transaction Code input screen to improve the user experience. The length of the string MUST NOT exceed\n * 300 characters. The description does not support internationalization, however the Issuer MAY detect the Holder's\n * language by previous communication or an HTTP Accept-Language header within an HTTP GET request for a Credential Offer URI.\n */\n description?: string\n}\n\nexport interface GrantUrnIetf {\n /**\n * REQUIRED. The code representing the Credential Issuer's authorization for the Wallet to obtain Credentials of a certain type.\n */\n 'pre-authorized_code': string\n\n // v13\n /**\n * OPTIONAL. Object specifying whether the Authorization Server expects presentation of a Transaction Code by the\n * End-User along with the Token Request in a Pre-Authorized Code Flow. If the Authorization Server does not expect a\n * Transaction Code, this object is absent; this is the default. The Transaction Code is intended to bind the Pre-Authorized\n * Code to a certain transaction to prevent replay of this code by an attacker that, for example, scanned the QR code while\n * standing behind the legitimate End-User. It is RECOMMENDED to send the Transaction Code via a separate channel. If the Wallet\n * decides to use the Pre-Authorized Code Flow, the Transaction Code value MUST be sent in the tx_code parameter with\n * the respective Token Request as defined in Section 6.1. If no length or description is given, this object may be empty,\n * indicating that a Transaction Code is required.\n */\n tx_code?: TxCode\n\n // v12, v13\n /**\n * OPTIONAL. The minimum amount of time in seconds that the Wallet SHOULD wait between polling requests to the token endpoint (in case the Authorization Server responds with error code authorization_pending - see Section 6.3). If no value is provided, Wallets MUST use 5 as the default.\n */\n interval?: number\n\n // v12, v13 feature\n /**\n * OPTIONAL string that the Wallet can use to identify the Authorization Server to use with this grant type when authorization_servers parameter in the Credential Issuer metadata has multiple entries. MUST NOT be used otherwise. The value of this parameter MUST match with one of the values in the authorization_servers array obtained from the Credential Issuer metadata\n */\n authorization_server?: string\n\n // v12 and below feature\n /**\n * OPTIONAL. Boolean value specifying whether the AS\n * expects presentation of the End-User PIN along with the Token Request\n * in a Pre-Authorized Code Flow. Default is false. This PIN is intended\n * to bind the Pre-Authorized Code to a certain transaction to prevent\n * replay of this code by an attacker that, for example, scanned the QR\n * code while standing behind the legitimate End-User. It is RECOMMENDED\n * to send a PIN via a separate channel. If the Wallet decides to use\n * the Pre-Authorized Code Flow, a PIN value MUST be sent in\n * the user_pin parameter with the respective Token Request.\n */\n user_pin_required?: boolean\n}\n\nexport const PRE_AUTH_CODE_LITERAL = 'pre-authorized_code'\nexport const PRE_AUTH_GRANT_LITERAL = 'urn:ietf:params:oauth:grant-type:pre-authorized_code'\n\nexport type EndpointMetadataResult = EndpointMetadataResultV1_0_15\n\nexport type IssuerMetadata = IssuerMetadataV1_0_15\n\nexport type NotificationEventType = 'credential_accepted' | 'credential_failure' | 'credential_deleted'\n\nexport interface NotificationRequest {\n notification_id: string\n event: NotificationEventType | string\n event_description?: string\n credential?: any // Experimental support to have a wallet sign a credential. Not part of the spec\n}\n\nexport type NotificationError = 'invalid_notification_id' | 'invalid_notification_request'\n\nexport type NotificationResponseResult = {\n error: boolean\n response?: NotificationErrorResponse\n}\n\nexport interface NotificationErrorResponse {\n error: NotificationError | string\n}\n\nexport interface StatusListOpts {\n statusListId?: string // Explicit status list to use. Determines the id from the credentialStatus object in the VC itself or uses the default otherwise\n statusListCorrelationId?: string\n statusListIndex?: number\n statusEntryCorrelationId?: string // An id to use for correlation. Can be the credential id, but also a business identifier. Will only be used for lookups/management\n}\n","import { BaseJWK } from '@sphereon/oid4vc-common'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { AuthzFlowType } from './Authorization.types'\nimport { OID4VCICredentialFormat, TxCode } from './Generic.types'\nimport { OpenId4VCIVersion } from './OpenID4VCIVersions.types'\nimport { CredentialOfferPayloadV1_0_15, CredentialOfferV1_0_15, CredentialResponseCredentialV1_0_15 } from './v1_0_15.types'\n\nexport interface CredentialResponse extends ExperimentalSubjectIssuance {\n credentials?: Array<CredentialResponseCredentialV1_0_15>\n format?: OID4VCICredentialFormat /* | OID4VCICredentialFormat[]*/ // REQUIRED. JSON string denoting the format of the issued Credential TODO: remove when cleaning <v13\n transaction_id?: string //OPTIONAL. A string identifying a Deferred Issuance transaction. This claim is contained in the response if the Credential Issuer was unable to immediately issue the credential. The value is subsequently used to obtain the respective Credential with the Deferred Credential Endpoint (see Section 9). It MUST be present when the credential parameter is not returned. It MUST be invalidated after the credential for which it was meant has been obtained by the Wallet.\n acceptance_token?: string //deprecated // OPTIONAL. A JSON string containing a security token subsequently used to obtain a Credential. MUST be present when credential is not returned\n c_nonce?: string // OPTIONAL. JSON string containing a nonce to be used to create a proof of possession of key material when requesting a Credential (see Section 7.2). When received, the Wallet MUST use this nonce value for its subsequent credential requests until the Credential Issuer provides a fresh nonce\n c_nonce_expires_in?: number // OPTIONAL. JSON integer denoting the lifetime in seconds of the c_nonce\n notification_id?: string\n}\n\nexport interface CredentialOfferRequestWithBaseUrl extends UniformCredentialOfferRequest {\n scheme: string\n clientId?: string\n baseUrl: string\n txCode?: TxCode\n issuerState?: string\n preAuthorizedCode?: string\n userPinRequired: boolean\n}\n\nexport type CredentialOffer = CredentialOfferV1_0_15\n\nexport type CredentialOfferPayloadLatest = CredentialOfferPayloadV1_0_15\n\nexport type CredentialOfferPayload = CredentialOfferPayloadV1_0_15 & {\n [x: string]: any\n}\n\nexport interface AssertedUniformCredentialOffer extends UniformCredentialOffer {\n credential_offer: UniformCredentialOfferPayload\n}\n\nexport interface UniformCredentialOffer {\n credential_offer?: UniformCredentialOfferPayload\n credential_offer_uri?: string\n}\n\nexport interface UniformCredentialOfferRequest extends AssertedUniformCredentialOffer {\n original_credential_offer: CredentialOfferPayload\n version: OpenId4VCIVersion\n supportedFlows: AuthzFlowType[]\n}\n\n//todo: drop v11 (done for now, but maybe not final)\nexport type UniformCredentialOfferPayload = CredentialOfferPayloadV1_0_15\n\nexport interface ProofOfPossession {\n proof_type: 'jwt'\n jwt: string\n\n [x: string]: unknown\n}\n\nexport type SearchValue = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string\n}\n\nexport enum JsonURIMode {\n JSON_STRINGIFY,\n X_FORM_WWW_URLENCODED,\n}\n\nexport type EncodeJsonAsURIOpts = {\n uriTypeProperties?: string[]\n arrayTypeProperties?: string[]\n baseUrl?: string\n param?: string\n mode?: JsonURIMode\n version?: OpenId4VCIVersion\n}\n\nexport type DecodeURIAsJsonOpts = {\n requiredProperties?: string[]\n arrayTypeProperties?: string[]\n}\n\nexport interface Jwt {\n header: JWTHeader\n payload: JWTPayload\n}\n\nexport interface ProofOfPossessionCallbacks {\n signCallback: JWTSignerCallback\n verifyCallback?: JWTVerifyCallback\n}\n\n/**\n * Signature algorithms.\n *\n * TODO: Move towards string literal unions and string type, given we do not provide signature/key implementations in this library to begin with\n * @See: https://github.com/Sphereon-Opensource/OID4VC/issues/88\n */\nexport enum Alg {\n EdDSA = 'EdDSA',\n ES256 = 'ES256',\n ES256K = 'ES256K',\n PS256 = 'PS256',\n PS384 = 'PS384',\n PS512 = 'PS512',\n RS256 = 'RS256',\n RS384 = 'RS384',\n RS512 = 'RS512',\n}\n\nexport type Typ =\n | 'JWT'\n // https://www.rfc-editor.org/rfc/rfc8725.pdf#name-use-explicit-typing\n // https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#section-7.2.1-2.1.2.1.2.1.1\n | 'openid4vci-proof+jwt'\n\nexport interface JoseHeaderParameters {\n kid?: string // CONDITIONAL. JWT header containing the key ID. If the Credential shall be bound to a DID, the kid refers to a DID URL which identifies a particular key in the DID Document that the Credential shall be bound to. MUST NOT be present if jwk or x5c is present.\n x5t?: string\n x5c?: string[] // CONDITIONAL. JWT header containing a certificate or certificate chain corresponding to the key used to sign the JWT. This element may be used to convey a key attestation. In such a case, the actual key certificate will contain attributes related to the key properties. MUST NOT be present if kid or jwk is present.\n x5u?: string\n jku?: string\n jwk?: BaseJWK // CONDITIONAL. JWT header containing the key material the new Credential shall be bound to. MUST NOT be present if kid or x5c is present.\n typ?: string //JWT always\n cty?: string\n}\n\nexport interface JWSHeaderParameters extends JoseHeaderParameters {\n alg?: Alg | string // REQUIRED by the JWT signer\n b64?: boolean\n crit?: string[]\n\n [propName: string]: unknown\n}\n\nexport interface CompactJWSHeaderParameters extends JWSHeaderParameters {\n alg: string\n}\n\nexport interface JWTHeaderParameters extends CompactJWSHeaderParameters {\n b64?: true\n}\n\nexport type JWTHeader = JWTHeaderParameters\n\nexport interface JWTPayload {\n iss?: string // REQUIRED (string). The value of this claim MUST be the client_id of the client making the credential request.\n aud?: string | string[] // REQUIRED (string). The value of this claim MUST be the issuer URL of credential issuer.\n iat?: number // REQUIRED (number). The value of this claim MUST be the time at which the proof was issued using the syntax defined in [RFC7519].\n nonce?: string // REQUIRED (string). The value type of this claim MUST be a string, where the value is a c_nonce provided by the credential issuer. //TODO: Marked as required not present in NGI flow\n jti?: string // A new nonce chosen by the wallet. Used to prevent replay\n exp?: number // Not longer than 5 minutes\n client_id?: string // (string). The value of this claim MUST be the client_id of the client making the credential request.\n [s: string]: unknown\n}\n\nexport type JWTSignerCallback = (jwt: Jwt, kid?: string, noIssPayloadUpdate?: boolean) => Promise<string>\nexport type JWTVerifyCallback = (args: { jwt: string; kid?: string }) => Promise<JwtVerifyResult>\n\nexport interface JwtVerifyResult {\n jwt: Jwt\n kid?: string\n alg?: string\n did?: string\n didDocument?: Record<string, unknown>\n x5c?: string[]\n jwk?: BaseJWK\n}\n","import { JWK } from '@sphereon/oid4vc-common'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { ProofOfPossession } from './CredentialIssuance.types'\nimport {\n AlgValue,\n CredentialDataSupplierInput,\n CredentialOfferMode,\n CredentialsSupportedDisplay,\n CredentialSupplierConfig,\n EncValue,\n Grant,\n IssuerCredentialSubject,\n MetadataDisplay,\n OID4VCICredentialFormat,\n ProofTypesSupported,\n ResponseEncryption,\n StatusListOpts,\n} from './Generic.types'\nimport { QRCodeOpts } from './QRCode.types'\nimport { AuthorizationServerMetadata, AuthorizationServerType, EndpointMetadata } from './ServerMetadata'\n\nexport interface IssuerMetadataV1_0_15 {\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. A JSON object containing a list of key value pairs, where the key is a string serving as an abstract identifier of the Credential. This identifier is RECOMMENDED to be collision resistant - it can be globally unique, but does not have to be when naming conflicts are unlikely to arise in a given use case. The value is a JSON object. The JSON object MUST conform to the structure of the Section 11.2.1.\n credential_issuer: string // REQUIRED. A Credential Issuer is identified by a case sensitive URL using the https scheme that contains scheme, host and, optionally, port number and path components, but no query or fragment components.\n credential_endpoint: string // REQUIRED. URL of the OP's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint, as defined in Section 7. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint.\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n deferred_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Deferred Credential Endpoint, as defined in Section 9. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Deferred Credential Endpoint.\n notification_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Notification Endpoint, as defined in Section 10. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Notification Endpoint.\n credential_response_encryption?: ResponseEncryption // OPTIONAL. Object containing information about whether the Credential Issuer supports encryption of the Credential Response on top of TLS.\n batch_credential_issuance?: BatchCredentialIssuance // OPTIONAL. Object containing information about the Credential Issuer's supports for batch issuance of Credentials on the Credential Endpoint. The presence of this parameter means that the issuer supports the proofs parameter in the Credential Request so can issue more than one Verifiable Credential for the same Credential Dataset in a single request/response.\n token_endpoint?: string // OPTIONAL. URL of the token endpoint.\n display?: MetadataDisplay[] // OPTIONAL. An array of objects, where each object contains display properties of a Credential Issuer for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n authorization_challenge_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Authorization Challenge Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. Described on https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-end\n signed_metadata?: string // OPTIONAL. String that is a signed JWT. This JWT contains Credential Issuer metadata parameters as claims.\n\n [x: string]: unknown\n}\n\nexport interface BatchCredentialIssuance {\n batch_size: number // REQUIRED. Integer value specifying the maximum array size for the proofs parameter in a Credential Request.\n}\n\nexport type CredentialDefinitionJwtVcJsonV1_0_15 = {\n type: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n}\n\nexport type CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 = {\n '@context': string[] // REQUIRED. JSON array as defined in [VC_DATA], Section 4.1.\n type: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n}\n\nexport type CredentialConfigurationSupportedV1_0_15 = CredentialConfigurationSupportedCommonV1_0_15 &\n (\n | CredentialConfigurationSupportedSdJwtVcV1_0_15\n | CredentialConfigurationSupportedJwtVcJsonV1_0_15\n | CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialConfigurationSupportedMsoMdocV1_0_15\n )\n\nexport type CredentialConfigurationSupportedCommonV1_0_15 = {\n format: OID4VCICredentialFormat | string // REQUIRED. A JSON string identifying the format of this credential, e.g. jwt_vc_json or ldp_vc.\n scope?: string // OPTIONAL. A JSON string identifying the scope value that this Credential Issuer supports for this particular Credential. The value can be the same across multiple credential_configurations_supported objects. The Authorization Server MUST be able to uniquely identify the Credential Issuer based on the scope value. The Wallet can use this value in the Authorization Request as defined in Section 5.1.2. Scope values in this Credential Issuer metadata MAY duplicate those in the scopes_supported parameter of the Authorization Server.\n cryptographic_binding_methods_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify how the Credential is bound to the identifier of the End-User who possesses the Credential\n credential_signing_alg_values_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify the algorithms that the Issuer uses to sign the issued Credential. Algorithm names used are determined by the Credential Format and are defined in Appendix A.\n proof_types_supported?: ProofTypesSupported // OPTIONAL. Object that describes specifics of the key proof(s) that the Credential Issuer supports. This object contains a list of name/value pairs, where each name is a unique identifier of the supported proof type(s).\n display?: CredentialsSupportedDisplay[] // OPTIONAL. An array of objects, where each object contains the display properties of the supported credential for a certain language\n [x: string]: unknown\n}\n\nexport interface CredentialConfigurationSupportedSdJwtVcV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'dc+sd-jwt' | 'vc+sd-jwt' // REQUIRED. Updated format identifier for SD-JWT VC to align with the media type in draft -06 of [I-D.ietf-oauth-sd-jwt-vc]\n vct: string // REQUIRED. String designating the type of a Credential, as defined in [I-D.ietf-oauth-sd-jwt-vc].\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedMsoMdocV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'mso_mdoc' // REQUIRED. Format identifier for ISO mDL credentials\n doctype: string // REQUIRED. String identifying the Credential type, as defined in [ISO.18013-5].\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'jwt_vc_json' | 'jwt_vc' // REQUIRED. jwt_vc added for backward compat\n credential_definition: CredentialDefinitionJwtVcJsonV1_0_15 // REQUIRED. Object containing the detailed description of the Credential type.\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'ldp_vc' | 'jwt_vc_json-ld' // REQUIRED. Format identifier for JSON-LD based credentials\n credential_definition: CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 // REQUIRED. Object containing the detailed description of the Credential type.\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\n// Claims description using path pointers as per v15 spec change to syntax of credential metadata\nexport interface ClaimsDescriptionV1_0_15 {\n path: (string | number | null)[] // REQUIRED. The value MUST be a non-empty array representing a claims path pointer that specifies the path to a claim within the credential, as defined in Appendix C.\n mandatory?: boolean // OPTIONAL. Boolean which, when set to true, indicates that the Credential Issuer will always include this claim in the issued Credential. If set to false, the claim is not included in the issued Credential if the wallet did not request the inclusion of the claim, and/or if the Credential Issuer chose to not include the claim. If the mandatory parameter is omitted, the default value is false.\n display?: CredentialsSupportedDisplay[] // OPTIONAL. Array of objects, where each object contains display properties of a certain claim in the Credential for a certain language.\n}\n\nexport type CredentialRequestV1_0_15ResponseEncryption = {\n jwk: JWK // REQUIRED. JWK containing the key material for encryption\n alg: AlgValue // REQUIRED. JWE algorithm for encryption\n enc: EncValue // REQUIRED. JWE encryption method\n}\n\nexport interface CredentialRequestV1_0_15Common extends ExperimentalSubjectIssuance {\n credential_response_encryption?: CredentialRequestV1_0_15ResponseEncryption // OPTIONAL. Object containing information for encrypting the Credential Response. If this request element is not present, the corresponding credential response returned is not encrypted.\n proof?: ProofOfPossession // OPTIONAL. Object providing a single proof of possession of the cryptographic key material to which the issued Credential instance will be bound to. proof parameter MUST NOT be present if proofs parameter is used.\n proofs?: ProofOfPossessionMap // OPTIONAL. Object providing one or more proof of possessions of the cryptographic key material to which the issued Credential instances will be bound to. The proofs parameter MUST NOT be present if proof parameter is used.\n issuer_state?: string // OPTIONAL. We allow sending a issuer state back to the credential offer in case an auth code flow is used with an external AS and no nonces are used (not recommended), but does allow to integrate any OIDC server\n}\n\nexport interface ProofOfPossessionMap {\n [proofType: string]: ProofOfPossession[] // Array of proofs for each proof type - proofs object contains exactly one parameter named as the proof type\n}\n\n// Main credential request type for v15 - removes format and format-specific parameters from Credential Request\nexport type CredentialRequestV1_0_15 = CredentialRequestV1_0_15Common &\n (CredentialRequestV1_0_15CredentialIdentifier | CredentialRequestV1_0_15CredentialConfigurationId)\n\nexport interface CredentialRequestV1_0_15CredentialIdentifier extends CredentialRequestV1_0_15Common {\n credential_identifier: string // REQUIRED when an Authorization Details of type openid_credential was returned from the Token Response. It MUST NOT be used otherwise. A string that identifies a Credential Dataset that is requested for issuance. When this parameter is used, the credential_configuration_id MUST NOT be present.\n credential_configuration_id?: undefined // MUST NOT be present when credential_identifier is used.\n}\n\nexport interface CredentialRequestV1_0_15CredentialConfigurationId extends CredentialRequestV1_0_15Common {\n credential_configuration_id: string // REQUIRED if a credential_identifiers parameter was not returned from the Token Response as part of the authorization_details parameter. It MUST NOT be used otherwise. String that uniquely identifies one of the keys in the name/value pairs stored in the credential_configurations_supported Credential Issuer metadata.\n credential_identifier?: undefined // MUST NOT be present when credential_configuration_id is used.\n}\n\nexport interface CredentialOfferV1_0_15 {\n credential_offer?: CredentialOfferPayloadV1_0_15 // OPTIONAL. Object with the Credential Offer parameters. This MUST NOT be present when the credential_offer_uri parameter is present.\n credential_offer_uri?: string // OPTIONAL. String that is a URL using the https scheme referencing a resource containing a JSON object with the Credential Offer parameters. This MUST NOT be present when the credential_offer parameter is present.\n}\n\nexport interface CredentialOfferRESTRequestV1_0_15 extends Partial<CredentialOfferPayloadV1_0_15> {\n redirectUri?: string\n baseUri?: string\n scheme?: string\n correlationId?: string\n sessionLifeTimeInSec?: number\n pinLength?: number\n qrCodeOpts?: QRCodeOpts\n client_id?: string\n credentialDataSupplierInput?: CredentialDataSupplierInput\n statusListOpts?: Array<StatusListOpts>\n offerMode?: CredentialOfferMode\n}\n\nexport interface CredentialOfferPayloadV1_0_15 {\n /**\n * REQUIRED. The URL of the Credential Issuer, as defined in Section 11.2.1, from which the Wallet is requested to\n * obtain one or more Credentials. The Wallet uses it to obtain the Credential Issuer's Metadata following the steps\n * defined in Section 11.2.2.\n */\n credential_issuer: string\n\n /**\n * REQUIRED. Array of unique strings that each identify one of the keys in the name/value pairs stored in\n * the credential_configurations_supported Credential Issuer metadata. The Wallet uses these string values\n * to obtain the respective object that contains information about the Credential being offered as defined\n * in Section 11.2.3. For example, these string values can be used to obtain scope values to be used in\n * the Authorization Request.\n */\n credential_configuration_ids: string[]\n\n /**\n * OPTIONAL. Object indicating to the Wallet the Grant Types the Credential Issuer's Authorization Server is prepared\n * to process for this Credential Offer. Every grant is represented by a name/value pair. The name is the Grant Type identifier;\n * the value is an object that contains parameters either determining the way the Wallet MUST use the particular grant and/or\n * parameters the Wallet MUST send with the respective request(s). If grants is not present or is empty, the Wallet MUST determine\n * the Grant Types the Credential Issuer's Authorization Server supports using the respective metadata. When multiple grants are present,\n * it is at the Wallet's discretion which one to use.\n */\n grants?: Grant\n\n /**\n * OPTIONAL. Some implementations might include a client_id in the offer. For instance EBSI in a same-device flow. (Cross-device tucks it in the state JWT)\n */\n client_id?: string\n}\n\n// Credential Response for v15 - credential response always returns an array when not returning a transaction_id\nexport interface CredentialResponseV1_0_15 extends ExperimentalSubjectIssuance {\n credentials?: CredentialResponseCredentialV1_0_15[] // OPTIONAL. Contains an array of one or more issued Credentials. It MUST NOT be used if the transaction_id parameter is present. The elements of the array MUST be objects.\n transaction_id?: string // OPTIONAL. String identifying a Deferred Issuance transaction. This parameter is contained in the response if the Credential Issuer cannot immediately issue the Credential. The value is subsequently used to obtain the respective Credential with the Deferred Credential Endpoint. It MUST NOT be used if the credentials parameter is present. It MUST be invalidated after the Credential for which it was meant has been obtained by the Wallet.\n notification_id?: string // OPTIONAL. String identifying one or more Credentials issued in one Credential Response. It MUST be included in the Notification Request as defined in Section 10. It MUST NOT be present if the credentials parameter is not present.\n}\n\nexport interface CredentialResponseCredentialV1_0_15 {\n credential: string | object // REQUIRED. Contains one issued Credential. It MAY be a string or an object, depending on the Credential Format. See Appendix A for the Credential Format-specific encoding requirements.\n // Additional metadata can be included here with the option for additional meta-data\n}\n\n// Deferred Credential Response for v15 - deferred credential response always returns an array (same as credential response)\nexport interface DeferredCredentialResponseV1_0_15 {\n credentials: CredentialResponseCredentialV1_0_15[] // REQUIRED. Array of issued credentials using the same structure as the immediate credential response.\n notification_id?: string // OPTIONAL. String identifying one or more Credentials issued in one Credential Response.\n}\n\n// Token Response with credential_identifiers support - add an option to return credential_identifiers in the Token Response and use them in the Credential Request, when scopes are used in the Authorization Request\nexport interface TokenResponseV1_0_15 {\n access_token: string\n token_type: string\n expires_in?: number\n refresh_token?: string\n scope?: string\n authorization_details?: AuthorizationDetailsV1_0_15[]\n // Note: removes c_nonce and c_nonce_expires_in from the Token Response as they are now obtained from the Nonce Endpoint\n}\n\nexport interface AuthorizationDetailsV1_0_15 {\n type: 'openid_credential' // REQUIRED. JSON string that determines the authorization details type. MUST be set to openid_credential for the purpose of this specification.\n credential_configuration_id?: string // OPTIONAL. String specifying a unique identifier of the Credential being described in the credential_configurations_supported map\n credential_identifiers?: string[] // REQUIRED when the authorization_details parameter is used to request issuance of a Credential of a certain Credential Configuration. Array of strings, each uniquely identifying a Credential Dataset that can be issued using the Access Token returned in this response.\n locations?: string[] // OPTIONAL. If the Credential Issuer metadata contains an authorization_server parameter, the authorization detail's locations common data field MUST be set to the Credential Issuer Identifier value.\n [x: string]: unknown\n}\n\n// Nonce Endpoint - added a Nonce Endpoint where a Client can acquire a fresh c_nonce value without the overhead of a full Credential Request\nexport interface NonceRequestV1_0_15 {\n // Empty request body - The request for a nonce is made by sending an HTTP POST request to the URL provided in the nonce_endpoint Credential Issuer Metadata parameter.\n}\n\nexport interface NonceResponseV1_0_15 {\n c_nonce: string // REQUIRED. String containing a nonce to be used when creating a proof of possession of the key proof\n // Note: removes c_nonce_expires_in from Nonce Endpoint response\n}\n\n// Error responses updated for v15 - removes c_nonce and c_nonce_expires_in from the Credential Error Response\nexport interface CredentialErrorResponseV1_0_15 {\n error: string // REQUIRED. The error parameter SHOULD be a single ASCII error code\n error_description?: string // OPTIONAL. Human-readable ASCII text providing additional information\n error_uri?: string // OPTIONAL. A URI identifying a human-readable web page with information about the error\n // Note: c_nonce and c_nonce_expires_in removed from error response\n}\n\n// Proof types for v15 - removes CWT proof type, adds key attestation as additional information in a proof of possession and new proof type\nexport interface ProofTypesV1_0_15 {\n jwt?: ProofTypeV1_0_15 // OPTIONAL. JWT proof type support\n ldp_vp?: ProofTypeV1_0_15 // OPTIONAL. Linked Data Proof VP support\n attestation?: ProofTypeV1_0_15 // OPTIONAL. New attestation proof type for key attestation\n}\n\nexport interface ProofTypeV1_0_15 {\n proof_signing_alg_values_supported: string[] // REQUIRED. Array of case sensitive strings that identify the algorithms that the Issuer supports for this proof type.\n key_attestations_required?: KeyAttestationsRequiredV1_0_15 // OPTIONAL. Object that describes the requirement for key attestations, which the Credential Issuer expects the Wallet to send within the proof of the Credential Request.\n}\n\nexport interface KeyAttestationsRequiredV1_0_15 {\n key_storage?: string[] // OPTIONAL. Array defining values for key storage attack potential resistance\n user_authentication?: string[] // OPTIONAL. Array defining values for user authentication attack potential resistance\n}\n\n// Key Attestation JWT format - add key attestation as additional information in a proof of possession\nexport interface KeyAttestationJWT {\n // JOSE Header\n alg: string // REQUIRED. A digital signature algorithm identifier such as per IANA \"JSON Web Signature and Encryption Algorithms\" registry\n typ: 'keyattestation+jwt' // REQUIRED. MUST be keyattestation+jwt, which explicitly types the key attestation JWT\n kid?: string // OPTIONAL. Key identifier\n x5c?: string[] // OPTIONAL. Certificate chain corresponding to the key used to sign the JWT\n trust_chain?: string[] // OPTIONAL. Trust chain for validation\n\n // JWT Claims\n iss?: string // OPTIONAL. Issuer of the key attestation\n iat: number // REQUIRED. Integer for the time at which the key attestation was issued\n exp?: number // OPTIONAL. Integer for the time at which the key attestation and the key(s) it is attesting expire\n attested_keys: JWK[] // REQUIRED. Array of attested keys from the same key storage component\n key_storage?: string[] // OPTIONAL. Array of case sensitive strings that assert the attack potential resistance of the key storage component\n user_authentication?: string[] // OPTIONAL. Array of case sensitive strings that assert the attack potential resistance of the user authentication methods\n certification?: string // OPTIONAL. A String that contains a URL that links to the certification of the key storage component\n nonce?: string // OPTIONAL. String that represents a nonce provided by the Issuer to prove that a key attestation was freshly generated\n status?: object // OPTIONAL. JSON Object representing the supported revocation check mechanisms\n}\n\n// Wallet Attestation format - add section on Wallet Attestations\nexport interface WalletAttestationJWT {\n // JOSE Header\n typ: 'oauth-client-attestation+jwt' // REQUIRED. Type header for wallet attestation\n alg: string // REQUIRED. Signature algorithm\n kid?: string // OPTIONAL. Key identifier\n\n // JWT Claims\n iss: string // REQUIRED. Issuer of the wallet attestation\n sub: string // REQUIRED. Subject (wallet identifier)\n wallet_name?: string // OPTIONAL. String containing a human-readable name of the Wallet\n wallet_link?: string // OPTIONAL. String containing a URL to get further information about the Wallet and the Wallet Provider\n nbf?: number // OPTIONAL. Not before time\n exp?: number // OPTIONAL. Expiration time\n cnf: {\n jwk: JWK // REQUIRED. Confirmation key for proof of possession\n }\n status?: object // OPTIONAL. Status mechanism for the Wallet Attestation\n}\n\nexport interface CredentialIssuerMetadataOptsV1_0_15 {\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint.\n deferred_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Deferred Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Deferred Credential Endpoint.\n notification_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Notification Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Notification Endpoint.\n credential_response_encryption?: ResponseEncryption // OPTIONAL. Object containing information about whether the Credential Issuer supports encryption of the Credential Response on top of TLS.\n batch_credential_issuance?: BatchCredentialIssuance // OPTIONAL. Object containing information about the Credential Issuer's supports for batch issuance of Credentials on the Credential Endpoint.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter in the authorization_details Token Response parameter, with true indicating support. If omitted, the default value is false.\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. Object that describes specifics of the Credential that the Credential Issuer supports issuance of.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers the Credential Issuer relies on for authorization.\n signed_metadata?: string // OPTIONAL. String that is a signed JWT. This JWT contains Credential Issuer metadata parameters as claims.\n display?: MetadataDisplay[] // OPTIONAL. Array of objects, where each object contains display properties of a Credential Issuer for a certain language.\n authorization_challenge_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Authorization Challenge Endpoint.\n token_endpoint?: string // OPTIONAL. URL of the token endpoint.\n credential_supplier_config?: CredentialSupplierConfig // OPTIONAL. Configuration for credential suppliers.\n}\n\nexport const credentialIssuerMetadataFieldNamesV1_0_15: Array<keyof CredentialIssuerMetadataOptsV1_0_15> = [\n 'credential_issuer',\n 'credential_configurations_supported',\n 'credential_endpoint',\n 'nonce_endpoint',\n 'deferred_credential_endpoint',\n 'notification_endpoint',\n 'credential_response_encryption',\n 'batch_credential_issuance',\n 'authorization_servers',\n 'token_endpoint',\n 'display',\n 'credential_supplier_config',\n 'credential_identifiers_supported',\n 'signed_metadata',\n 'authorization_challenge_endpoint',\n] as const\n\nexport interface EndpointMetadataResultV1_0_15 extends EndpointMetadata {\n authorizationServerType: AuthorizationServerType\n authorizationServerMetadata?: AuthorizationServerMetadata\n credentialIssuerMetadata?: Partial<AuthorizationServerMetadata> & IssuerMetadataV1_0_15\n}\n\nexport interface CredentialIssuerMetadataV1_0_15 extends CredentialIssuerMetadataOptsV1_0_15, Partial<AuthorizationServerMetadata> {\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers the Credential Issuer relies on for authorization.\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint.\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. Supported credential configurations.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n credential_response_encryption_alg_values_supported?: string // OPTIONAL. Array containing a list of the JWE encryption algorithms (alg values) supported.\n credential_response_encryption_enc_values_supported?: string // OPTIONAL. Array containing a list of the JWE encryption algorithms (enc values) supported.\n require_credential_response_encryption?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer requires additional encryption on top of TLS.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint, as defined in Section 7. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint\n}\n\nexport interface NotificationResponseV1_0_15 {\n // Success responses typically return 204 No Content - When the Credential Issuer has successfully received the Notification Request from the Wallet, it MUST respond with an HTTP status code in the 2xx range.\n}\n\nexport interface NotificationErrorResponseV1_0_15 {\n error: 'invalid_notification_id' | 'invalid_notification_request' // REQUIRED. Error code for notification failures.\n error_description?: string // OPTIONAL. Human-readable error description.\n}\n\n// Authorization Server metadata extension for v15 - remove use of the authorization_pending and slow_down error codes\nexport interface AuthorizationServerMetadataV1_0_15 extends AuthorizationServerMetadata {\n 'pre-authorized_grant_anonymous_access_supported'?: boolean // OPTIONAL. A boolean indicating whether the Credential Issuer accepts a Token Request with a Pre-Authorized Code but without a client_id. The default is false.\n // Note: authorization_pending and slow_down error codes removed in v14\n}\n","import { DynamicRegistrationClientMetadata, SigningAlgo } from '@sphereon/oid4vc-common'\n\nexport type OAuthResponseType = 'code' | 'token' | 'id_token' | 'code token' | 'code id_token' | 'token id_token' | 'code token id_token'\n\nexport type TokenEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'client_secret_jwt' | 'private_key_jwt' | 'none'\n\nexport type TokenEndpointAuthSigningAlg =\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'PS256'\n | 'PS384'\n | 'PS512'\n | 'HS256'\n | 'HS384'\n | 'HS512'\n\nexport type OAuthScope = 'openid' | 'profile' | 'email' | 'address' | 'phone' | 'offline_access'\n\nexport type OAuthResponseMode = 'query' | 'fragment' | 'form_post'\n\nexport type OAuthGrantType =\n | 'authorization_code'\n | 'implicit'\n | 'password'\n | 'client_credentials'\n | 'refresh_token'\n | 'urn:ietf:params:oauth:grant-type:device_code'\n | 'urn:ietf:params:oauth:grant-type:saml2-bearer'\n | 'urn:ietf:params:oauth:grant-type:jwt-bearer'\n\nexport type RevocationEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'client_secret_jwt' | 'private_key_jwt' | 'none'\n\nexport type RevocationEndpointAuthSigningAlg =\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'PS256'\n | 'PS384'\n | 'PS512'\n | 'HS256'\n | 'HS384'\n | 'HS512'\n\nexport type PKCECodeChallengeMethod = 'plain' | 'S256'\n\nexport interface AuthorizationServerMetadata extends DynamicRegistrationClientMetadata {\n issuer: string\n authorization_endpoint?: string\n authorization_challenge_endpoint?: string\n token_endpoint?: string\n token_endpoint_auth_methods_supported?: Array<TokenEndpointAuthMethod>\n token_endpoint_auth_signing_alg_values_supported?: Array<TokenEndpointAuthSigningAlg>\n\n registration_endpoint?: string\n scopes_supported?: Array<OAuthScope | string>\n response_types_supported: Array<OAuthResponseType>\n response_modes_supported?: Array<OAuthResponseMode>\n grant_types_supported?: Array<OAuthGrantType>\n service_documentation?: string\n ui_locales_supported?: string[]\n op_policy_uri?: string\n op_tos_uri?: string\n\n revocation_endpoint?: string\n revocation_endpoint_auth_methods_supported?: Array<RevocationEndpointAuthMethod>\n revocation_endpoint_auth_signing_alg_values_supported?: Array<RevocationEndpointAuthSigningAlg>\n\n introspection_endpoint?: string\n code_challenge_methods_supported?: Array<PKCECodeChallengeMethod>\n\n // TODO below fields are not in the rfc8414 spec, do we need them?\n pushed_authorization_request_endpoint?: string // The URL of the pushed authorization request endpoint at which a client can post an authorization request to exchange for a request_uri value usable at the authorization server\n // Note that the presence of pushed_authorization_request_endpoint is sufficient for a client to determine that it may use the PAR flow. A request_uri value obtained from the PAR endpoint is usable at the authorization endpoint regardless of other authorization server metadata such as request_uri_parameter_supported or require_request_uri_registration\n require_pushed_authorization_requests?: boolean // Boolean parameter indicating whether Indicates whether the client is required to use PAR to initiate authorization. If omitted, the default value is false.\n 'pre-authorized_grant_anonymous_access_supported'?: boolean // OPTIONAL. A JSON Boolean indicating whether the issuer accepts a Token Request with a Pre-Authorized Code but without a client id. The default is false\n // A JSON array containing a list of the JWS alg values (from the [IANA.JOSE.ALGS] registry) supported by the authorization server for DPoP proof JWTs.\n dpop_signing_alg_values_supported?: (string | SigningAlgo)[]\n // OIDC values\n frontchannel_logout_supported?: boolean\n frontchannel_logout_session_supported?: boolean\n backchannel_logout_supported?: boolean\n backchannel_logout_session_supported?: boolean\n userinfo_endpoint?: string\n check_session_iframe?: string\n end_session_endpoint?: string\n acr_values_supported?: string[]\n subject_types_supported?: string[]\n request_object_signing_alg_values_supported?: string[]\n display_values_supported?: string[]\n claim_types_supported?: string[]\n claims_supported?: string[]\n claims_parameter_supported?: boolean\n\n // VCI values. In case an AS provides a credential_endpoint itself\n credential_endpoint?: string\n deferred_credential_endpoint?: string\n nonce_endpoint?: string // New in v15\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any //We use any, so you can access properties if you know the structure\n}\n\n// These can be used be a reducer\nexport const authorizationServerMetadataFieldNames: Array<keyof AuthorizationServerMetadata> = [\n 'issuer',\n 'authorization_endpoint',\n 'authorization_challenge_endpoint',\n 'token_endpoint',\n 'jwks_uri',\n 'registration_endpoint',\n 'scopes_supported',\n 'response_types_supported',\n 'response_modes_supported',\n 'grant_types_supported',\n 'token_endpoint_auth_methods_supported',\n 'token_endpoint_auth_signing_alg_values_supported',\n 'service_documentation',\n 'ui_locales_supported',\n 'op_policy_uri',\n 'op_tos_uri',\n 'revocation_endpoint',\n 'revocation_endpoint_auth_methods_supported',\n 'revocation_endpoint_auth_signing_alg_values_supported',\n 'introspection_endpoint',\n 'introspection_endpoint_auth_methods_supported',\n 'introspection_endpoint_auth_signing_alg_values_supported',\n 'code_challenge_methods_supported',\n 'signed_metadata',\n] as const\n\nexport enum WellKnownEndpoints {\n OPENID_CONFIGURATION = '/.well-known/openid-configuration',\n OAUTH_AS = '/.well-known/oauth-authorization-server',\n OPENID4VCI_ISSUER = '/.well-known/openid-credential-issuer',\n}\n\nexport type AuthorizationServerType = 'OIDC' | 'OAuth 2.0' | 'OID4VCI' // OID4VCI means the Issuer hosts a token endpoint itself\n\nexport interface EndpointMetadata {\n issuer: string\n token_endpoint: string\n credential_endpoint: string\n deferred_credential_endpoint?: string\n notification_endpoint?: string\n authorization_server?: string\n authorization_endpoint?: string // Can be undefined in pre-auth flow\n authorization_challenge_endpoint?: string\n}\n","import { Alg } from './CredentialIssuance.types'\n\nexport const BAD_PARAMS = 'Wrong parameters provided'\nexport const URL_NOT_VALID = 'Request url is not valid'\nexport const JWS_NOT_VALID = 'JWS is not valid'\nexport const PROOF_CANT_BE_CONSTRUCTED = \"Proof can't be constructed.\"\nexport const NO_JWT_PROVIDED = 'No JWT provided'\nexport const TYP_ERROR = 'Typ must be \"openid4vci-proof+jwt\"'\nexport const ALG_ERROR = `Algorithm is a required field, you are free to use the signing algorithm of your choice or one of the following: ${Object.keys(\n Alg,\n).join(', ')}`\nexport const KID_JWK_X5C_ERROR = 'Only one must be present: x5c should not present when kid and/or jwk is already present'\nexport const KID_DID_NO_DID_ERROR = 'A DID value needs to be returned when kid is present'\nexport const DID_NO_DIDDOC_ERROR = 'A DID Document needs to be resolved when a DID is encountered'\nexport const AUD_ERROR = 'aud must be the URL of the credential issuer'\nexport const IAT_ERROR = 'iat must be the time at which the proof was issued'\nexport const NONCE_ERROR = 'nonce must be c_nonce provided by the credential issuer'\nexport const JWT_VERIFY_CONFIG_ERROR = 'JWT verify callback not configured correctly.'\nexport const ISSUER_CONFIG_ERROR = 'Issuer not configured correctly.'\nexport const UNKNOWN_CLIENT_ERROR = 'The client is not known by the issuer'\nexport const NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT = 'iss missing in authorization-code context'\nexport const ISS_PRESENT_IN_PRE_AUTHORIZED_CODE_CONTEXT = 'iss should be omitted in pre-authorized-code context'\nexport const ISS_MUST_BE_CLIENT_ID = 'iss must be the client id'\nexport const GRANTS_MUST_NOT_BE_UNDEFINED = 'Grants must not be undefined'\nexport const STATE_MISSING_ERROR = 'issuer state or pre-authorized key not found'\nexport const CREDENTIAL_MISSING_ERROR = 'Credential must be present in response'\nexport const UNSUPPORTED_GRANT_TYPE_ERROR = 'unsupported grant_type'\nexport const PRE_AUTHORIZED_CODE_REQUIRED_ERROR = 'pre-authorized_code is required'\nexport const USER_PIN_REQUIRED_ERROR = 'User pin is required'\nexport const USER_PIN_TX_CODE_SPEC_ERROR = 'user_pin is mixed with tx_code, indicating a spec mismatch'\nexport const USER_PIN_NOT_REQUIRED_ERROR = 'User pin is not required'\nexport const PIN_VALIDATION_ERROR = 'PIN must consist the following amount of characters:'\nexport const PIN_NOT_MATCH_ERROR = 'PIN is invalid'\nexport const INVALID_PRE_AUTHORIZED_CODE = 'pre-authorized_code is invalid'\nexport const EXPIRED_PRE_AUTHORIZED_CODE = 'pre-authorized_code is expired'\nexport const JWT_SIGNER_CALLBACK_REQUIRED_ERROR = 'JWT signer callback function is required'\nexport const STATE_MANAGER_REQUIRED_ERROR = 'StateManager instance is required'\nexport const NONCE_STATE_MANAGER_REQUIRED_ERROR = 'NonceStateManager instance is required'\nexport const ACCESS_TOKEN_ISSUER_REQUIRED_ERROR = 'access token issuer is required'\nexport const WRONG_METADATA_FORMAT = 'Wrong metadata format'\n","export enum OpenId4VCIVersion {\n VER_1_0_15 = 1015,\n VER_UNKNOWN = Number.MAX_VALUE,\n}\n\nexport enum DefaultURISchemes {\n INITIATE_ISSUANCE = 'openid-initiate-issuance',\n CREDENTIAL_OFFER = 'openid-credential-offer',\n}\n","import { AssertedUniformCredentialOffer } from './CredentialIssuance.types'\nimport { CredentialDataSupplierInput, NotificationRequest, StatusListOpts } from './Generic.types'\nimport { AuthorizationDetailsV1_0_15 } from './v1_0_15.types'\n\nexport interface StateType {\n createdAt: number\n expiresAt?: number\n}\n\nexport interface CredentialOfferSession extends StateType {\n clientId?: string\n credentialOffer: AssertedUniformCredentialOffer\n credentialDataSupplierInput?: CredentialDataSupplierInput // Optional storage that can help the credential Data Supplier. For instance to store credential input data during offer creation, if no additional data can be supplied later on\n txCode?: string // in here we only store the txCode, previously < V13 this was the userPin. We map the userPin onto this value\n status: IssueStatus\n error?: string\n lastUpdatedAt: number\n notification_id: string\n notification?: NotificationRequest\n issuerState?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n preAuthorizedCode?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n authorizationCode?: string\n redirectUri?: string\n statusLists?: Array<StatusListOpts>\n authorizationDetails?: AuthorizationDetailsV1_0_15[]\n}\n\nexport enum IssueStatus {\n OFFER_CREATED = 'OFFER_CREATED', // An offer is created. This is the initial state\n ACCESS_TOKEN_REQUESTED = 'ACCESS_TOKEN_REQUESTED', // Optional state, given the token endpoint could also be on a separate AS\n ACCESS_TOKEN_CREATED = 'ACCESS_TOKEN_CREATED', // Optional state, given the token endpoint could also be on a separate AS\n CREDENTIAL_REQUEST_RECEIVED = 'CREDENTIAL_REQUEST_RECEIVED', // Credential request received. Next state would either be error or issued\n CREDENTIAL_ISSUED = 'CREDENTIAL_ISSUED', // The credential iss issued from the issuer's perspective\n NOTIFICATION_CREDENTIAL_ACCEPTED = 'NOTIFICATION_CREDENTIAL_ACCEPTED', // The holder/user stored the credential in the wallet (If notifications are enabled)\n NOTIFICATION_CREDENTIAL_DELETED = 'NOTIFICATION_CREDENTIAL_DELETED', // The holder/user did not store the credential in the wallet (If notifications are enabled)\n NOTIFICATION_CREDENTIAL_FAILURE = 'NOTIFICATION_CREDENTIAL_FAILURE', // The holder/user encountered an error (If notifications are enabled)\n ERROR = 'ERROR', // An error occurred\n}\n\nexport interface CNonceState extends StateType {\n cNonce: string\n}\n\nexport interface URIState extends StateType {\n issuerState?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n preAuthorizedCode?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n uri: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n correlationId?: string\n}\n\nexport interface IssueStatusResponse {\n createdAt: number\n lastUpdatedAt: number\n expiresAt?: number\n status: IssueStatus\n error?: string\n clientId?: string\n statusLists?: Array<StatusListOpts>\n}\n\nexport interface IStateManager<T extends StateType> {\n set(id: string, stateValue: T): Promise<void>\n\n get(id: string): Promise<T | undefined>\n\n has(id: string): Promise<boolean>\n\n delete(id: string): Promise<boolean>\n\n clearExpired(timestamp?: number): Promise<void> // clears all expired states compared against timestamp if provided, otherwise current timestamp\n\n clearAll(): Promise<void> // clears all states\n\n getAsserted(id: string): Promise<T>\n\n startCleanupRoutine(timeout?: number): Promise<void>\n\n stopCleanupRoutine(): Promise<void>\n}\n","export enum TokenErrorResponse {\n invalid_request = 'invalid_request',\n invalid_grant = 'invalid_grant',\n invalid_client = 'invalid_client', // this code has been added only in v1_0-11, but I've added this to the common interface. @nklomp is this ok?\n invalid_scope = 'invalid_scope',\n invalid_dpop_proof = 'invalid_dpop_proof',\n}\n\nexport class TokenError extends Error {\n private readonly _statusCode: number\n private readonly _responseError: TokenErrorResponse\n constructor(statusCode: number, responseError: TokenErrorResponse, message: string) {\n super(message)\n this._statusCode = statusCode\n this._responseError = responseError\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, TokenError.prototype)\n }\n get statusCode(): number {\n return this._statusCode\n }\n get responseError(): TokenErrorResponse {\n return this._responseError\n }\n\n getDescription() {\n return this.message\n }\n}\n","export interface ComponentOptions {\n /**\n * Component options for data/ECC.\n */\n data?: {\n /**\n * Scale factor for data/ECC dots.\n * @default 1\n */\n scale?: number\n }\n\n /**\n * Component options for timing patterns.\n */\n timing?: {\n /**\n * Scale factor for timing patterns.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for timing patterns.\n * @default false\n */\n protectors?: boolean\n }\n\n /**\n * Component options for alignment patterns.\n */\n alignment?: {\n /**\n * Scale factor for alignment patterns.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for alignment patterns.\n * @default false\n */\n protectors?: boolean\n }\n\n /**\n * Component options for alignment pattern on the bottom-right corner.\n */\n cornerAlignment?: {\n /**\n * Scale factor for alignment pattern on the bottom-right corner.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for alignment pattern on the bottom-right corner.\n * @default true\n */\n protectors?: boolean\n }\n}\n\nexport interface QRCodeOpts {\n /**\n * Size of the QR code in pixel.\n *\n * @defaultValue 400\n */\n size?: number\n\n /**\n * Size of margins around the QR code body in pixel.\n *\n * @defaultValue 20\n */\n margin?: number\n\n /**\n * Error correction level of the QR code.\n *\n * Accepts a value provided by _QRErrorCorrectLevel_.\n *\n * For more information, please refer to [https://www.qrcode.com/en/about/error_correction.html](https://www.qrcode.com/en/about/error_correction.html).\n *\n * @defaultValue 0\n */\n correctLevel?: number\n\n /**\n * **This is an advanced option.**\n *\n * Specify the mask pattern to be used in QR code encoding.\n *\n * Accepts a value provided by _QRMaskPattern_.\n *\n * To find out all eight mask patterns, please refer to [https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg](https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg)\n *\n * For more information, please refer to [https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking](https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking).\n */\n maskPattern?: number\n\n /**\n * **This is an advanced option.**\n *\n * Specify the version to be used in QR code encoding.\n *\n * Accepts an integer in range [1, 40].\n *\n * For more information, please refer to [https://www.qrcode.com/en/about/version.html](https://www.qrcode.com/en/about/version.html).\n */\n version?: number\n\n /**\n * Options to control components in the QR code.\n *\n * @deafultValue undefined\n */\n components?: ComponentOptions\n\n /**\n * Color of the blocks on the QR code.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"#000000\"\n */\n colorDark?: string\n\n /**\n * Color of the empty areas on the QR code.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"#ffffff\"\n */\n colorLight?: string\n\n /**\n * Automatically calculate the _colorLight_ value from the QR code's background.\n *\n * @defaultValue true\n */\n autoColor?: boolean\n\n /**\n * Background image to be used in the QR code.\n *\n * Accepts a `data:` string in web browsers or a Buffer in Node.js.\n *\n * @defaultValue undefined\n */\n backgroundImage?: string | Buffer\n\n /**\n * Color of the dimming mask above the background image.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"rgba(0, 0, 0, 0)\"\n */\n backgroundDimming?: string\n\n /**\n * GIF background image to be used in the QR code.\n *\n * @defaultValue undefined\n */\n gifBackground?: ArrayBuffer\n\n /**\n * Use a white margin instead of a transparent one which reveals the background of the QR code on margins.\n *\n * @defaultValue true\n */\n whiteMargin?: boolean\n\n /**\n * Logo image to be displayed at the center of the QR code.\n *\n * Accepts a `data:` string in web browsers or a Buffer in Node.js.\n *\n * When set to `undefined` or `null`, the logo is disabled.\n *\n * @defaultValue undefined\n */\n logoImage?: string | Buffer\n\n /**\n * Ratio of the logo size to the QR code size.\n *\n * @defaultValue 0.2\n */\n logoScale?: number\n\n /**\n * Size of margins around the logo image in pixels.\n *\n * @defaultValue 6\n */\n logoMargin?: number\n\n /**\n * Corner radius of the logo image in pixels.\n *\n * @defaultValue 8\n */\n logoCornerRadius?: number\n\n /**\n * @deprecated\n *\n * Ratio of the real size to the full size of the blocks.\n *\n * This can be helpful when you want to make more parts of the background visible.\n *\n * @deafultValue 0.4\n */\n dotScale?: number\n}\n","import { Loggers, ObjectUtils } from '@sphereon/ssi-types'\nimport { jwtDecode, JwtPayload } from 'jwt-decode'\nimport { CredentialOfferPayloadV1_0_15, VCI_LOG_COMMON } from '../index'\n\nimport {\n AssertedUniformCredentialOffer,\n AuthzFlowType,\n CredentialOffer,\n CredentialOfferPayload,\n DefaultURISchemes,\n Grant,\n GrantTypes,\n OpenId4VCIVersion,\n OpenIDResponse,\n PRE_AUTH_CODE_LITERAL,\n PRE_AUTH_GRANT_LITERAL,\n UniformCredentialOffer,\n UniformCredentialOfferPayload,\n UniformCredentialOfferRequest,\n} from '../types'\n\nimport { getJson } from './HttpUtils'\nimport { base64urlToString } from '@sphereon/oid4vc-common'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:offer')\n\nexport function determineSpecVersionFromURI(uri: string): OpenId4VCIVersion {\n let version = determineSpecVersionFromScheme(uri, OpenId4VCIVersion.VER_UNKNOWN) ?? OpenId4VCIVersion.VER_UNKNOWN\n // version = getVersionFromURIParam(uri, version, [OpenId4VCIVersion.VER_1_0_13, OpenId4VCIVersion.VER_1_0_15], 'tx_code') (left as examples)\n // version = getVersionFromURIParam(uri, version, [OpenId4VCIVersion.VER_1_0_15], 'credential_offer_uri ') // optional so last resort\n if (version === OpenId4VCIVersion.VER_UNKNOWN) {\n version = OpenId4VCIVersion.VER_1_0_15\n }\n return version\n}\n\nexport function determineSpecVersionFromScheme(credentialOfferURI: string, openId4VCIVersion: OpenId4VCIVersion) {\n const scheme = getScheme(credentialOfferURI)\n\n const url = toUrlWithDummyBase(credentialOfferURI)\n const qp = url.searchParams\n\n // ----------------- 1) openid-initiate-issuance -----------------\n if (scheme === DefaultURISchemes.INITIATE_ISSUANCE) {\n // v15 indicators\n if (qp.has('credential_offer') || qp.has('credential_offer_uri')) {\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_1_0_15], scheme)\n }\n\n // Could not decide\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n }\n\n // ----------------- 2) openid-credential-offer -----------------\n if (scheme === DefaultURISchemes.CREDENTIAL_OFFER) {\n // Indirection URI -> Draft 15 style (can't confirm 11/13 via scheme alone)\n if (qp.has('credential_offer_uri')) {\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_1_0_15], scheme)\n }\n\n // Inline payload -> sniff JSON keys\n const rawParam = getParamValueLoose(qp, 'credential_offer')\n if (rawParam) {\n const decoded = tryDecodeOffer(rawParam)\n\n const version = sniffOfferVersion(decoded)\n if (version !== OpenId4VCIVersion.VER_UNKNOWN) {\n return recordVersion(openId4VCIVersion, [version], scheme)\n }\n }\n\n // If we still can't tell, DO NOT default to 15 — stay unknown\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n }\n\n // ----------------- 3) Unknown scheme -----------------\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n}\n\n/* ----------------- helpers ----------------- */\n\n/**\n * Replace custom \"openid-...\" schemes with a dummy base so URL() can parse query params.\n * Make sure to end with '/?' to avoid the \"?param\" name issue.\n */\nfunction toUrlWithDummyBase(uri: string): URL {\n const normalized = uri.replace(/^openid-[^?]+:\\/\\//, 'https://dummy/?')\n return new URL(normalized)\n}\n\n/**\n * Some runtimes/libraries have bugs that result in the param name being `'?credential_offer'`.\n * This helper checks both.\n */\nfunction getParamValueLoose(qp: URLSearchParams, key: string): string | null {\n if (qp.has(key)) return qp.get(key)\n if (qp.has(`?${key}`)) return qp.get(`?${key}`)\n return null\n}\n\n/**\n * Try to decode the inline offer string:\n * 1) decodeURIComponent if needed,\n * 2) base64url decode if it looks base64y,\n * return the final string (JSON) or empty string on failure.\n */\nfunction tryDecodeOffer(input: string): string {\n let candidate = input\n\n try {\n candidate = decodeURIComponent(candidate)\n } catch {\n /* ignore */\n }\n // Fast check for base64url: only URL-safe chars and no braces\n if (!/[{}]/.test(candidate) && /^[A-Za-z0-9\\-_]+$/.test(candidate)) {\n try {\n const b64 = candidate\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .padEnd(Math.ceil(candidate.length / 4) * 4, '=')\n candidate = atob(b64)\n } catch {\n /* ignore */\n }\n }\n return candidate // may still be encoded JSON but good enough for key sniffing\n}\n\n/**\n * Look for version-specific keys.\n * returns only VER_UNKNOWN atm, for future versions support\n */\nfunction sniffOfferVersion(jsonLike: string): OpenId4VCIVersion {\n if (!jsonLike) return OpenId4VCIVersion.VER_UNKNOWN\n\n // Use cheap regex so we don't crash on invalid JSON\n // const has = (k: string) => new RegExp(`\"${k}\"\\\\s*:`, 'i').test(jsonLike);\n // if (has('credentials')) return OpenId4VCIVersion.VER_1_0_11; left as example\n\n return OpenId4VCIVersion.VER_UNKNOWN\n}\n\nexport function getScheme(credentialOfferURI: string) {\n if (!credentialOfferURI || !credentialOfferURI.includes('://')) {\n throw Error('Invalid credential offer URI')\n }\n return credentialOfferURI.split('://')[0]\n}\n\nexport function getIssuerFromCredentialOfferPayload(request: CredentialOfferPayload): string | undefined {\n if (!request || (!('issuer' in request) && !('credential_issuer' in request))) {\n return undefined\n }\n return 'issuer' in request ? request.issuer : request['credential_issuer']\n}\n\nexport const getClientIdFromCredentialOfferPayload = (credentialOffer?: CredentialOfferPayload): string | undefined => {\n if (!credentialOffer) {\n return\n }\n if ('client_id' in credentialOffer) {\n return credentialOffer.client_id\n }\n\n const state: string | undefined = getStateFromCredentialOfferPayload(credentialOffer)\n if (state && isJWT(state)) {\n const decoded = jwtDecode<JwtPayload>(state, { header: false })\n if ('client_id' in decoded && typeof decoded.client_id === 'string') {\n return decoded.client_id\n }\n }\n return\n}\n\nconst isJWT = (input?: string) => {\n if (!input) {\n return false\n }\n const noParts = input?.split('.').length\n return input?.startsWith('ey') && noParts === 3\n}\nexport const getStateFromCredentialOfferPayload = (credentialOffer: CredentialOfferPayload): string | undefined => {\n if ('grants' in credentialOffer) {\n if (credentialOffer.grants?.authorization_code) {\n return credentialOffer.grants.authorization_code.issuer_state\n } else if (credentialOffer.grants?.[PRE_AUTH_GRANT_LITERAL]) {\n return credentialOffer.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]\n }\n }\n if ('op_state' in credentialOffer) {\n // older spec versions\n return credentialOffer.op_state\n } else if (PRE_AUTH_CODE_LITERAL in credentialOffer) {\n return credentialOffer[PRE_AUTH_CODE_LITERAL]\n }\n\n return\n}\n\nexport function determineSpecVersionFromOffer(offer: CredentialOfferPayload | CredentialOffer): OpenId4VCIVersion {\n if (isCredentialOfferV1_0_15(offer)) {\n return OpenId4VCIVersion.VER_1_0_15\n }\n return OpenId4VCIVersion.VER_UNKNOWN\n}\n\nexport function isCredentialOfferVersion(offer: CredentialOfferPayload | CredentialOffer, min: OpenId4VCIVersion, max?: OpenId4VCIVersion) {\n if (max && max.valueOf() < min.valueOf()) {\n throw Error(`Cannot have a max ${max.valueOf()} version smaller than the min version ${min.valueOf()}`)\n }\n const version = determineSpecVersionFromOffer(offer)\n if (version.valueOf() < min.valueOf()) {\n logger.debug(`Credential offer version (${version.valueOf()}) is lower than minimum required version (${min.valueOf()})`)\n return false\n } else if (max && version.valueOf() > max.valueOf()) {\n logger.debug(`Credential offer version (${version.valueOf()}) is higher than maximum required version (${max.valueOf()})`)\n return false\n }\n return true\n}\n\nfunction isCredentialOfferV1_0_15(offer: CredentialOfferPayload | CredentialOffer): boolean {\n if (!offer) {\n return false\n }\n offer = normalizeOfferInput(offer)\n\n // Direct payload\n if ('credential_issuer' in offer && 'credential_configuration_ids' in offer) {\n return Array.isArray((offer as any).credential_configuration_ids)\n }\n\n // Wrapped in credential_offer\n if ('credential_offer' in offer && offer['credential_offer']) {\n return isCredentialOfferV1_0_15((offer as any)['credential_offer'])\n }\n\n // Fallback: URI only (credential_offer_uri) – still v15 style but cannot assert without dereferencing.\n return 'credential_offer_uri' in offer\n}\n\nexport async function toUniformCredentialOfferRequest(\n offer: CredentialOffer,\n opts?: {\n resolve?: boolean\n version?: OpenId4VCIVersion\n },\n): Promise<UniformCredentialOfferRequest> {\n let version = opts?.version ?? determineSpecVersionFromOffer(offer)\n let originalCredentialOffer = offer.credential_offer\n let credentialOfferURI: string | undefined\n if ('credential_offer_uri' in offer && offer?.credential_offer_uri !== undefined) {\n credentialOfferURI = offer.credential_offer_uri\n\n if (opts?.resolve || opts?.resolve === undefined) {\n VCI_LOG_COMMON.log(`Credential offer contained a URI. Will use that to get the credential offer payload: ${credentialOfferURI}`)\n originalCredentialOffer = (await resolveCredentialOfferURI(credentialOfferURI)) as CredentialOfferPayloadV1_0_15\n } else if (!originalCredentialOffer) {\n throw Error(`Credential offer uri (${credentialOfferURI}) found, but resolution was explicitly disabled and credential_offer was supplied`)\n }\n // We need to redetermine the version of the offer, as we only had the offer_uri until now\n version = determineSpecVersionFromOffer(originalCredentialOffer)\n VCI_LOG_COMMON.log(`Offer URI payload determined to be of version ${version}`)\n }\n if (!originalCredentialOffer) {\n throw Error('No credential offer available')\n }\n const payload = toUniformCredentialOfferPayload(originalCredentialOffer, { ...opts, version })\n const supportedFlows = determineFlowType(payload, version)\n return {\n credential_offer: payload,\n original_credential_offer: originalCredentialOffer,\n ...(credentialOfferURI && { credential_offer_uri: credentialOfferURI }),\n supportedFlows,\n version,\n }\n}\n\nexport function isPreAuthCode(request: UniformCredentialOfferPayload | UniformCredentialOffer) {\n request = normalizeOfferInput(request)\n\n const payload = 'credential_offer' in request ? request.credential_offer : (request as UniformCredentialOfferPayload)\n return payload?.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL] !== undefined\n}\n\nexport async function assertedUniformCredentialOffer(\n origCredentialOffer: UniformCredentialOffer,\n opts?: {\n resolve?: boolean\n },\n): Promise<AssertedUniformCredentialOffer> {\n const credentialOffer = JSON.parse(JSON.stringify(origCredentialOffer))\n if (credentialOffer.credential_offer_uri && !credentialOffer.credential_offer) {\n if (opts?.resolve === undefined || opts.resolve) {\n credentialOffer.credential_offer = await resolveCredentialOfferURI(credentialOffer.credential_offer_uri)\n } else {\n throw Error(`No credential_offer present, but we did get a URI, but resolution was explicitly disabled`)\n }\n }\n if (!credentialOffer.credential_offer) {\n throw Error(`No credential_offer present`)\n }\n credentialOffer.credential_offer = await toUniformCredentialOfferPayload(credentialOffer.credential_offer, { version: credentialOffer.version })\n return credentialOffer as AssertedUniformCredentialOffer\n}\n\nexport async function resolveCredentialOfferURI(uri?: string): Promise<UniformCredentialOfferPayload | undefined> {\n if (!uri) {\n return undefined\n }\n const response = (await getJson(uri)) as OpenIDResponse<UniformCredentialOfferPayload>\n if (!response || !response.successBody) {\n throw Error(`Could not get credential offer from uri: ${uri}: ${JSON.stringify(response?.errorBody)}`)\n }\n return response.successBody as UniformCredentialOfferPayload\n}\n\nexport function toUniformCredentialOfferPayload(\n rawOffer: CredentialOfferPayload,\n opts?: {\n version?: OpenId4VCIVersion\n },\n): UniformCredentialOfferPayload {\n const offer = normalizeOfferInput<CredentialOfferPayload>(rawOffer)\n\n // todo: create test to check idempotence once a payload is already been made uniform.\n const version = opts?.version ?? determineSpecVersionFromOffer(offer)\n if (version >= OpenId4VCIVersion.VER_1_0_15) {\n const orig = offer as UniformCredentialOfferPayload\n return {\n ...orig,\n }\n }\n\n throw Error(`Could not create uniform payload for version ${version}`)\n}\n\nexport function determineFlowType(\n suppliedOffer: AssertedUniformCredentialOffer | UniformCredentialOfferPayload,\n version: OpenId4VCIVersion,\n): AuthzFlowType[] {\n const payload: UniformCredentialOfferPayload = getCredentialOfferPayload(suppliedOffer)\n const supportedFlows: AuthzFlowType[] = []\n if (payload.grants?.authorization_code) {\n supportedFlows.push(AuthzFlowType.AUTHORIZATION_CODE_FLOW)\n }\n if (payload.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]) {\n supportedFlows.push(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)\n }\n return supportedFlows\n}\n\nexport function getCredentialOfferPayload(offer: AssertedUniformCredentialOffer | UniformCredentialOfferPayload): UniformCredentialOfferPayload {\n offer = normalizeOfferInput(offer)\n\n let payload: UniformCredentialOfferPayload\n if ('credential_offer' in offer && offer['credential_offer']) {\n payload = offer.credential_offer\n } else {\n payload = offer as UniformCredentialOfferPayload\n }\n return payload\n}\n\nexport function determineGrantTypes(\n offer:\n | AssertedUniformCredentialOffer\n | UniformCredentialOfferPayload\n | ({\n grants: Grant\n } & Record<never, never>),\n): GrantTypes[] {\n offer = normalizeOfferInput(offer)\n\n let grants: Grant | undefined\n if ('grants' in offer && offer.grants) {\n grants = offer.grants\n } else {\n grants = getCredentialOfferPayload(offer as AssertedUniformCredentialOffer | UniformCredentialOfferPayload).grants\n }\n\n const types: GrantTypes[] = []\n if (grants) {\n if ('authorization_code' in grants) {\n types.push(GrantTypes.AUTHORIZATION_CODE)\n }\n if (PRE_AUTH_GRANT_LITERAL in grants) {\n types.push(GrantTypes.PRE_AUTHORIZED_CODE)\n }\n }\n return types\n}\n/*\nfunction getVersionFromURIParam(\n credentialOfferURI: string,\n currentVersion: OpenId4VCIVersion,\n matchingVersion: OpenId4VCIVersion[],\n param: string,\n allowUpgrade = true\n) {\n if (credentialOfferURI.includes(param)) {\n return recordVersion(currentVersion, matchingVersion, param, allowUpgrade)\n }\n return currentVersion\n}*/\n\nfunction recordVersion(currentVersion: OpenId4VCIVersion, matchingVersion: OpenId4VCIVersion[], key: string, allowUpgrade = true) {\n matchingVersion = matchingVersion.sort().reverse()\n if (currentVersion === OpenId4VCIVersion.VER_UNKNOWN) {\n return matchingVersion[0]\n } else if (matchingVersion.includes(currentVersion)) {\n if (!allowUpgrade) {\n return currentVersion\n }\n return matchingVersion[0]\n }\n\n throw new Error(\n `Invalid param. Some keys have been used from version: ${currentVersion} version while '${key}' is used from version: ${JSON.stringify(matchingVersion)}`,\n )\n}\n\nexport function getCredentialConfigurationIdsFromOfferV1_0_15(offer: CredentialOfferPayloadV1_0_15): string[] {\n return offer.credential_configuration_ids ?? []\n}\n\nexport function normalizeOfferInput<T = any>(input: unknown): T {\n if (typeof input !== 'string') {\n return input as T\n }\n\n // JWT?\n if (ObjectUtils.isString(input) && input.startsWith('ey')) {\n const payload = base64urlToString(input)\n return JSON.parse(payload) as T\n }\n\n // JSON?\n try {\n return JSON.parse(input) as T\n } catch {}\n\n // Last resort: just return as-is\n return input as T\n}\n","import { BAD_PARAMS, DecodeURIAsJsonOpts, EncodeJsonAsURIOpts, JsonURIMode, SearchValue } from '../types'\n\n/**\n * @type {(json: {[s:string]: never} | ArrayLike<never> | string | object, opts?: EncodeJsonAsURIOpts)} encodes a Json object into a URI\n * @param { {[s:string]: never} | ArrayLike<never> | string | object } json\n * @param {EncodeJsonAsURIOpts} [opts] Option to encode json as uri\n * - urlTypeProperties: a list of properties of which the value is a URL\n * - arrayTypeProperties: a list of properties which are an array\n */\n\n// /* eslint-disable @typescript-eslint/no-explicit-any */\nexport function convertJsonToURI(\n json:\n | {\n [s: string]: never\n }\n | ArrayLike<never>\n | string\n | object,\n opts?: EncodeJsonAsURIOpts,\n): string {\n if (typeof json === 'string') {\n return convertJsonToURI(JSON.parse(json), opts)\n }\n\n const results = []\n\n function encodeAndStripWhitespace(key: string): string {\n return encodeURIComponent(key.replace(' ', ''))\n }\n\n let components: string\n if (opts?.mode === JsonURIMode.JSON_STRINGIFY) {\n // v11 changed from encoding every param to a encoded json object with a credential_offer param key\n components = encodeAndStripWhitespace(JSON.stringify(json))\n } else {\n // mode is x-form-www-urlencoded\n for (const [key, value] of Object.entries(json)) {\n if (!value) {\n continue\n }\n //Skip properties that are not of URL type\n if (!opts?.uriTypeProperties?.includes(key)) {\n results.push(`${key}=${value}`)\n continue\n }\n if (opts?.arrayTypeProperties?.includes(key) && Array.isArray(value)) {\n results.push(value.map((v) => `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(v, /\\./g)}`).join('&'))\n continue\n }\n const isBool = typeof value == 'boolean'\n const isNumber = typeof value == 'number'\n const isString = typeof value == 'string'\n let encoded\n if (isBool || isNumber) {\n encoded = `${encodeAndStripWhitespace(key)}=${value}`\n } else if (isString) {\n encoded = `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(value, /\\./g)}`\n } else {\n encoded = `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(JSON.stringify(value), /\\./g)}`\n }\n results.push(encoded)\n }\n components = results.join('&')\n }\n if (opts?.baseUrl) {\n if (opts.baseUrl.endsWith('=')) {\n if (opts.param) {\n throw Error('Cannot combine param with an url ending in =')\n }\n return `${opts.baseUrl}${components}`\n } else if (!opts.baseUrl.includes('?')) {\n return `${opts.baseUrl}?${opts.param ? opts.param + '=' : ''}${components}`\n } else if (opts.baseUrl.endsWith('?')) {\n return `${opts.baseUrl}${opts.param ? opts.param + '=' : ''}${components}`\n } else {\n return `${opts.baseUrl}${opts.param ? '&' + opts.param : ''}=${components}`\n }\n }\n return components\n}\n\n/**\n * @type {(uri: string, opts?: DecodeURIAsJsonOpts): unknown} convertURIToJsonObject converts an URI into a Json object decoding its properties\n * @param {string} uri\n * @param {DecodeURIAsJsonOpts} [opts]\n * - requiredProperties: the required properties\n * - arrayTypeProperties: properties that can show up more that once\n * @returns JSON object\n */\nexport function convertURIToJsonObject(uri: string, opts?: DecodeURIAsJsonOpts): unknown {\n if (!uri || (opts?.requiredProperties && !opts.requiredProperties?.every((p) => uri.includes(p)))) {\n throw new Error(BAD_PARAMS)\n }\n\n const uriComponents = getURIComponentsAsArray(uri, opts?.arrayTypeProperties)\n return decodeJsonProperties(uriComponents)\n}\n\nexport function decodeJsonProperties(parts: string[] | string[][]): unknown {\n const result: { [s: string]: unknown } | ArrayLike<unknown> = {}\n for (const key in parts) {\n const value = parts[key]\n if (!value) {\n continue\n }\n if (Array.isArray(value)) {\n result[decodeURIComponent(key)] = value.map((v) => decodeURIComponent(v))\n continue\n }\n\n const isBool = typeof value == 'boolean'\n const isNumber = typeof value == 'number'\n const isString = typeof value == 'string'\n const isObject = typeof value == 'object'\n if (isBool || isNumber) {\n result[decodeURIComponent(key)] = value\n } else if (isString) {\n const decoded = decodeURIComponent(value)\n if (decoded.startsWith('{') && decoded.endsWith('}')) {\n result[decodeURIComponent(key)] = JSON.parse(decoded)\n } else {\n result[decodeURIComponent(key)] = decoded\n }\n } else if (isObject) {\n result[decodeURIComponent(key)] = decodeJsonProperties(value)\n }\n }\n return result\n}\n\n/**\n * @function get URI Components as Array\n * @param {string} uri uri\n * @param {string[]} [arrayTypes] array of string containing array like keys\n */\nexport function getURIComponentsAsArray(uri: string, arrayTypes?: string[]): string[] | string[][] {\n const parts = uri.includes('?') ? uri.split('?')[1] : uri.includes('://') ? uri.split('://')[1] : uri\n const json: string[] | string[][] = []\n const dict: string[] = parts.split('&')\n for (const entry of dict) {\n const pair: string[] = entry.split('=')\n const p0: any = pair[0]\n const p1: any = pair[1]\n if (arrayTypes?.includes(p0)) {\n const key = json[p0]\n if (Array.isArray(key)) {\n key.push(p1)\n } else {\n json[p0] = [p1]\n }\n continue\n }\n json[p0] = p1\n }\n return json\n}\n\n/**\n * @function customEncodeURIComponent is used to encode chars that are not encoded by default\n * @param searchValue The pattern/regexp to find the char(s) to be encoded\n * @param uriComponent query string\n */\nfunction customEncodeURIComponent(uriComponent: string, searchValue: SearchValue): string {\n // -_.!~*'() are not escaped because they are considered safe.\n // Add them to the regex as you need\n return encodeURIComponent(uriComponent).replace(searchValue, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)\n}\n","import {\n AuthorizationDetailsV1_0_15,\n CredentialConfigurationSupportedMsoMdocV1_0_15,\n CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialDefinitionJwtVcJsonV1_0_15,\n VCI_LOG_COMMON,\n} from '../index'\nimport {\n CredentialConfigurationSupported,\n CredentialConfigurationSupportedSdJwtVcV1_0_15,\n CredentialOfferFormatV1_0_11,\n CredentialsSupportedLegacy,\n CredentialSupportedMsoMdoc,\n CredentialSupportedSdJwtVc,\n JsonLdIssuerCredentialDefinition,\n} from '../types'\n\nexport function isW3cCredentialSupported(\n supported: CredentialConfigurationSupported | CredentialsSupportedLegacy,\n): supported is Exclude<\n CredentialConfigurationSupported,\n | CredentialConfigurationSupportedMsoMdocV1_0_15\n | CredentialSupportedMsoMdoc\n | CredentialConfigurationSupportedSdJwtVcV1_0_15\n | CredentialSupportedSdJwtVc\n> {\n return ['jwt_vc_json', 'jwt_vc_json-ld', 'ldp_vc', 'jwt_vc'].includes(supported.format)\n}\n\nexport const getNumberOrUndefined = (input?: string): number | undefined => {\n return input && !isNaN(+input) ? +input : undefined\n}\n\n/**\n * The specs had many places where types could be expressed. This method ensures we get them in any way possible\n * @param subject\n */\nexport function getTypesFromObject(\n subject:\n | CredentialConfigurationSupported\n | CredentialOfferFormatV1_0_11\n | CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialDefinitionJwtVcJsonV1_0_15\n | JsonLdIssuerCredentialDefinition\n | string,\n): string[] | undefined {\n if (subject === undefined) {\n return undefined\n } else if (typeof subject === 'string') {\n return [subject]\n } else if ('credential_definition' in subject) {\n return getTypesFromObject(\n subject.credential_definition as\n | CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialDefinitionJwtVcJsonV1_0_15\n | JsonLdIssuerCredentialDefinition,\n )\n } else if ('types' in subject && subject.types) {\n return Array.isArray(subject.types) ? subject.types : [subject.types as string]\n } else if ('type' in subject && subject.type) {\n return Array.isArray(subject.type) ? subject.type : [subject.type as string]\n } else if ('vct' in subject && subject.vct) {\n return [subject.vct as string]\n } else if ('doctype' in subject && subject.doctype) {\n return [subject.doctype as string]\n }\n VCI_LOG_COMMON.warning('Could not deduce credential types. Probably a failure down the line will happen!')\n return undefined\n}\n\nexport function getTypesFromAuthorizationDetails(\n authDetails: AuthorizationDetailsV1_0_15,\n opts?: { configIdAsType?: boolean },\n): string[] | undefined {\n const { configIdAsType = false } = { ...opts }\n if (typeof authDetails === 'string') {\n return [authDetails]\n } else if ('types' in authDetails && Array.isArray(authDetails.types)) {\n return authDetails.types\n } else if (configIdAsType && authDetails.credential_configuration_id) {\n return [authDetails.credential_configuration_id]\n }\n\n return undefined\n}\n\nexport function getTypesFromCredentialSupported(\n credentialSupported: CredentialConfigurationSupported,\n opts?: { filterVerifiableCredential: boolean },\n) {\n let types: string[] = []\n if (\n credentialSupported.format === 'jwt_vc_json' ||\n credentialSupported.format === 'jwt_vc' ||\n credentialSupported.format === 'jwt_vc_json-ld' ||\n credentialSupported.format === 'ldp_vc'\n ) {\n types = getTypesFromObject(credentialSupported) ?? []\n } else if (credentialSupported.format === 'dc+sd-jwt' || credentialSupported.format === 'vc+sd-jwt') {\n types = [credentialSupported.vct]\n } else if (credentialSupported.format === 'mso_mdoc') {\n types = [credentialSupported.doctype]\n }\n\n if (!types || types.length === 0) {\n throw Error('Could not deduce types from credential supported')\n }\n if (opts?.filterVerifiableCredential) {\n return types.filter((type) => type !== 'VerifiableCredential')\n }\n return types\n}\n","import { CredentialConfigurationSupportedV1_0_15, VCI_LOG_COMMON } from '../index'\nimport {\n AuthorizationServerMetadata,\n CredentialConfigurationSupported,\n CredentialIssuerMetadata,\n IssuerMetadata,\n MetadataDisplay,\n OID4VCICredentialFormat,\n OpenId4VCIVersion,\n} from '../types'\nimport { getTypesFromObject, isW3cCredentialSupported } from './TypeConversionUtils'\n\nexport function getSupportedCredentials(opts?: {\n issuerMetadata?: CredentialIssuerMetadata | IssuerMetadata\n version: OpenId4VCIVersion\n types?: string[][]\n format?: OID4VCICredentialFormat | string | (OID4VCICredentialFormat | string)[]\n}): Record<string, CredentialConfigurationSupportedV1_0_15> | Array<CredentialConfigurationSupported> {\n const { version = OpenId4VCIVersion.VER_1_0_15, types } = opts ?? {}\n if (types && Array.isArray(types)) {\n return types\n .map((typeSet) => {\n return getSupportedCredential({ ...opts, version, types: typeSet })\n })\n .reduce(\n (acc, result) => {\n Object.assign(acc, result)\n return acc\n },\n {} as Record<string, CredentialConfigurationSupportedV1_0_15>,\n )\n }\n\n return getSupportedCredential(opts ? { ...opts, types: undefined } : undefined)\n}\n\nexport function determineVersionsFromIssuerMetadata(issuerMetadata: CredentialIssuerMetadata | IssuerMetadata): Array<OpenId4VCIVersion> {\n const versions = new Set<OpenId4VCIVersion>()\n if ('credential_configurations_supported' in issuerMetadata) {\n versions.add(OpenId4VCIVersion.VER_1_0_15)\n }\n\n // if (versions.size === 0) {\n // The above checks where already very specific and only applicable to single versions we support, so let's skip if we encounter them\n // OLD VERSIONS REMOVED, re-enable when supporting new version\n // }\n if (versions.size === 0) {\n versions.add(OpenId4VCIVersion.VER_UNKNOWN)\n }\n\n return Array.from(versions).sort().reverse() // highest version first\n}\n\nexport function getSupportedCredential(opts?: {\n issuerMetadata?: CredentialIssuerMetadata | IssuerMetadata\n version: OpenId4VCIVersion\n types?: string | string[]\n format?: OID4VCICredentialFormat | string | (OID4VCICredentialFormat | string)[]\n}): Record<string, CredentialConfigurationSupportedV1_0_15> | Array<CredentialConfigurationSupported> {\n const { issuerMetadata, types, format, version = OpenId4VCIVersion.VER_1_0_15 } = opts ?? {}\n\n let credentialConfigurationsV15: Record<string, CredentialConfigurationSupportedV1_0_15> | undefined = undefined\n\n // Check if we have v15 credential_configurations_supported\n if (issuerMetadata?.credential_configurations_supported && version >= OpenId4VCIVersion.VER_1_0_15) {\n credentialConfigurationsV15 = issuerMetadata.credential_configurations_supported as Record<string, CredentialConfigurationSupportedV1_0_15>\n }\n if (!issuerMetadata || (!issuerMetadata.credential_configurations_supported && !issuerMetadata.credentials_supported)) {\n VCI_LOG_COMMON.warning(`No credential issuer metadata or supported credentials found for issuer`)\n if (version >= OpenId4VCIVersion.VER_1_0_15) {\n return credentialConfigurationsV15 ?? {}\n } else {\n return []\n }\n }\n\n const normalizedTypes: string[] = Array.isArray(types) ? types : types ? [types] : []\n const normalizedFormats: string[] = Array.isArray(format) ? format : format ? [format] : []\n\n function filterMatchingConfig(config: CredentialConfigurationSupported): CredentialConfigurationSupported | undefined {\n let isTypeMatch = normalizedTypes.length === 0\n const types = getTypesFromObject(config)\n if (!isTypeMatch) {\n if (normalizedTypes.length === 1 && config.id === normalizedTypes[0]) {\n isTypeMatch = true\n } else if (types) {\n isTypeMatch = normalizedTypes.every((type) => types.includes(type))\n } else {\n // Type guard to check if credential_definition has the expected structure\n const hasValidCredentialDefinition =\n isW3cCredentialSupported(config) &&\n 'credential_definition' in config &&\n config.credential_definition &&\n typeof config.credential_definition === 'object' &&\n 'type' in config.credential_definition &&\n Array.isArray(config.credential_definition.type)\n\n if (hasValidCredentialDefinition) {\n const credDef = config.credential_definition as { type: string[] }\n isTypeMatch = normalizedTypes.every((type) => credDef.type.includes(type))\n } else if (isW3cCredentialSupported(config) && 'type' in config && Array.isArray(config.type)) {\n isTypeMatch = normalizedTypes.every((type) => (config.type as string[]).includes(type))\n } else if (isW3cCredentialSupported(config) && 'types' in config && Array.isArray(config.types)) {\n isTypeMatch = normalizedTypes.every((type) => (config.types as string[]).includes(type))\n }\n }\n }\n\n const isFormatMatch = normalizedFormats.length === 0 || normalizedFormats.includes(config.format)\n\n return isTypeMatch && isFormatMatch ? config : undefined\n }\n\n if (credentialConfigurationsV15) {\n return Object.entries(credentialConfigurationsV15).reduce(\n (filteredConfigs, [id, config]) => {\n if (filterMatchingConfig(config)) {\n filteredConfigs[id] = config\n // Added to enable support < 13. We basically assign the id\n if (!config.id) {\n config.id = id\n }\n }\n return filteredConfigs\n },\n {} as Record<string, CredentialConfigurationSupportedV1_0_15>,\n )\n }\n\n // Handle legacy credentials_supported for older versions\n if (issuerMetadata.credentials_supported && Array.isArray(issuerMetadata.credentials_supported)) {\n return issuerMetadata.credentials_supported.filter(filterMatchingConfig) as Array<CredentialConfigurationSupported>\n }\n\n return version >= OpenId4VCIVersion.VER_1_0_15 ? {} : []\n}\n\nexport function getIssuerDisplays(\n metadata: CredentialIssuerMetadata | IssuerMetadata,\n opts?: {\n prefLocales: string[]\n },\n): MetadataDisplay[] {\n const matchedDisplays =\n metadata.display?.filter(\n (item: MetadataDisplay) =>\n !opts?.prefLocales || opts.prefLocales.length === 0 || (item.locale && opts.prefLocales.includes(item.locale)) || !item.locale,\n ) ?? []\n return matchedDisplays.sort((item: MetadataDisplay) => (item.locale ? (opts?.prefLocales.indexOf(item.locale) ?? 1) : Number.MAX_VALUE))\n}\n\n/**\n * TODO check again when WAL-617 is done to replace how we get the issuer name.\n */\nexport function getIssuerName(\n url: string,\n credentialIssuerMetadata?: Partial<AuthorizationServerMetadata> & (CredentialIssuerMetadata | IssuerMetadata),\n): string {\n if (credentialIssuerMetadata) {\n const displays: Array<MetadataDisplay> = credentialIssuerMetadata ? getIssuerDisplays(credentialIssuerMetadata) : []\n for (const display of displays) {\n if (display.name) {\n return display.name\n }\n }\n }\n return url\n}\n","import { CredentialFormat } from '@sphereon/ssi-types'\n\nimport { OID4VCICredentialFormat, OpenId4VCIVersion } from '../types'\n\nexport function isFormat<T extends { format?: OID4VCICredentialFormat }, Format extends OID4VCICredentialFormat>(\n formatObject: T,\n format: Format,\n): formatObject is T & { format: Format } {\n return formatObject.format === format\n}\n\nexport function isNotFormat<T extends { format?: OID4VCICredentialFormat }, Format extends OID4VCICredentialFormat>(\n formatObject: T,\n format: Format,\n): formatObject is T & { format: Exclude<OID4VCICredentialFormat, Format> } {\n return formatObject.format !== format\n}\n\nconst isUniformFormat = (format: string): format is OID4VCICredentialFormat => {\n return ['jwt_vc_json', 'jwt_vc_json-ld', 'ldp_vc', 'dc+sd-jwt', 'mso_mdoc'].includes(format)\n}\n\nexport function getUniformFormat(format: string | OID4VCICredentialFormat | CredentialFormat): OID4VCICredentialFormat {\n // Already valid format\n if (isUniformFormat(format)) {\n return format\n }\n\n // Older formats\n if (format.toLocaleLowerCase() === 'jwt_vc' || format.toLocaleLowerCase() === 'jwt') {\n return 'jwt_vc'\n }\n if (format === 'ldp_vc' || format === 'ldp') {\n return 'ldp_vc'\n }\n\n throw new Error(`Invalid format: ${format}`)\n}\n\nexport function getFormatForVersion(format: string, version: OpenId4VCIVersion) {\n const uniformFormat = isUniformFormat(format) ? format : getUniformFormat(format)\n\n // Removed version specific format rules\n\n return uniformFormat\n}\n","import { BaseJWK, JWK } from '@sphereon/oid4vc-common'\nimport { Loggers } from '@sphereon/ssi-types'\nimport { jwtDecode } from 'jwt-decode'\n\nimport { PoPMode, VCI_LOG_COMMON } from '..'\nimport {\n BAD_PARAMS,\n JWS_NOT_VALID,\n Jwt,\n JWTHeader,\n JWTPayload,\n JWTVerifyCallback,\n JwtVerifyResult,\n ProofOfPossession,\n ProofOfPossessionCallbacks,\n Typ,\n} from '../types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:common')\n\n/**\n *\n * - proofOfPossessionCallback: JWTSignerCallback\n * Mandatory if you want to create (sign) ProofOfPossession\n * - proofOfPossessionVerifierCallback?: JWTVerifyCallback\n * If exists, verifies the ProofOfPossession\n * - proofOfPossessionCallbackArgs: ProofOfPossessionCallbackArgs\n * arguments needed for signing ProofOfPossession\n * - proofOfPossessionCallback: JWTSignerCallback\n * Mandatory to create (sign) ProofOfPossession\n * - proofOfPossessionVerifierCallback?: JWTVerifyCallback\n * If exists, verifies the ProofOfPossession\n * @param popMode\n * @param callbacks\n * @param jwtProps\n * @param existingJwt\n * - Optional, clientId of the party requesting the credential\n */\nexport const createProofOfPossession = async <DIDDoc extends object = never>(\n popMode: PoPMode,\n callbacks: ProofOfPossessionCallbacks,\n jwtProps?: JwtProps,\n existingJwt?: Jwt,\n): Promise<ProofOfPossession> => {\n if (!callbacks.signCallback) {\n logger.debug(`no jwt signer callback or arguments supplied!`)\n throw new Error(BAD_PARAMS)\n }\n\n const jwtPayload = createJWT(popMode, jwtProps, existingJwt)\n const jwt = await callbacks.signCallback(jwtPayload, jwtPayload.header.kid, popMode === 'pop')\n const proof = {\n proof_type: 'jwt',\n jwt,\n } as ProofOfPossession\n\n try {\n partiallyValidateJWS(jwt)\n if (callbacks.verifyCallback) {\n logger.debug(`Calling supplied verify callback....`)\n await callbacks.verifyCallback({ jwt, kid: jwtPayload.header.kid })\n logger.debug(`Supplied verify callback return success result`)\n }\n } catch {\n logger.debug(`JWS was not valid`)\n throw new Error(JWS_NOT_VALID)\n }\n logger.debug(`Proof of Possession JWT:\\r\\n${jwt}`)\n return proof\n}\n\nconst partiallyValidateJWS = (jws: string): void => {\n if (jws.split('.').length !== 3 || !jws.startsWith('ey')) {\n throw new Error(JWS_NOT_VALID)\n }\n}\n\nexport const isJWS = (token: string): boolean => {\n try {\n partiallyValidateJWS(token)\n return true\n } catch (e) {\n return false\n }\n}\n\nexport const extractBearerToken = (authorizationHeader?: string): string | undefined => {\n return authorizationHeader ? /Bearer (.*)/i.exec(authorizationHeader)?.[1] : undefined\n}\n\nexport const validateJWT = async <DIDDoc extends object = never>(\n jwt?: string,\n opts?: { kid?: string; accessTokenVerificationCallback?: JWTVerifyCallback },\n): Promise<JwtVerifyResult> => {\n if (!jwt) {\n throw Error('No JWT was supplied')\n }\n\n if (!opts?.accessTokenVerificationCallback) {\n VCI_LOG_COMMON.warning(`No access token verification callback supplied. Access tokens will not be verified, except for a very basic check`)\n partiallyValidateJWS(jwt)\n const header = jwtDecode<JWTHeader>(jwt, { header: true })\n const payload = jwtDecode<JWTPayload>(jwt, { header: false })\n return {\n jwt: { header, payload } satisfies Jwt,\n ...header,\n ...payload,\n }\n } else {\n return await opts.accessTokenVerificationCallback({ jwt, kid: opts.kid })\n }\n}\n\nexport interface JwtProps {\n typ?: Typ\n kid?: string\n jwk?: JWK\n x5c?: string[]\n aud?: string | string[]\n issuer?: string\n clientId?: string\n alg?: string\n jti?: string\n nonce?: string\n}\n\nconst createJWT = (mode: PoPMode, jwtProps?: JwtProps, existingJwt?: Jwt): Jwt => {\n const aud =\n mode === 'pop'\n ? getJwtProperty<string | string[]>('aud', true, jwtProps?.issuer, existingJwt?.payload?.aud)\n : getJwtProperty<string | string[]>('aud', false, jwtProps?.aud, existingJwt?.payload?.aud)\n const iss =\n mode === 'pop'\n ? getJwtProperty<string>('iss', false, jwtProps?.clientId, existingJwt?.payload?.iss)\n : getJwtProperty<string>('iss', false, jwtProps?.issuer, existingJwt?.payload?.iss)\n const client_id = mode === 'JWT' ? getJwtProperty<string>('client_id', false, jwtProps?.clientId, existingJwt?.payload?.client_id) : undefined\n const jti = getJwtProperty<string>('jti', false, jwtProps?.jti, existingJwt?.payload?.jti)\n const typ = getJwtProperty<string>('typ', true, jwtProps?.typ, existingJwt?.header?.typ, 'openid4vci-proof+jwt')\n const nonce = getJwtProperty<string>('nonce', false, jwtProps?.nonce, existingJwt?.payload?.nonce) // Officially this is required, but some implementations don't have it\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const alg = getJwtProperty<string>('alg', false, jwtProps?.alg, existingJwt?.header?.alg, 'ES256')!\n const kid = getJwtProperty<string>('kid', false, jwtProps?.kid, existingJwt?.header?.kid)\n const jwk = getJwtProperty<BaseJWK>('jwk', false, jwtProps?.jwk, existingJwt?.header?.jwk)\n const x5c = getJwtProperty<string[]>('x5c', false, jwtProps?.x5c, existingJwt?.header.x5c)\n const jwt: Partial<Jwt> = { ...existingJwt }\n const now = +new Date()\n const jwtPayload: Partial<JWTPayload> = {\n ...(aud && { aud }),\n iat: jwt.payload?.iat ?? Math.floor(now / 1000) - 60, // Let's ensure we subtract 60 seconds for potential time offsets\n exp: jwt.payload?.exp ?? Math.floor(now / 1000) + 10 * 60,\n nonce,\n ...(client_id && { client_id }),\n ...(iss && { iss }),\n ...(jti && { jti }),\n }\n\n const jwtHeader: JWTHeader = {\n typ,\n alg,\n ...(kid && { kid }),\n ...(jwk && { jwk }),\n ...(x5c && { x5c }),\n }\n return {\n payload: { ...jwt.payload, ...jwtPayload },\n header: { ...jwt.header, ...jwtHeader },\n }\n}\n\nconst getJwtProperty = <T>(\n propertyName: string,\n required: boolean,\n option?: string | string[] | JWK,\n jwtProperty?: T,\n defaultValue?: T,\n): T | undefined => {\n if ((typeof option === 'string' || Array.isArray(option)) && option && jwtProperty && option !== jwtProperty) {\n throw Error(`Cannot have a property '${propertyName}' with value '${option}' and different JWT value '${jwtProperty}' at the same time`)\n }\n let result = (jwtProperty ? jwtProperty : option) as T | undefined\n if (!result) {\n if (required) {\n throw Error(`No ${propertyName} property provided either in a JWT or as option`)\n }\n result = defaultValue\n }\n return result\n}\n","import { AuthorizationChallengeCodeResponse, AuthorizationResponse } from '../types'\n\nimport { convertURIToJsonObject } from './Encoding'\n\nexport const toAuthorizationResponsePayload = (\n input: AuthorizationResponse | AuthorizationChallengeCodeResponse | string,\n): AuthorizationResponse | AuthorizationChallengeCodeResponse => {\n let response = input\n if (typeof input === 'string') {\n if (input.trim().startsWith('{') && input.trim().endsWith('}')) {\n response = JSON.parse(input)\n } else if (input.includes('?') && input.includes('code')) {\n response = convertURIToJsonObject(input) as AuthorizationResponse\n }\n }\n if (response && typeof response !== 'string') {\n return response\n }\n throw Error(`Could not create authorization response from the input ${input}`)\n}\n","import { defaultHasher } from '@sphereon/oid4vc-common'\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { toString } = u8a\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport { SupportedEncodings } from 'uint8arrays/to-string'\n\nimport { CodeChallengeMethod } from '../types'\n\nimport randomBytes from './randomBytes.cjs'\n\nexport const CODE_VERIFIER_DEFAULT_LENGTH = 128\nexport const NONCE_LENGTH = 32\n\nexport const generateRandomString = (length: number, encoding?: SupportedEncodings): string => {\n return toString(randomBytes(length), encoding).slice(0, length)\n}\n\nexport const generateNonce = (length?: number): string => {\n return generateRandomString(length ?? NONCE_LENGTH)\n}\nexport const generateCodeVerifier = (length?: number): string => {\n const codeVerifier = generateRandomString(length ?? CODE_VERIFIER_DEFAULT_LENGTH, 'base64url')\n assertValidCodeVerifier(codeVerifier)\n return codeVerifier\n}\n\nexport const createCodeChallenge = (codeVerifier: string, codeChallengeMethod?: CodeChallengeMethod): string => {\n if (codeChallengeMethod === CodeChallengeMethod.plain) {\n return codeVerifier\n } else if (!codeChallengeMethod || codeChallengeMethod === CodeChallengeMethod.S256) {\n return toString(defaultHasher(codeVerifier, 'sha256'), 'base64url')\n } else {\n // Just a precaution if a new method would be introduced\n throw Error(`code challenge method ${codeChallengeMethod} not implemented`)\n }\n}\n\nexport const assertValidCodeVerifier = (codeVerifier: string) => {\n const length = codeVerifier.length\n if (length < 43) {\n throw Error(`code_verifier should have a minimum length of 43; see rfc7636`)\n } else if (length > 128) {\n throw Error(`code_verifier should have a maximum length of 128; see rfc7636`)\n }\n}\n","/**\n * Experimental support not following the VCI spec to have the holder actually (re)sign the issued credential and return it to the issuer\n */\n\nexport const EXPERIMENTAL_SUBJECT_PROOF_MODE_ENABLED = process.env.EXPERIMENTAL_SUBJECT_PROOF_MODE?.trim().toLowerCase() === 'true'\n\nexport type SubjectProofMode = 'proof_chain' | 'proof_set' | 'proof_replace'\n\nexport type SubjectProofNotificationEventsSupported = 'credential_accepted_holder_signed' | 'credential_deleted_holder_signed' | 'credential_accepted'\n\nexport interface ExperimentalSubjectIssuance {\n credential_subject_issuance?: {\n subject_proof_mode: SubjectProofMode\n notification_events_supported: Array<SubjectProofNotificationEventsSupported>\n }\n}\n","import { EventManager } from '@sphereon/ssi-types'\n\nexport type EventNames = CredentialOfferEventNames | NotificationStatusEventNames | LogEvents | CredentialEventNames\n\nexport enum CredentialOfferEventNames {\n OID4VCI_OFFER_CREATED = 'OID4VCI_OFFER_CREATED',\n OID4VCI_OFFER_EXPIRED = 'OID4VCI_OFFER_EXPIRED',\n OID4VCI_OFFER_DELETED = 'OID4VCI_OFFER_DELETED',\n}\n\nexport enum CredentialEventNames {\n OID4VCI_CREDENTIAL_ISSUED = 'OID4VCI_CREDENTIAL_ISSUED',\n}\n\nexport enum NotificationStatusEventNames {\n OID4VCI_NOTIFICATION_RECEIVED = 'OID4VCI_NOTIFICATION_RECEIVED',\n OID4VC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BE,MAAM;AACnF,WAAOjB,aAASkB,qCAAcP,cAAc,QAAA,GAAW,WAAA;EACzD,OAAO;AAEL,UAAMQ,MAAM,yBAAyBL,mBAAAA,kBAAqC;EAC5E;AACF,GATmC;AAW5B,IAAMF,0BAA0B,wBAACD,iBAAAA;AACtC,QAAMN,SAASM,aAAaN;AAC5B,MAAIA,SAAS,IAAI;AACf,UAAMc,MAAM,+DAA+D;EAC7E,WAAWd,SAAS,KAAK;AACvB,UAAMc,MAAM,gEAAgE;EAC9E;AACF,GAPuC;;;ACxCvC;AAIO,IAAMC,0CAA0CC,QAAQC,IAAIC,iCAAiCC,KAAAA,EAAOC,YAAAA,MAAkB;;;ACJ7H;IAAAC,oBAA6B;AAItB,IAAKC,4BAAAA,0BAAAA,4BAAAA;;;;SAAAA;;AAML,IAAKC,uBAAAA,0BAAAA,uBAAAA;;SAAAA;;AAIL,IAAKC,+BAAAA,0BAAAA,+BAAAA;;;;SAAAA;;AAML,IAAMC,SAASC,+BAAaC,SAAQ;;;A1BlBpC,IAAMC,cAAcC,0BAAQC;AAC5B,IAAMC,iBAAiBH,YAAYI,IAAI,yBAAA;","names":["module","randomBytes","import_ssi_types","supportedOID4VCICredentialFormat","PRE_AUTH_CODE_LITERAL","PRE_AUTH_GRANT_LITERAL","AuthorizationChallengeError","GrantTypes","Encoding","ResponseType","CodeChallengeMethod","PARMode","CreateRequestObjectMode","AuthzFlowType","valueOf","request","PRE_AUTH_CODE_LITERAL","JsonURIMode","Alg","credentialIssuerMetadataFieldNamesV1_0_15","authorizationServerMetadataFieldNames","WellKnownEndpoints","BAD_PARAMS","URL_NOT_VALID","JWS_NOT_VALID","PROOF_CANT_BE_CONSTRUCTED","NO_JWT_PROVIDED","TYP_ERROR","ALG_ERROR","Object","keys","Alg","join","KID_JWK_X5C_ERROR","KID_DID_NO_DID_ERROR","DID_NO_DIDDOC_ERROR","AUD_ERROR","IAT_ERROR","NONCE_ERROR","JWT_VERIFY_CONFIG_ERROR","ISSUER_CONFIG_ERROR","UNKNOWN_CLIENT_ERROR","NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT","ISS_PRESENT_IN_PRE_AUTHORIZED_CODE_CONTEXT","ISS_MUST_BE_CLIENT_ID","GRANTS_MUST_NOT_BE_UNDEFINED","STATE_MISSING_ERROR","CREDENTIAL_MISSING_ERROR","UNSUPPORTED_GRANT_TYPE_ERROR","PRE_AUTHORIZED_CODE_REQUIRED_ERROR","USER_PIN_REQUIRED_ERROR","USER_PIN_TX_CODE_SPEC_ERROR","USER_PIN_NOT_REQUIRED_ERROR","PIN_VALIDATION_ERROR","PIN_NOT_MATCH_ERROR","INVALID_PRE_AUTHORIZED_CODE","EXPIRED_PRE_AUTHORIZED_CODE","JWT_SIGNER_CALLBACK_REQUIRED_ERROR","STATE_MANAGER_REQUIRED_ERROR","NONCE_STATE_MANAGER_REQUIRED_ERROR","ACCESS_TOKEN_ISSUER_REQUIRED_ERROR","WRONG_METADATA_FORMAT","OpenId4VCIVersion","Number","MAX_VALUE","DefaultURISchemes","IssueStatus","TokenErrorResponse","TokenError","Error","_statusCode","_responseError","statusCode","responseError","message","Object","setPrototypeOf","prototype","getDescription","logger","Loggers","DEFAULT","get","getJson","URL","opts","openIdFetch","undefined","method","formPost","url","body","post","contentType","Encoding","FORM_URL_ENCODED","headers","customHeaders","bearerToken","dpop","accept","Error","payload","debug","JSON","stringify","origResponse","fetch","isJSONResponse","success","status","responseText","text","responseBody","includes","parse","exceptionOnHttpErrorStatus","error","successBody","errorBody","isValidURL","urlPattern","RegExp","test","trimBoth","value","trim","trimEnd","trimStart","endsWith","substring","length","startsWith","adjustUrl","urlOrPath","toString","append","prepend","host","path","pathname","stripSlashStart","stripSlashEnd","isDeferredCredentialResponse","credentialResponse","orig","successBody","origResponse","status","credentials","acceptance_token","transaction_id","assertNonFatalError","errorBody","error","includes","Error","isDeferredCredentialIssuancePending","error_description","toLowerCase","sleep","ms","Promise","resolve","setTimeout","acquireDeferredCredential","bearerToken","transactionId","deferredCredentialEndpoint","deferredCredentialIntervalInMS","deferredCredentialAwait","acquireDeferredCredentialImpl","DEFAULT_SLEEP_IN_MS","pending","console","log","reject","response","post","JSON","stringify","access_token","import_ssi_types","logger","Loggers","DEFAULT","get","determineSpecVersionFromURI","uri","version","determineSpecVersionFromScheme","OpenId4VCIVersion","VER_UNKNOWN","VER_1_0_15","credentialOfferURI","openId4VCIVersion","scheme","getScheme","url","toUrlWithDummyBase","qp","searchParams","DefaultURISchemes","INITIATE_ISSUANCE","has","recordVersion","CREDENTIAL_OFFER","rawParam","getParamValueLoose","decoded","tryDecodeOffer","sniffOfferVersion","normalized","replace","URL","key","input","candidate","decodeURIComponent","test","b64","padEnd","Math","ceil","length","atob","jsonLike","includes","Error","split","getIssuerFromCredentialOfferPayload","request","undefined","issuer","getClientIdFromCredentialOfferPayload","credentialOffer","client_id","state","getStateFromCredentialOfferPayload","isJWT","jwtDecode","header","noParts","startsWith","grants","authorization_code","issuer_state","PRE_AUTH_GRANT_LITERAL","PRE_AUTH_CODE_LITERAL","op_state","determineSpecVersionFromOffer","offer","isCredentialOfferV1_0_15","isCredentialOfferVersion","min","max","valueOf","debug","normalizeOfferInput","Array","isArray","credential_configuration_ids","toUniformCredentialOfferRequest","opts","originalCredentialOffer","credential_offer","credential_offer_uri","resolve","VCI_LOG_COMMON","log","resolveCredentialOfferURI","payload","toUniformCredentialOfferPayload","supportedFlows","determineFlowType","original_credential_offer","isPreAuthCode","assertedUniformCredentialOffer","origCredentialOffer","JSON","parse","stringify","response","getJson","successBody","errorBody","rawOffer","orig","suppliedOffer","getCredentialOfferPayload","push","AuthzFlowType","AUTHORIZATION_CODE_FLOW","PRE_AUTHORIZED_CODE_FLOW","determineGrantTypes","types","GrantTypes","AUTHORIZATION_CODE","PRE_AUTHORIZED_CODE","currentVersion","matchingVersion","allowUpgrade","sort","reverse","getCredentialConfigurationIdsFromOfferV1_0_15","ObjectUtils","isString","base64urlToString","convertJsonToURI","json","opts","JSON","parse","results","encodeAndStripWhitespace","key","encodeURIComponent","replace","components","mode","JsonURIMode","JSON_STRINGIFY","stringify","value","Object","entries","uriTypeProperties","includes","push","arrayTypeProperties","Array","isArray","map","v","customEncodeURIComponent","join","isBool","isNumber","isString","encoded","baseUrl","endsWith","param","Error","convertURIToJsonObject","uri","requiredProperties","every","p","BAD_PARAMS","uriComponents","getURIComponentsAsArray","decodeJsonProperties","parts","result","decodeURIComponent","isObject","decoded","startsWith","arrayTypes","split","dict","entry","pair","p0","p1","uriComponent","searchValue","c","charCodeAt","toString","toUpperCase","isW3cCredentialSupported","supported","includes","format","getNumberOrUndefined","input","isNaN","undefined","getTypesFromObject","subject","credential_definition","types","Array","isArray","type","vct","doctype","VCI_LOG_COMMON","warning","getTypesFromAuthorizationDetails","authDetails","opts","configIdAsType","credential_configuration_id","getTypesFromCredentialSupported","credentialSupported","length","Error","filterVerifiableCredential","filter","getSupportedCredentials","opts","version","OpenId4VCIVersion","VER_1_0_15","types","Array","isArray","map","typeSet","getSupportedCredential","reduce","acc","result","Object","assign","undefined","determineVersionsFromIssuerMetadata","issuerMetadata","versions","Set","add","size","VER_UNKNOWN","from","sort","reverse","format","credentialConfigurationsV15","credential_configurations_supported","credentials_supported","VCI_LOG_COMMON","warning","normalizedTypes","normalizedFormats","filterMatchingConfig","config","isTypeMatch","length","getTypesFromObject","id","every","type","includes","hasValidCredentialDefinition","isW3cCredentialSupported","credential_definition","credDef","isFormatMatch","entries","filteredConfigs","filter","getIssuerDisplays","metadata","matchedDisplays","display","item","prefLocales","locale","indexOf","Number","MAX_VALUE","getIssuerName","url","credentialIssuerMetadata","displays","name","isFormat","formatObject","format","isNotFormat","isUniformFormat","includes","getUniformFormat","toLocaleLowerCase","Error","getFormatForVersion","version","uniformFormat","import_ssi_types","import_jwt_decode","logger","Loggers","DEFAULT","get","createProofOfPossession","popMode","callbacks","jwtProps","existingJwt","signCallback","debug","Error","BAD_PARAMS","jwtPayload","createJWT","jwt","header","kid","proof","proof_type","partiallyValidateJWS","verifyCallback","JWS_NOT_VALID","jws","split","length","startsWith","isJWS","token","e","extractBearerToken","authorizationHeader","exec","undefined","validateJWT","opts","accessTokenVerificationCallback","VCI_LOG_COMMON","warning","jwtDecode","payload","mode","aud","getJwtProperty","issuer","iss","clientId","client_id","jti","typ","nonce","alg","jwk","x5c","now","Date","iat","Math","floor","exp","jwtHeader","propertyName","required","option","jwtProperty","defaultValue","Array","isArray","result","toAuthorizationResponsePayload","input","response","trim","startsWith","endsWith","JSON","parse","includes","convertURIToJsonObject","Error","import_oid4vc_common","toString","u8a","CODE_VERIFIER_DEFAULT_LENGTH","NONCE_LENGTH","generateRandomString","length","encoding","randomBytes","slice","generateNonce","generateCodeVerifier","codeVerifier","assertValidCodeVerifier","createCodeChallenge","codeChallengeMethod","CodeChallengeMethod","plain","S256","defaultHasher","Error","EXPERIMENTAL_SUBJECT_PROOF_MODE_ENABLED","process","env","EXPERIMENTAL_SUBJECT_PROOF_MODE","trim","toLowerCase","import_ssi_types","CredentialOfferEventNames","CredentialEventNames","NotificationStatusEventNames","EVENTS","EventManager","instance","VCI_LOGGERS","Loggers","DEFAULT","VCI_LOG_COMMON","get"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_@swc+core@1.14.0_postcss@8.5.6_tsx@4.20.6_typescript@5.8.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js","../lib/functions/randomBytes.cjs","../lib/index.ts","../lib/functions/index.ts","../lib/functions/CredentialRequestUtil.ts","../lib/functions/CredentialResponseUtil.ts","../lib/functions/HttpUtils.ts","../lib/types/index.ts","../lib/types/OpenIDClient.ts","../lib/types/Authorization.types.ts","../lib/types/Generic.types.ts","../lib/types/CredentialIssuance.types.ts","../lib/types/v1_0_15.types.ts","../lib/types/v1_0.types.ts","../lib/types/ServerMetadata.ts","../lib/types/OpenID4VCIErrors.ts","../lib/types/OpenID4VCIVersions.types.ts","../lib/types/StateManager.types.ts","../lib/types/Token.types.ts","../lib/types/QRCode.types.ts","../lib/functions/CredentialOfferUtil.ts","../lib/functions/Encoding.ts","../lib/functions/TypeConversionUtils.ts","../lib/functions/IssuerMetadataUtils.ts","../lib/functions/FormatUtils.ts","../lib/functions/ProofUtil.ts","../lib/functions/AuthorizationResponseUtil.ts","../lib/functions/RandomUtils.ts","../lib/functions/SignedMetadataUtils.ts","../lib/experimental/holder-vci.ts","../lib/events/index.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nconst MAX_BYTES = 65536\n\n// Node supports requesting up to this number of bytes\n// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48\nconst MAX_UINT32 = 4294967295\n\nfunction oldBrowser() {\n throw new Error('Secure random number generation is not supported by this browser.\\nUse Chrome, Firefox or Internet Explorer 11')\n}\n\n// eslint-disable-next-line no-undef\nconst _global = typeof globalThis !== 'undefined' ? globalThis : global\n\nlet crypto = _global.crypto || _global.msCrypto\nif (!crypto) {\n try {\n // eslint-disable-next-line no-undef\n crypto = require('crypto')\n } catch (err) {\n throw Error('crypto module is not available')\n }\n}\n\nfunction randomBytes(size) {\n // phantomjs needs to throw\n if (size > MAX_UINT32) throw new Error('requested too many random bytes')\n\n // eslint-disable-next-line no-undef\n const bytes = Buffer.allocUnsafe(size)\n\n if (size > 0) {\n // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) {\n // this is the max bytes crypto.getRandomValues\n // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues\n for (let generated = 0; generated < size; generated += MAX_BYTES) {\n // buffer.slice automatically checks if the end is past the end of\n // the buffer so we don't have to here\n crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n return Uint8Array.from(bytes)\n}\n\n// eslint-disable-next-line no-undef\nmodule.exports = randomBytes\n","import { Loggers } from '@sphereon/ssi-types'\n\nexport const VCI_LOGGERS = Loggers.DEFAULT\nexport const VCI_LOG_COMMON = VCI_LOGGERS.get('sphereon:oid4vci:common')\n\nexport * from './functions'\nexport * from './types'\nexport * from './experimental/holder-vci'\nexport * from './events'\n","export * from './CredentialRequestUtil'\nexport * from './CredentialResponseUtil'\nexport * from './CredentialOfferUtil'\nexport * from './Encoding'\nexport * from './TypeConversionUtils'\nexport * from './IssuerMetadataUtils'\nexport * from './FormatUtils'\nexport * from './HttpUtils'\nexport * from './ProofUtil'\nexport * from './AuthorizationResponseUtil'\nexport * from './RandomUtils'\nexport * from './SignedMetadataUtils'\n","//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","import { CredentialResponse, OpenIDResponse } from '../types'\n\nimport { post } from './HttpUtils'\n\nexport function isDeferredCredentialResponse(credentialResponse: OpenIDResponse<CredentialResponse>) {\n const orig = credentialResponse.successBody\n // Specs mention 202, but some implementations like EBSI return 200\n // Check for both d15 (credentials array) and 1.0 final (singular credential) absence\n const hasNoCredential = !orig?.credentials && !orig?.credential\n return credentialResponse.origResponse.status % 200 <= 2 && !!orig && hasNoCredential && (!!orig.acceptance_token || !!orig.transaction_id)\n}\nfunction assertNonFatalError(credentialResponse: OpenIDResponse<CredentialResponse>) {\n if (credentialResponse.origResponse.status === 400 && credentialResponse.errorBody?.error) {\n if (credentialResponse.errorBody.error === 'invalid_transaction_id' || credentialResponse.errorBody.error.includes('acceptance_token')) {\n throw Error('Invalid transaction id. Probably the deferred credential request expired')\n }\n }\n}\n\nexport function isDeferredCredentialIssuancePending(credentialResponse: OpenIDResponse<CredentialResponse>) {\n if (isDeferredCredentialResponse(credentialResponse)) {\n return credentialResponse?.successBody?.transaction_id ?? !!credentialResponse?.successBody?.acceptance_token\n }\n if (credentialResponse.origResponse.status === 400 && credentialResponse.errorBody?.error) {\n if (credentialResponse.errorBody.error === 'issuance_pending') {\n return true\n } else if (credentialResponse.errorBody.error_description?.toLowerCase().includes('not available yet')) {\n return true\n }\n }\n return false\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n}\n\nexport async function acquireDeferredCredential({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n deferredCredentialIntervalInMS,\n deferredCredentialAwait,\n}: {\n bearerToken: string\n transactionId?: string\n deferredCredentialIntervalInMS?: number\n deferredCredentialAwait?: boolean\n deferredCredentialEndpoint: string\n}): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n let credentialResponse: OpenIDResponse<CredentialResponse> & { access_token: string } = await acquireDeferredCredentialImpl({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n })\n\n const DEFAULT_SLEEP_IN_MS = 5000\n while (!credentialResponse.successBody?.credentials && !credentialResponse.successBody?.credential && deferredCredentialAwait) {\n assertNonFatalError(credentialResponse)\n const pending = isDeferredCredentialIssuancePending(credentialResponse)\n console.log(`Issuance still pending?: ${pending}`)\n if (!pending) {\n return Promise.reject(Error(`Issuance isn't pending anymore: ${credentialResponse}`))\n }\n\n await sleep(deferredCredentialIntervalInMS ?? DEFAULT_SLEEP_IN_MS)\n credentialResponse = await acquireDeferredCredentialImpl({ bearerToken, transactionId, deferredCredentialEndpoint })\n }\n return credentialResponse\n}\n\nasync function acquireDeferredCredentialImpl({\n bearerToken,\n transactionId,\n deferredCredentialEndpoint,\n}: {\n bearerToken: string\n transactionId?: string\n deferredCredentialEndpoint: string\n}): Promise<OpenIDResponse<CredentialResponse> & { access_token: string }> {\n const response: OpenIDResponse<CredentialResponse> = await post(\n deferredCredentialEndpoint,\n JSON.stringify(transactionId ? { transaction_id: transactionId } : ''),\n { bearerToken },\n )\n console.log(JSON.stringify(response, null, 2))\n assertNonFatalError(response)\n\n return { ...response, access_token: bearerToken }\n}\n","import { Loggers } from '@sphereon/ssi-types'\nimport fetch from 'cross-fetch'\n\nimport { Encoding, OpenIDResponse } from '../types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:openid4vci:http')\n\nexport const getJson = async <T>(\n URL: string,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await openIdFetch(URL, undefined, { method: 'GET', ...opts })\n}\n\nexport const formPost = async <T>(\n url: string,\n body: BodyInit,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await post(url, body, opts?.contentType ? { ...opts } : { contentType: Encoding.FORM_URL_ENCODED, ...opts })\n}\n\nexport const post = async <T>(\n url: string,\n body?: BodyInit,\n opts?: {\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n return await openIdFetch(url, body, { method: 'POST', ...opts })\n}\n\nconst openIdFetch = async <T>(\n url: string,\n body?: BodyInit,\n opts?: {\n method?: string\n bearerToken?: (() => Promise<string>) | string\n contentType?: string\n accept?: string\n customHeaders?: Record<string, string>\n exceptionOnHttpErrorStatus?: boolean\n },\n): Promise<OpenIDResponse<T>> => {\n const headers: Record<string, string> = opts?.customHeaders ?? {}\n if (opts?.bearerToken) {\n headers['Authorization'] =\n `${headers.dpop ? 'DPoP' : 'Bearer'} ${typeof opts.bearerToken === 'function' ? await opts.bearerToken() : opts.bearerToken}`\n }\n const method = opts?.method ? opts.method : body ? 'POST' : 'GET'\n const accept = opts?.accept ? opts.accept : 'application/json'\n headers['Accept'] = accept\n if (headers['Content-Type']) {\n if (opts?.contentType && opts.contentType !== headers['Content-Type']) {\n throw Error(`Mismatch in content-types from custom headers (${headers['Content-Type']}) and supplied content type option (${opts.contentType})`)\n }\n } else {\n if (opts?.contentType) {\n headers['Content-Type'] = opts.contentType\n } else if (method !== 'GET') {\n headers['Content-Type'] = 'application/json'\n }\n }\n\n const payload: RequestInit = {\n method,\n headers,\n body,\n }\n\n logger.debug(`START fetching url: ${url}`)\n if (body) {\n logger.debug(`Body:\\r\\n${typeof body == 'string' ? body : JSON.stringify(body)}`)\n }\n logger.debug(`Headers:\\r\\n${JSON.stringify(payload.headers)}`)\n const origResponse = await fetch(url, payload)\n const isJSONResponse = accept === 'application/json' || origResponse.headers.get('Content-Type') === 'application/json'\n const success = origResponse && origResponse.status >= 200 && origResponse.status < 400\n const responseText = await origResponse.text()\n const responseBody = isJSONResponse && responseText.includes('{') ? JSON.parse(responseText) : responseText\n\n logger.debug(`${success ? 'success' : 'error'} status: ${origResponse.status}, body:\\r\\n${JSON.stringify(responseBody)}`)\n if (!success && opts?.exceptionOnHttpErrorStatus) {\n const error = JSON.stringify(responseBody)\n throw new Error(error === '{}' ? '{\"error\": \"not found\"}' : error)\n }\n logger.debug(`END fetching url: ${url}`)\n\n return {\n origResponse,\n successBody: success ? responseBody : undefined,\n errorBody: !success ? responseBody : undefined,\n }\n}\n\nexport const isValidURL = (url: string): boolean => {\n const urlPattern = new RegExp(\n '^(https?:\\\\/\\\\/)' + // validate protocol\n '((([a-z\\\\d]([a-z\\\\d-]*[a-z\\\\d])*)\\\\.)+[a-z]{2,}|' + // validate domain name\n '((localhost))|' + // validate OR localhost\n '((\\\\d{1,3}\\\\.){3}\\\\d{1,3}))' + // validate OR ip (v4) address\n '(\\\\:\\\\d+)?(\\\\/[-a-z\\\\d%_.~+:]*)*' + // validate port and path\n '(\\\\?[;&a-z\\\\d%_.~+=-]*)?' + // validate query string\n '(\\\\#[-a-z\\\\d_]*)?$', // validate fragment locator\n 'i',\n )\n return urlPattern.test(url)\n}\n\nexport const trimBoth = (value: string, trim: string): string => {\n return trimEnd(trimStart(value, trim), trim)\n}\n\nexport const trimEnd = (value: string, trim: string): string => {\n return value.endsWith(trim) ? value.substring(0, value.length - trim.length) : value\n}\n\nexport const trimStart = (value: string, trim: string): string => {\n return value.startsWith(trim) ? value.substring(trim.length) : value\n}\n\nexport const adjustUrl = <T extends string | URL>(\n urlOrPath: T,\n opts?: {\n stripSlashEnd?: boolean\n stripSlashStart?: boolean\n prepend?: string\n append?: string\n },\n): T => {\n let url = typeof urlOrPath === 'object' ? urlOrPath.toString() : (urlOrPath as string)\n if (opts?.append) {\n url = trimEnd(url, '/') + '/' + trimStart(opts.append, '/')\n }\n if (opts?.prepend) {\n if (opts.prepend.includes('://')) {\n // includes domain/hostname\n if (!url.startsWith(opts.prepend)) {\n url = trimEnd(opts.prepend, '/') + '/' + trimStart(url, '/')\n }\n } else {\n // path only for prepend\n let host = ''\n let path = url\n if (url.includes('://')) {\n // includes domain/hostname\n host = new URL(url).host\n path = new URL(url).pathname\n }\n if (!path.startsWith(opts.prepend)) {\n if (host && host !== '') {\n url = trimEnd(host, '/')\n }\n url += trimEnd(url, '/') + '/' + trimBoth(opts.prepend, '/') + '/' + trimStart(path, '/')\n }\n }\n }\n if (opts?.stripSlashStart) {\n url = trimStart(url, '/')\n }\n if (opts?.stripSlashEnd) {\n url = trimEnd(url, '/')\n }\n\n if (typeof urlOrPath === 'string') {\n return url as T\n }\n return new URL(url) as T\n}\n","export * from './OpenIDClient'\nexport * from './Authorization.types'\nexport * from './CredentialIssuance.types'\nexport * from './Generic.types'\nexport * from './v1_0_15.types'\nexport * from './v1_0.types'\nexport * from './ServerMetadata'\nexport * from './OpenID4VCIErrors'\nexport * from './OpenID4VCIVersions.types'\nexport * from './StateManager.types'\nexport * from './Token.types'\nexport * from './QRCode.types'\n","/**\n * Copied from openid-client\n */\nexport type ClientResponseType = 'code' | 'id_token' | 'code id_token' | 'none' | string\nexport type ClientAuthMethod =\n | 'client_secret_basic'\n | 'client_secret_post'\n | 'client_secret_jwt'\n | 'private_key_jwt'\n | 'tls_client_auth'\n | 'self_signed_tls_client_auth'\n | 'none'\nexport interface ClientMetadata {\n // important\n client_id: string\n id_token_signed_response_alg?: string\n token_endpoint_auth_method?: ClientAuthMethod\n client_secret?: string\n redirect_uris?: string[]\n response_types?: ClientResponseType[]\n post_logout_redirect_uris?: string[]\n default_max_age?: number\n require_auth_time?: boolean\n tls_client_certificate_bound_access_tokens?: boolean\n request_object_signing_alg?: string\n\n // less important\n id_token_encrypted_response_alg?: string\n id_token_encrypted_response_enc?: string\n introspection_endpoint_auth_method?: ClientAuthMethod\n introspection_endpoint_auth_signing_alg?: string\n request_object_encryption_alg?: string\n request_object_encryption_enc?: string\n revocation_endpoint_auth_method?: ClientAuthMethod\n revocation_endpoint_auth_signing_alg?: string\n token_endpoint_auth_signing_alg?: string\n userinfo_encrypted_response_alg?: string\n userinfo_encrypted_response_enc?: string\n userinfo_signed_response_alg?: string\n authorization_encrypted_response_alg?: string\n authorization_encrypted_response_enc?: string\n authorization_signed_response_alg?: string\n\n [key: string]: unknown\n}\n","import { CreateDPoPClientOpts } from '@sphereon/oid4vc-common'\n\nimport { Alg, CredentialOfferPayload, ProofOfPossessionCallbacks, UniformCredentialOffer } from './CredentialIssuance.types'\nimport {\n ErrorResponse,\n IssuerCredentialSubject,\n JsonLdIssuerCredentialDefinition,\n OID4VCICredentialFormat,\n PRE_AUTH_CODE_LITERAL,\n TxCode,\n} from './Generic.types'\nimport { EndpointMetadata } from './ServerMetadata'\nimport { AuthorizationDetailsV1_0_15 } from './v1_0_15.types'\n\nexport interface CommonAuthorizationRequest {\n /**\n * REQUIRED. Value MUST be set to \"code\". for Authorization Code Grant\n */\n response_type: ResponseType.AUTH_CODE\n /**\n * The authorization server issues the registered client a client\n * identifier -- a unique string representing the registration\n * information provided by the client.\n */\n client_id: string\n /**\n * If the \"code_challenge_method\" from Section 4.3 was \"S256\", the\n * received \"code_verifier\" is hashed by SHA-256, base64url-encoded, and\n * then compared to the \"code_challenge\", i.e.:\n * BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge\n *\n * If the \"code_challenge_method\" from Section 4.3 was \"plain\", they are\n * compared directly, i.e.:\n * code_verifier == code_challenge.\n */\n code_challenge: string\n /**\n * value must be set either to \"S256\" or a value defined by a cryptographically secure\n */\n code_challenge_method: CodeChallengeMethod\n /**\n * The redirection endpoint URI MUST be an absolute URI as defined by: absolute-URI = scheme \":\" hier-part [ \"?\" query ]\n */\n redirect_uri: string\n /**\n * The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings.\n */\n scope?: string\n /**\n * There are two possible ways to request issuance of a specific Credential type in an Authorization Request.\n * One way is to use of the authorization_details request parameter as defined in [I-D.ietf-oauth-rar]\n * with one or more authorization details objects of type openid_credential Section 5.1.1.\n * (The other is through the use of scopes as defined in Section 5.1.2.)\n */\n authorization_details?: AuthorizationDetailsV1_0_15[] | AuthorizationDetailsV1_0_15\n /**\n * OPTIONAL. JSON string containing the Wallet's OpenID Connect issuer URL. The Credential Issuer will use the discovery process as defined in\n * [SIOPv2] to determine the Wallet's capabilities and endpoints. RECOMMENDED in Dynamic Credential Request.\n */\n wallet_issuer?: string\n /**\n * OPTIONAL. JSON string containing an opaque user hint the Wallet MAY use in subsequent callbacks to optimize the user's experience.\n * RECOMMENDED in Dynamic Credential Request.\n */\n user_hint?: string\n /**\n * OPTIONAL. String value identifying a certain processing context at the Credential Issuer. A value for this parameter is typically passed in\n * an issuance initation request from the Credential Issuer to the Wallet (see (Section 4.1). This request parameter is used to pass the\n * issuer_state value back to the Credential Issuer.\n */\n issuer_state?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-req\nexport interface CommonAuthorizationChallengeRequest {\n /**\n * REQUIRED if the client is not authenticating with the authorization server and if no auth_session is included..\n */\n client_id?: string\n /**\n * OPTIONAL. String value identifying a certain processing context at the Credential Issuer. A value for this parameter is typically passed in\n * an issuance initation request from the Credential Issuer to the Wallet. This request parameter is used to pass the\n * issuer_state value back to the Credential Issuer.\n */\n issuer_state?: string\n /**\n * The value of the scope parameter is expressed as a list of space-delimited, case-sensitive strings.\n */\n scope?: string // TODO what we do with this\n /**\n * OPTIONAL. A random string or a JWE. The auth session allows the authorization server to associate subsequent\n * requests by this client with an ongoing authorization request sequence. The client MUST include the\n * auth_session in follow-up requests to the authorization challenge endpoint if it receives one along with\n * the error response.\n */\n auth_session?: string\n /**\n * OPTIONAL. If the \"code_challenge_method\" from Section 4.3 was \"S256\", the\n * received \"code_verifier\" is hashed by SHA-256, base64url-encoded, and\n * then compared to the \"code_challenge\", i.e.:\n * BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) == code_challenge\n *\n * If the \"code_challenge_method\" from Section 4.3 was \"plain\", they are\n * compared directly, i.e.:\n * code_verifier == code_challenge.\n */\n code_challenge?: string // TODO what we do with this\n /**\n * OPTIONAL. value must be set either to \"S256\" or a value defined by a cryptographically secure\n */\n code_challenge_method?: CodeChallengeMethod // TODO what we do with this\n /**\n * OPTIONAL. String containing information about the session when credential presentation is happening during issuance of another\n * credential. The content of this parameter is opaque to the wallet. When this parameter is present the Wallet MUST use this parameter in\n * the subsequent Authorization Challenge Request. This allows the Issuer to determine which it can be used by to prevent session\n * fixation attacks. The Response URI MAY return this parameter in response to successful Authorization Responses or for Error\n * Responses.\n */\n presentation_during_issuance_session?: string\n}\n\nexport interface AuthorizationChallengeRequestOpts {\n clientId?: string\n issuerState?: string\n authSession?: string\n scope?: string\n codeChallenge?: string\n codeChallengeMethod?: CodeChallengeMethod\n presentationDuringIssuanceSession?: string\n metadata?: EndpointMetadata\n credentialIssuer?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-error-response\nexport interface AuthorizationChallengeErrorResponse {\n /**\n * A single ASCII error code of type AuthorizationChallengeError.\n */\n error: AuthorizationChallengeError\n /**\n * OPTIONAL. OPTIONAL. Human-readable ASCII text providing additional information, used\n * to assist the client developer in understanding the error that occurred. Values for the error_description\n * parameter MUST NOT include characters outside the set %x20-21 / %x23-5B / %x5D-7E.\n */\n error_description?: string\n /**\n * OPTIONAL. A URI identifying a human-readable web page with information about the error, used\n * to provide the client developer with additional information about the error. Values for the error_uri\n * parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside the\n * set %x21 / %x23-5B / %x5D-7E.\n */\n error_uri?: string\n /**\n * OPTIONAL. A random string or a JWE. The auth session allows the authorization server to associate subsequent\n * requests by this client with an ongoing authorization request sequence. The client MUST include the\n * auth_session in follow-up requests to the authorization challenge endpoint if it receives one along with\n * the error response.\n */\n auth_session?: string\n /**\n * OPTIONAL. The request URI corresponding to the authorization request posted. This URI is a single-use reference\n * to the respective request data in the subsequent authorization request.\n */\n request_uri?: string\n /**\n * OPTIONAL. A JSON number that represents the lifetime of the request URI in seconds as a positive integer.\n */\n expires_in?: number\n /**\n * String containing the OID4VP request URI. The Wallet will use this URI to start the OID4VP flow.\n */\n presentation?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-res\nexport interface AuthorizationChallengeCodeResponse {\n /**\n * The authorization code issued by the authorization server.\n */\n authorization_code: string\n state?: string\n}\n\n// https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-error-response\nexport enum AuthorizationChallengeError {\n invalid_request = 'invalid_request',\n invalid_client = 'invalid_client',\n unauthorized_client = 'unauthorized_client',\n invalid_session = 'invalid_session',\n invalid_scope = 'invalid_scope',\n insufficient_authorization = 'insufficient_authorization',\n redirect_to_web = 'redirect_to_web',\n}\n\n/**\n * string type added for conformity with our previous code in the client\n */\nexport type credential_identifiers =\n | (CommonAuthorizationDetails &\n (AuthorizationDetailsJwtVcJson | AuthorizationDetailsJwtVcJsonLdAndLdpVc | AuthorizationDetailsSdJwtVc | AuthorizationDetailsMsoMdoc))\n | string\n\nexport type AuthorizationRequest =\n | AuthorizationRequestJwtVcJson\n | AuthorizationRequestJwtVcJsonLdAndLdpVc\n | AuthorizationRequestSdJwtVc\n | AuthorizationRequestMsoMdoc\n\nexport interface AuthorizationRequestJwtVcJson extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsJwtVcJson[]\n}\n\nexport interface AuthorizationRequestJwtVcJsonLdAndLdpVc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsJwtVcJsonLdAndLdpVc[]\n}\n\nexport interface AuthorizationRequestSdJwtVc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsSdJwtVc[]\n}\n\nexport interface AuthorizationRequestMsoMdoc extends CommonAuthorizationRequest {\n authorization_details?: AuthorizationDetailsMsoMdoc[]\n}\n\n/*\nexport interface AuthDetails {\n type: 'openid_credential' | string;\n locations?: string | string[];\n format: CredentialFormat | CredentialFormat[];\n\n [s: string]: unknown;\n}\n*/\n\nexport interface CommonAuthorizationDetails {\n /**\n * REQUIRED. JSON string that determines the authorization details type.\n * MUST be set to openid_credential for the purpose of this specification.\n */\n type: 'openid_credential'\n\n /**\n * REQUIRED when format parameter is not present. String specifying a unique identifier of the Credential being described in the credential_configurations_supported map in the Credential Issuer Metadata as defined in Section 11.2.3. The referenced object in the credential_configurations_supported map conveys the details, such as the format, for issuance of the requested Credential. This specification defines Credential Format specific Issuer Metadata in Appendix A. It MUST NOT be present if format parameter is present.\n */\n credential_configuration_id?: string // FIXME maybe split up and make this & format required again\n\n /**\n * REQUIRED. JSON string representing the format in which the Credential is requested to be issued.\n * This Credential format identifier determines further claims in the authorization details object\n * specifically used to identify the Credential type to be issued. This specification defines\n * Credential Format Profiles in Appendix E.\n */\n format?: OID4VCICredentialFormat\n /**\n * If the Credential Issuer metadata contains an authorization_server parameter,\n * the authorization detail's locations common data field MUST be set to the Credential Issuer Identifier value.\n */\n locations?: string[]\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [key: string]: any\n}\n\nexport interface AuthorizationDetailsJwtVcJson extends CommonAuthorizationDetails {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc added for backward compat\n\n /**\n * A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential.\n * The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the\n * verifiable credential to be issued. This object indicates the claims the Wallet would like to turn up in the\n * credential to be issued.\n */\n credentialSubject?: IssuerCredentialSubject\n\n types: string[] // This claim contains the type values the Wallet requests authorization for at the issuer.\n}\n\nexport interface AuthorizationDetailsJwtVcJsonLdAndLdpVc extends CommonAuthorizationDetails {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n\n /**\n * REQUIRED. JSON object containing (and isolating) the detailed description of the credential type.\n * This object MUST be processed using full JSON-LD processing. It consists of the following sub-claims:\n * - @context: REQUIRED. JSON array as defined in Appendix E.1.3.2\n * - types: REQUIRED. JSON array as defined in Appendix E.1.3.2.\n * This claim contains the type values the Wallet shall request in the subsequent Credential Request\n */\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface AuthorizationDetailsSdJwtVc extends CommonAuthorizationDetails {\n format: 'dc+sd-jwt' | 'vc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface AuthorizationDetailsMsoMdoc extends CommonAuthorizationDetails {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport enum GrantTypes {\n AUTHORIZATION_CODE = 'authorization_code',\n PRE_AUTHORIZED_CODE = 'urn:ietf:params:oauth:grant-type:pre-authorized_code',\n PASSWORD = 'password',\n}\n\nexport enum Encoding {\n FORM_URL_ENCODED = 'application/x-www-form-urlencoded',\n UTF_8 = 'UTF-8',\n}\n\nexport enum ResponseType {\n AUTH_CODE = 'code',\n}\n\nexport enum CodeChallengeMethod {\n plain = 'plain',\n S256 = 'S256',\n}\n\nexport interface AuthorizationServerOpts {\n allowInsecureEndpoints?: boolean\n as?: string // If not provided the issuer hostname will be used!\n tokenEndpoint?: string // Allows to override the default '/token' endpoint\n clientOpts?: AuthorizationServerClientOpts\n}\n\nexport type AuthorizationServerClientOpts = {\n clientId: string\n clientAssertionType?: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n kid?: string\n alg?: Alg\n signCallbacks?: ProofOfPossessionCallbacks\n}\n\nexport interface IssuerOpts {\n issuer: string\n tokenEndpoint?: string\n fetchMetadata?: boolean\n}\n\nexport interface AccessTokenFromAuthorizationResponseOpts extends AccessTokenRequestOpts {\n authorizationResponse: AuthorizationResponse\n}\n\nexport type TxCodeAndPinRequired = { isPinRequired?: boolean; txCode?: TxCode }\n\nexport interface AccessTokenRequestOpts {\n credentialOffer?: UniformCredentialOffer\n credentialIssuer?: string\n asOpts?: AuthorizationServerOpts\n metadata?: EndpointMetadata\n codeVerifier?: string // only required for authorization flow\n code?: string // only required for authorization flow\n redirectUri?: string // only required for authorization flow\n pin?: string // Pin-number. Only used when required\n pinMetadata?: TxCodeAndPinRequired // OPTIONAL. String value containing a Transaction Code. This value MUST be present if a tx_code object was present in the Credential Offer (including if the object was empty). This parameter MUST only be used if the grant_type is urn:ietf:params:oauth:grant-type:pre-authorized_code.\n // if the CreateDPoPOpts are provided, a dPoP will be created using the provided callback,\n // if the authorization server indicates that it supports dPoP via the dpop_signing_alg_values_supported parameter.\n createDPoPOpts?: CreateDPoPClientOpts\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n additionalParams?: Record<string, any>\n}\n\n/*export interface AuthorizationRequestOpts {\n clientId: string;\n codeChallenge: string;\n codeChallengeMethod: CodeChallengeMethod;\n authorizationDetails?: AuthorizationDetails[];\n redirectUri: string;\n scope?: string;\n}*/\n\n/**\n * Determinse whether PAR should be used when supported\n *\n * REQUIRE: Require PAR, if AS does not support it throw an error\n * AUTO: Use PAR is the AS supports it, otherwise construct a reqular URI,\n * NEVER: Do not use PAR even if the AS supports it (not recommended)\n */\nexport enum PARMode {\n REQUIRE,\n AUTO,\n NEVER,\n}\n\n/**\n * Optional options to provide PKCE params like code verifier and challenge yourself, or to disable PKCE altogether. If not provide PKCE will still be used! If individual params are not provide, they will be generated/calculated\n */\nexport interface PKCEOpts {\n /**\n * PKCE is enabled by default even if you do not provide these options. Set this to true to disable PKCE\n */\n disabled?: boolean\n\n /**\n * Provide a code_challenge, otherwise it will be calculated using the code_verifier and method\n */\n codeChallenge?: string\n\n /**\n * The code_challenge_method, should always by S256\n */\n codeChallengeMethod?: CodeChallengeMethod\n\n /**\n * Provide a code_verifier, otherwise it will be generated\n */\n codeVerifier?: string\n}\n\nexport enum CreateRequestObjectMode {\n NONE,\n REQUEST_OBJECT,\n REQUEST_URI,\n}\n\nexport type RequestObjectOpts = {\n requestObjectMode?: CreateRequestObjectMode\n signCallbacks?: ProofOfPossessionCallbacks\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n clientMetadata?: Record<string, any> // TODO: Merge SIOP/OID4VP\n iss?: string\n jwksUri?: string\n kid?: string\n}\n\nexport interface AuthorizationRequestOpts {\n clientId?: string\n pkce?: PKCEOpts\n parMode?: PARMode\n authorizationDetails?: AuthorizationDetailsV1_0_15 | AuthorizationDetailsV1_0_15[]\n redirectUri?: string\n scope?: string\n requestObjectOpts?: RequestObjectOpts\n holderPreferredAuthzFlowTypeOrder?: AuthzFlowType[]\n}\n\nexport interface AuthorizationResponse {\n code: string\n scope?: string\n state?: string\n}\n\nexport interface AuthorizationGrantResponse extends AuthorizationResponse {\n grant_type: string\n}\n\nexport interface AccessTokenRequest {\n client_id?: string\n code?: string\n code_verifier?: string\n grant_type: GrantTypes\n 'pre-authorized_code': string\n redirect_uri?: string\n scope?: string\n user_pin?: string //this is for v11, not required in v13 anymore\n tx_code?: string //draft 13\n [s: string]: unknown\n}\n\nexport interface OpenIDResponse<T, P = never> {\n origResponse: Response\n successBody?: T\n errorBody?: ErrorResponse\n params?: P\n}\n\nexport interface DPoPResponseParams {\n dpop?: { dpopNonce: string }\n}\n\nexport interface AccessTokenResponse {\n access_token: string\n scope?: string\n token_type?: string\n expires_in?: number // in seconds\n c_nonce?: string\n c_nonce_expires_in?: number // in seconds\n authorization_pending?: boolean\n interval?: number // in seconds\n authorization_details?: AuthorizationDetailsV1_0_15[]\n}\n\nexport enum AuthzFlowType {\n AUTHORIZATION_CODE_FLOW = 'Authorization Code Flow',\n PRE_AUTHORIZED_CODE_FLOW = 'Pre-Authorized Code Flow',\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace AuthzFlowType {\n export function valueOf(request: CredentialOfferPayload): AuthzFlowType {\n if (PRE_AUTH_CODE_LITERAL in request) {\n return AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW\n }\n return AuthzFlowType.AUTHORIZATION_CODE_FLOW\n }\n}\n\nexport interface PushedAuthorizationResponse {\n request_uri: string\n expires_in: number\n}\n","import { ICredentialContextType, IVerifiableCredential, W3CVerifiableCredential } from '@sphereon/ssi-types'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { ProofOfPossession } from './CredentialIssuance.types'\nimport { AuthorizationServerMetadata } from './ServerMetadata'\nimport { CredentialOfferSession } from './StateManager.types'\nimport {\n AuthorizationDetailsV1_0_15,\n CredentialConfigurationSupportedV1_0_15,\n CredentialRequestV1_0_15,\n EndpointMetadataResultV1_0_15,\n IssuerMetadataV1_0_15,\n} from './v1_0_15.types'\nimport {\n AuthorizationDetailsV1_0,\n CredentialConfigurationSupportedV1_0,\n CredentialRequestV1_0,\n EndpointMetadataResultV1_0,\n IssuerMetadataV1_0,\n} from './v1_0.types'\n\nexport type InputCharSet = 'numeric' | 'text'\nexport type KeyProofType = 'jwt' | 'cwt' | 'ldp_vp' | 'di_vp'\n\nexport type PoPMode = 'pop' | 'JWT' // Proof of possession, or regular JWT\n\nexport type CredentialOfferMode = 'VALUE' | 'REFERENCE'\n\n/**\n * Important Note: please be aware that these Common interfaces are based on versions v1_0.11 and v1_0.09\n */\nexport interface ImageInfo {\n uri?: string\n alt_text?: string\n\n [key: string]: unknown\n}\n\nexport type OID4VCICredentialFormat = 'jwt_vc_json' | 'jwt_vc_json-ld' | 'ldp_vc' | 'dc+sd-jwt' | 'vc+sd-jwt' | 'jwt_vc' | 'mso_mdoc' // jwt_vc & vc+sd-jwt are added for backwards compat TODO SSISDK-36\n\nexport const supportedOID4VCICredentialFormat: readonly (OID4VCICredentialFormat | string)[] = [\n 'jwt_vc_json',\n 'jwt_vc_json-ld',\n 'ldp_vc',\n 'dc+sd-jwt',\n 'jwt_vc',\n 'mso_mdoc',\n]\n\nexport interface NameAndLocale {\n name?: string // REQUIRED. String value of a display name for the Credential.\n locale?: string // OPTIONAL. String value that identifies the language of this object represented as a language tag taken from values defined in BCP47 [RFC5646]. Multiple display objects MAY be included for separate languages. There MUST be only one object with the same language identifier.\n [key: string]: unknown\n}\n\nexport interface LogoAndColor {\n logo?: ImageInfo // OPTIONAL. A JSON object with information about the logo of the Credential with a following non-exhaustive list of parameters that MAY be included:\n description?: string // OPTIONAL. String value of a description of the Credential.\n background_color?: string //OPTIONAL. String value of a background color of the Credential represented as numerical color values defined in CSS Color Module Level 37 [CSS-Color].\n text_color?: string // OPTIONAL. String value of a text color of the Credential represented as numerical color values defined in CSS Color Module Level 37 [CSS-Color].\n}\n\nexport type CredentialsSupportedDisplay = NameAndLocale &\n LogoAndColor & {\n name: string // REQUIRED. String value of a display name for the Credential.\n background_image?: ImageInfo //OPTIONAL, NON-SPEC compliant!. URL of a background image useful for card views of credentials. Expected to an image that fills the full card-view of a wallet\n }\n\nexport type MetadataDisplay = NameAndLocale &\n LogoAndColor & {\n name?: string //OPTIONAL. String value of a display name for the Credential Issuer.\n }\n\nexport interface CredentialSupplierConfig {\n [key: string]: any // This allows additional properties for credential suppliers\n}\n\nexport interface CredentialIssuerMetadataOpts {\n credential_endpoint?: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n batch_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Batch Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. If omitted, the Credential Issuer does not support the Batch Credential Endpoint.\n credentials_supported: CredentialsSupportedLegacy[] // REQUIRED in versions below 13. A JSON array containing a list of JSON objects, each of them representing metadata about a separate credential type that the Credential Issuer can issue. The JSON objects in the array MUST conform to the structure of the Section 10.2.3.1.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n authorization_server?: string // OPTIONAL. Identifier of the OAuth 2.0 Authorization Server (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n token_endpoint?: string\n notification_endpoint?: string\n authorization_challenge_endpoint?: string // OPTIONAL URL of the Credential Issuer's Authorization Challenge Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. Described on https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-end\n display?: MetadataDisplay[] // An array of objects, where each object contains display properties of a Credential Issuer for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n credential_supplier_config?: CredentialSupplierConfig\n}\n\n//todo: investigate if these values are enough.\nexport type AlgValue = 'RS256' | 'ES256' | 'PS256' | 'HS256' | string\nexport type EncValue = 'A128GCM' | 'A256GCM' | 'A128CBC-HS256' | 'A256CBC-HS512' | string\n\nexport interface ResponseEncryption {\n /**\n * REQUIRED. Array containing a list of the JWE [RFC7516] encryption algorithms\n * (alg values) [RFC7518] supported by the Credential and Batch Credential Endpoint to encode the\n * Credential or Batch Credential Response in a JWT\n */\n alg_values_supported: AlgValue[]\n\n /**\n * REQUIRED. Array containing a list of the JWE [RFC7516] encryption algorithms\n * (enc values) [RFC7518] supported by the Credential and Batch Credential Endpoint to encode the\n * Credential or Batch Credential Response in a JWT\n */\n enc_values_supported: EncValue[]\n\n /**\n * REQUIRED. Boolean value specifying whether the Credential Issuer requires the\n * additional encryption on top of TLS for the Credential Response. If the value is true, the Credential\n * Issuer requires encryption for every Credential Response and therefore the Wallet MUST provide\n * encryption keys in the Credential Request. If the value is false, the Wallet MAY chose whether it\n * provides encryption keys or not.\n */\n encryption_required: boolean\n}\n\n// For now we extend the opts above. Only difference is that the credential endpoint is optional in the Opts, as it can come from other sources. The value is however required in the eventual Issuer Metadata\nexport interface CredentialIssuerMetadata extends CredentialIssuerMetadataOpts, Partial<AuthorizationServerMetadata> {\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n credential_configurations_supported: Record<string, CredentialConfigurationSupported> // REQUIRED. A JSON array containing a list of JSON objects, each of them representing metadata about a separate credential type that the Credential Issuer can issue. The JSON objects in the array MUST conform to the structure of the Section 10.2.3.1.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n credential_response_encryption_alg_values_supported?: string // OPTIONAL. Array containing a list of the JWE [RFC7516] encryption algorithms (alg values) [RFC7518] supported by the Credential and/or Batch Credential Endpoint to encode the Credential or Batch Credential Response in a JWT [RFC7519].\n credential_response_encryption_enc_values_supported?: string //OPTIONAL. Array containing a list of the JWE [RFC7516] encryption algorithms (enc values) [RFC7518] supported by the Credential and/or Batch Credential Endpoint to encode the Credential or Batch Credential Response in a JWT [RFC7519].\n require_credential_response_encryption?: boolean //OPTIONAL. Boolean value specifying whether the Credential Issuer requires additional encryption on top of TLS for the Credential Response and expects encryption parameters to be present in the Credential Request and/or Batch Credential Request, with true indicating support. When the value is true, credential_response_encryption_alg_values_supported parameter MUST also be provided. If omitted, the default value is false.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter in the authorization_details Token Response parameter, with true indicating support. If omitted, the default value is false.\n}\n\n// For now we extend the opts above. Only difference is that the credential endpoint is optional in the Opts, as it can come from other sources. The value is however required in the eventual Issuer Metadata\n\nexport interface CredentialSupportedBrief {\n cryptographic_binding_methods_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify how the Credential is bound to the identifier of the End-User who possesses the Credential\n cryptographic_suites_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify the cryptographic suites that are supported for the cryptographic_binding_methods_supported\n}\n\nexport interface ProofType {\n proof_signing_alg_values_supported: string[]\n}\n\nexport type ProofTypesSupported = {\n [key in KeyProofType]?: ProofType\n}\n\nexport type CommonCredentialSupported = CredentialSupportedBrief &\n ExperimentalSubjectIssuance & {\n format: OID4VCICredentialFormat | string //REQUIRED. A JSON string identifying the format of this credential, e.g. jwt_vc_json or ldp_vc.\n id?: string // OPTIONAL. A JSON string identifying the respective object. The value MUST be unique across all credentials_supported entries in the Credential Issuer Metadata\n display?: CredentialsSupportedDisplay[] // OPTIONAL. An array of objects, where each object contains the display properties of the supported credential for a certain language\n scope?: string // OPTIONAL. A JSON string identifying the scope value that this Credential Issuer supports for this particular Credential. The value can be the same across multiple credential_configurations_supported objects. The Authorization Server MUST be able to uniquely identify the Credential Issuer based on the scope value. The Wallet can use this value in the Authorization Request as defined in Section 5.1.2. Scope values in this Credential Issuer metadata MAY duplicate those in the scopes_supported parameter of the Authorization Server.\n proof_types_supported?: ProofTypesSupported\n\n /**\n * following properties are non-mso_mdoc specific and we might wanna rethink them when we're going to support mso_mdoc\n */\n }\n\nexport interface CredentialSupportedJwtVcJsonLdAndLdpVc extends CommonCredentialSupported {\n types: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n '@context': ICredentialContextType[] // REQUIRED. JSON array as defined in [VC_DATA], Section 4.1.\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n}\n\nexport interface CredentialSupportedJwtVcJson extends CommonCredentialSupported {\n types: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc added for backwards compat\n}\n\nexport interface CredentialSupportedSdJwtVc extends CommonCredentialSupported {\n format: 'dc+sd-jwt' | 'vc+sd-jwt' // TODO Separate CredentialSupportedSdJwtVc for vcdm2?\n\n vct: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialSupportedSdJwtVcV13 extends CommonCredentialSupported {\n format: 'vc+sd-jwt' // TODO SSISDK-13\n\n vct: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialSupportedMsoMdoc extends CommonCredentialSupported {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n\n order?: string[] //An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport type CredentialConfigurationSupported =\n | CredentialConfigurationSupportedV1_0_15\n | CredentialConfigurationSupportedV1_0\n | (CommonCredentialSupported &\n (CredentialSupportedJwtVcJson | CredentialSupportedJwtVcJsonLdAndLdpVc | CredentialSupportedSdJwtVc | CredentialSupportedMsoMdoc))\n\nexport type CredentialsSupportedLegacy = CommonCredentialSupported &\n (\n | CredentialSupportedJwtVcJson\n | CredentialSupportedJwtVcJsonLdAndLdpVc\n | CredentialSupportedSdJwtVc\n | CredentialSupportedSdJwtVcV13\n | CredentialSupportedMsoMdoc\n )\n\nexport interface CommonCredentialOfferFormat {\n format: OID4VCICredentialFormat | string\n}\n\nexport interface CredentialOfferFormatJwtVcJsonLdAndLdpVc extends CommonCredentialOfferFormat {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n // REQUIRED. JSON object containing (and isolating) the detailed description of the credential type. This object MUST be processed using full JSON-LD processing.\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface CredentialOfferFormatJwtVcJson extends CommonCredentialOfferFormat {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc is added for backwards compat\n types: string[] // REQUIRED. JSON array as defined in Appendix E.1.1.2. This claim contains the type values the Wallet shall request in the subsequent Credential Request.\n}\n\n// NOTE: the sd-jwt format is added to oid4vci in a later draft version than currently\n// supported, so there's no defined offer format. However, based on the request structure\n// we support sd-jwt for older drafts of oid4vci as well\nexport interface CredentialOfferFormatSdJwtVc extends CommonCredentialOfferFormat {\n format: 'dc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CredentialOfferFormatSdJwtVcv13 extends CommonCredentialOfferFormat {\n format: 'vc+sd-jwt'\n\n vct: string\n claims?: IssuerCredentialSubject\n}\n\n// NOTE: the sd-jwt format is added to oid4vci in a later draft version than currently\n// supported, so there's no defined offer format. However, based on the request structure\n// we support sd-jwt for older drafts of oid4vci as well\nexport interface CredentialOfferFormatMsoMdoc extends CommonCredentialOfferFormat {\n format: 'mso_mdoc'\n\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport type CredentialOfferFormatV1_0_11 = CommonCredentialOfferFormat &\n (CredentialOfferFormatJwtVcJsonLdAndLdpVc | CredentialOfferFormatJwtVcJson | CredentialOfferFormatSdJwtVcv13 | CredentialOfferFormatMsoMdoc)\n\n/**\n * Optional storage that can help the credential Data Supplier. For instance to store credential input data during offer creation, if no additional data can be supplied later on\n */\nexport type CredentialDataSupplierInput = any\n\nexport type CreateCredentialOfferURIResult = {\n uri: string\n correlationId: string\n qrCodeDataUri?: string\n session: CredentialOfferSession\n userPin?: string\n txCode?: TxCode\n}\n\nexport interface JsonLdIssuerCredentialDefinition {\n '@context': ICredentialContextType[]\n types: string[]\n credentialSubject?: IssuerCredentialSubject\n}\n\nexport interface ErrorResponse {\n error: string\n error_description?: string\n error_uri?: string\n state?: string\n}\n\nexport type CredentialRequest = CredentialRequestV1_0_15 | CredentialRequestV1_0\n\nexport type AuthorizationDetails = AuthorizationDetailsV1_0_15 | AuthorizationDetailsV1_0\n\nexport interface CommonCredentialRequest extends ExperimentalSubjectIssuance {\n format: OID4VCICredentialFormat /* | OID4VCICredentialFormat[];*/ // for now it seems only one is supported in the spec\n proof?: ProofOfPossession\n}\n\nexport interface CredentialRequestJwtVcJson extends CommonCredentialRequest {\n format: 'jwt_vc_json' | 'jwt_vc' // jwt_vc for backwards compat\n types: string[]\n credentialSubject?: IssuerCredentialSubject\n}\n\nexport interface CredentialRequestJwtVcJsonLdAndLdpVc extends CommonCredentialRequest {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n credential_definition: JsonLdIssuerCredentialDefinition\n}\n\nexport interface CredentialRequestSdJwtVc extends CommonCredentialRequest {\n format: 'dc+sd-jwt'\n vct: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CredentialRequestMsoMdoc extends CommonCredentialRequest {\n format: 'mso_mdoc'\n doctype: string\n claims?: IssuerCredentialSubject\n}\n\nexport interface CommonCredentialResponse extends ExperimentalSubjectIssuance {\n // format: string; TODO do we still need this for previous version support?\n credential?: W3CVerifiableCredential\n acceptance_token?: string\n c_nonce?: string\n c_nonce_expires_in?: string\n}\n\nexport interface CredentialResponseLdpVc extends CommonCredentialResponse {\n // format: 'ldp_vc';\n credential: IVerifiableCredential\n}\n\nexport interface CredentialResponseJwtVc {\n // format: 'jwt_vc_json' | 'jwt_vc_json-ld'; TODO do we still need this for previous version support?\n credential: string\n}\n\nexport interface CredentialResponseSdJwtVc {\n // format: 'vc+sd-jwt'; TODO do we still need this for previous version support?\n credential: string\n}\n\n// export type CredentialSubjectDisplay = NameAndLocale[];\n\nexport type IssuerCredentialSubjectDisplay = CredentialSubjectDisplay & { [key: string]: CredentialSubjectDisplay }\n\nexport interface CredentialSubjectDisplay {\n mandatory?: boolean // OPTIONAL. Boolean which when set to true indicates the claim MUST be present in the issued Credential. If the mandatory property is omitted its default should be assumed to be false.\n value_type?: string // OPTIONAL. String value determining type of value of the claim. A non-exhaustive list of valid values defined by this specification are string, number, and image media types such as image/jpeg as defined in IANA media type registry for images\n display?: NameAndLocale[] // OPTIONAL. An array of objects, where each object contains display properties of a certain claim in the Credential for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n}\n\nexport interface IssuerCredentialSubject {\n [key: string]: IssuerCredentialSubjectDisplay\n}\n\nexport interface Grant {\n authorization_code?: GrantAuthorizationCode\n [PRE_AUTH_GRANT_LITERAL]?: GrantUrnIetf\n}\n\nexport interface GrantAuthorizationCode {\n /**\n * OPTIONAL. String value created by the Credential Issuer and opaque to the Wallet that is used to bind the subsequent\n * Authorization Request with the Credential Issuer to a context set up during previous steps.\n */\n issuer_state?: string\n\n // v12 feature\n /**\n * OPTIONAL string that the Wallet can use to identify the Authorization Server to use with this grant type when authorization_servers parameter in the Credential Issuer metadata has multiple entries. MUST NOT be used otherwise. The value of this parameter MUST match with one of the values in the authorization_servers array obtained from the Credential Issuer metadata\n */\n authorization_server?: string\n}\n\nexport interface TxCode {\n /**\n * OPTIONAL. String specifying the input character set. Possible values are numeric (only digits) and text (any characters). The default is numeric.\n */\n input_mode?: InputCharSet\n\n /**\n * OPTIONAL. Integer specifying the length of the Transaction Code. This helps the Wallet to render the input screen and improve the user experience.\n */\n length?: number\n\n /**\n * OPTIONAL. String containing guidance for the Holder of the Wallet on how to obtain the Transaction Code, e.g.,\n * describing over which communication channel it is delivered. The Wallet is RECOMMENDED to display this description\n * next to the Transaction Code input screen to improve the user experience. The length of the string MUST NOT exceed\n * 300 characters. The description does not support internationalization, however the Issuer MAY detect the Holder's\n * language by previous communication or an HTTP Accept-Language header within an HTTP GET request for a Credential Offer URI.\n */\n description?: string\n}\n\nexport interface GrantUrnIetf {\n /**\n * REQUIRED. The code representing the Credential Issuer's authorization for the Wallet to obtain Credentials of a certain type.\n */\n 'pre-authorized_code': string\n\n // v13\n /**\n * OPTIONAL. Object specifying whether the Authorization Server expects presentation of a Transaction Code by the\n * End-User along with the Token Request in a Pre-Authorized Code Flow. If the Authorization Server does not expect a\n * Transaction Code, this object is absent; this is the default. The Transaction Code is intended to bind the Pre-Authorized\n * Code to a certain transaction to prevent replay of this code by an attacker that, for example, scanned the QR code while\n * standing behind the legitimate End-User. It is RECOMMENDED to send the Transaction Code via a separate channel. If the Wallet\n * decides to use the Pre-Authorized Code Flow, the Transaction Code value MUST be sent in the tx_code parameter with\n * the respective Token Request as defined in Section 6.1. If no length or description is given, this object may be empty,\n * indicating that a Transaction Code is required.\n */\n tx_code?: TxCode\n\n // v12, v13\n /**\n * OPTIONAL. The minimum amount of time in seconds that the Wallet SHOULD wait between polling requests to the token endpoint (in case the Authorization Server responds with error code authorization_pending - see Section 6.3). If no value is provided, Wallets MUST use 5 as the default.\n */\n interval?: number\n\n // v12, v13 feature\n /**\n * OPTIONAL string that the Wallet can use to identify the Authorization Server to use with this grant type when authorization_servers parameter in the Credential Issuer metadata has multiple entries. MUST NOT be used otherwise. The value of this parameter MUST match with one of the values in the authorization_servers array obtained from the Credential Issuer metadata\n */\n authorization_server?: string\n\n // v12 and below feature\n /**\n * OPTIONAL. Boolean value specifying whether the AS\n * expects presentation of the End-User PIN along with the Token Request\n * in a Pre-Authorized Code Flow. Default is false. This PIN is intended\n * to bind the Pre-Authorized Code to a certain transaction to prevent\n * replay of this code by an attacker that, for example, scanned the QR\n * code while standing behind the legitimate End-User. It is RECOMMENDED\n * to send a PIN via a separate channel. If the Wallet decides to use\n * the Pre-Authorized Code Flow, a PIN value MUST be sent in\n * the user_pin parameter with the respective Token Request.\n */\n user_pin_required?: boolean\n}\n\nexport const PRE_AUTH_CODE_LITERAL = 'pre-authorized_code'\nexport const PRE_AUTH_GRANT_LITERAL = 'urn:ietf:params:oauth:grant-type:pre-authorized_code'\n\nexport type EndpointMetadataResult = EndpointMetadataResultV1_0_15 | EndpointMetadataResultV1_0\n\nexport type IssuerMetadata = IssuerMetadataV1_0_15 | IssuerMetadataV1_0\n\nexport type SignedMetadataVerifyCallback = (args: {\n signedMetadata: string // The raw signed JWT from the issuer metadata\n issuer: string // The credential_issuer URL for validation\n}) => Promise<{\n verified: boolean // Whether the JWT signature was successfully verified\n metadata: Record<string, unknown> // The decoded metadata claims from the JWT payload\n}>\n\nexport type NotificationEventType = 'credential_accepted' | 'credential_failure' | 'credential_deleted'\n\nexport interface NotificationRequest {\n notification_id: string\n event: NotificationEventType | string\n event_description?: string\n credential?: any // Experimental support to have a wallet sign a credential. Not part of the spec\n}\n\nexport type NotificationError = 'invalid_notification_id' | 'invalid_notification_request'\n\nexport type NotificationResponseResult = {\n error: boolean\n response?: NotificationErrorResponse\n}\n\nexport interface NotificationErrorResponse {\n error: NotificationError | string\n}\n\nexport interface StatusListOpts {\n statusListId?: string // Explicit status list to use. Determines the id from the credentialStatus object in the VC itself or uses the default otherwise\n statusListCorrelationId?: string\n statusListIndex?: number\n statusEntryCorrelationId?: string // An id to use for correlation. Can be the credential id, but also a business identifier. Will only be used for lookups/management\n}\n","import { BaseJWK, JWK } from '@sphereon/oid4vc-common'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { AuthzFlowType } from './Authorization.types'\nimport { OID4VCICredentialFormat, TxCode } from './Generic.types'\nimport { OpenId4VCIVersion } from './OpenID4VCIVersions.types'\nimport { CredentialOfferPayloadV1_0_15, CredentialOfferV1_0_15, CredentialResponseCredentialV1_0_15 } from './v1_0_15.types'\nimport { CredentialOfferPayloadV1_0, CredentialOfferV1_0 } from './v1_0.types'\n\nexport interface CredentialResponse extends ExperimentalSubjectIssuance {\n credential?: string | object // 1.0 final: singular credential value\n credentials?: Array<CredentialResponseCredentialV1_0_15> // draft 15: array of wrapped credentials\n format?: OID4VCICredentialFormat /* | OID4VCICredentialFormat[]*/ // REQUIRED. JSON string denoting the format of the issued Credential TODO: remove when cleaning <v13\n transaction_id?: string //OPTIONAL. A string identifying a Deferred Issuance transaction. This claim is contained in the response if the Credential Issuer was unable to immediately issue the credential. The value is subsequently used to obtain the respective Credential with the Deferred Credential Endpoint (see Section 9). It MUST be present when the credential parameter is not returned. It MUST be invalidated after the credential for which it was meant has been obtained by the Wallet.\n acceptance_token?: string // OPTIONAL. Token for deferred issuance (1.0 final) / deprecated in draft 15\n interval?: number // OPTIONAL. Seconds before retrying deferred request (1.0 final)\n c_nonce?: string // OPTIONAL. JSON string containing a nonce to be used to create a proof of possession of key material when requesting a Credential (see Section 7.2). When received, the Wallet MUST use this nonce value for its subsequent credential requests until the Credential Issuer provides a fresh nonce\n c_nonce_expires_in?: number // OPTIONAL. JSON integer denoting the lifetime in seconds of the c_nonce\n notification_id?: string\n}\n\nexport interface CredentialOfferRequestWithBaseUrl extends UniformCredentialOfferRequest {\n scheme: string\n clientId?: string\n baseUrl: string\n txCode?: TxCode\n issuerState?: string\n preAuthorizedCode?: string\n userPinRequired: boolean\n}\n\nexport type CredentialOffer = CredentialOfferV1_0_15 | CredentialOfferV1_0\n\nexport type CredentialOfferPayloadLatest = CredentialOfferPayloadV1_0\n\nexport type CredentialOfferPayload = (CredentialOfferPayloadV1_0_15 | CredentialOfferPayloadV1_0) & {\n [x: string]: any\n}\n\nexport interface AssertedUniformCredentialOffer extends UniformCredentialOffer {\n credential_offer: UniformCredentialOfferPayload\n}\n\nexport interface UniformCredentialOffer {\n credential_offer?: UniformCredentialOfferPayload\n credential_offer_uri?: string\n}\n\nexport interface UniformCredentialOfferRequest extends AssertedUniformCredentialOffer {\n original_credential_offer: CredentialOfferPayload\n version: OpenId4VCIVersion\n supportedFlows: AuthzFlowType[]\n}\n\n//todo: drop v11 (done for now, but maybe not final)\nexport type UniformCredentialOfferPayload = CredentialOfferPayloadV1_0_15 | CredentialOfferPayloadV1_0\n\nexport interface JwtProofOfPossession {\n proof_type: 'jwt'\n jwt: string\n\n [x: string]: unknown\n}\n\nexport interface CwtProofOfPossession {\n proof_type: 'cwt'\n cwt: string\n\n [x: string]: unknown\n}\n\nexport type ProofOfPossession = JwtProofOfPossession | CwtProofOfPossession\n\nexport type SearchValue = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string\n}\n\nexport enum JsonURIMode {\n JSON_STRINGIFY,\n X_FORM_WWW_URLENCODED,\n}\n\nexport type EncodeJsonAsURIOpts = {\n uriTypeProperties?: string[]\n arrayTypeProperties?: string[]\n baseUrl?: string\n param?: string\n mode?: JsonURIMode\n version?: OpenId4VCIVersion\n}\n\nexport type DecodeURIAsJsonOpts = {\n requiredProperties?: string[]\n arrayTypeProperties?: string[]\n}\n\nexport interface Jwt {\n header: JWTHeader\n payload: JWTPayload\n}\n\nexport interface ProofOfPossessionCallbacks {\n signCallback: JWTSignerCallback\n cwtSignCallback?: CWTSignerCallback\n verifyCallback?: JWTVerifyCallback\n}\n\n/**\n * Signature algorithms.\n *\n * TODO: Move towards string literal unions and string type, given we do not provide signature/key implementations in this library to begin with\n * @See: https://github.com/Sphereon-Opensource/OID4VC/issues/88\n */\nexport enum Alg {\n EdDSA = 'EdDSA',\n ES256 = 'ES256',\n ES256K = 'ES256K',\n PS256 = 'PS256',\n PS384 = 'PS384',\n PS512 = 'PS512',\n RS256 = 'RS256',\n RS384 = 'RS384',\n RS512 = 'RS512',\n}\n\nexport type Typ =\n | 'JWT'\n // https://www.rfc-editor.org/rfc/rfc8725.pdf#name-use-explicit-typing\n // https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#section-7.2.1-2.1.2.1.2.1.1\n | 'openid4vci-proof+jwt'\n\nexport interface JoseHeaderParameters {\n kid?: string // CONDITIONAL. JWT header containing the key ID. If the Credential shall be bound to a DID, the kid refers to a DID URL which identifies a particular key in the DID Document that the Credential shall be bound to. MUST NOT be present if jwk or x5c is present.\n x5t?: string\n x5c?: string[] // CONDITIONAL. JWT header containing a certificate or certificate chain corresponding to the key used to sign the JWT. This element may be used to convey a key attestation. In such a case, the actual key certificate will contain attributes related to the key properties. MUST NOT be present if kid or jwk is present.\n x5u?: string\n jku?: string\n jwk?: BaseJWK // CONDITIONAL. JWT header containing the key material the new Credential shall be bound to. MUST NOT be present if kid or x5c is present.\n typ?: string //JWT always\n cty?: string\n}\n\nexport interface JWSHeaderParameters extends JoseHeaderParameters {\n alg?: Alg | string // REQUIRED by the JWT signer\n b64?: boolean\n crit?: string[]\n\n [propName: string]: unknown\n}\n\nexport interface CompactJWSHeaderParameters extends JWSHeaderParameters {\n alg: string\n}\n\nexport interface JWTHeaderParameters extends CompactJWSHeaderParameters {\n b64?: true\n}\n\nexport type JWTHeader = JWTHeaderParameters\n\nexport interface JWTPayload {\n iss?: string // REQUIRED (string). The value of this claim MUST be the client_id of the client making the credential request.\n aud?: string | string[] // REQUIRED (string). The value of this claim MUST be the issuer URL of credential issuer.\n iat?: number // REQUIRED (number). The value of this claim MUST be the time at which the proof was issued using the syntax defined in [RFC7519].\n nonce?: string // REQUIRED (string). The value type of this claim MUST be a string, where the value is a c_nonce provided by the credential issuer. //TODO: Marked as required not present in NGI flow\n jti?: string // A new nonce chosen by the wallet. Used to prevent replay\n exp?: number // Not longer than 5 minutes\n client_id?: string // (string). The value of this claim MUST be the client_id of the client making the credential request.\n [s: string]: unknown\n}\n\nexport type JWTSignerCallback = (jwt: Jwt, kid?: string, noIssPayloadUpdate?: boolean) => Promise<string>\nexport type CWTSignerCallback = (args: {\n iss?: string\n aud: string\n nonce?: string\n alg?: string\n jwk?: JWK\n kid?: string\n coseKey?: unknown\n}) => Promise<string>\nexport type JWTVerifyCallback = (args: { jwt: string; kid?: string }) => Promise<JwtVerifyResult>\n\nexport interface JwtVerifyResult {\n jwt: Jwt\n kid?: string\n alg?: string\n did?: string\n didDocument?: Record<string, unknown>\n x5c?: string[]\n jwk?: BaseJWK\n}\n","import { JWK } from '@sphereon/oid4vc-common'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { ProofOfPossession } from './CredentialIssuance.types'\nimport {\n AlgValue,\n CredentialDataSupplierInput,\n CredentialOfferMode,\n CredentialsSupportedDisplay,\n CredentialSupplierConfig,\n EncValue,\n Grant,\n IssuerCredentialSubject,\n MetadataDisplay,\n OID4VCICredentialFormat,\n ProofTypesSupported,\n ResponseEncryption,\n StatusListOpts,\n} from './Generic.types'\nimport { QRCodeOpts } from './QRCode.types'\nimport { AuthorizationServerMetadata, AuthorizationServerType, EndpointMetadata } from './ServerMetadata'\n\nexport interface IssuerMetadataV1_0_15 {\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. A JSON object containing a list of key value pairs, where the key is a string serving as an abstract identifier of the Credential. This identifier is RECOMMENDED to be collision resistant - it can be globally unique, but does not have to be when naming conflicts are unlikely to arise in a given use case. The value is a JSON object. The JSON object MUST conform to the structure of the Section 11.2.1.\n credential_issuer: string // REQUIRED. A Credential Issuer is identified by a case sensitive URL using the https scheme that contains scheme, host and, optionally, port number and path components, but no query or fragment components.\n credential_endpoint: string // REQUIRED. URL of the OP's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint, as defined in Section 7. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint.\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers (as defined in [RFC8414]) the Credential Issuer relies on for authorization. If this element is omitted, the entity providing the Credential Issuer is also acting as the AS, i.e. the Credential Issuer's identifier is used as the OAuth 2.0 Issuer value to obtain the Authorization Server metadata as per [RFC8414].\n deferred_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Deferred Credential Endpoint, as defined in Section 9. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Deferred Credential Endpoint.\n notification_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Notification Endpoint, as defined in Section 10. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Notification Endpoint.\n credential_response_encryption?: ResponseEncryption // OPTIONAL. Object containing information about whether the Credential Issuer supports encryption of the Credential Response on top of TLS.\n batch_credential_issuance?: BatchCredentialIssuance // OPTIONAL. Object containing information about the Credential Issuer's supports for batch issuance of Credentials on the Credential Endpoint. The presence of this parameter means that the issuer supports the proofs parameter in the Credential Request so can issue more than one Verifiable Credential for the same Credential Dataset in a single request/response.\n token_endpoint?: string // OPTIONAL. URL of the token endpoint.\n display?: MetadataDisplay[] // OPTIONAL. An array of objects, where each object contains display properties of a Credential Issuer for a certain language. Below is a non-exhaustive list of valid parameters that MAY be included:\n authorization_challenge_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Authorization Challenge Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components. Described on https://www.ietf.org/archive/id/draft-parecki-oauth-first-party-apps-02.html#name-authorization-challenge-end\n signed_metadata?: string // OPTIONAL. String that is a signed JWT. This JWT contains Credential Issuer metadata parameters as claims.\n\n [x: string]: unknown\n}\n\nexport interface BatchCredentialIssuance {\n batch_size: number // REQUIRED. Integer value specifying the maximum array size for the proofs parameter in a Credential Request.\n}\n\nexport type CredentialDefinitionJwtVcJsonV1_0_15 = {\n type: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n}\n\nexport type CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 = {\n '@context': string[] // REQUIRED. JSON array as defined in [VC_DATA], Section 4.1.\n type: string[] // REQUIRED. JSON array designating the types a certain credential type supports\n credentialSubject?: IssuerCredentialSubject // OPTIONAL. A JSON object containing a list of key value pairs, where the key identifies the claim offered in the Credential. The value MAY be a dictionary, which allows to represent the full (potentially deeply nested) structure of the verifiable credential to be issued.\n}\n\nexport type CredentialConfigurationSupportedV1_0_15 = CredentialConfigurationSupportedCommonV1_0_15 &\n (\n | CredentialConfigurationSupportedSdJwtVcV1_0_15\n | CredentialConfigurationSupportedJwtVcJsonV1_0_15\n | CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialConfigurationSupportedMsoMdocV1_0_15\n )\n\nexport type CredentialConfigurationSupportedCommonV1_0_15 = {\n format: OID4VCICredentialFormat | string // REQUIRED. A JSON string identifying the format of this credential, e.g. jwt_vc_json or ldp_vc.\n scope?: string // OPTIONAL. A JSON string identifying the scope value that this Credential Issuer supports for this particular Credential. The value can be the same across multiple credential_configurations_supported objects. The Authorization Server MUST be able to uniquely identify the Credential Issuer based on the scope value. The Wallet can use this value in the Authorization Request as defined in Section 5.1.2. Scope values in this Credential Issuer metadata MAY duplicate those in the scopes_supported parameter of the Authorization Server.\n cryptographic_binding_methods_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify how the Credential is bound to the identifier of the End-User who possesses the Credential\n credential_signing_alg_values_supported?: string[] // OPTIONAL. Array of case sensitive strings that identify the algorithms that the Issuer uses to sign the issued Credential. Algorithm names used are determined by the Credential Format and are defined in Appendix A.\n proof_types_supported?: ProofTypesSupported // OPTIONAL. Object that describes specifics of the key proof(s) that the Credential Issuer supports. This object contains a list of name/value pairs, where each name is a unique identifier of the supported proof type(s).\n display?: CredentialsSupportedDisplay[] // OPTIONAL. An array of objects, where each object contains the display properties of the supported credential for a certain language\n credential_metadata?: CredentialMetadataV1_0_15 // OPTIONAL (OID4VCI 1.0 final §12.2.4 / #credential-issuer-parameters). Object holding credential-level `display` and `claims`. In 1.0 final these live here rather than at the top level of the configuration object; the top-level `display`/`claims` above are retained for pre-final / draft issuers.\n [x: string]: unknown\n}\n\n// OID4VCI 1.0 final §12.2.4 credential_metadata object: the spec-compliant home for credential-level\n// `display` and `claims`, used by every Credential Format (the §A.x format profiles only add format-specific\n// members like `vct`/`doctype`/`credential_definition` on top of those defined in #credential-issuer-parameters).\nexport interface CredentialMetadataV1_0_15 {\n display?: CredentialsSupportedDisplay[] // OPTIONAL. Display properties of the supported Credential for each language.\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n}\n\nexport interface CredentialConfigurationSupportedSdJwtVcV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'dc+sd-jwt' | 'vc+sd-jwt' // REQUIRED. Updated format identifier for SD-JWT VC to align with the media type in draft -06 of [I-D.ietf-oauth-sd-jwt-vc]\n vct: string // REQUIRED. String designating the type of a Credential, as defined in [I-D.ietf-oauth-sd-jwt-vc].\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedMsoMdocV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'mso_mdoc' // REQUIRED. Format identifier for ISO mDL credentials\n doctype: string // REQUIRED. String identifying the Credential type, as defined in [ISO.18013-5].\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'jwt_vc_json' | 'jwt_vc' // REQUIRED. jwt_vc added for backward compat\n credential_definition: CredentialDefinitionJwtVcJsonV1_0_15 // REQUIRED. Object containing the detailed description of the Credential type.\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15 extends CredentialConfigurationSupportedCommonV1_0_15 {\n format: 'ldp_vc' | 'jwt_vc_json-ld' // REQUIRED. Format identifier for JSON-LD based credentials\n credential_definition: CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 // REQUIRED. Object containing the detailed description of the Credential type.\n claims?: ClaimsDescriptionV1_0_15[] // OPTIONAL. Array of claims description objects using claims path pointers as defined in Appendix C.\n order?: string[] // OPTIONAL. An array of claims.display.name values that lists them in the order they should be displayed by the Wallet.\n}\n\n// Claims description using path pointers as per v15 spec change to syntax of credential metadata\nexport interface ClaimsDescriptionV1_0_15 {\n path: (string | number | null)[] // REQUIRED. The value MUST be a non-empty array representing a claims path pointer that specifies the path to a claim within the credential, as defined in Appendix C.\n mandatory?: boolean // OPTIONAL. Boolean which, when set to true, indicates that the Credential Issuer will always include this claim in the issued Credential. If set to false, the claim is not included in the issued Credential if the wallet did not request the inclusion of the claim, and/or if the Credential Issuer chose to not include the claim. If the mandatory parameter is omitted, the default value is false.\n display?: CredentialsSupportedDisplay[] // OPTIONAL. Array of objects, where each object contains display properties of a certain claim in the Credential for a certain language.\n}\n\nexport type CredentialRequestV1_0_15ResponseEncryption = {\n jwk: JWK // REQUIRED. JWK containing the key material for encryption\n alg: AlgValue // REQUIRED. JWE algorithm for encryption\n enc: EncValue // REQUIRED. JWE encryption method\n}\n\nexport interface CredentialRequestV1_0_15Common extends ExperimentalSubjectIssuance {\n credential_response_encryption?: CredentialRequestV1_0_15ResponseEncryption // OPTIONAL. Object containing information for encrypting the Credential Response. If this request element is not present, the corresponding credential response returned is not encrypted.\n proof?: ProofOfPossession // OPTIONAL. Object providing a single proof of possession of the cryptographic key material to which the issued Credential instance will be bound to. proof parameter MUST NOT be present if proofs parameter is used.\n proofs?: ProofOfPossessionMap // OPTIONAL. Object providing one or more proof of possessions of the cryptographic key material to which the issued Credential instances will be bound to. The proofs parameter MUST NOT be present if proof parameter is used.\n issuer_state?: string // OPTIONAL. We allow sending a issuer state back to the credential offer in case an auth code flow is used with an external AS and no nonces are used (not recommended), but does allow to integrate any OIDC server\n}\n\nexport interface ProofOfPossessionMap {\n [proofType: string]: ProofOfPossession[] // Array of proofs for each proof type - proofs object contains exactly one parameter named as the proof type\n}\n\n// Main credential request type for v15 - removes format and format-specific parameters from Credential Request\nexport type CredentialRequestV1_0_15 = CredentialRequestV1_0_15Common &\n (CredentialRequestV1_0_15CredentialIdentifier | CredentialRequestV1_0_15CredentialConfigurationId)\n\nexport interface CredentialRequestV1_0_15CredentialIdentifier extends CredentialRequestV1_0_15Common {\n credential_identifier: string // REQUIRED when an Authorization Details of type openid_credential was returned from the Token Response. It MUST NOT be used otherwise. A string that identifies a Credential Dataset that is requested for issuance. When this parameter is used, the credential_configuration_id MUST NOT be present.\n credential_configuration_id?: undefined // MUST NOT be present when credential_identifier is used.\n}\n\nexport interface CredentialRequestV1_0_15CredentialConfigurationId extends CredentialRequestV1_0_15Common {\n credential_configuration_id: string // REQUIRED if a credential_identifiers parameter was not returned from the Token Response as part of the authorization_details parameter. It MUST NOT be used otherwise. String that uniquely identifies one of the keys in the name/value pairs stored in the credential_configurations_supported Credential Issuer metadata.\n credential_identifier?: undefined // MUST NOT be present when credential_configuration_id is used.\n}\n\nexport interface CredentialOfferV1_0_15 {\n credential_offer?: CredentialOfferPayloadV1_0_15 // OPTIONAL. Object with the Credential Offer parameters. This MUST NOT be present when the credential_offer_uri parameter is present.\n credential_offer_uri?: string // OPTIONAL. String that is a URL using the https scheme referencing a resource containing a JSON object with the Credential Offer parameters. This MUST NOT be present when the credential_offer parameter is present.\n}\n\nexport interface CredentialOfferRESTRequestV1_0_15 extends Partial<CredentialOfferPayloadV1_0_15> {\n redirectUri?: string\n baseUri?: string\n scheme?: string\n correlationId?: string\n sessionLifeTimeInSec?: number\n pinLength?: number\n qrCodeOpts?: QRCodeOpts\n client_id?: string\n credentialDataSupplierInput?: CredentialDataSupplierInput\n statusListOpts?: Array<StatusListOpts>\n offerMode?: CredentialOfferMode\n}\n\nexport interface CredentialOfferPayloadV1_0_15 {\n /**\n * REQUIRED. The URL of the Credential Issuer, as defined in Section 11.2.1, from which the Wallet is requested to\n * obtain one or more Credentials. The Wallet uses it to obtain the Credential Issuer's Metadata following the steps\n * defined in Section 11.2.2.\n */\n credential_issuer: string\n\n /**\n * REQUIRED. Array of unique strings that each identify one of the keys in the name/value pairs stored in\n * the credential_configurations_supported Credential Issuer metadata. The Wallet uses these string values\n * to obtain the respective object that contains information about the Credential being offered as defined\n * in Section 11.2.3. For example, these string values can be used to obtain scope values to be used in\n * the Authorization Request.\n */\n credential_configuration_ids: string[]\n\n /**\n * OPTIONAL. Object indicating to the Wallet the Grant Types the Credential Issuer's Authorization Server is prepared\n * to process for this Credential Offer. Every grant is represented by a name/value pair. The name is the Grant Type identifier;\n * the value is an object that contains parameters either determining the way the Wallet MUST use the particular grant and/or\n * parameters the Wallet MUST send with the respective request(s). If grants is not present or is empty, the Wallet MUST determine\n * the Grant Types the Credential Issuer's Authorization Server supports using the respective metadata. When multiple grants are present,\n * it is at the Wallet's discretion which one to use.\n */\n grants?: Grant\n\n /**\n * OPTIONAL. Some implementations might include a client_id in the offer. For instance EBSI in a same-device flow. (Cross-device tucks it in the state JWT)\n */\n client_id?: string\n}\n\n// Credential Response for v15 - credential response always returns an array when not returning a transaction_id\nexport interface CredentialResponseV1_0_15 extends ExperimentalSubjectIssuance {\n credentials?: CredentialResponseCredentialV1_0_15[] // OPTIONAL. Contains an array of one or more issued Credentials. It MUST NOT be used if the transaction_id parameter is present. The elements of the array MUST be objects.\n transaction_id?: string // OPTIONAL. String identifying a Deferred Issuance transaction. This parameter is contained in the response if the Credential Issuer cannot immediately issue the Credential. The value is subsequently used to obtain the respective Credential with the Deferred Credential Endpoint. It MUST NOT be used if the credentials parameter is present. It MUST be invalidated after the Credential for which it was meant has been obtained by the Wallet.\n notification_id?: string // OPTIONAL. String identifying one or more Credentials issued in one Credential Response. It MUST be included in the Notification Request as defined in Section 10. It MUST NOT be present if the credentials parameter is not present.\n}\n\nexport interface CredentialResponseCredentialV1_0_15 {\n credential: string | object // REQUIRED. Contains one issued Credential. It MAY be a string or an object, depending on the Credential Format. See Appendix A for the Credential Format-specific encoding requirements.\n // Additional metadata can be included here with the option for additional meta-data\n}\n\n// Deferred Credential Response for v15 - deferred credential response always returns an array (same as credential response)\nexport interface DeferredCredentialResponseV1_0_15 {\n credentials: CredentialResponseCredentialV1_0_15[] // REQUIRED. Array of issued credentials using the same structure as the immediate credential response.\n notification_id?: string // OPTIONAL. String identifying one or more Credentials issued in one Credential Response.\n}\n\n// Token Response with credential_identifiers support - add an option to return credential_identifiers in the Token Response and use them in the Credential Request, when scopes are used in the Authorization Request\nexport interface TokenResponseV1_0_15 {\n access_token: string\n token_type: string\n expires_in?: number\n refresh_token?: string\n scope?: string\n authorization_details?: AuthorizationDetailsV1_0_15[]\n // Note: removes c_nonce and c_nonce_expires_in from the Token Response as they are now obtained from the Nonce Endpoint\n}\n\nexport interface AuthorizationDetailsV1_0_15 {\n type: 'openid_credential' // REQUIRED. JSON string that determines the authorization details type. MUST be set to openid_credential for the purpose of this specification.\n credential_configuration_id?: string // OPTIONAL. String specifying a unique identifier of the Credential being described in the credential_configurations_supported map\n credential_identifiers?: string[] // REQUIRED when the authorization_details parameter is used to request issuance of a Credential of a certain Credential Configuration. Array of strings, each uniquely identifying a Credential Dataset that can be issued using the Access Token returned in this response.\n locations?: string[] // OPTIONAL. If the Credential Issuer metadata contains an authorization_server parameter, the authorization detail's locations common data field MUST be set to the Credential Issuer Identifier value.\n [x: string]: unknown\n}\n\n// Nonce Endpoint - added a Nonce Endpoint where a Client can acquire a fresh c_nonce value without the overhead of a full Credential Request\nexport interface NonceRequestV1_0_15 {\n // Empty request body - The request for a nonce is made by sending an HTTP POST request to the URL provided in the nonce_endpoint Credential Issuer Metadata parameter.\n}\n\nexport interface NonceResponseV1_0_15 {\n c_nonce: string // REQUIRED. String containing a nonce to be used when creating a proof of possession of the key proof\n // Note: removes c_nonce_expires_in from Nonce Endpoint response\n}\n\n// Error responses updated for v15 - removes c_nonce and c_nonce_expires_in from the Credential Error Response\nexport interface CredentialErrorResponseV1_0_15 {\n error: string // REQUIRED. The error parameter SHOULD be a single ASCII error code\n error_description?: string // OPTIONAL. Human-readable ASCII text providing additional information\n error_uri?: string // OPTIONAL. A URI identifying a human-readable web page with information about the error\n // Note: c_nonce and c_nonce_expires_in removed from error response\n}\n\n// Proof types for v15 - removes CWT proof type, adds key attestation as additional information in a proof of possession and new proof type\nexport interface ProofTypesV1_0_15 {\n jwt?: ProofTypeV1_0_15 // OPTIONAL. JWT proof type support\n ldp_vp?: ProofTypeV1_0_15 // OPTIONAL. Linked Data Proof VP support\n attestation?: ProofTypeV1_0_15 // OPTIONAL. New attestation proof type for key attestation\n}\n\nexport interface ProofTypeV1_0_15 {\n proof_signing_alg_values_supported: string[] // REQUIRED. Array of case sensitive strings that identify the algorithms that the Issuer supports for this proof type.\n key_attestations_required?: KeyAttestationsRequiredV1_0_15 // OPTIONAL. Object that describes the requirement for key attestations, which the Credential Issuer expects the Wallet to send within the proof of the Credential Request.\n}\n\nexport interface KeyAttestationsRequiredV1_0_15 {\n key_storage?: string[] // OPTIONAL. Array defining values for key storage attack potential resistance\n user_authentication?: string[] // OPTIONAL. Array defining values for user authentication attack potential resistance\n}\n\n// Key Attestation JWT format - add key attestation as additional information in a proof of possession\nexport interface KeyAttestationJWT {\n // JOSE Header\n alg: string // REQUIRED. A digital signature algorithm identifier such as per IANA \"JSON Web Signature and Encryption Algorithms\" registry\n typ: 'keyattestation+jwt' // REQUIRED. MUST be keyattestation+jwt, which explicitly types the key attestation JWT\n kid?: string // OPTIONAL. Key identifier\n x5c?: string[] // OPTIONAL. Certificate chain corresponding to the key used to sign the JWT\n trust_chain?: string[] // OPTIONAL. Trust chain for validation\n\n // JWT Claims\n iss?: string // OPTIONAL. Issuer of the key attestation\n iat: number // REQUIRED. Integer for the time at which the key attestation was issued\n exp?: number // OPTIONAL. Integer for the time at which the key attestation and the key(s) it is attesting expire\n attested_keys: JWK[] // REQUIRED. Array of attested keys from the same key storage component\n key_storage?: string[] // OPTIONAL. Array of case sensitive strings that assert the attack potential resistance of the key storage component\n user_authentication?: string[] // OPTIONAL. Array of case sensitive strings that assert the attack potential resistance of the user authentication methods\n certification?: string // OPTIONAL. A String that contains a URL that links to the certification of the key storage component\n nonce?: string // OPTIONAL. String that represents a nonce provided by the Issuer to prove that a key attestation was freshly generated\n status?: object // OPTIONAL. JSON Object representing the supported revocation check mechanisms\n}\n\n// Wallet Attestation format - add section on Wallet Attestations\nexport interface WalletAttestationJWT {\n // JOSE Header\n typ: 'oauth-client-attestation+jwt' // REQUIRED. Type header for wallet attestation\n alg: string // REQUIRED. Signature algorithm\n kid?: string // OPTIONAL. Key identifier\n\n // JWT Claims\n iss: string // REQUIRED. Issuer of the wallet attestation\n sub: string // REQUIRED. Subject (wallet identifier)\n wallet_name?: string // OPTIONAL. String containing a human-readable name of the Wallet\n wallet_link?: string // OPTIONAL. String containing a URL to get further information about the Wallet and the Wallet Provider\n nbf?: number // OPTIONAL. Not before time\n exp?: number // OPTIONAL. Expiration time\n cnf: {\n jwk: JWK // REQUIRED. Confirmation key for proof of possession\n }\n status?: object // OPTIONAL. Status mechanism for the Wallet Attestation\n}\n\nexport interface CredentialIssuerMetadataOptsV1_0_15 {\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path and query parameter components.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint.\n deferred_credential_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Deferred Credential Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Deferred Credential Endpoint.\n notification_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Notification Endpoint. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Notification Endpoint.\n credential_response_encryption?: ResponseEncryption // OPTIONAL. Object containing information about whether the Credential Issuer supports encryption of the Credential Response on top of TLS.\n batch_credential_issuance?: BatchCredentialIssuance // OPTIONAL. Object containing information about the Credential Issuer's supports for batch issuance of Credentials on the Credential Endpoint.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter in the authorization_details Token Response parameter, with true indicating support. If omitted, the default value is false.\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. Object that describes specifics of the Credential that the Credential Issuer supports issuance of.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers the Credential Issuer relies on for authorization.\n signed_metadata?: string // OPTIONAL. String that is a signed JWT. This JWT contains Credential Issuer metadata parameters as claims.\n display?: MetadataDisplay[] // OPTIONAL. Array of objects, where each object contains display properties of a Credential Issuer for a certain language.\n authorization_challenge_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Authorization Challenge Endpoint.\n token_endpoint?: string // OPTIONAL. URL of the token endpoint.\n credential_supplier_config?: CredentialSupplierConfig // OPTIONAL. Configuration for credential suppliers.\n}\n\nexport const credentialIssuerMetadataFieldNamesV1_0_15: Array<keyof CredentialIssuerMetadataOptsV1_0_15> = [\n 'credential_issuer',\n 'credential_configurations_supported',\n 'credential_endpoint',\n 'nonce_endpoint',\n 'deferred_credential_endpoint',\n 'notification_endpoint',\n 'credential_response_encryption',\n 'batch_credential_issuance',\n 'authorization_servers',\n 'token_endpoint',\n 'display',\n 'credential_supplier_config',\n 'credential_identifiers_supported',\n 'signed_metadata',\n 'authorization_challenge_endpoint',\n] as const\n\nexport interface EndpointMetadataResultV1_0_15 extends EndpointMetadata {\n authorizationServerType: AuthorizationServerType\n authorizationServerMetadata?: AuthorizationServerMetadata\n credentialIssuerMetadata?: Partial<AuthorizationServerMetadata> & IssuerMetadataV1_0_15\n}\n\nexport interface CredentialIssuerMetadataV1_0_15 extends CredentialIssuerMetadataOptsV1_0_15, Partial<AuthorizationServerMetadata> {\n authorization_servers?: string[] // OPTIONAL. Array of strings that identify the OAuth 2.0 Authorization Servers the Credential Issuer relies on for authorization.\n credential_endpoint: string // REQUIRED. URL of the Credential Issuer's Credential Endpoint.\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> // REQUIRED. Supported credential configurations.\n credential_issuer: string // REQUIRED. The Credential Issuer's identifier.\n credential_response_encryption_alg_values_supported?: string // OPTIONAL. Array containing a list of the JWE encryption algorithms (alg values) supported.\n credential_response_encryption_enc_values_supported?: string // OPTIONAL. Array containing a list of the JWE encryption algorithms (enc values) supported.\n require_credential_response_encryption?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer requires additional encryption on top of TLS.\n credential_identifiers_supported?: boolean // OPTIONAL. Boolean value specifying whether the Credential Issuer supports returning credential_identifiers parameter.\n nonce_endpoint?: string // OPTIONAL. URL of the Credential Issuer's Nonce Endpoint, as defined in Section 7. This URL MUST use the https scheme and MAY contain port, path, and query parameter components. If omitted, the Credential Issuer does not support the Nonce Endpoint\n}\n\nexport interface NotificationResponseV1_0_15 {\n // Success responses typically return 204 No Content - When the Credential Issuer has successfully received the Notification Request from the Wallet, it MUST respond with an HTTP status code in the 2xx range.\n}\n\nexport interface NotificationErrorResponseV1_0_15 {\n error: 'invalid_notification_id' | 'invalid_notification_request' // REQUIRED. Error code for notification failures.\n error_description?: string // OPTIONAL. Human-readable error description.\n}\n\n// Authorization Server metadata extension for v15 - remove use of the authorization_pending and slow_down error codes\nexport interface AuthorizationServerMetadataV1_0_15 extends AuthorizationServerMetadata {\n 'pre-authorized_grant_anonymous_access_supported'?: boolean // OPTIONAL. A boolean indicating whether the Credential Issuer accepts a Token Request with a Pre-Authorized Code but without a client_id. The default is false.\n // Note: authorization_pending and slow_down error codes removed in v14\n}\n","import { JWK } from '@sphereon/oid4vc-common'\n\nimport { ExperimentalSubjectIssuance } from '../experimental/holder-vci'\n\nimport { ProofOfPossession } from './CredentialIssuance.types'\nimport {\n AlgValue,\n CredentialDataSupplierInput,\n CredentialOfferMode,\n CredentialsSupportedDisplay,\n CredentialSupplierConfig,\n EncValue,\n Grant,\n MetadataDisplay,\n OID4VCICredentialFormat,\n ResponseEncryption,\n StatusListOpts,\n} from './Generic.types'\nimport { QRCodeOpts } from './QRCode.types'\nimport { AuthorizationServerMetadata, AuthorizationServerType, EndpointMetadata } from './ServerMetadata'\nimport {\n CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialDefinitionJwtVcJsonV1_0_15,\n KeyAttestationJWT,\n KeyAttestationsRequiredV1_0_15,\n ProofOfPossessionMap,\n WalletAttestationJWT,\n} from './v1_0_15.types'\n\n// =====================\n// Proof Types\n// =====================\n\nexport interface ProofTypesV1_0 {\n jwt?: ProofTypeV1_0\n di_vp?: ProofTypeV1_0 // Renamed from ldp_vp in draft 15 to di_vp in 1.0 final\n attestation?: ProofTypeV1_0\n}\n\nexport interface ProofTypeV1_0 {\n proof_signing_alg_values_supported: string[] // REQUIRED\n key_attestations_required?: KeyAttestationsRequiredV1_0_15 // OPTIONAL. Reuses same structure from d15\n}\n\nexport type ProofTypesSupportedV1_0 = {\n [key: string]: ProofTypeV1_0\n}\n\n// =====================\n// Credential Configuration\n// =====================\n\nexport type CredentialConfigurationSupportedCommonV1_0 = {\n format: OID4VCICredentialFormat | string // REQUIRED\n scope?: string // OPTIONAL\n cryptographic_binding_methods_supported?: string[] // OPTIONAL\n cryptographic_suites_supported?: string[] // OPTIONAL. Replaces credential_signing_alg_values_supported from draft 15\n credential_signing_alg_values_supported?: string[] // Keep for backward compat with issuers that use draft 15 naming\n proof_types_supported?: ProofTypesSupportedV1_0 // OPTIONAL\n display?: CredentialsSupportedDisplay[] // OPTIONAL\n credential_metadata?: CredentialMetadataV1_0 // OPTIONAL (OID4VCI 1.0 final §12.2.4 / #credential-issuer-parameters). Object holding credential-level `display` and `claims`. In 1.0 final these live here rather than at the top level of the configuration object; the top-level `display`/`claims` are retained for pre-final / draft-15 issuers.\n [x: string]: unknown\n}\n\nexport interface CredentialConfigurationSupportedSdJwtVcV1_0 extends CredentialConfigurationSupportedCommonV1_0 {\n format: 'dc+sd-jwt' | 'vc+sd-jwt'\n vct: string // REQUIRED\n claims?: ClaimsDescriptionV1_0[] // OPTIONAL\n order?: string[] // OPTIONAL\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonV1_0 extends CredentialConfigurationSupportedCommonV1_0 {\n format: 'jwt_vc_json' | 'jwt_vc'\n credential_definition: CredentialDefinitionJwtVcJsonV1_0_15 // REQUIRED. Reuses same structure\n claims?: ClaimsDescriptionV1_0[] // OPTIONAL\n order?: string[] // OPTIONAL\n}\n\nexport interface CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0 extends CredentialConfigurationSupportedCommonV1_0 {\n format: 'ldp_vc' | 'jwt_vc_json-ld'\n credential_definition: CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 // REQUIRED. Reuses same structure\n claims?: ClaimsDescriptionV1_0[] // OPTIONAL\n order?: string[] // OPTIONAL\n}\n\nexport interface CredentialConfigurationSupportedMsoMdocV1_0 extends CredentialConfigurationSupportedCommonV1_0 {\n format: 'mso_mdoc'\n doctype: string // REQUIRED\n claims?: ClaimsDescriptionV1_0[] // OPTIONAL\n order?: string[] // OPTIONAL\n}\n\nexport type CredentialConfigurationSupportedV1_0 = CredentialConfigurationSupportedCommonV1_0 &\n (\n | CredentialConfigurationSupportedSdJwtVcV1_0\n | CredentialConfigurationSupportedJwtVcJsonV1_0\n | CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0\n | CredentialConfigurationSupportedMsoMdocV1_0\n )\n\n// Claims description - same structure as draft 15 (using path pointers)\nexport interface ClaimsDescriptionV1_0 {\n path: (string | number | null)[] // REQUIRED. Claims path pointer\n mandatory?: boolean // OPTIONAL. Defaults to false\n display?: CredentialsSupportedDisplay[] // OPTIONAL\n}\n\n// OID4VCI 1.0 final §12.2.4 credential_metadata object: the spec-compliant home for credential-level\n// `display` and `claims`, used by every Credential Format (the §A.x format profiles only add format-specific\n// members like `vct`/`doctype`/`credential_definition` on top of those defined in #credential-issuer-parameters).\nexport interface CredentialMetadataV1_0 {\n display?: CredentialsSupportedDisplay[] // OPTIONAL. Display properties of the supported Credential for each language.\n claims?: ClaimsDescriptionV1_0[] // OPTIONAL. Array of claims description objects using claims path pointers.\n}\n\n// =====================\n// Issuer Metadata\n// =====================\n\nexport interface IssuerMetadataV1_0 {\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0> // REQUIRED\n credential_issuer: string // REQUIRED\n credential_endpoint: string // REQUIRED\n token_endpoint?: string // OPTIONAL (REQUIRED per spec, but may come from AS metadata)\n nonce_endpoint?: string // OPTIONAL\n authorization_servers?: string[] // OPTIONAL\n authorization_endpoint?: string // OPTIONAL\n deferred_credential_endpoint?: string // OPTIONAL\n notification_endpoint?: string // OPTIONAL\n credential_response_encryption?: ResponseEncryption // OPTIONAL\n batch_credential_issuance_supported?: boolean // OPTIONAL. Changed from object (d15) to boolean (1.0 final)\n credential_issuer_public_key?: object // OPTIONAL. JWKS with issuer's public keys. New in 1.0 final\n display?: MetadataDisplay[] // OPTIONAL\n authorization_challenge_endpoint?: string // OPTIONAL\n signed_metadata?: string // OPTIONAL\n [x: string]: unknown\n}\n\n// =====================\n// Credential Request\n// =====================\n\nexport type CredentialRequestV1_0ResponseEncryption = {\n jwk: JWK // REQUIRED\n alg: AlgValue // REQUIRED\n enc: EncValue // REQUIRED\n}\n\nexport interface CredentialRequestV1_0Common extends ExperimentalSubjectIssuance {\n credential_configuration_id: string // REQUIRED always in 1.0 final\n credential_identifiers?: string[] // OPTIONAL array. Replaces singular credential_identifier from d15\n credential_response_encryption?: CredentialRequestV1_0ResponseEncryption // OPTIONAL\n proof?: ProofOfPossession // OPTIONAL\n proofs?: ProofOfPossessionMap // OPTIONAL\n}\n\n// In 1.0 final, credential_configuration_id is always required and credential_identifiers is an optional array\n// No discriminated union needed like in d15\nexport type CredentialRequestV1_0 = CredentialRequestV1_0Common\n\n// =====================\n// Credential Response\n// =====================\n\n// 1.0 final: singular credential field (NOT array, NOT wrapped)\nexport interface CredentialResponseV1_0 extends ExperimentalSubjectIssuance {\n credential?: string | object // OPTIONAL. Singular credential value. Mutually exclusive with transaction_id\n transaction_id?: string // OPTIONAL. Deferred issuance indicator. Mutually exclusive with credential\n acceptance_token?: string // OPTIONAL. Token for deferred issuance acknowledgment\n interval?: number // OPTIONAL. Seconds before retrying deferred request\n c_nonce?: string // OPTIONAL. Fresh nonce for subsequent requests. Back in 1.0 final\n c_nonce_expires_in?: number // OPTIONAL. Nonce validity period. Back in 1.0 final\n notification_id?: string // OPTIONAL\n}\n\n// Deferred Credential Response - singular credential\nexport interface DeferredCredentialResponseV1_0 {\n credential: string | object // REQUIRED\n acceptance_token?: string // OPTIONAL. For subsequent deferred requests\n interval?: number // OPTIONAL\n c_nonce?: string // OPTIONAL\n c_nonce_expires_in?: number // OPTIONAL\n notification_id?: string // OPTIONAL\n}\n\n// =====================\n// Token Response\n// =====================\n\n// 1.0 final: c_nonce and c_nonce_expires_in are back as OPTIONAL\nexport interface TokenResponseV1_0 {\n access_token: string\n token_type: string\n expires_in?: number\n refresh_token?: string\n scope?: string\n authorization_details?: AuthorizationDetailsV1_0[]\n c_nonce?: string // OPTIONAL. Back in 1.0 final\n c_nonce_expires_in?: number // OPTIONAL. Back in 1.0 final\n}\n\n// =====================\n// Authorization Details\n// =====================\n\nexport interface AuthorizationDetailsV1_0 {\n type: 'openid_credential' // REQUIRED\n credential_configuration_id: string // REQUIRED in 1.0 final (was optional in d15)\n credential_identifiers?: string[] // OPTIONAL. Array of credential dataset identifiers\n locations?: string[] // OPTIONAL\n [x: string]: unknown\n}\n\n// =====================\n// Nonce Endpoint\n// =====================\n\nexport interface NonceRequestV1_0 {\n // Empty request body\n}\n\n// 1.0 final: both fields REQUIRED\nexport interface NonceResponseV1_0 {\n c_nonce: string // REQUIRED\n c_nonce_expires_in: number // REQUIRED. Was absent in d15 nonce response\n}\n\n// =====================\n// Error Response\n// =====================\n\n// 1.0 final: c_nonce and c_nonce_expires_in are back in error response\nexport interface CredentialErrorResponseV1_0 {\n error: string // REQUIRED\n error_description?: string // OPTIONAL\n error_uri?: string // OPTIONAL\n c_nonce?: string // OPTIONAL. Back in 1.0 final\n c_nonce_expires_in?: number // OPTIONAL. Back in 1.0 final\n}\n\n// =====================\n// Credential Offer (structurally identical to d15)\n// =====================\n\nexport interface CredentialOfferV1_0 {\n credential_offer?: CredentialOfferPayloadV1_0\n credential_offer_uri?: string\n}\n\nexport interface CredentialOfferPayloadV1_0 {\n credential_issuer: string // REQUIRED\n credential_configuration_ids: string[] // REQUIRED\n grants?: Grant // OPTIONAL\n client_id?: string // OPTIONAL\n}\n\nexport interface CredentialOfferRESTRequestV1_0 extends Partial<CredentialOfferPayloadV1_0> {\n redirectUri?: string\n baseUri?: string\n scheme?: string\n correlationId?: string\n sessionLifeTimeInSec?: number\n pinLength?: number\n qrCodeOpts?: QRCodeOpts\n client_id?: string\n credentialDataSupplierInput?: CredentialDataSupplierInput\n statusListOpts?: Array<StatusListOpts>\n offerMode?: CredentialOfferMode\n}\n\n// =====================\n// Issuer Metadata Builder Types\n// =====================\n\nexport interface CredentialIssuerMetadataOptsV1_0 {\n credential_endpoint: string // REQUIRED\n nonce_endpoint?: string // OPTIONAL\n deferred_credential_endpoint?: string // OPTIONAL\n notification_endpoint?: string // OPTIONAL\n credential_response_encryption?: ResponseEncryption // OPTIONAL\n batch_credential_issuance_supported?: boolean // OPTIONAL. Boolean in 1.0 (was object in d15)\n credential_issuer_public_key?: object // OPTIONAL. New in 1.0 final\n credential_identifiers_supported?: boolean // OPTIONAL\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0> // REQUIRED\n credential_issuer: string // REQUIRED\n authorization_servers?: string[] // OPTIONAL\n signed_metadata?: string // OPTIONAL\n display?: MetadataDisplay[] // OPTIONAL\n authorization_challenge_endpoint?: string // OPTIONAL\n token_endpoint?: string // OPTIONAL\n credential_supplier_config?: CredentialSupplierConfig // OPTIONAL\n}\n\nexport interface CredentialIssuerMetadataV1_0 extends CredentialIssuerMetadataOptsV1_0, Partial<AuthorizationServerMetadata> {\n authorization_servers?: string[] // OPTIONAL\n credential_endpoint: string // REQUIRED\n credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0> // REQUIRED\n credential_issuer: string // REQUIRED\n credential_response_encryption_alg_values_supported?: string // OPTIONAL\n credential_response_encryption_enc_values_supported?: string // OPTIONAL\n require_credential_response_encryption?: boolean // OPTIONAL\n credential_identifiers_supported?: boolean // OPTIONAL\n nonce_endpoint?: string // OPTIONAL\n}\n\nexport const credentialIssuerMetadataFieldNamesV1_0: Array<keyof CredentialIssuerMetadataOptsV1_0> = [\n 'credential_issuer',\n 'credential_configurations_supported',\n 'credential_endpoint',\n 'nonce_endpoint',\n 'deferred_credential_endpoint',\n 'notification_endpoint',\n 'credential_response_encryption',\n 'batch_credential_issuance_supported',\n 'credential_issuer_public_key',\n 'authorization_servers',\n 'token_endpoint',\n 'display',\n 'credential_supplier_config',\n 'credential_identifiers_supported',\n 'signed_metadata',\n 'authorization_challenge_endpoint',\n] as const\n\nexport interface EndpointMetadataResultV1_0 extends EndpointMetadata {\n authorizationServerType: AuthorizationServerType\n authorizationServerMetadata?: AuthorizationServerMetadata\n credentialIssuerMetadata?: Partial<AuthorizationServerMetadata> & IssuerMetadataV1_0\n}\n\n// =====================\n// Notification (same structure as d15)\n// =====================\n\nexport interface NotificationResponseV1_0 {\n // Success responses return 204 No Content\n}\n\nexport interface NotificationErrorResponseV1_0 {\n error: 'invalid_notification_id' | 'invalid_notification_request' // REQUIRED\n error_description?: string // OPTIONAL\n}\n\n// =====================\n// Authorization Server metadata extension\n// =====================\n\nexport interface AuthorizationServerMetadataV1_0 extends AuthorizationServerMetadata {\n 'pre-authorized_grant_anonymous_access_supported'?: boolean // OPTIONAL\n}\n\n// Re-export reused types from d15 for convenience\nexport type { KeyAttestationJWT, WalletAttestationJWT, ProofOfPossessionMap }\n","import { DynamicRegistrationClientMetadata, SigningAlgo } from '@sphereon/oid4vc-common'\n\nexport type OAuthResponseType = 'code' | 'token' | 'id_token' | 'code token' | 'code id_token' | 'token id_token' | 'code token id_token'\n\nexport type TokenEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'client_secret_jwt' | 'private_key_jwt' | 'none'\n\nexport type TokenEndpointAuthSigningAlg =\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'PS256'\n | 'PS384'\n | 'PS512'\n | 'HS256'\n | 'HS384'\n | 'HS512'\n\nexport type OAuthScope = 'openid' | 'profile' | 'email' | 'address' | 'phone' | 'offline_access'\n\nexport type OAuthResponseMode = 'query' | 'fragment' | 'form_post'\n\nexport type OAuthGrantType =\n | 'authorization_code'\n | 'implicit'\n | 'password'\n | 'client_credentials'\n | 'refresh_token'\n | 'urn:ietf:params:oauth:grant-type:device_code'\n | 'urn:ietf:params:oauth:grant-type:saml2-bearer'\n | 'urn:ietf:params:oauth:grant-type:jwt-bearer'\n\nexport type RevocationEndpointAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'client_secret_jwt' | 'private_key_jwt' | 'none'\n\nexport type RevocationEndpointAuthSigningAlg =\n | 'RS256'\n | 'RS384'\n | 'RS512'\n | 'ES256'\n | 'ES384'\n | 'ES512'\n | 'PS256'\n | 'PS384'\n | 'PS512'\n | 'HS256'\n | 'HS384'\n | 'HS512'\n\nexport type PKCECodeChallengeMethod = 'plain' | 'S256'\n\nexport interface AuthorizationServerMetadata extends DynamicRegistrationClientMetadata {\n issuer: string\n authorization_endpoint?: string\n authorization_challenge_endpoint?: string\n token_endpoint?: string\n token_endpoint_auth_methods_supported?: Array<TokenEndpointAuthMethod>\n token_endpoint_auth_signing_alg_values_supported?: Array<TokenEndpointAuthSigningAlg>\n\n registration_endpoint?: string\n scopes_supported?: Array<OAuthScope | string>\n response_types_supported: Array<OAuthResponseType>\n response_modes_supported?: Array<OAuthResponseMode>\n grant_types_supported?: Array<OAuthGrantType>\n service_documentation?: string\n ui_locales_supported?: string[]\n op_policy_uri?: string\n op_tos_uri?: string\n\n revocation_endpoint?: string\n revocation_endpoint_auth_methods_supported?: Array<RevocationEndpointAuthMethod>\n revocation_endpoint_auth_signing_alg_values_supported?: Array<RevocationEndpointAuthSigningAlg>\n\n introspection_endpoint?: string\n code_challenge_methods_supported?: Array<PKCECodeChallengeMethod>\n\n // TODO below fields are not in the rfc8414 spec, do we need them?\n pushed_authorization_request_endpoint?: string // The URL of the pushed authorization request endpoint at which a client can post an authorization request to exchange for a request_uri value usable at the authorization server\n // Note that the presence of pushed_authorization_request_endpoint is sufficient for a client to determine that it may use the PAR flow. A request_uri value obtained from the PAR endpoint is usable at the authorization endpoint regardless of other authorization server metadata such as request_uri_parameter_supported or require_request_uri_registration\n require_pushed_authorization_requests?: boolean // Boolean parameter indicating whether Indicates whether the client is required to use PAR to initiate authorization. If omitted, the default value is false.\n 'pre-authorized_grant_anonymous_access_supported'?: boolean // OPTIONAL. A JSON Boolean indicating whether the issuer accepts a Token Request with a Pre-Authorized Code but without a client id. The default is false\n // A JSON array containing a list of the JWS alg values (from the [IANA.JOSE.ALGS] registry) supported by the authorization server for DPoP proof JWTs.\n dpop_signing_alg_values_supported?: (string | SigningAlgo)[]\n // OIDC values\n frontchannel_logout_supported?: boolean\n frontchannel_logout_session_supported?: boolean\n backchannel_logout_supported?: boolean\n backchannel_logout_session_supported?: boolean\n userinfo_endpoint?: string\n check_session_iframe?: string\n end_session_endpoint?: string\n acr_values_supported?: string[]\n subject_types_supported?: string[]\n request_object_signing_alg_values_supported?: string[]\n display_values_supported?: string[]\n claim_types_supported?: string[]\n claims_supported?: string[]\n claims_parameter_supported?: boolean\n\n // VCI values. In case an AS provides a credential_endpoint itself\n credential_endpoint?: string\n deferred_credential_endpoint?: string\n nonce_endpoint?: string // New in v15\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any //We use any, so you can access properties if you know the structure\n}\n\n// These can be used be a reducer\nexport const authorizationServerMetadataFieldNames: Array<keyof AuthorizationServerMetadata> = [\n 'issuer',\n 'authorization_endpoint',\n 'authorization_challenge_endpoint',\n 'token_endpoint',\n 'jwks_uri',\n 'registration_endpoint',\n 'scopes_supported',\n 'response_types_supported',\n 'response_modes_supported',\n 'grant_types_supported',\n 'token_endpoint_auth_methods_supported',\n 'token_endpoint_auth_signing_alg_values_supported',\n 'service_documentation',\n 'ui_locales_supported',\n 'op_policy_uri',\n 'op_tos_uri',\n 'revocation_endpoint',\n 'revocation_endpoint_auth_methods_supported',\n 'revocation_endpoint_auth_signing_alg_values_supported',\n 'introspection_endpoint',\n 'introspection_endpoint_auth_methods_supported',\n 'introspection_endpoint_auth_signing_alg_values_supported',\n 'code_challenge_methods_supported',\n 'signed_metadata',\n] as const\n\nexport enum WellKnownEndpoints {\n OPENID_CONFIGURATION = '/.well-known/openid-configuration',\n OAUTH_AS = '/.well-known/oauth-authorization-server',\n OPENID4VCI_ISSUER = '/.well-known/openid-credential-issuer',\n}\n\nexport type AuthorizationServerType = 'OIDC' | 'OAuth 2.0' | 'OID4VCI' // OID4VCI means the Issuer hosts a token endpoint itself\n\nexport interface EndpointMetadata {\n issuer: string\n token_endpoint: string\n credential_endpoint: string\n deferred_credential_endpoint?: string\n notification_endpoint?: string\n authorization_server?: string\n authorization_endpoint?: string // Can be undefined in pre-auth flow\n authorization_challenge_endpoint?: string\n}\n","import { Alg } from './CredentialIssuance.types'\n\nexport const BAD_PARAMS = 'Wrong parameters provided'\nexport const URL_NOT_VALID = 'Request url is not valid'\nexport const JWS_NOT_VALID = 'JWS is not valid'\nexport const PROOF_CANT_BE_CONSTRUCTED = \"Proof can't be constructed.\"\nexport const NO_JWT_PROVIDED = 'No JWT provided'\nexport const TYP_ERROR = 'Typ must be \"openid4vci-proof+jwt\"'\nexport const ALG_ERROR = `Algorithm is a required field, you are free to use the signing algorithm of your choice or one of the following: ${Object.keys(\n Alg,\n).join(', ')}`\nexport const KID_JWK_X5C_ERROR = 'Only one must be present: x5c should not present when kid and/or jwk is already present'\nexport const KID_DID_NO_DID_ERROR = 'A DID value needs to be returned when kid is present'\nexport const DID_NO_DIDDOC_ERROR = 'A DID Document needs to be resolved when a DID is encountered'\nexport const AUD_ERROR = 'aud must be the URL of the credential issuer'\nexport const IAT_ERROR = 'iat must be the time at which the proof was issued'\nexport const NONCE_ERROR = 'nonce must be c_nonce provided by the credential issuer'\nexport const JWT_VERIFY_CONFIG_ERROR = 'JWT verify callback not configured correctly.'\nexport const ISSUER_CONFIG_ERROR = 'Issuer not configured correctly.'\nexport const UNKNOWN_CLIENT_ERROR = 'The client is not known by the issuer'\nexport const NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT = 'iss missing in authorization-code context'\nexport const ISS_PRESENT_IN_PRE_AUTHORIZED_CODE_CONTEXT = 'iss should be omitted in pre-authorized-code context'\nexport const ISS_MUST_BE_CLIENT_ID = 'iss must be the client id'\nexport const GRANTS_MUST_NOT_BE_UNDEFINED = 'Grants must not be undefined'\nexport const STATE_MISSING_ERROR = 'issuer state or pre-authorized key not found'\nexport const CREDENTIAL_MISSING_ERROR = 'Credential must be present in response'\nexport const UNSUPPORTED_GRANT_TYPE_ERROR = 'unsupported grant_type'\nexport const PRE_AUTHORIZED_CODE_REQUIRED_ERROR = 'pre-authorized_code is required'\nexport const USER_PIN_REQUIRED_ERROR = 'User pin is required'\nexport const USER_PIN_TX_CODE_SPEC_ERROR = 'user_pin is mixed with tx_code, indicating a spec mismatch'\nexport const USER_PIN_NOT_REQUIRED_ERROR = 'User pin is not required'\nexport const PIN_VALIDATION_ERROR = 'PIN must consist the following amount of characters:'\nexport const PIN_NOT_MATCH_ERROR = 'PIN is invalid'\nexport const INVALID_PRE_AUTHORIZED_CODE = 'pre-authorized_code is invalid'\nexport const EXPIRED_PRE_AUTHORIZED_CODE = 'pre-authorized_code is expired'\nexport const JWT_SIGNER_CALLBACK_REQUIRED_ERROR = 'JWT signer callback function is required'\nexport const STATE_MANAGER_REQUIRED_ERROR = 'StateManager instance is required'\nexport const NONCE_STATE_MANAGER_REQUIRED_ERROR = 'NonceStateManager instance is required'\nexport const ACCESS_TOKEN_ISSUER_REQUIRED_ERROR = 'access token issuer is required'\nexport const WRONG_METADATA_FORMAT = 'Wrong metadata format'\n","export enum OpenId4VCIVersion {\n VER_1_0_15 = 1015,\n VER_1_0 = 1100,\n VER_UNKNOWN = Number.MAX_VALUE,\n}\n\nexport enum DefaultURISchemes {\n INITIATE_ISSUANCE = 'openid-initiate-issuance',\n CREDENTIAL_OFFER = 'openid-credential-offer',\n}\n","import { AssertedUniformCredentialOffer } from './CredentialIssuance.types'\nimport { CredentialDataSupplierInput, NotificationRequest, StatusListOpts } from './Generic.types'\nimport { AuthorizationDetailsV1_0_15 } from './v1_0_15.types'\n\nexport interface StateType {\n createdAt: number\n expiresAt?: number\n}\n\nexport interface CredentialOfferSession extends StateType {\n clientId?: string\n credentialOffer: AssertedUniformCredentialOffer\n credentialDataSupplierInput?: CredentialDataSupplierInput // Optional storage that can help the credential Data Supplier. For instance to store credential input data during offer creation, if no additional data can be supplied later on\n txCode?: string // in here we only store the txCode, previously < V13 this was the userPin. We map the userPin onto this value\n status: IssueStatus\n error?: string\n lastUpdatedAt: number\n notification_id: string\n notification?: NotificationRequest\n issuerState?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n preAuthorizedCode?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n authorizationCode?: string\n redirectUri?: string\n statusLists?: Array<StatusListOpts>\n authorizationDetails?: AuthorizationDetailsV1_0_15[]\n}\n\nexport enum IssueStatus {\n OFFER_CREATED = 'OFFER_CREATED', // An offer is created. This is the initial state\n ACCESS_TOKEN_REQUESTED = 'ACCESS_TOKEN_REQUESTED', // Optional state, given the token endpoint could also be on a separate AS\n ACCESS_TOKEN_CREATED = 'ACCESS_TOKEN_CREATED', // Optional state, given the token endpoint could also be on a separate AS\n CREDENTIAL_REQUEST_RECEIVED = 'CREDENTIAL_REQUEST_RECEIVED', // Credential request received. Next state would either be error or issued\n CREDENTIAL_ISSUED = 'CREDENTIAL_ISSUED', // The credential iss issued from the issuer's perspective\n NOTIFICATION_CREDENTIAL_ACCEPTED = 'NOTIFICATION_CREDENTIAL_ACCEPTED', // The holder/user stored the credential in the wallet (If notifications are enabled)\n NOTIFICATION_CREDENTIAL_DELETED = 'NOTIFICATION_CREDENTIAL_DELETED', // The holder/user did not store the credential in the wallet (If notifications are enabled)\n NOTIFICATION_CREDENTIAL_FAILURE = 'NOTIFICATION_CREDENTIAL_FAILURE', // The holder/user encountered an error (If notifications are enabled)\n ERROR = 'ERROR', // An error occurred\n}\n\nexport interface CNonceState extends StateType {\n cNonce: string\n}\n\nexport interface URIState extends StateType {\n issuerState?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n preAuthorizedCode?: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n uri: string //todo: Probably good to hash it here, since it would come in from the client and we could match the hash and thus use the client value\n correlationId?: string\n}\n\nexport interface IssueStatusResponse {\n createdAt: number\n lastUpdatedAt: number\n expiresAt?: number\n status: IssueStatus\n error?: string\n clientId?: string\n statusLists?: Array<StatusListOpts>\n}\n\nexport interface IStateManager<T extends StateType> {\n set(id: string, stateValue: T): Promise<void>\n\n get(id: string): Promise<T | undefined>\n\n has(id: string): Promise<boolean>\n\n delete(id: string): Promise<boolean>\n\n clearExpired(timestamp?: number): Promise<void> // clears all expired states compared against timestamp if provided, otherwise current timestamp\n\n clearAll(): Promise<void> // clears all states\n\n getAsserted(id: string): Promise<T>\n\n startCleanupRoutine(timeout?: number): Promise<void>\n\n stopCleanupRoutine(): Promise<void>\n}\n","export enum TokenErrorResponse {\n invalid_request = 'invalid_request',\n invalid_grant = 'invalid_grant',\n invalid_client = 'invalid_client', // this code has been added only in v1_0-11, but I've added this to the common interface. @nklomp is this ok?\n invalid_scope = 'invalid_scope',\n invalid_dpop_proof = 'invalid_dpop_proof',\n}\n\nexport class TokenError extends Error {\n private readonly _statusCode: number\n private readonly _responseError: TokenErrorResponse\n constructor(statusCode: number, responseError: TokenErrorResponse, message: string) {\n super(message)\n this._statusCode = statusCode\n this._responseError = responseError\n\n // 👇️ because we are extending a built-in class\n Object.setPrototypeOf(this, TokenError.prototype)\n }\n get statusCode(): number {\n return this._statusCode\n }\n get responseError(): TokenErrorResponse {\n return this._responseError\n }\n\n getDescription() {\n return this.message\n }\n}\n","export interface ComponentOptions {\n /**\n * Component options for data/ECC.\n */\n data?: {\n /**\n * Scale factor for data/ECC dots.\n * @default 1\n */\n scale?: number\n }\n\n /**\n * Component options for timing patterns.\n */\n timing?: {\n /**\n * Scale factor for timing patterns.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for timing patterns.\n * @default false\n */\n protectors?: boolean\n }\n\n /**\n * Component options for alignment patterns.\n */\n alignment?: {\n /**\n * Scale factor for alignment patterns.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for alignment patterns.\n * @default false\n */\n protectors?: boolean\n }\n\n /**\n * Component options for alignment pattern on the bottom-right corner.\n */\n cornerAlignment?: {\n /**\n * Scale factor for alignment pattern on the bottom-right corner.\n * @default 1\n */\n scale?: number\n\n /**\n * Protector for alignment pattern on the bottom-right corner.\n * @default true\n */\n protectors?: boolean\n }\n}\n\nexport interface QRCodeOpts {\n /**\n * Size of the QR code in pixel.\n *\n * @defaultValue 400\n */\n size?: number\n\n /**\n * Size of margins around the QR code body in pixel.\n *\n * @defaultValue 20\n */\n margin?: number\n\n /**\n * Error correction level of the QR code.\n *\n * Accepts a value provided by _QRErrorCorrectLevel_.\n *\n * For more information, please refer to [https://www.qrcode.com/en/about/error_correction.html](https://www.qrcode.com/en/about/error_correction.html).\n *\n * @defaultValue 0\n */\n correctLevel?: number\n\n /**\n * **This is an advanced option.**\n *\n * Specify the mask pattern to be used in QR code encoding.\n *\n * Accepts a value provided by _QRMaskPattern_.\n *\n * To find out all eight mask patterns, please refer to [https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg](https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg)\n *\n * For more information, please refer to [https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking](https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking).\n */\n maskPattern?: number\n\n /**\n * **This is an advanced option.**\n *\n * Specify the version to be used in QR code encoding.\n *\n * Accepts an integer in range [1, 40].\n *\n * For more information, please refer to [https://www.qrcode.com/en/about/version.html](https://www.qrcode.com/en/about/version.html).\n */\n version?: number\n\n /**\n * Options to control components in the QR code.\n *\n * @deafultValue undefined\n */\n components?: ComponentOptions\n\n /**\n * Color of the blocks on the QR code.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"#000000\"\n */\n colorDark?: string\n\n /**\n * Color of the empty areas on the QR code.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"#ffffff\"\n */\n colorLight?: string\n\n /**\n * Automatically calculate the _colorLight_ value from the QR code's background.\n *\n * @defaultValue true\n */\n autoColor?: boolean\n\n /**\n * Background image to be used in the QR code.\n *\n * Accepts a `data:` string in web browsers or a Buffer in Node.js.\n *\n * @defaultValue undefined\n */\n backgroundImage?: string | Buffer\n\n /**\n * Color of the dimming mask above the background image.\n *\n * Accepts a CSS <color>.\n *\n * For more information about CSS <color>, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n *\n * @defaultValue \"rgba(0, 0, 0, 0)\"\n */\n backgroundDimming?: string\n\n /**\n * GIF background image to be used in the QR code.\n *\n * @defaultValue undefined\n */\n gifBackground?: ArrayBuffer\n\n /**\n * Use a white margin instead of a transparent one which reveals the background of the QR code on margins.\n *\n * @defaultValue true\n */\n whiteMargin?: boolean\n\n /**\n * Logo image to be displayed at the center of the QR code.\n *\n * Accepts a `data:` string in web browsers or a Buffer in Node.js.\n *\n * When set to `undefined` or `null`, the logo is disabled.\n *\n * @defaultValue undefined\n */\n logoImage?: string | Buffer\n\n /**\n * Ratio of the logo size to the QR code size.\n *\n * @defaultValue 0.2\n */\n logoScale?: number\n\n /**\n * Size of margins around the logo image in pixels.\n *\n * @defaultValue 6\n */\n logoMargin?: number\n\n /**\n * Corner radius of the logo image in pixels.\n *\n * @defaultValue 8\n */\n logoCornerRadius?: number\n\n /**\n * @deprecated\n *\n * Ratio of the real size to the full size of the blocks.\n *\n * This can be helpful when you want to make more parts of the background visible.\n *\n * @deafultValue 0.4\n */\n dotScale?: number\n}\n","import { Loggers, ObjectUtils } from '@sphereon/ssi-types'\nimport { jwtDecode, JwtPayload } from 'jwt-decode'\nimport { CredentialOfferPayloadV1_0_15, VCI_LOG_COMMON } from '../index'\n\nimport {\n AssertedUniformCredentialOffer,\n AuthzFlowType,\n CredentialOffer,\n CredentialOfferPayload,\n DefaultURISchemes,\n Grant,\n GrantTypes,\n OpenId4VCIVersion,\n OpenIDResponse,\n PRE_AUTH_CODE_LITERAL,\n PRE_AUTH_GRANT_LITERAL,\n UniformCredentialOffer,\n UniformCredentialOfferPayload,\n UniformCredentialOfferRequest,\n} from '../types'\n\nimport { getJson } from './HttpUtils'\nimport { base64urlToString } from '@sphereon/oid4vc-common'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:offer')\n\nexport function determineSpecVersionFromURI(uri: string): OpenId4VCIVersion {\n let version = determineSpecVersionFromScheme(uri, OpenId4VCIVersion.VER_UNKNOWN) ?? OpenId4VCIVersion.VER_UNKNOWN\n // version = getVersionFromURIParam(uri, version, [OpenId4VCIVersion.VER_1_0_13, OpenId4VCIVersion.VER_1_0_15], 'tx_code') (left as examples)\n // version = getVersionFromURIParam(uri, version, [OpenId4VCIVersion.VER_1_0_15], 'credential_offer_uri ') // optional so last resort\n if (version === OpenId4VCIVersion.VER_UNKNOWN) {\n version = OpenId4VCIVersion.VER_1_0\n }\n return version\n}\n\nexport function determineSpecVersionFromScheme(credentialOfferURI: string, openId4VCIVersion: OpenId4VCIVersion) {\n const scheme = getScheme(credentialOfferURI)\n\n const url = toUrlWithDummyBase(credentialOfferURI)\n const qp = url.searchParams\n\n // ----------------- 1) openid-initiate-issuance -----------------\n if (scheme === DefaultURISchemes.INITIATE_ISSUANCE) {\n // v15 indicators\n if (qp.has('credential_offer') || qp.has('credential_offer_uri')) {\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_1_0_15], scheme)\n }\n\n // Could not decide\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n }\n\n // ----------------- 2) openid-credential-offer -----------------\n if (scheme === DefaultURISchemes.CREDENTIAL_OFFER) {\n // Indirection URI -> Draft 15 style (can't confirm 11/13 via scheme alone)\n if (qp.has('credential_offer_uri')) {\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_1_0_15], scheme)\n }\n\n // Inline payload -> sniff JSON keys\n const rawParam = getParamValueLoose(qp, 'credential_offer')\n if (rawParam) {\n const decoded = tryDecodeOffer(rawParam)\n\n const version = sniffOfferVersion(decoded)\n if (version !== OpenId4VCIVersion.VER_UNKNOWN) {\n return recordVersion(openId4VCIVersion, [version], scheme)\n }\n }\n\n // If we still can't tell, DO NOT default to 15 — stay unknown\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n }\n\n // ----------------- 3) Unknown scheme -----------------\n return recordVersion(openId4VCIVersion, [OpenId4VCIVersion.VER_UNKNOWN], scheme)\n}\n\n/* ----------------- helpers ----------------- */\n\n/**\n * Replace custom \"openid-...\" schemes with a dummy base so URL() can parse query params.\n * Make sure to end with '/?' to avoid the \"?param\" name issue.\n */\nfunction toUrlWithDummyBase(uri: string): URL {\n const normalized = uri.replace(/^openid-[^?]+:\\/\\//, 'https://dummy/?')\n return new URL(normalized)\n}\n\n/**\n * Some runtimes/libraries have bugs that result in the param name being `'?credential_offer'`.\n * This helper checks both.\n */\nfunction getParamValueLoose(qp: URLSearchParams, key: string): string | null {\n if (qp.has(key)) return qp.get(key)\n if (qp.has(`?${key}`)) return qp.get(`?${key}`)\n return null\n}\n\n/**\n * Try to decode the inline offer string:\n * 1) decodeURIComponent if needed,\n * 2) base64url decode if it looks base64y,\n * return the final string (JSON) or empty string on failure.\n */\nfunction tryDecodeOffer(input: string): string {\n let candidate = input\n\n try {\n candidate = decodeURIComponent(candidate)\n } catch {\n /* ignore */\n }\n // Fast check for base64url: only URL-safe chars and no braces\n if (!/[{}]/.test(candidate) && /^[A-Za-z0-9\\-_]+$/.test(candidate)) {\n try {\n const b64 = candidate\n .replace(/-/g, '+')\n .replace(/_/g, '/')\n .padEnd(Math.ceil(candidate.length / 4) * 4, '=')\n candidate = atob(b64)\n } catch {\n /* ignore */\n }\n }\n return candidate // may still be encoded JSON but good enough for key sniffing\n}\n\n/**\n * Look for version-specific keys.\n * returns only VER_UNKNOWN atm, for future versions support\n */\nfunction sniffOfferVersion(jsonLike: string): OpenId4VCIVersion {\n if (!jsonLike) return OpenId4VCIVersion.VER_UNKNOWN\n\n // Use cheap regex so we don't crash on invalid JSON\n // const has = (k: string) => new RegExp(`\"${k}\"\\\\s*:`, 'i').test(jsonLike);\n // if (has('credentials')) return OpenId4VCIVersion.VER_1_0_11; left as example\n\n return OpenId4VCIVersion.VER_UNKNOWN\n}\n\nexport function getScheme(credentialOfferURI: string) {\n if (!credentialOfferURI || !credentialOfferURI.includes('://')) {\n throw Error('Invalid credential offer URI')\n }\n return credentialOfferURI.split('://')[0]\n}\n\nexport function getIssuerFromCredentialOfferPayload(request: CredentialOfferPayload): string | undefined {\n if (!request || (!('issuer' in request) && !('credential_issuer' in request))) {\n return undefined\n }\n return 'issuer' in request ? request.issuer : request['credential_issuer']\n}\n\nexport const getClientIdFromCredentialOfferPayload = (credentialOffer?: CredentialOfferPayload): string | undefined => {\n if (!credentialOffer) {\n return\n }\n if ('client_id' in credentialOffer) {\n return credentialOffer.client_id\n }\n\n const state: string | undefined = getStateFromCredentialOfferPayload(credentialOffer)\n if (state && isJWT(state)) {\n const decoded = jwtDecode<JwtPayload>(state, { header: false })\n if ('client_id' in decoded && typeof decoded.client_id === 'string') {\n return decoded.client_id\n }\n }\n return\n}\n\nconst isJWT = (input?: string) => {\n if (!input) {\n return false\n }\n const noParts = input?.split('.').length\n return input?.startsWith('ey') && noParts === 3\n}\nexport const getStateFromCredentialOfferPayload = (credentialOffer: CredentialOfferPayload): string | undefined => {\n if ('grants' in credentialOffer) {\n if (credentialOffer.grants?.authorization_code) {\n return credentialOffer.grants.authorization_code.issuer_state\n } else if (credentialOffer.grants?.[PRE_AUTH_GRANT_LITERAL]) {\n return credentialOffer.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]\n }\n }\n if ('op_state' in credentialOffer) {\n // older spec versions\n return credentialOffer.op_state\n } else if (PRE_AUTH_CODE_LITERAL in credentialOffer) {\n return credentialOffer[PRE_AUTH_CODE_LITERAL]\n }\n\n return\n}\n\nexport function determineSpecVersionFromOffer(offer: CredentialOfferPayload | CredentialOffer): OpenId4VCIVersion {\n if (isCredentialOfferV1_0_15(offer)) {\n // Cannot distinguish 1.0 final from draft 15 based on offer alone (same fields).\n // Default to VER_1_0 since it's the latest version. Metadata-based detection\n // will refine this if the issuer uses d15-specific metadata fields.\n return OpenId4VCIVersion.VER_1_0\n }\n return OpenId4VCIVersion.VER_UNKNOWN\n}\n\nexport function isCredentialOfferVersion(offer: CredentialOfferPayload | CredentialOffer, min: OpenId4VCIVersion, max?: OpenId4VCIVersion) {\n if (max && max.valueOf() < min.valueOf()) {\n throw Error(`Cannot have a max ${max.valueOf()} version smaller than the min version ${min.valueOf()}`)\n }\n const version = determineSpecVersionFromOffer(offer)\n if (version.valueOf() < min.valueOf()) {\n logger.debug(`Credential offer version (${version.valueOf()}) is lower than minimum required version (${min.valueOf()})`)\n return false\n } else if (max && version.valueOf() > max.valueOf()) {\n logger.debug(`Credential offer version (${version.valueOf()}) is higher than maximum required version (${max.valueOf()})`)\n return false\n }\n return true\n}\n\nfunction isCredentialOfferV1_0_15(offer: CredentialOfferPayload | CredentialOffer): boolean {\n if (!offer) {\n return false\n }\n offer = normalizeOfferInput(offer)\n\n // Direct payload\n if ('credential_issuer' in offer && 'credential_configuration_ids' in offer) {\n return Array.isArray((offer as any).credential_configuration_ids)\n }\n\n // Wrapped in credential_offer\n if ('credential_offer' in offer && offer['credential_offer']) {\n return isCredentialOfferV1_0_15((offer as any)['credential_offer'])\n }\n\n // Fallback: URI only (credential_offer_uri) – still v15 style but cannot assert without dereferencing.\n return 'credential_offer_uri' in offer\n}\n\nexport async function toUniformCredentialOfferRequest(\n offer: CredentialOffer,\n opts?: {\n resolve?: boolean\n version?: OpenId4VCIVersion\n },\n): Promise<UniformCredentialOfferRequest> {\n let version = opts?.version ?? determineSpecVersionFromOffer(offer)\n let originalCredentialOffer = offer.credential_offer\n let credentialOfferURI: string | undefined\n if ('credential_offer_uri' in offer && offer?.credential_offer_uri !== undefined) {\n credentialOfferURI = offer.credential_offer_uri\n\n if (opts?.resolve || opts?.resolve === undefined) {\n VCI_LOG_COMMON.log(`Credential offer contained a URI. Will use that to get the credential offer payload: ${credentialOfferURI}`)\n originalCredentialOffer = (await resolveCredentialOfferURI(credentialOfferURI)) as CredentialOfferPayloadV1_0_15\n } else if (!originalCredentialOffer) {\n throw Error(`Credential offer uri (${credentialOfferURI}) found, but resolution was explicitly disabled and credential_offer was supplied`)\n }\n // We need to redetermine the version of the offer, as we only had the offer_uri until now\n version = determineSpecVersionFromOffer(originalCredentialOffer)\n VCI_LOG_COMMON.log(`Offer URI payload determined to be of version ${version}`)\n }\n if (!originalCredentialOffer) {\n throw Error('No credential offer available')\n }\n const payload = toUniformCredentialOfferPayload(originalCredentialOffer, { ...opts, version })\n const supportedFlows = determineFlowType(payload, version)\n return {\n credential_offer: payload,\n original_credential_offer: originalCredentialOffer,\n ...(credentialOfferURI && { credential_offer_uri: credentialOfferURI }),\n supportedFlows,\n version,\n }\n}\n\nexport function isPreAuthCode(request: UniformCredentialOfferPayload | UniformCredentialOffer) {\n request = normalizeOfferInput(request)\n\n const payload = 'credential_offer' in request ? request.credential_offer : (request as UniformCredentialOfferPayload)\n return payload?.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL] !== undefined\n}\n\nexport async function assertedUniformCredentialOffer(\n origCredentialOffer: UniformCredentialOffer,\n opts?: {\n resolve?: boolean\n },\n): Promise<AssertedUniformCredentialOffer> {\n const credentialOffer = JSON.parse(JSON.stringify(origCredentialOffer))\n if (credentialOffer.credential_offer_uri && !credentialOffer.credential_offer) {\n if (opts?.resolve === undefined || opts.resolve) {\n credentialOffer.credential_offer = await resolveCredentialOfferURI(credentialOffer.credential_offer_uri)\n } else {\n throw Error(`No credential_offer present, but we did get a URI, but resolution was explicitly disabled`)\n }\n }\n if (!credentialOffer.credential_offer) {\n throw Error(`No credential_offer present`)\n }\n credentialOffer.credential_offer = await toUniformCredentialOfferPayload(credentialOffer.credential_offer, { version: credentialOffer.version })\n return credentialOffer as AssertedUniformCredentialOffer\n}\n\nexport async function resolveCredentialOfferURI(uri?: string): Promise<UniformCredentialOfferPayload | undefined> {\n if (!uri) {\n return undefined\n }\n const response = (await getJson(uri)) as OpenIDResponse<UniformCredentialOfferPayload>\n if (!response || !response.successBody) {\n throw Error(`Could not get credential offer from uri: ${uri}: ${JSON.stringify(response?.errorBody)}`)\n }\n return response.successBody as UniformCredentialOfferPayload\n}\n\nexport function toUniformCredentialOfferPayload(\n rawOffer: CredentialOfferPayload,\n opts?: {\n version?: OpenId4VCIVersion\n },\n): UniformCredentialOfferPayload {\n const offer = normalizeOfferInput<CredentialOfferPayload>(rawOffer)\n\n // todo: create test to check idempotence once a payload is already been made uniform.\n const version = opts?.version ?? determineSpecVersionFromOffer(offer)\n if (version >= OpenId4VCIVersion.VER_1_0_15) {\n const orig = offer as UniformCredentialOfferPayload\n return {\n ...orig,\n }\n }\n\n throw Error(`Could not create uniform payload for version ${version}`)\n}\n\nexport function determineFlowType(\n suppliedOffer: AssertedUniformCredentialOffer | UniformCredentialOfferPayload,\n version: OpenId4VCIVersion,\n): AuthzFlowType[] {\n const payload: UniformCredentialOfferPayload = getCredentialOfferPayload(suppliedOffer)\n const supportedFlows: AuthzFlowType[] = []\n if (payload.grants?.authorization_code) {\n supportedFlows.push(AuthzFlowType.AUTHORIZATION_CODE_FLOW)\n }\n if (payload.grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]) {\n supportedFlows.push(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)\n }\n return supportedFlows\n}\n\nexport function getCredentialOfferPayload(offer: AssertedUniformCredentialOffer | UniformCredentialOfferPayload): UniformCredentialOfferPayload {\n offer = normalizeOfferInput(offer)\n\n let payload: UniformCredentialOfferPayload\n if ('credential_offer' in offer && offer['credential_offer']) {\n payload = offer.credential_offer\n } else {\n payload = offer as UniformCredentialOfferPayload\n }\n return payload\n}\n\nexport function determineGrantTypes(\n offer:\n | AssertedUniformCredentialOffer\n | UniformCredentialOfferPayload\n | ({\n grants: Grant\n } & Record<never, never>),\n): GrantTypes[] {\n offer = normalizeOfferInput(offer)\n\n let grants: Grant | undefined\n if ('grants' in offer && offer.grants) {\n grants = offer.grants\n } else {\n grants = getCredentialOfferPayload(offer as AssertedUniformCredentialOffer | UniformCredentialOfferPayload).grants\n }\n\n const types: GrantTypes[] = []\n if (grants) {\n if ('authorization_code' in grants) {\n types.push(GrantTypes.AUTHORIZATION_CODE)\n }\n if (PRE_AUTH_GRANT_LITERAL in grants) {\n types.push(GrantTypes.PRE_AUTHORIZED_CODE)\n }\n }\n return types\n}\n/*\nfunction getVersionFromURIParam(\n credentialOfferURI: string,\n currentVersion: OpenId4VCIVersion,\n matchingVersion: OpenId4VCIVersion[],\n param: string,\n allowUpgrade = true\n) {\n if (credentialOfferURI.includes(param)) {\n return recordVersion(currentVersion, matchingVersion, param, allowUpgrade)\n }\n return currentVersion\n}*/\n\nfunction recordVersion(currentVersion: OpenId4VCIVersion, matchingVersion: OpenId4VCIVersion[], key: string, allowUpgrade = true) {\n matchingVersion = matchingVersion.sort().reverse()\n if (currentVersion === OpenId4VCIVersion.VER_UNKNOWN) {\n return matchingVersion[0]\n } else if (matchingVersion.includes(currentVersion)) {\n if (!allowUpgrade) {\n return currentVersion\n }\n return matchingVersion[0]\n }\n\n throw new Error(\n `Invalid param. Some keys have been used from version: ${currentVersion} version while '${key}' is used from version: ${JSON.stringify(matchingVersion)}`,\n )\n}\n\nexport function getCredentialConfigurationIdsFromOfferV1_0_15(offer: CredentialOfferPayloadV1_0_15): string[] {\n return offer.credential_configuration_ids ?? []\n}\n\nexport function normalizeOfferInput<T = any>(input: unknown): T {\n if (typeof input !== 'string') {\n return input as T\n }\n\n // JWT?\n if (ObjectUtils.isString(input) && input.startsWith('ey')) {\n const payload = base64urlToString(input)\n return JSON.parse(payload) as T\n }\n\n // JSON?\n try {\n return JSON.parse(input) as T\n } catch {}\n\n // Last resort: just return as-is\n return input as T\n}\n","import { BAD_PARAMS, DecodeURIAsJsonOpts, EncodeJsonAsURIOpts, JsonURIMode, SearchValue } from '../types'\n\n/**\n * @type {(json: {[s:string]: never} | ArrayLike<never> | string | object, opts?: EncodeJsonAsURIOpts)} encodes a Json object into a URI\n * @param { {[s:string]: never} | ArrayLike<never> | string | object } json\n * @param {EncodeJsonAsURIOpts} [opts] Option to encode json as uri\n * - urlTypeProperties: a list of properties of which the value is a URL\n * - arrayTypeProperties: a list of properties which are an array\n */\n\n// /* eslint-disable @typescript-eslint/no-explicit-any */\nexport function convertJsonToURI(\n json:\n | {\n [s: string]: never\n }\n | ArrayLike<never>\n | string\n | object,\n opts?: EncodeJsonAsURIOpts,\n): string {\n if (typeof json === 'string') {\n return convertJsonToURI(JSON.parse(json), opts)\n }\n\n const results = []\n\n function encodeAndStripWhitespace(key: string): string {\n return encodeURIComponent(key.replace(' ', ''))\n }\n\n let components: string\n if (opts?.mode === JsonURIMode.JSON_STRINGIFY) {\n // v11 changed from encoding every param to a encoded json object with a credential_offer param key\n components = encodeAndStripWhitespace(JSON.stringify(json))\n } else {\n // mode is x-form-www-urlencoded\n for (const [key, value] of Object.entries(json)) {\n if (!value) {\n continue\n }\n //Skip properties that are not of URL type\n if (!opts?.uriTypeProperties?.includes(key)) {\n results.push(`${key}=${value}`)\n continue\n }\n if (opts?.arrayTypeProperties?.includes(key) && Array.isArray(value)) {\n results.push(value.map((v) => `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(v, /\\./g)}`).join('&'))\n continue\n }\n const isBool = typeof value == 'boolean'\n const isNumber = typeof value == 'number'\n const isString = typeof value == 'string'\n let encoded\n if (isBool || isNumber) {\n encoded = `${encodeAndStripWhitespace(key)}=${value}`\n } else if (isString) {\n encoded = `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(value, /\\./g)}`\n } else {\n encoded = `${encodeAndStripWhitespace(key)}=${customEncodeURIComponent(JSON.stringify(value), /\\./g)}`\n }\n results.push(encoded)\n }\n components = results.join('&')\n }\n if (opts?.baseUrl) {\n if (opts.baseUrl.endsWith('=')) {\n if (opts.param) {\n throw Error('Cannot combine param with an url ending in =')\n }\n return `${opts.baseUrl}${components}`\n } else if (!opts.baseUrl.includes('?')) {\n return `${opts.baseUrl}?${opts.param ? opts.param + '=' : ''}${components}`\n } else if (opts.baseUrl.endsWith('?')) {\n return `${opts.baseUrl}${opts.param ? opts.param + '=' : ''}${components}`\n } else {\n return `${opts.baseUrl}${opts.param ? '&' + opts.param : ''}=${components}`\n }\n }\n return components\n}\n\n/**\n * @type {(uri: string, opts?: DecodeURIAsJsonOpts): unknown} convertURIToJsonObject converts an URI into a Json object decoding its properties\n * @param {string} uri\n * @param {DecodeURIAsJsonOpts} [opts]\n * - requiredProperties: the required properties\n * - arrayTypeProperties: properties that can show up more that once\n * @returns JSON object\n */\nexport function convertURIToJsonObject(uri: string, opts?: DecodeURIAsJsonOpts): unknown {\n if (!uri || (opts?.requiredProperties && !opts.requiredProperties?.every((p) => uri.includes(p)))) {\n throw new Error(BAD_PARAMS)\n }\n\n const uriComponents = getURIComponentsAsArray(uri, opts?.arrayTypeProperties)\n return decodeJsonProperties(uriComponents)\n}\n\nexport function decodeJsonProperties(parts: string[] | string[][]): unknown {\n const result: { [s: string]: unknown } | ArrayLike<unknown> = {}\n for (const key in parts) {\n const value = parts[key]\n if (!value) {\n continue\n }\n if (Array.isArray(value)) {\n result[decodeURIComponent(key)] = value.map((v) => decodeURIComponent(v))\n continue\n }\n\n const isBool = typeof value == 'boolean'\n const isNumber = typeof value == 'number'\n const isString = typeof value == 'string'\n const isObject = typeof value == 'object'\n if (isBool || isNumber) {\n result[decodeURIComponent(key)] = value\n } else if (isString) {\n const decoded = decodeURIComponent(value)\n if (decoded.startsWith('{') && decoded.endsWith('}')) {\n result[decodeURIComponent(key)] = JSON.parse(decoded)\n } else {\n result[decodeURIComponent(key)] = decoded\n }\n } else if (isObject) {\n result[decodeURIComponent(key)] = decodeJsonProperties(value)\n }\n }\n return result\n}\n\n/**\n * @function get URI Components as Array\n * @param {string} uri uri\n * @param {string[]} [arrayTypes] array of string containing array like keys\n */\nexport function getURIComponentsAsArray(uri: string, arrayTypes?: string[]): string[] | string[][] {\n const parts = uri.includes('?') ? uri.split('?')[1] : uri.includes('://') ? uri.split('://')[1] : uri\n const json: string[] | string[][] = []\n const dict: string[] = parts.split('&')\n for (const entry of dict) {\n const pair: string[] = entry.split('=')\n const p0: any = pair[0]\n const p1: any = pair[1]\n if (arrayTypes?.includes(p0)) {\n const key = json[p0]\n if (Array.isArray(key)) {\n key.push(p1)\n } else {\n json[p0] = [p1]\n }\n continue\n }\n json[p0] = p1\n }\n return json\n}\n\n/**\n * @function customEncodeURIComponent is used to encode chars that are not encoded by default\n * @param searchValue The pattern/regexp to find the char(s) to be encoded\n * @param uriComponent query string\n */\nfunction customEncodeURIComponent(uriComponent: string, searchValue: SearchValue): string {\n // -_.!~*'() are not escaped because they are considered safe.\n // Add them to the regex as you need\n return encodeURIComponent(uriComponent).replace(searchValue, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)\n}\n","import {\n AuthorizationDetailsV1_0_15,\n CredentialConfigurationSupportedMsoMdocV1_0_15,\n CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialDefinitionJwtVcJsonV1_0_15,\n VCI_LOG_COMMON,\n} from '../index'\nimport {\n CredentialConfigurationSupported,\n CredentialConfigurationSupportedSdJwtVcV1_0_15,\n CredentialOfferFormatV1_0_11,\n CredentialsSupportedLegacy,\n CredentialSupportedMsoMdoc,\n CredentialSupportedSdJwtVc,\n JsonLdIssuerCredentialDefinition,\n} from '../types'\n\nexport function isW3cCredentialSupported(\n supported: CredentialConfigurationSupported | CredentialsSupportedLegacy,\n): supported is Exclude<\n CredentialConfigurationSupported,\n | CredentialConfigurationSupportedMsoMdocV1_0_15\n | CredentialSupportedMsoMdoc\n | CredentialConfigurationSupportedSdJwtVcV1_0_15\n | CredentialSupportedSdJwtVc\n> {\n return ['jwt_vc_json', 'jwt_vc_json-ld', 'ldp_vc', 'jwt_vc'].includes(supported.format)\n}\n\nexport const getNumberOrUndefined = (input?: string): number | undefined => {\n return input && !isNaN(+input) ? +input : undefined\n}\n\n/**\n * The specs had many places where types could be expressed. This method ensures we get them in any way possible\n * @param subject\n */\nexport function getTypesFromObject(\n subject:\n | CredentialConfigurationSupported\n | CredentialOfferFormatV1_0_11\n | CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialDefinitionJwtVcJsonV1_0_15\n | JsonLdIssuerCredentialDefinition\n | string,\n): string[] | undefined {\n if (subject === undefined) {\n return undefined\n } else if (typeof subject === 'string') {\n return [subject]\n } else if ('credential_definition' in subject) {\n return getTypesFromObject(\n subject.credential_definition as\n | CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15\n | CredentialDefinitionJwtVcJsonV1_0_15\n | JsonLdIssuerCredentialDefinition,\n )\n } else if ('types' in subject && subject.types) {\n return Array.isArray(subject.types) ? subject.types : [subject.types as string]\n } else if ('type' in subject && subject.type) {\n return Array.isArray(subject.type) ? subject.type : [subject.type as string]\n } else if ('vct' in subject && subject.vct) {\n return [subject.vct as string]\n } else if ('doctype' in subject && subject.doctype) {\n return [subject.doctype as string]\n }\n VCI_LOG_COMMON.warning('Could not deduce credential types. Probably a failure down the line will happen!')\n return undefined\n}\n\nexport function getTypesFromAuthorizationDetails(\n authDetails: AuthorizationDetailsV1_0_15,\n opts?: { configIdAsType?: boolean },\n): string[] | undefined {\n const { configIdAsType = false } = { ...opts }\n if (typeof authDetails === 'string') {\n return [authDetails]\n } else if ('types' in authDetails && Array.isArray(authDetails.types)) {\n return authDetails.types\n } else if (configIdAsType && authDetails.credential_configuration_id) {\n return [authDetails.credential_configuration_id]\n }\n\n return undefined\n}\n\nexport function getTypesFromCredentialSupported(\n credentialSupported: CredentialConfigurationSupported,\n opts?: { filterVerifiableCredential: boolean },\n) {\n let types: string[] = []\n const format = credentialSupported.format\n if (format === 'jwt_vc_json' || format === 'jwt_vc' || format === 'jwt_vc_json-ld' || format === 'ldp_vc') {\n types = getTypesFromObject(credentialSupported) ?? []\n } else if (format === 'dc+sd-jwt' || format === 'vc+sd-jwt') {\n types = [credentialSupported.vct]\n } else if (format === 'mso_mdoc') {\n types = [credentialSupported.doctype]\n } else {\n throw Error(`Unsupported credential format '${format}'`)\n }\n\n if (!types || types.length === 0) {\n throw Error(`Could not deduce types from credential supported (format '${format}')`)\n }\n if (opts?.filterVerifiableCredential) {\n return types.filter((type) => type !== 'VerifiableCredential')\n }\n return types\n}\n","import { CredentialConfigurationSupportedV1_0_15, VCI_LOG_COMMON } from '../index'\nimport {\n AuthorizationServerMetadata,\n CredentialConfigurationSupported,\n CredentialIssuerMetadata,\n IssuerMetadata,\n MetadataDisplay,\n OID4VCICredentialFormat,\n OpenId4VCIVersion,\n} from '../types'\nimport { getTypesFromObject, isW3cCredentialSupported } from './TypeConversionUtils'\n\nexport function getSupportedCredentials(opts?: {\n issuerMetadata?: CredentialIssuerMetadata | IssuerMetadata\n version: OpenId4VCIVersion\n types?: string[][]\n format?: OID4VCICredentialFormat | string | (OID4VCICredentialFormat | string)[]\n}): Record<string, CredentialConfigurationSupportedV1_0_15> | Array<CredentialConfigurationSupported> {\n const { version = OpenId4VCIVersion.VER_1_0_15, types } = opts ?? {}\n if (types && Array.isArray(types)) {\n return types\n .map((typeSet) => {\n return getSupportedCredential({ ...opts, version, types: typeSet })\n })\n .reduce(\n (acc, result) => {\n Object.assign(acc, result)\n return acc\n },\n {} as Record<string, CredentialConfigurationSupportedV1_0_15>,\n )\n }\n\n return getSupportedCredential(opts ? { ...opts, types: undefined } : undefined)\n}\n\nexport function determineVersionsFromIssuerMetadata(issuerMetadata: CredentialIssuerMetadata | IssuerMetadata): Array<OpenId4VCIVersion> {\n const versions = new Set<OpenId4VCIVersion>()\n if ('credential_configurations_supported' in issuerMetadata) {\n // detect 1.0 final vs draft 15 based on metadata field differences\n let is1_0Final = false\n\n // 1.0 final uses batch_credential_issuance_supported (boolean) instead of batch_credential_issuance (object)\n if ('batch_credential_issuance_supported' in issuerMetadata && typeof (issuerMetadata as any).batch_credential_issuance_supported === 'boolean') {\n is1_0Final = true\n }\n\n // 1.0 final has credential_issuer_public_key\n if ('credential_issuer_public_key' in issuerMetadata) {\n is1_0Final = true\n }\n\n // Check credential configs for 1.0-specific fields\n if (!is1_0Final) {\n const configs = issuerMetadata.credential_configurations_supported\n if (configs) {\n for (const config of Object.values(configs)) {\n // 1.0 final uses cryptographic_suites_supported instead of credential_signing_alg_values_supported\n if ('cryptographic_suites_supported' in config) {\n is1_0Final = true\n break\n }\n // 1.0 final uses di_vp proof type instead of ldp_vp\n if (config.proof_types_supported && 'di_vp' in config.proof_types_supported) {\n is1_0Final = true\n break\n }\n }\n }\n }\n\n if (is1_0Final) {\n versions.add(OpenId4VCIVersion.VER_1_0)\n } else {\n // Default to 1.0 final if ambiguous (since both versions share credential_configurations_supported)\n // but if batch_credential_issuance object exists, it's clearly draft 15\n if ('batch_credential_issuance' in issuerMetadata && typeof (issuerMetadata as any).batch_credential_issuance === 'object') {\n versions.add(OpenId4VCIVersion.VER_1_0_15)\n } else {\n // Ambiguous - default to 1.0 final as the latest version\n versions.add(OpenId4VCIVersion.VER_1_0)\n }\n }\n }\n\n if (versions.size === 0) {\n versions.add(OpenId4VCIVersion.VER_UNKNOWN)\n }\n\n return Array.from(versions).sort().reverse() // highest version first\n}\n\nexport function getSupportedCredential(opts?: {\n issuerMetadata?: CredentialIssuerMetadata | IssuerMetadata\n version: OpenId4VCIVersion\n types?: string | string[]\n format?: OID4VCICredentialFormat | string | (OID4VCICredentialFormat | string)[]\n}): Record<string, CredentialConfigurationSupportedV1_0_15> | Array<CredentialConfigurationSupported> {\n const { issuerMetadata, types, format, version = OpenId4VCIVersion.VER_1_0_15 } = opts ?? {}\n\n let credentialConfigurationsV15: Record<string, CredentialConfigurationSupportedV1_0_15> | undefined = undefined\n\n // Check if we have v15 credential_configurations_supported\n if (issuerMetadata?.credential_configurations_supported && version >= OpenId4VCIVersion.VER_1_0_15) {\n credentialConfigurationsV15 = issuerMetadata.credential_configurations_supported as Record<string, CredentialConfigurationSupportedV1_0_15>\n }\n if (!issuerMetadata || (!issuerMetadata.credential_configurations_supported && !issuerMetadata.credentials_supported)) {\n VCI_LOG_COMMON.warning(`No credential issuer metadata or supported credentials found for issuer`)\n if (version >= OpenId4VCIVersion.VER_1_0_15) {\n return credentialConfigurationsV15 ?? {}\n } else {\n return []\n }\n }\n\n const normalizedTypes: string[] = Array.isArray(types) ? types : types ? [types] : []\n const normalizedFormats: string[] = Array.isArray(format) ? format : format ? [format] : []\n\n function filterMatchingConfig(config: CredentialConfigurationSupported): CredentialConfigurationSupported | undefined {\n let isTypeMatch = normalizedTypes.length === 0\n const types = getTypesFromObject(config)\n if (!isTypeMatch) {\n if (normalizedTypes.length === 1 && config.id === normalizedTypes[0]) {\n isTypeMatch = true\n } else if (types) {\n isTypeMatch = normalizedTypes.every((type) => types.includes(type))\n } else {\n // Type guard to check if credential_definition has the expected structure\n const hasValidCredentialDefinition =\n isW3cCredentialSupported(config) &&\n 'credential_definition' in config &&\n config.credential_definition &&\n typeof config.credential_definition === 'object' &&\n 'type' in config.credential_definition &&\n Array.isArray(config.credential_definition.type)\n\n if (hasValidCredentialDefinition) {\n const credDef = config.credential_definition as { type: string[] }\n isTypeMatch = normalizedTypes.every((type) => credDef.type.includes(type))\n } else if (isW3cCredentialSupported(config) && 'type' in config && Array.isArray(config.type)) {\n isTypeMatch = normalizedTypes.every((type) => (config.type as string[]).includes(type))\n } else if (isW3cCredentialSupported(config) && 'types' in config && Array.isArray(config.types)) {\n isTypeMatch = normalizedTypes.every((type) => (config.types as string[]).includes(type))\n }\n }\n }\n\n const isFormatMatch = normalizedFormats.length === 0 || normalizedFormats.includes(config.format)\n\n return isTypeMatch && isFormatMatch ? config : undefined\n }\n\n if (credentialConfigurationsV15) {\n return Object.entries(credentialConfigurationsV15).reduce(\n (filteredConfigs, [id, config]) => {\n if (filterMatchingConfig(config)) {\n filteredConfigs[id] = config\n // Added to enable support < 13. We basically assign the id\n if (!config.id) {\n config.id = id\n }\n }\n return filteredConfigs\n },\n {} as Record<string, CredentialConfigurationSupportedV1_0_15>,\n )\n }\n\n // Handle legacy credentials_supported for older versions\n if (issuerMetadata.credentials_supported && Array.isArray(issuerMetadata.credentials_supported)) {\n return issuerMetadata.credentials_supported.filter(filterMatchingConfig) as Array<CredentialConfigurationSupported>\n }\n\n return version >= OpenId4VCIVersion.VER_1_0_15 ? {} : []\n}\n\nexport function getIssuerDisplays(\n metadata: CredentialIssuerMetadata | IssuerMetadata,\n opts?: {\n prefLocales: string[]\n },\n): MetadataDisplay[] {\n const matchedDisplays =\n metadata.display?.filter(\n (item: MetadataDisplay) =>\n !opts?.prefLocales || opts.prefLocales.length === 0 || (item.locale && opts.prefLocales.includes(item.locale)) || !item.locale,\n ) ?? []\n return matchedDisplays.sort((item: MetadataDisplay) => (item.locale ? (opts?.prefLocales.indexOf(item.locale) ?? 1) : Number.MAX_VALUE))\n}\n\n/**\n * TODO check again when WAL-617 is done to replace how we get the issuer name.\n */\nexport function getIssuerName(\n url: string,\n credentialIssuerMetadata?: Partial<AuthorizationServerMetadata> & (CredentialIssuerMetadata | IssuerMetadata),\n): string {\n if (credentialIssuerMetadata) {\n const displays: Array<MetadataDisplay> = credentialIssuerMetadata ? getIssuerDisplays(credentialIssuerMetadata) : []\n for (const display of displays) {\n if (display.name) {\n return display.name\n }\n }\n }\n return url\n}\n","import { CredentialFormat } from '@sphereon/ssi-types'\n\nimport { OID4VCICredentialFormat, OpenId4VCIVersion } from '../types'\n\nexport function isFormat<T extends { format?: OID4VCICredentialFormat }, Format extends OID4VCICredentialFormat>(\n formatObject: T,\n format: Format,\n): formatObject is T & { format: Format } {\n return formatObject.format === format\n}\n\nexport function isNotFormat<T extends { format?: OID4VCICredentialFormat }, Format extends OID4VCICredentialFormat>(\n formatObject: T,\n format: Format,\n): formatObject is T & { format: Exclude<OID4VCICredentialFormat, Format> } {\n return formatObject.format !== format\n}\n\nconst isUniformFormat = (format: string): format is OID4VCICredentialFormat => {\n return ['jwt_vc_json', 'jwt_vc_json-ld', 'ldp_vc', 'dc+sd-jwt', 'mso_mdoc'].includes(format)\n}\n\nexport function getUniformFormat(format: string | OID4VCICredentialFormat | CredentialFormat): OID4VCICredentialFormat {\n // Already valid format\n if (isUniformFormat(format)) {\n return format\n }\n\n // Older formats\n if (format.toLocaleLowerCase() === 'jwt_vc' || format.toLocaleLowerCase() === 'jwt') {\n return 'jwt_vc'\n }\n if (format === 'ldp_vc' || format === 'ldp') {\n return 'ldp_vc'\n }\n\n throw new Error(`Invalid format: ${format}`)\n}\n\nexport function getFormatForVersion(format: string, version: OpenId4VCIVersion) {\n const uniformFormat = isUniformFormat(format) ? format : getUniformFormat(format)\n\n // Removed version specific format rules\n\n return uniformFormat\n}\n","import { BaseJWK, JWK } from '@sphereon/oid4vc-common'\nimport { Loggers } from '@sphereon/ssi-types'\nimport { jwtDecode } from 'jwt-decode'\n\nimport { PoPMode, VCI_LOG_COMMON } from '..'\nimport {\n BAD_PARAMS,\n JWS_NOT_VALID,\n Jwt,\n JWTHeader,\n JWTPayload,\n JWTVerifyCallback,\n JwtVerifyResult,\n ProofOfPossession,\n ProofOfPossessionCallbacks,\n Typ,\n} from '../types'\nimport type { CwtProofOfPossession } from '../types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:common')\n\n/**\n *\n * - proofOfPossessionCallback: JWTSignerCallback\n * Mandatory if you want to create (sign) ProofOfPossession\n * - proofOfPossessionVerifierCallback?: JWTVerifyCallback\n * If exists, verifies the ProofOfPossession\n * - proofOfPossessionCallbackArgs: ProofOfPossessionCallbackArgs\n * arguments needed for signing ProofOfPossession\n * - proofOfPossessionCallback: JWTSignerCallback\n * Mandatory to create (sign) ProofOfPossession\n * - proofOfPossessionVerifierCallback?: JWTVerifyCallback\n * If exists, verifies the ProofOfPossession\n * @param popMode\n * @param callbacks\n * @param jwtProps\n * @param existingJwt\n * - Optional, clientId of the party requesting the credential\n */\nexport const createProofOfPossession = async <DIDDoc extends object = never>(\n popMode: PoPMode,\n callbacks: ProofOfPossessionCallbacks,\n jwtProps?: JwtProps,\n existingJwt?: Jwt,\n): Promise<ProofOfPossession> => {\n if (!callbacks.signCallback) {\n logger.debug(`no jwt signer callback or arguments supplied!`)\n throw new Error(BAD_PARAMS)\n }\n\n const jwtPayload = createJWT(popMode, jwtProps, existingJwt)\n const jwt = await callbacks.signCallback(jwtPayload, jwtPayload.header.kid, popMode === 'pop')\n const proof = {\n proof_type: 'jwt',\n jwt,\n } as ProofOfPossession\n\n try {\n partiallyValidateJWS(jwt)\n if (callbacks.verifyCallback) {\n logger.debug(`Calling supplied verify callback....`)\n await callbacks.verifyCallback({ jwt, kid: jwtPayload.header.kid })\n logger.debug(`Supplied verify callback return success result`)\n }\n } catch {\n logger.debug(`JWS was not valid`)\n throw new Error(JWS_NOT_VALID)\n }\n logger.debug(`Proof of Possession JWT:\\r\\n${jwt}`)\n return proof\n}\n\nexport const createCwtProofOfPossession = async (\n callbacks: ProofOfPossessionCallbacks,\n opts: {\n iss?: string\n aud: string\n nonce?: string\n alg?: string\n jwk?: JWK\n kid?: string\n coseKey?: unknown\n },\n): Promise<CwtProofOfPossession> => {\n if (!callbacks.cwtSignCallback) {\n throw new Error('No CWT signer callback supplied')\n }\n const cwt = await callbacks.cwtSignCallback(opts)\n return {\n proof_type: 'cwt',\n cwt,\n }\n}\n\nconst partiallyValidateJWS = (jws: string): void => {\n if (jws.split('.').length !== 3 || !jws.startsWith('ey')) {\n throw new Error(JWS_NOT_VALID)\n }\n}\n\nexport const isJWS = (token: string): boolean => {\n try {\n partiallyValidateJWS(token)\n return true\n } catch (e) {\n return false\n }\n}\n\nexport const extractBearerToken = (authorizationHeader?: string): string | undefined => {\n return authorizationHeader ? /Bearer (.*)/i.exec(authorizationHeader)?.[1] : undefined\n}\n\nexport const validateJWT = async <DIDDoc extends object = never>(\n jwt?: string,\n opts?: { kid?: string; accessTokenVerificationCallback?: JWTVerifyCallback },\n): Promise<JwtVerifyResult> => {\n if (!jwt) {\n throw Error('No JWT was supplied')\n }\n\n if (!opts?.accessTokenVerificationCallback) {\n VCI_LOG_COMMON.warning(`No access token verification callback supplied. Access tokens will not be verified, except for a very basic check`)\n partiallyValidateJWS(jwt)\n const header = jwtDecode<JWTHeader>(jwt, { header: true })\n const payload = jwtDecode<JWTPayload>(jwt, { header: false })\n return {\n jwt: { header, payload } satisfies Jwt,\n ...header,\n ...payload,\n }\n } else {\n return await opts.accessTokenVerificationCallback({ jwt, kid: opts.kid })\n }\n}\n\nexport interface JwtProps {\n typ?: Typ\n kid?: string\n jwk?: JWK\n x5c?: string[]\n aud?: string | string[]\n issuer?: string\n clientId?: string\n alg?: string\n jti?: string\n nonce?: string\n}\n\nconst createJWT = (mode: PoPMode, jwtProps?: JwtProps, existingJwt?: Jwt): Jwt => {\n const aud =\n mode === 'pop'\n ? getJwtProperty<string | string[]>('aud', true, jwtProps?.issuer, existingJwt?.payload?.aud)\n : getJwtProperty<string | string[]>('aud', false, jwtProps?.aud, existingJwt?.payload?.aud)\n const iss =\n mode === 'pop'\n ? getJwtProperty<string>('iss', false, jwtProps?.clientId, existingJwt?.payload?.iss)\n : getJwtProperty<string>('iss', false, jwtProps?.issuer, existingJwt?.payload?.iss)\n const client_id = mode === 'JWT' ? getJwtProperty<string>('client_id', false, jwtProps?.clientId, existingJwt?.payload?.client_id) : undefined\n const jti = getJwtProperty<string>('jti', false, jwtProps?.jti, existingJwt?.payload?.jti)\n const typ = getJwtProperty<string>('typ', true, jwtProps?.typ, existingJwt?.header?.typ, 'openid4vci-proof+jwt')\n const nonce = getJwtProperty<string>('nonce', false, jwtProps?.nonce, existingJwt?.payload?.nonce) // Officially this is required, but some implementations don't have it\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const alg = getJwtProperty<string>('alg', false, jwtProps?.alg, existingJwt?.header?.alg, 'ES256')!\n const kid = getJwtProperty<string>('kid', false, jwtProps?.kid, existingJwt?.header?.kid)\n const jwk = getJwtProperty<BaseJWK>('jwk', false, jwtProps?.jwk, existingJwt?.header?.jwk)\n const x5c = getJwtProperty<string[]>('x5c', false, jwtProps?.x5c, existingJwt?.header.x5c)\n const jwt: Partial<Jwt> = { ...existingJwt }\n const now = +new Date()\n const jwtPayload: Partial<JWTPayload> = {\n ...(aud && { aud }),\n iat: jwt.payload?.iat ?? Math.floor(now / 1000) - 60, // Let's ensure we subtract 60 seconds for potential time offsets\n exp: jwt.payload?.exp ?? Math.floor(now / 1000) + 10 * 60,\n nonce,\n ...(client_id && { client_id }),\n ...(iss && { iss }),\n ...(jti && { jti }),\n }\n\n const jwtHeader: JWTHeader = {\n typ,\n alg,\n ...(kid && { kid }),\n ...(jwk && { jwk }),\n ...(x5c && { x5c }),\n }\n return {\n payload: { ...jwt.payload, ...jwtPayload },\n header: { ...jwt.header, ...jwtHeader },\n }\n}\n\nconst getJwtProperty = <T>(\n propertyName: string,\n required: boolean,\n option?: string | string[] | JWK,\n jwtProperty?: T,\n defaultValue?: T,\n): T | undefined => {\n if ((typeof option === 'string' || Array.isArray(option)) && option && jwtProperty && option !== jwtProperty) {\n throw Error(`Cannot have a property '${propertyName}' with value '${option}' and different JWT value '${jwtProperty}' at the same time`)\n }\n let result = (jwtProperty ? jwtProperty : option) as T | undefined\n if (!result) {\n if (required) {\n throw Error(`No ${propertyName} property provided either in a JWT or as option`)\n }\n result = defaultValue\n }\n return result\n}\n","import { AuthorizationChallengeCodeResponse, AuthorizationResponse } from '../types'\n\nimport { convertURIToJsonObject } from './Encoding'\n\nexport const toAuthorizationResponsePayload = (\n input: AuthorizationResponse | AuthorizationChallengeCodeResponse | string,\n): AuthorizationResponse | AuthorizationChallengeCodeResponse => {\n let response = input\n if (typeof input === 'string') {\n if (input.trim().startsWith('{') && input.trim().endsWith('}')) {\n response = JSON.parse(input)\n } else if (input.includes('?') && input.includes('code')) {\n response = convertURIToJsonObject(input) as AuthorizationResponse\n }\n }\n if (response && typeof response !== 'string') {\n return response\n }\n throw Error(`Could not create authorization response from the input ${input}`)\n}\n","import { defaultHasher } from '@sphereon/oid4vc-common'\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport * as u8a from 'uint8arrays'\nconst { toString } = u8a\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport { SupportedEncodings } from 'uint8arrays/to-string'\n\nimport { CodeChallengeMethod } from '../types'\n\nimport randomBytes from './randomBytes.cjs'\n\nexport const CODE_VERIFIER_DEFAULT_LENGTH = 128\nexport const NONCE_LENGTH = 32\n\nexport const generateRandomString = (length: number, encoding?: SupportedEncodings): string => {\n return toString(randomBytes(length), encoding).slice(0, length)\n}\n\nexport const generateNonce = (length?: number): string => {\n return generateRandomString(length ?? NONCE_LENGTH)\n}\nexport const generateCodeVerifier = (length?: number): string => {\n const codeVerifier = generateRandomString(length ?? CODE_VERIFIER_DEFAULT_LENGTH, 'base64url')\n assertValidCodeVerifier(codeVerifier)\n return codeVerifier\n}\n\nexport const createCodeChallenge = (codeVerifier: string, codeChallengeMethod?: CodeChallengeMethod): string => {\n if (codeChallengeMethod === CodeChallengeMethod.plain) {\n return codeVerifier\n } else if (!codeChallengeMethod || codeChallengeMethod === CodeChallengeMethod.S256) {\n return toString(defaultHasher(codeVerifier, 'sha256'), 'base64url')\n } else {\n // Just a precaution if a new method would be introduced\n throw Error(`code challenge method ${codeChallengeMethod} not implemented`)\n }\n}\n\nexport const assertValidCodeVerifier = (codeVerifier: string) => {\n const length = codeVerifier.length\n if (length < 43) {\n throw Error(`code_verifier should have a minimum length of 43; see rfc7636`)\n } else if (length > 128) {\n throw Error(`code_verifier should have a maximum length of 128; see rfc7636`)\n }\n}\n","import { VCI_LOG_COMMON } from '../index'\nimport { IssuerMetadata, SignedMetadataVerifyCallback } from '../types'\n\n/**\n * Process the signed_metadata JWT from issuer metadata.\n *\n * Per OID4VCI spec, signed_metadata is a signed JWT containing Credential Issuer\n * metadata parameters as claims. When present and verified, the signed claims\n * take precedence over unsigned metadata fields.\n *\n * @param opts.metadata - The fetched issuer metadata (may contain signed_metadata)\n * @param opts.issuer - The credential_issuer URL for JWT validation\n * @param opts.signedMetadataVerifyCallback - Callback to verify and decode the signed JWT\n * @returns The metadata with signed claims merged in (signed claims override unsigned)\n */\nexport async function processSignedMetadata<T extends IssuerMetadata>(opts: {\n metadata: T\n issuer: string\n signedMetadataVerifyCallback?: SignedMetadataVerifyCallback\n}): Promise<T> {\n const { metadata, issuer, signedMetadataVerifyCallback } = opts\n\n if (!metadata.signed_metadata) {\n return metadata\n }\n\n if (!signedMetadataVerifyCallback) {\n VCI_LOG_COMMON.warning(\n `Issuer ${issuer} provides signed_metadata but no signedMetadataVerifyCallback was provided. Signed metadata will not be verified or applied.`,\n )\n return metadata\n }\n\n const result = await signedMetadataVerifyCallback({\n signedMetadata: metadata.signed_metadata,\n issuer,\n })\n\n if (!result.verified) {\n throw Error(`Signed metadata verification failed for issuer ${issuer}`)\n }\n\n VCI_LOG_COMMON.info(`Signed metadata verified for issuer ${issuer}, applying signed claims`)\n\n // Merge signed claims into metadata. Signed claims override unsigned fields.\n // Exclude JWT-specific claims that are not metadata parameters.\n const { iss: _iss, iat: _iat, exp: _exp, nbf: _nbf, jti: _jti, aud: _aud, sub: _sub, ...metadataClaims } = result.metadata\n return { ...metadata, ...metadataClaims } as T\n}\n","/**\n * Experimental support not following the VCI spec to have the holder actually (re)sign the issued credential and return it to the issuer\n */\n\nexport const EXPERIMENTAL_SUBJECT_PROOF_MODE_ENABLED = process.env.EXPERIMENTAL_SUBJECT_PROOF_MODE?.trim().toLowerCase() === 'true'\n\nexport type SubjectProofMode = 'proof_chain' | 'proof_set' | 'proof_replace'\n\nexport type SubjectProofNotificationEventsSupported = 'credential_accepted_holder_signed' | 'credential_deleted_holder_signed' | 'credential_accepted'\n\nexport interface ExperimentalSubjectIssuance {\n credential_subject_issuance?: {\n subject_proof_mode: SubjectProofMode\n notification_events_supported: Array<SubjectProofNotificationEventsSupported>\n }\n}\n","import { EventManager } from '@sphereon/ssi-types'\n\nexport type EventNames = CredentialOfferEventNames | NotificationStatusEventNames | LogEvents | CredentialEventNames\n\nexport enum CredentialOfferEventNames {\n OID4VCI_OFFER_CREATED = 'OID4VCI_OFFER_CREATED',\n OID4VCI_OFFER_EXPIRED = 'OID4VCI_OFFER_EXPIRED',\n OID4VCI_OFFER_DELETED = 'OID4VCI_OFFER_DELETED',\n}\n\nexport enum CredentialEventNames {\n OID4VCI_CREDENTIAL_ISSUED = 'OID4VCI_CREDENTIAL_ISSUED',\n}\n\nexport enum NotificationStatusEventNames {\n OID4VCI_NOTIFICATION_RECEIVED = 'OID4VCI_NOTIFICATION_RECEIVED',\n OID4VCI_NOTIFICATION_PROCESSED = 'OID4VCI_NOTIFICATION_PROCESSED',\n OID4VCI_NOTIFICATION_ERROR = 'OID4VCI_NOTIFICATION_ERROR',\n}\nexport type LogEvents = 'oid4vciLog'\nexport const EVENTS = EventManager.instance()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;ACAA;AAAA,2CAAAA,SAAA;AAAA;AAAA;AAEA,QAAM,YAAY;AAIlB,QAAM,aAAa;AAOnB,QAAM,UAAU,OAAO,eAAe,cAAc,aAAa;AAEjE,QAAI,SAAS,QAAQ,UAAU,QAAQ;AACvC,QAAI,CAAC,QAAQ;AACX,UAAI;AAEF,iBAAS,QAAQ,QAAQ;AAAA,MAC3B,SAAS,KAAK;AACZ,cAAM,MAAM,gCAAgC;AAAA,MAC9C;AAAA,IACF;AAEA,aAASC,aAAY,MAAM;AAEzB,UAAI,OAAO,WAAY,OAAM,IAAI,MAAM,iCAAiC;AAGxE,YAAM,QAAQ,OAAO,YAAY,IAAI;AAErC,UAAI,OAAO,GAAG;AAEZ,YAAI,OAAO,WAAW;AAGpB,mBAAS,YAAY,GA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,KAAKC,MAAMC,KAAKC,MAAM,GAAGC,eAAAA,IAAmBnB,OAAON;AAClH,SAAO;IAAE,GAAGA;IAAU,GAAGyB;EAAe;AAC1C;AAjCsB3B;;;ACftB;AAIO,IAAM4B,0CAA0CC,QAAQC,IAAIC,iCAAiCC,KAAAA,EAAOC,YAAAA,MAAkB;;;ACJ7H;IAAAC,oBAA6B;AAItB,IAAKC,4BAAAA,0BAAAA,4BAAAA;;;;SAAAA;;AAML,IAAKC,uBAAAA,0BAAAA,uBAAAA;;SAAAA;;AAIL,IAAKC,+BAAAA,0BAAAA,+BAAAA;;;;SAAAA;;AAML,IAAMC,SAASC,+BAAaC,SAAQ;;;A5BlBpC,IAAMC,cAAcC,0BAAQC;AAC5B,IAAMC,iBAAiBH,YAAYI,IAAI,yBAAA;","names":["module","randomBytes","import_ssi_types","supportedOID4VCICredentialFormat","PRE_AUTH_CODE_LITERAL","PRE_AUTH_GRANT_LITERAL","AuthorizationChallengeError","GrantTypes","Encoding","ResponseType","CodeChallengeMethod","PARMode","CreateRequestObjectMode","AuthzFlowType","valueOf","request","PRE_AUTH_CODE_LITERAL","JsonURIMode","Alg","credentialIssuerMetadataFieldNamesV1_0_15","credentialIssuerMetadataFieldNamesV1_0","authorizationServerMetadataFieldNames","WellKnownEndpoints","BAD_PARAMS","URL_NOT_VALID","JWS_NOT_VALID","PROOF_CANT_BE_CONSTRUCTED","NO_JWT_PROVIDED","TYP_ERROR","ALG_ERROR","Object","keys","Alg","join","KID_JWK_X5C_ERROR","KID_DID_NO_DID_ERROR","DID_NO_DIDDOC_ERROR","AUD_ERROR","IAT_ERROR","NONCE_ERROR","JWT_VERIFY_CONFIG_ERROR","ISSUER_CONFIG_ERROR","UNKNOWN_CLIENT_ERROR","NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT","ISS_PRESENT_IN_PRE_AUTHORIZED_CODE_CONTEXT","ISS_MUST_BE_CLIENT_ID","GRANTS_MUST_NOT_BE_UNDEFINED","STATE_MISSING_ERROR","CREDENTIAL_MISSING_ERROR","UNSUPPORTED_GRANT_TYPE_ERROR","PRE_AUTHORIZED_CODE_REQUIRED_ERROR","USER_PIN_REQUIRED_ERROR","USER_PIN_TX_CODE_SPEC_ERROR","USER_PIN_NOT_REQUIRED_ERROR","PIN_VALIDATION_ERROR","PIN_NOT_MATCH_ERROR","INVALID_PRE_AUTHORIZED_CODE","EXPIRED_PRE_AUTHORIZED_CODE","JWT_SIGNER_CALLBACK_REQUIRED_ERROR","STATE_MANAGER_REQUIRED_ERROR","NONCE_STATE_MANAGER_REQUIRED_ERROR","ACCESS_TOKEN_ISSUER_REQUIRED_ERROR","WRONG_METADATA_FORMAT","OpenId4VCIVersion","Number","MAX_VALUE","DefaultURISchemes","IssueStatus","TokenErrorResponse","TokenError","Error","_statusCode","_responseError","statusCode","responseError","message","Object","setPrototypeOf","prototype","getDescription","logger","Loggers","DEFAULT","get","getJson","URL","opts","openIdFetch","undefined","method","formPost","url","body","post","contentType","Encoding","FORM_URL_ENCODED","headers","customHeaders","bearerToken","dpop","accept","Error","payload","debug","JSON","stringify","origResponse","fetch","isJSONResponse","success","status","responseText","text","responseBody","includes","parse","exceptionOnHttpErrorStatus","error","successBody","errorBody","isValidURL","urlPattern","RegExp","test","trimBoth","value","trim","trimEnd","trimStart","endsWith","substring","length","startsWith","adjustUrl","urlOrPath","toString","append","prepend","host","path","pathname","stripSlashStart","stripSlashEnd","isDeferredCredentialResponse","credentialResponse","orig","successBody","hasNoCredential","credentials","credential","origResponse","status","acceptance_token","transaction_id","assertNonFatalError","errorBody","error","includes","Error","isDeferredCredentialIssuancePending","error_description","toLowerCase","sleep","ms","Promise","resolve","setTimeout","acquireDeferredCredential","bearerToken","transactionId","deferredCredentialEndpoint","deferredCredentialIntervalInMS","deferredCredentialAwait","acquireDeferredCredentialImpl","DEFAULT_SLEEP_IN_MS","pending","console","log","reject","response","post","JSON","stringify","access_token","import_ssi_types","logger","Loggers","DEFAULT","get","determineSpecVersionFromURI","uri","version","determineSpecVersionFromScheme","OpenId4VCIVersion","VER_UNKNOWN","VER_1_0","credentialOfferURI","openId4VCIVersion","scheme","getScheme","url","toUrlWithDummyBase","qp","searchParams","DefaultURISchemes","INITIATE_ISSUANCE","has","recordVersion","VER_1_0_15","CREDENTIAL_OFFER","rawParam","getParamValueLoose","decoded","tryDecodeOffer","sniffOfferVersion","normalized","replace","URL","key","input","candidate","decodeURIComponent","test","b64","padEnd","Math","ceil","length","atob","jsonLike","includes","Error","split","getIssuerFromCredentialOfferPayload","request","undefined","issuer","getClientIdFromCredentialOfferPayload","credentialOffer","client_id","state","getStateFromCredentialOfferPayload","isJWT","jwtDecode","header","noParts","startsWith","grants","authorization_code","issuer_state","PRE_AUTH_GRANT_LITERAL","PRE_AUTH_CODE_LITERAL","op_state","determineSpecVersionFromOffer","offer","isCredentialOfferV1_0_15","isCredentialOfferVersion","min","max","valueOf","debug","normalizeOfferInput","Array","isArray","credential_configuration_ids","toUniformCredentialOfferRequest","opts","originalCredentialOffer","credential_offer","credential_offer_uri","resolve","VCI_LOG_COMMON","log","resolveCredentialOfferURI","payload","toUniformCredentialOfferPayload","supportedFlows","determineFlowType","original_credential_offer","isPreAuthCode","assertedUniformCredentialOffer","origCredentialOffer","JSON","parse","stringify","response","getJson","successBody","errorBody","rawOffer","orig","suppliedOffer","getCredentialOfferPayload","push","AuthzFlowType","AUTHORIZATION_CODE_FLOW","PRE_AUTHORIZED_CODE_FLOW","determineGrantTypes","types","GrantTypes","AUTHORIZATION_CODE","PRE_AUTHORIZED_CODE","currentVersion","matchingVersion","allowUpgrade","sort","reverse","getCredentialConfigurationIdsFromOfferV1_0_15","ObjectUtils","isString","base64urlToString","convertJsonToURI","json","opts","JSON","parse","results","encodeAndStripWhitespace","key","encodeURIComponent","replace","components","mode","JsonURIMode","JSON_STRINGIFY","stringify","value","Object","entries","uriTypeProperties","includes","push","arrayTypeProperties","Array","isArray","map","v","customEncodeURIComponent","join","isBool","isNumber","isString","encoded","baseUrl","endsWith","param","Error","convertURIToJsonObject","uri","requiredProperties","every","p","BAD_PARAMS","uriComponents","getURIComponentsAsArray","decodeJsonProperties","parts","result","decodeURIComponent","isObject","decoded","startsWith","arrayTypes","split","dict","entry","pair","p0","p1","uriComponent","searchValue","c","charCodeAt","toString","toUpperCase","isW3cCredentialSupported","supported","includes","format","getNumberOrUndefined","input","isNaN","undefined","getTypesFromObject","subject","credential_definition","types","Array","isArray","type","vct","doctype","VCI_LOG_COMMON","warning","getTypesFromAuthorizationDetails","authDetails","opts","configIdAsType","credential_configuration_id","getTypesFromCredentialSupported","credentialSupported","Error","length","filterVerifiableCredential","filter","getSupportedCredentials","opts","version","OpenId4VCIVersion","VER_1_0_15","types","Array","isArray","map","typeSet","getSupportedCredential","reduce","acc","result","Object","assign","undefined","determineVersionsFromIssuerMetadata","issuerMetadata","versions","Set","is1_0Final","batch_credential_issuance_supported","configs","credential_configurations_supported","config","values","proof_types_supported","add","VER_1_0","batch_credential_issuance","size","VER_UNKNOWN","from","sort","reverse","format","credentialConfigurationsV15","credentials_supported","VCI_LOG_COMMON","warning","normalizedTypes","normalizedFormats","filterMatchingConfig","isTypeMatch","length","getTypesFromObject","id","every","type","includes","hasValidCredentialDefinition","isW3cCredentialSupported","credential_definition","credDef","isFormatMatch","entries","filteredConfigs","filter","getIssuerDisplays","metadata","matchedDisplays","display","item","prefLocales","locale","indexOf","Number","MAX_VALUE","getIssuerName","url","credentialIssuerMetadata","displays","name","isFormat","formatObject","format","isNotFormat","isUniformFormat","includes","getUniformFormat","toLocaleLowerCase","Error","getFormatForVersion","version","uniformFormat","import_ssi_types","import_jwt_decode","logger","Loggers","DEFAULT","get","createProofOfPossession","popMode","callbacks","jwtProps","existingJwt","signCallback","debug","Error","BAD_PARAMS","jwtPayload","createJWT","jwt","header","kid","proof","proof_type","partiallyValidateJWS","verifyCallback","JWS_NOT_VALID","createCwtProofOfPossession","opts","cwtSignCallback","cwt","jws","split","length","startsWith","isJWS","token","e","extractBearerToken","authorizationHeader","exec","undefined","validateJWT","accessTokenVerificationCallback","VCI_LOG_COMMON","warning","jwtDecode","payload","mode","aud","getJwtProperty","issuer","iss","clientId","client_id","jti","typ","nonce","alg","jwk","x5c","now","Date","iat","Math","floor","exp","jwtHeader","propertyName","required","option","jwtProperty","defaultValue","Array","isArray","result","toAuthorizationResponsePayload","input","response","trim","startsWith","endsWith","JSON","parse","includes","convertURIToJsonObject","Error","import_oid4vc_common","toString","u8a","CODE_VERIFIER_DEFAULT_LENGTH","NONCE_LENGTH","generateRandomString","length","encoding","randomBytes","slice","generateNonce","generateCodeVerifier","codeVerifier","assertValidCodeVerifier","createCodeChallenge","codeChallengeMethod","CodeChallengeMethod","plain","S256","defaultHasher","Error","processSignedMetadata","opts","metadata","issuer","signedMetadataVerifyCallback","signed_metadata","VCI_LOG_COMMON","warning","result","signedMetadata","verified","Error","info","iss","_iss","iat","_iat","exp","_exp","nbf","_nbf","jti","_jti","aud","_aud","sub","_sub","metadataClaims","EXPERIMENTAL_SUBJECT_PROOF_MODE_ENABLED","process","env","EXPERIMENTAL_SUBJECT_PROOF_MODE","trim","toLowerCase","import_ssi_types","CredentialOfferEventNames","CredentialEventNames","NotificationStatusEventNames","EVENTS","EventManager","instance","VCI_LOGGERS","Loggers","DEFAULT","VCI_LOG_COMMON","get"]}
|