{"version":3,"sources":["../lib/index.ts","../lib/builder/CredentialSupportedBuilderV1_15.ts","../lib/builder/VcIssuerBuilder.ts","../lib/VcIssuer.ts","../lib/functions/CredentialOfferUtils.ts","../lib/functions/ASOidcClient.ts","../lib/state-manager/MemoryStates.ts","../lib/state-manager/LookupStateManager.ts","../lib/state-manager/CredentialOfferStateBuilder.ts","../lib/builder/DisplayBuilder.ts","../lib/builder/IssuerMetadataBuilderV1_15.ts","../lib/builder/AuthorizationServerMetadataBuilder.ts","../lib/tokens/index.ts"],"sourcesContent":["import { VCI_LOGGERS } from '@sphereon/oid4vci-common'\nimport { ISimpleLogger } from '@sphereon/ssi-types'\n\nexport const LOG: ISimpleLogger<string | unknown> = VCI_LOGGERS.get('sphereon:oid4vci:issuer')\n\nexport * from './builder'\nexport * from './functions'\nexport * from './VcIssuer'\nexport * from './state-manager'\nexport * from './tokens'\nexport * from './types'\n","import {\n  ClaimsDescriptionV1_0_15,\n  CredentialConfigurationSupportedV1_0_15,\n  CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n  CredentialDefinitionJwtVcJsonV1_0_15,\n  CredentialsSupportedDisplay,\n  KeyProofType,\n  OID4VCICredentialFormat,\n  ProofType,\n  ProofTypesSupported,\n  TokenErrorResponse,\n} from '@sphereon/oid4vci-common'\n\nexport class CredentialSupportedBuilderV1_15 {\n  format?: OID4VCICredentialFormat\n  scope?: string\n  credentialName?: string\n  credentialDefinition?: CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 | CredentialDefinitionJwtVcJsonV1_0_15\n  cryptographicBindingMethodsSupported?: ('jwk' | 'cose_key' | 'did' | string)[]\n  credentialSigningAlgValuesSupported?: string[]\n  proofTypesSupported?: ProofTypesSupported\n  display?: CredentialsSupportedDisplay[]\n  claims?: ClaimsDescriptionV1_0_15[] // Changed to use claims path pointers in v15\n  vct?: string // For dc+sd-jwt format\n  doctype?: string // For mso_mdoc format\n\n  withFormat(credentialFormat: OID4VCICredentialFormat): CredentialSupportedBuilderV1_15 {\n    this.format = credentialFormat\n    return this\n  }\n\n  withCredentialName(credentialName: string): CredentialSupportedBuilderV1_15 {\n    this.credentialName = credentialName\n    return this\n  }\n\n  withCredentialDefinition(\n    credentialDefinition: CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 | CredentialDefinitionJwtVcJsonV1_0_15,\n  ): CredentialSupportedBuilderV1_15 {\n    if (!credentialDefinition.type) {\n      throw new Error('credentialDefinition should contain a type array')\n    }\n    this.credentialDefinition = credentialDefinition\n    return this\n  }\n\n  withScope(scope: string): CredentialSupportedBuilderV1_15 {\n    this.scope = scope\n    return this\n  }\n\n  // New in v15: VCT support for dc+sd-jwt format\n  withVct(vct: string): CredentialSupportedBuilderV1_15 {\n    this.vct = vct\n    return this\n  }\n\n  // New in v15: Doctype support for mso_mdoc format\n  withDoctype(doctype: string): CredentialSupportedBuilderV1_15 {\n    this.doctype = doctype\n    return this\n  }\n\n  addCryptographicBindingMethod(method: string | string[]): CredentialSupportedBuilderV1_15 {\n    if (!Array.isArray(method)) {\n      this.cryptographicBindingMethodsSupported = this.cryptographicBindingMethodsSupported\n        ? [...this.cryptographicBindingMethodsSupported, method]\n        : [method]\n    } else {\n      this.cryptographicBindingMethodsSupported = this.cryptographicBindingMethodsSupported\n        ? [...this.cryptographicBindingMethodsSupported, ...method]\n        : method\n    }\n    return this\n  }\n\n  withCryptographicBindingMethod(method: string | string[]): CredentialSupportedBuilderV1_15 {\n    this.cryptographicBindingMethodsSupported = Array.isArray(method) ? method : [method]\n    return this\n  }\n\n  addCredentialSigningAlgValuesSupported(algValues: string | string[]): CredentialSupportedBuilderV1_15 {\n    if (!Array.isArray(algValues)) {\n      this.credentialSigningAlgValuesSupported = this.credentialSigningAlgValuesSupported\n        ? [...this.credentialSigningAlgValuesSupported, algValues]\n        : [algValues]\n    } else {\n      this.credentialSigningAlgValuesSupported = this.credentialSigningAlgValuesSupported\n        ? [...this.credentialSigningAlgValuesSupported, ...algValues]\n        : algValues\n    }\n    return this\n  }\n\n  withCredentialSigningAlgValuesSupported(algValues: string | string[]): CredentialSupportedBuilderV1_15 {\n    this.credentialSigningAlgValuesSupported = Array.isArray(algValues) ? algValues : [algValues]\n    return this\n  }\n\n  addProofTypesSupported(keyProofType: KeyProofType, proofType: ProofType): CredentialSupportedBuilderV1_15 {\n    if (!this.proofTypesSupported) {\n      this.proofTypesSupported = {}\n    }\n    this.proofTypesSupported[keyProofType] = proofType\n    return this\n  }\n\n  withProofTypesSupported(proofTypesSupported: ProofTypesSupported): CredentialSupportedBuilderV1_15 {\n    this.proofTypesSupported = proofTypesSupported\n    return this\n  }\n\n  addCredentialSupportedDisplay(credentialDisplay: CredentialsSupportedDisplay | CredentialsSupportedDisplay[]): CredentialSupportedBuilderV1_15 {\n    if (!Array.isArray(credentialDisplay)) {\n      this.display = this.display ? [...this.display, credentialDisplay] : [credentialDisplay]\n    } else {\n      this.display = this.display ? [...this.display, ...credentialDisplay] : credentialDisplay\n    }\n    return this\n  }\n\n  withCredentialSupportedDisplay(credentialDisplay: CredentialsSupportedDisplay | CredentialsSupportedDisplay[]): CredentialSupportedBuilderV1_15 {\n    this.display = Array.isArray(credentialDisplay) ? credentialDisplay : [credentialDisplay]\n    return this\n  }\n\n  // New in v15: Claims description using path pointers\n  withClaims(claims: ClaimsDescriptionV1_0_15[]): CredentialSupportedBuilderV1_15 {\n    this.claims = claims\n    return this\n  }\n\n  addClaim(claim: ClaimsDescriptionV1_0_15): CredentialSupportedBuilderV1_15 {\n    if (!this.claims) {\n      this.claims = []\n    }\n    this.claims.push(claim)\n    return this\n  }\n\n  public build(): Record<string, CredentialConfigurationSupportedV1_0_15> {\n    if (!this.format) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n\n    const credentialSupported: CredentialConfigurationSupportedV1_0_15 = {\n      format: this.format,\n    } as CredentialConfigurationSupportedV1_0_15\n\n    if (!this.credentialName) {\n      throw new Error('A unique credential name is required')\n    }\n\n    // Format-specific handling for v15\n    if (this.format === 'dc+sd-jwt') {\n      if (!this.vct) {\n        throw new Error('vct is required for dc+sd-jwt format')\n      }\n      ;(credentialSupported as any).vct = this.vct\n    } else if (this.format === 'mso_mdoc') {\n      if (!this.doctype) {\n        throw new Error('doctype is required for mso_mdoc format')\n      }\n      ;(credentialSupported as any).doctype = this.doctype\n    } else {\n      if (!this.credentialDefinition) {\n        throw new Error('credentialDefinition is required')\n      }\n      credentialSupported.credential_definition = this.credentialDefinition\n    }\n\n    if (this.scope) {\n      credentialSupported.scope = this.scope\n    }\n    if (this.credentialSigningAlgValuesSupported) {\n      credentialSupported.credential_signing_alg_values_supported = this.credentialSigningAlgValuesSupported\n    }\n    if (this.cryptographicBindingMethodsSupported) {\n      credentialSupported.cryptographic_binding_methods_supported = this.cryptographicBindingMethodsSupported\n    }\n    if (this.display) {\n      credentialSupported.display = this.display\n    }\n    if (this.claims) {\n      ;(credentialSupported as any).claims = this.claims\n    }\n\n    const supportedConfiguration: Record<string, CredentialConfigurationSupportedV1_0_15> = {}\n    supportedConfiguration[this.credentialName] = credentialSupported as CredentialConfigurationSupportedV1_0_15\n\n    return supportedConfiguration\n  }\n}\n","import {\n  AuthorizationServerMetadata,\n  ClientMetadata,\n  ClientResponseType,\n  CNonceState,\n  CredentialConfigurationSupportedV1_0_15,\n  CredentialIssuerMetadataOptsV1_0_15,\n  CredentialOfferSession,\n  IssuerMetadata,\n  IssuerMetadataV1_0_15,\n  IStateManager,\n  JWTVerifyCallback,\n  MetadataDisplay,\n  TokenErrorResponse,\n  TxCode,\n  URIState,\n} from '@sphereon/oid4vci-common'\n\nimport { VcIssuer } from '../VcIssuer'\nimport { oidcAccessTokenVerifyCallback } from '../functions'\nimport { MemoryStates } from '../state-manager'\nimport { CredentialDataSupplier, CredentialSignerCallback } from '../types'\n\nimport { IssuerMetadataBuilderV1_15 } from './IssuerMetadataBuilderV1_15'\n\nexport class VcIssuerBuilder {\n  issuerMetadataBuilder?: IssuerMetadataBuilderV1_15\n  issuerMetadata: Partial<CredentialIssuerMetadataOptsV1_0_15> = {}\n  authorizationServerMetadata: Partial<AuthorizationServerMetadata> = {}\n  asClientOpts?: ClientMetadata\n  txCode?: TxCode\n  defaultCredentialOfferBaseUri?: string\n  userPinRequired?: boolean\n  cNonceExpiresIn?: number\n  credentialOfferStateManager?: IStateManager<CredentialOfferSession>\n  credentialOfferURIManager?: IStateManager<URIState>\n  cNonceStateManager?: IStateManager<CNonceState>\n  credentialSignerCallback?: CredentialSignerCallback\n  jwtVerifyCallback?: JWTVerifyCallback\n  credentialDataSupplier?: CredentialDataSupplier\n\n  public withIssuerMetadata(issuerMetadata: IssuerMetadata) {\n    if (!issuerMetadata.credential_configurations_supported) {\n      throw new Error('IssuerMetadata should be from type v1_0_15 or higher.')\n    }\n    this.issuerMetadata = issuerMetadata as IssuerMetadataV1_0_15\n    return this\n  }\n\n  public withASClientMetadata(clientMetadata: ClientMetadata): this {\n    this.asClientOpts = clientMetadata\n    return this\n  }\n\n  public withASClientMetadataParams({\n    client_id,\n    client_secret,\n    redirect_uris,\n    response_types,\n    ...other\n  }: { client_id: string; client_secret?: string; redirect_uris?: string[]; response_types?: ClientResponseType[] } & ClientMetadata): this {\n    this.asClientOpts = { ...other, client_id, client_secret, redirect_uris, response_types }\n    return this\n  }\n\n  public withAuthorizationMetadata(authorizationServerMetadata: AuthorizationServerMetadata) {\n    this.authorizationServerMetadata = authorizationServerMetadata\n    return this\n  }\n\n  public withIssuerMetadataBuilder(builder: IssuerMetadataBuilderV1_15) {\n    this.issuerMetadataBuilder = builder\n    return this\n  }\n\n  public withDefaultCredentialOfferBaseUri(baseUri: string) {\n    this.defaultCredentialOfferBaseUri = baseUri\n    return this\n  }\n\n  public withCredentialIssuer(issuer: string): this {\n    this.issuerMetadata.credential_issuer = issuer\n    return this\n  }\n\n  public withAuthorizationServers(authorizationServers: string | string[]): this {\n    this.issuerMetadata.authorization_servers = typeof authorizationServers === 'string' ? [authorizationServers] : authorizationServers\n    return this\n  }\n\n  public withCredentialEndpoint(credentialEndpoint: string): this {\n    this.issuerMetadata.credential_endpoint = credentialEndpoint\n    return this\n  }\n\n  public withTokenEndpoint(tokenEndpoint: string): this {\n    this.issuerMetadata.token_endpoint = tokenEndpoint\n    return this\n  }\n\n  public withNonceEndpoint(nonceEndpoint: string): this {\n    this.issuerMetadata.nonce_endpoint = nonceEndpoint\n    return this\n  }\n\n  public withIssuerDisplay(issuerDisplay: MetadataDisplay[] | MetadataDisplay): this {\n    this.issuerMetadata.display = Array.isArray(issuerDisplay) ? issuerDisplay : [issuerDisplay]\n    return this\n  }\n\n  public addIssuerDisplay(issuerDisplay: MetadataDisplay): this {\n    this.issuerMetadata.display = [...(this.issuerMetadata.display ?? []), issuerDisplay]\n    return this\n  }\n\n  public withCredentialConfigurationsSupported(credentialConfigurationsSupported: Record<string, CredentialConfigurationSupportedV1_0_15>) {\n    this.issuerMetadata.credential_configurations_supported = credentialConfigurationsSupported\n    return this\n  }\n\n  public addCredentialConfigurationsSupported(id: string, supportedCredential: CredentialConfigurationSupportedV1_0_15) {\n    if (!this.issuerMetadata.credential_configurations_supported) {\n      this.issuerMetadata.credential_configurations_supported = {}\n    }\n    this.issuerMetadata.credential_configurations_supported[id] = supportedCredential\n    return this\n  }\n\n  public withTXCode(txCode: TxCode): this {\n    this.txCode = txCode\n    return this\n  }\n\n  public withCredentialOfferURIStateManager(credentialOfferURIManager: IStateManager<URIState>): this {\n    this.credentialOfferURIManager = credentialOfferURIManager\n    return this\n  }\n\n  public withInMemoryCredentialOfferURIState(): this {\n    this.withCredentialOfferURIStateManager(new MemoryStates<URIState>())\n    return this\n  }\n\n  public withCredentialOfferStateManager(credentialOfferManager: IStateManager<CredentialOfferSession>): this {\n    this.credentialOfferStateManager = credentialOfferManager\n    return this\n  }\n\n  public withInMemoryCredentialOfferState(): this {\n    this.withCredentialOfferStateManager(new MemoryStates<CredentialOfferSession>())\n    return this\n  }\n\n  public withCNonceStateManager(cNonceManager: IStateManager<CNonceState>): this {\n    this.cNonceStateManager = cNonceManager\n    return this\n  }\n\n  public withInMemoryCNonceState(): this {\n    this.withCNonceStateManager(new MemoryStates())\n    return this\n  }\n\n  public withCNonceExpiresIn(cNonceExpiresIn: number): this {\n    this.cNonceExpiresIn = cNonceExpiresIn\n    return this\n  }\n\n  public withCredentialSignerCallback(cb: CredentialSignerCallback): this {\n    this.credentialSignerCallback = cb\n    return this\n  }\n\n  public withJWTVerifyCallback(verifyCallback: JWTVerifyCallback): this {\n    this.jwtVerifyCallback = verifyCallback\n    return this\n  }\n\n  public withCredentialDataSupplier(credentialDataSupplier: CredentialDataSupplier): this {\n    this.credentialDataSupplier = credentialDataSupplier\n    return this\n  }\n\n  public build(): VcIssuer {\n    if (!this.credentialOfferStateManager) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n    if (!this.cNonceStateManager) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n    if (Object.keys(this.issuerMetadata).length === 0) {\n      throw new Error('issuerMetadata not set')\n    }\n    if (Object.keys(this.authorizationServerMetadata).length === 0) {\n      throw new Error('authorizationServerMetadata not set')\n    }\n\n    const builder = this.issuerMetadataBuilder?.build()\n    const metadata: Partial<IssuerMetadataV1_0_15> = { ...this.issuerMetadata, ...builder }\n    // Let's make sure these get merged correctly:\n    metadata.credential_configurations_supported = this.issuerMetadata.credential_configurations_supported\n    metadata.display = [...(this.issuerMetadata.display ?? []), ...(builder?.display ?? [])]\n    if (!metadata.credential_endpoint || !metadata.credential_issuer || !this.issuerMetadata.credential_configurations_supported) {\n      throw new Error(TokenErrorResponse.invalid_request)\n    }\n    if (this.asClientOpts && typeof this.jwtVerifyCallback !== 'function') {\n      if (!this.issuerMetadata.credential_issuer) {\n        throw Error('issuerMetadata.credential_issuer is required when using asClientOpts')\n      } else if (!this.issuerMetadata.authorization_servers) {\n        throw Error('issuerMetadata.authorization_servers is required when using asClientOpts')\n      }\n      this.jwtVerifyCallback = oidcAccessTokenVerifyCallback({\n        clientMetadata: this.asClientOpts,\n        credentialIssuer: this.issuerMetadata.credential_issuer,\n        authorizationServer: this.issuerMetadata.authorization_servers[0],\n      })\n    }\n    return new VcIssuer(metadata as IssuerMetadataV1_0_15, this.authorizationServerMetadata as AuthorizationServerMetadata, {\n      //TODO: discuss this with Niels. I did not find this in the spec. but I think we should somehow communicate this\n      ...(this.txCode && { txCode: this.txCode }),\n      defaultCredentialOfferBaseUri: this.defaultCredentialOfferBaseUri,\n      credentialSignerCallback: this.credentialSignerCallback,\n      jwtVerifyCallback: this.jwtVerifyCallback,\n      credentialDataSupplier: this.credentialDataSupplier,\n      credentialOfferSessions: this.credentialOfferStateManager,\n      cNonces: this.cNonceStateManager,\n      cNonceExpiresIn: this.cNonceExpiresIn,\n      uris: this.credentialOfferURIManager,\n      asClientOpts: this.asClientOpts,\n    })\n  }\n}\n","import { uuidv4 } from '@sphereon/oid4vc-common'\nimport {\n  ALG_ERROR,\n  AUD_ERROR,\n  AuthorizationServerMetadata,\n  ClientMetadata,\n  CNonceState,\n  CreateCredentialOfferURIResult,\n  CREDENTIAL_MISSING_ERROR,\n  CredentialDataSupplierInput,\n  CredentialEventNames,\n  CredentialIssuerMetadataOptsV1_0_15,\n  CredentialOfferEventNames,\n  CredentialOfferMode,\n  CredentialOfferSession,\n  CredentialOfferV1_0_15,\n  CredentialRequest,\n  CredentialRequestV1_0_15,\n  CredentialResponse,\n  DID_NO_DIDDOC_ERROR,\n  EVENTS,\n  IAT_ERROR,\n  ISSUER_CONFIG_ERROR,\n  IssueStatus,\n  IStateManager,\n  JsonLdIssuerCredentialDefinition,\n  JWT_VERIFY_CONFIG_ERROR,\n  JWTVerifyCallback,\n  JwtVerifyResult,\n  KID_DID_NO_DID_ERROR,\n  KID_JWK_X5C_ERROR,\n  NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT,\n  NotificationRequest,\n  OID4VCICredentialFormat,\n  OpenId4VCIVersion,\n  PRE_AUTH_GRANT_LITERAL,\n  ProofOfPossession,\n  QRCodeOpts,\n  StatusListOpts,\n  TokenErrorResponse,\n  toUniformCredentialOfferRequest,\n  TxCode,\n  TYP_ERROR,\n  URIState,\n} from '@sphereon/oid4vci-common'\nimport { CompactSdJwtVc, CredentialMapper, InitiatorType, SubSystem, System, W3CVerifiableCredential } from '@sphereon/ssi-types'\nimport ShortUUID from 'short-uuid'\n\nimport { assertValidPinNumber, createCredentialOfferObject, createCredentialOfferURIFromObject, CredentialOfferGrantInput } from './functions'\nimport { LookupStateManager, lookupStateManagerMultiGetAsserted, MemoryStates } from './state-manager'\nimport { CredentialDataSupplier, CredentialDataSupplierArgs, CredentialIssuanceInput, CredentialSignerCallback, IssuerCorrelation } from './types'\n\nimport { LOG } from './index'\n\nconst shortUUID = ShortUUID()\n\nexport class VcIssuer {\n  private _issuerMetadata: CredentialIssuerMetadataOptsV1_0_15 // TODO SSISDK-87 create proper solution to update issuer metadata\n  private readonly _authorizationServerMetadata: AuthorizationServerMetadata\n  private readonly _defaultCredentialOfferBaseUri?: string\n  private readonly _credentialSignerCallback?: CredentialSignerCallback\n  private readonly _jwtVerifyCallback?: JWTVerifyCallback\n  private readonly _credentialDataSupplier?: CredentialDataSupplier\n  private readonly _credentialOfferSessions: IStateManager<CredentialOfferSession>\n  private readonly _cNonces: IStateManager<CNonceState>\n  private readonly _uris: IStateManager<URIState>\n  private readonly _cNonceExpiresIn: number\n  private readonly _asClientOpts?: ClientMetadata\n\n  constructor(\n    issuerMetadata: CredentialIssuerMetadataOptsV1_0_15,\n    authorizationServerMetadata: AuthorizationServerMetadata,\n    args: {\n      txCode?: TxCode\n      baseUri?: string\n      credentialOfferSessions: IStateManager<CredentialOfferSession>\n      defaultCredentialOfferBaseUri?: string\n      cNonces: IStateManager<CNonceState>\n      uris?: IStateManager<URIState>\n      credentialSignerCallback?: CredentialSignerCallback\n      jwtVerifyCallback?: JWTVerifyCallback\n      credentialDataSupplier?: CredentialDataSupplier\n      cNonceExpiresIn?: number | undefined // expiration duration in seconds\n      asClientOpts?: ClientMetadata\n    },\n  ) {\n    this._issuerMetadata = issuerMetadata\n    this._authorizationServerMetadata = authorizationServerMetadata\n    this._defaultCredentialOfferBaseUri = args.defaultCredentialOfferBaseUri\n    this._credentialOfferSessions = args.credentialOfferSessions ?? new MemoryStates()\n    this._uris = args.uris ?? new MemoryStates()\n    this._cNonces = args.cNonces\n    this._credentialSignerCallback = args?.credentialSignerCallback\n    this._jwtVerifyCallback = args?.jwtVerifyCallback\n    this._credentialDataSupplier = args?.credentialDataSupplier\n    this._cNonceExpiresIn = (args?.cNonceExpiresIn ?? (process.env.C_NONCE_EXPIRES_IN ? parseInt(process.env.C_NONCE_EXPIRES_IN) : 300)) as number\n    this._asClientOpts = args?.asClientOpts\n  }\n\n  public async getCredentialOfferSessionById(\n    id: string,\n    lookups: Array<'uri' | 'preAuthorizedCode' | 'issuerState' | 'correlationId'> = ['preAuthorizedCode', 'issuerState', 'correlationId'],\n  ): Promise<CredentialOfferSession> {\n    // preAuth and issuerState can be looked up directly\n    if (Array.isArray(lookups) && lookups.length > 0) {\n      if (!this.uris) {\n        return Promise.reject(Error('Cannot lookup credential offer by id if URI state manager is not set'))\n      }\n      return lookupStateManagerMultiGetAsserted({\n        id,\n        keyValueMapper: this._uris,\n        valueStateManager: this._credentialOfferSessions,\n        lookups: ['preAuthorizedCode', 'issuerState', 'correlationId'],\n      })\n      // return new LookupStateManager<URIState, CredentialOfferSession>(this.uris, this._credentialOfferSessions, lookup).getFromMultiple(id)\n    }\n    const session = await this._credentialOfferSessions.get(id)\n    if (!session) {\n      return Promise.reject(Error(`No session found for id ${id}`))\n    }\n    return session\n  }\n\n  public async deleteCredentialOfferSessionById(\n    id: string,\n    lookups: Array<'uri' | 'preAuthorizedCode' | 'issuerState' | 'correlationId'> = ['preAuthorizedCode', 'issuerState'],\n  ): Promise<CredentialOfferSession> {\n    const session = await this.getCredentialOfferSessionById(id, lookups)\n    if (session) {\n      if (session.preAuthorizedCode && (await this._credentialOfferSessions.has(session.preAuthorizedCode))) {\n        await this._credentialOfferSessions.delete(session.preAuthorizedCode)\n      }\n      if (session.issuerState && (await this._credentialOfferSessions.has(session.issuerState))) {\n        await this._credentialOfferSessions.delete(session.issuerState)\n      }\n    }\n    return session\n  }\n\n  public async processNotification({\n    preAuthorizedCode,\n    issuerState,\n    notification,\n  }: {\n    preAuthorizedCode?: string\n    issuerState?: string\n    notification: NotificationRequest\n  }): Promise<Error | CredentialOfferSession> {\n    const sessionId = preAuthorizedCode ?? issuerState\n    const session = sessionId ? await this.getCredentialOfferSessionById(sessionId) : undefined\n    if (!session || !sessionId) {\n      LOG.error(`No session or session id found ${sessionId}`)\n      return Error('invalid_notification_request')\n    }\n    if (notification.notification_id !== session.notification_id) {\n      LOG.error(`Notification id ${notification.notification_id} not found in session. session notification id ${session.notification_id}`)\n      return Error('invalid_notification_id')\n    } else if (session.notification) {\n      LOG.info(`Overwriting existing notification, as a new notification came in ${session.notification_id}`)\n    }\n    await this.updateSession({ preAuthorizedCode: preAuthorizedCode, issuerState: issuerState, notification })\n    LOG.info(`Processed notification ${notification} for ${session.notification_id}`)\n    return session\n  }\n\n  public async createCredentialOfferURI(opts: {\n    offerMode?: CredentialOfferMode\n    grants?: CredentialOfferGrantInput\n    client_id?: string\n    redirectUri?: string\n    credential_configuration_ids?: Array<string>\n    credentialDefinition?: JsonLdIssuerCredentialDefinition\n    credentialOfferUri?: string\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    baseUri?: string\n    scheme?: string\n    pinLength?: number\n    qrCodeOpts?: QRCodeOpts\n    correlationId?: string\n    statusListOpts?: Array<StatusListOpts>\n    sessionLifeTimeInSec?: number\n  }): Promise<CreateCredentialOfferURIResult> {\n    const {\n      offerMode = 'VALUE',\n      correlationId = shortUUID.generate(),\n      credential_configuration_ids,\n      statusListOpts,\n      credentialOfferUri,\n      redirectUri,\n    } = opts\n    if (offerMode === 'REFERENCE' && !credentialOfferUri) {\n      return Promise.reject(Error('credentialOfferUri must be supplied for offerMode REFERENCE!'))\n    }\n\n    const grants = opts.grants ? { ...opts.grants } : {}\n    // for backwards compat, would be better if user sets the prop on the grants directly\n    if (opts.pinLength !== undefined) {\n      if (grants[PRE_AUTH_GRANT_LITERAL]) {\n        grants[PRE_AUTH_GRANT_LITERAL].tx_code = {\n          ...grants[PRE_AUTH_GRANT_LITERAL].tx_code,\n          length: grants[PRE_AUTH_GRANT_LITERAL].tx_code?.length ?? opts.pinLength,\n        }\n      }\n    }\n    if (grants[PRE_AUTH_GRANT_LITERAL]?.tx_code && !grants[PRE_AUTH_GRANT_LITERAL]?.tx_code?.length) {\n      grants[PRE_AUTH_GRANT_LITERAL].tx_code.length = 4\n    }\n\n    const baseUri = opts?.baseUri ?? this.defaultCredentialOfferBaseUri\n    const credentialOfferObject = createCredentialOfferObject(this._issuerMetadata, {\n      ...opts,\n      grants,\n      credentialOffer: credential_configuration_ids\n        ? {\n            credential_issuer: this._issuerMetadata.credential_issuer,\n            credential_configuration_ids,\n          }\n        : undefined,\n    })\n\n    const preAuthGrant = credentialOfferObject.credential_offer.grants?.[PRE_AUTH_GRANT_LITERAL]\n    const authGrant = credentialOfferObject.credential_offer.grants?.authorization_code\n\n    const preAuthorizedCode = preAuthGrant?.['pre-authorized_code']\n    const issuerState = authGrant?.issuer_state\n    const txCode = preAuthGrant?.tx_code\n\n    let userPin: string | undefined\n    if (preAuthGrant?.tx_code) {\n      const pinLength = preAuthGrant.tx_code.length ?? 4\n\n      userPin = ('' + Math.round((Math.pow(10, pinLength) - 1) * Math.random())).padStart(pinLength, '0')\n      assertValidPinNumber(userPin, pinLength)\n    }\n    const createdAt = +new Date()\n    const lastUpdatedAt = createdAt\n    const expirationInMs = (opts.sessionLifeTimeInSec ?? 10 * 60) * 1000\n    const expiresAt = createdAt + Math.abs(expirationInMs)\n    if (offerMode === 'REFERENCE') {\n      if (!this.uris) {\n        throw Error('No URI state manager set, whilst apparently credential offer by reference is being used')\n      }\n\n      const offerUri = opts.credentialOfferUri?.replace(':id', correlationId) // TODO how is this going to work with auth code flow?\n      if (!offerUri) {\n        return Promise.reject(Error('credentialOfferUri must be supplied for offerMode REFERENCE!'))\n      }\n\n      credentialOfferObject.credential_offer_uri = offerUri\n      await this.uris.set(correlationId, {\n        uri: offerUri,\n        createdAt: createdAt,\n        expiresAt,\n        preAuthorizedCode,\n        issuerState,\n        correlationId: correlationId,\n      })\n    }\n\n    const credentialOffer = await toUniformCredentialOfferRequest(\n      {\n        credential_offer: credentialOfferObject.credential_offer,\n        credential_offer_uri: credentialOfferObject.credential_offer_uri,\n      } as CredentialOfferV1_0_15,\n      {\n        version: OpenId4VCIVersion.VER_1_0_15,\n        resolve: false, // We are creating the object, so do not resolve\n      },\n    )\n\n    const status = IssueStatus.OFFER_CREATED\n    const session: CredentialOfferSession = {\n      redirectUri,\n      preAuthorizedCode,\n      issuerState,\n      createdAt,\n      lastUpdatedAt,\n      expiresAt,\n      status,\n      notification_id: uuidv4(),\n      ...(opts.client_id && { clientId: opts.client_id }),\n      ...(userPin && { txCode: userPin }), // We used to use userPin according to older specs. We map these onto txCode now. If both are used, txCode in the end wins, even if they are different\n      ...(opts.credentialDataSupplierInput && { credentialDataSupplierInput: opts.credentialDataSupplierInput }),\n      credentialOffer,\n      statusLists: statusListOpts,\n    }\n\n    const uri = createCredentialOfferURIFromObject(credentialOffer, offerMode, { ...opts, baseUri })\n    if (preAuthorizedCode) {\n      const lookupManager = new LookupStateManager<URIState, CredentialOfferSession>(this.uris, this._credentialOfferSessions, 'correlationId')\n      await lookupManager.setMapped(\n        preAuthorizedCode,\n        {\n          preAuthorizedCode,\n          uri,\n          createdAt,\n          expiresAt,\n          correlationId,\n          issuerState,\n        },\n        session,\n      )\n      // await this.credentialOfferSessions.set(preAuthorizedCode, session)\n    }\n    // todo: check whether we could have the same value for issuer state and pre auth code if both are supported.\n    if (issuerState) {\n      const lookupManager = new LookupStateManager<URIState, CredentialOfferSession>(this.uris, this._credentialOfferSessions, 'correlationId')\n      await lookupManager.setMapped(\n        issuerState,\n        {\n          preAuthorizedCode,\n          uri,\n          createdAt,\n          expiresAt,\n          correlationId,\n          issuerState,\n        },\n        session,\n      )\n      // await this.credentialOfferSessions.set(issuerState, session)\n    }\n    let qrCodeDataUri: string | undefined\n    if (opts.qrCodeOpts) {\n      const { AwesomeQR } = await import('awesome-qr')\n      const qrCode = new AwesomeQR({ ...opts.qrCodeOpts, text: uri })\n      qrCodeDataUri = `data:image/png;base64,${(await qrCode.draw())!.toString('base64')}`\n    }\n    const credentialOfferResult = {\n      session,\n      uri,\n      qrCodeDataUri,\n      correlationId,\n      txCode,\n      ...(userPin !== undefined && { userPin, pinLength: userPin?.length ?? 0 }),\n    }\n    EVENTS.emit(CredentialOfferEventNames.OID4VCI_OFFER_CREATED, {\n      eventName: CredentialOfferEventNames.OID4VCI_OFFER_CREATED,\n      id: correlationId,\n      data: credentialOfferResult,\n      initiator: '<Unknown>',\n      initiatorType: InitiatorType.EXTERNAL,\n      system: System.OID4VCI,\n      issuer: this.issuerMetadata.credential_issuer,\n      subsystem: SubSystem.API,\n      createdAt,\n      expiresAt,\n    })\n    return credentialOfferResult\n  }\n\n  /**\n   * issueCredentialFromIssueRequest\n   * @param opts issuerRequestParams\n   *  - issueCredentialsRequest the credential request\n   *  - issuerState the state of the issuer\n   *  - jwtVerifyCallback callback that verifies the Proof of Possession JWT\n   *  - issuerCallback callback to issue a Verifiable Credential\n   *  - cNonce an existing c_nonce\n   */\n  public async issueCredential(opts: {\n    credentialRequest: CredentialRequest\n    issuerCorrelation: IssuerCorrelation\n    credential?: CredentialIssuanceInput\n    credentialDataSupplier?: CredentialDataSupplier\n    credentialDataSupplierInput?: CredentialDataSupplierInput\n    newCNonce?: string\n    cNonceExpiresIn?: number // expiration duration in seconds\n    tokenExpiresIn?: number // expiration duration in seconds\n    jwtVerifyCallback?: JWTVerifyCallback\n    credentialSignerCallback?: CredentialSignerCallback\n    responseCNonce?: string\n  }): Promise<CredentialResponse> {\n    /*if (!('credential_identifier' in opts.credentialRequest)) {\n      throw new Error('credential request should be of spec version 1.0.13 or above')\n    }*/\n    const credentialRequest = opts.credentialRequest as CredentialRequestV1_0_15\n    const issuerCorrelation = opts.issuerCorrelation\n    try {\n      if (!('credential_identifier' in credentialRequest) && !('credential_configuration_id' in credentialRequest)) {\n        throw Error('credential request should have either credential_identifier or credential_configuration_id')\n      }\n\n      // Validate the credential_configuration_id exists in metadata if used\n      if ('credential_configuration_id' in credentialRequest && credentialRequest.credential_configuration_id) {\n        if (!this._issuerMetadata.credential_configurations_supported?.[credentialRequest.credential_configuration_id]) {\n          throw Error(TokenErrorResponse.invalid_request)\n        }\n      }\n\n      // Validate credential_identifier against authorization_details if present\n      if ('credential_identifier' in credentialRequest && credentialRequest.credential_identifier && issuerCorrelation.authorizationDetails) {\n        const validIdentifiers = issuerCorrelation.authorizationDetails.flatMap((detail: any) => detail.credential_identifiers || [])\n\n        if (!validIdentifiers.includes(credentialRequest.credential_identifier)) {\n          throw Error('credential_identifier not found in authorization_details')\n        }\n      }\n\n      let format = this.lookupCredentialFormat(credentialRequest)\n      const validated = await this.validateCredentialRequestProof({\n        ...opts,\n        format,\n        tokenExpiresIn: opts.tokenExpiresIn ?? 180,\n      })\n      if (validated.preAuthorizedCode && !issuerCorrelation.preAuthorizedCode) {\n        issuerCorrelation.preAuthorizedCode = validated.preAuthorizedCode\n      }\n      if (validated.issuerState && !issuerCorrelation.issuerState) {\n        issuerCorrelation.issuerState = validated.issuerState\n      }\n\n      const { preAuthSession, authSession, cNonceState, jwtVerifyResult } = validated\n      const did = jwtVerifyResult.did\n      const jwk = jwtVerifyResult.jwk\n      const kid = jwtVerifyResult.kid\n      const newcNonce = opts.newCNonce ? opts.newCNonce : uuidv4()\n      const newcNonceState = {\n        cNonce: newcNonce,\n        createdAt: +new Date(),\n        ...(authSession?.issuerState && { issuerState: authSession.issuerState }),\n        ...(preAuthSession && { preAuthorizedCode: preAuthSession.preAuthorizedCode }),\n      }\n      await this.cNonces.set(newcNonce, newcNonceState)\n\n      if (!opts.credential && this._credentialDataSupplier === undefined && opts.credentialDataSupplier === undefined) {\n        throw Error(`Either a credential needs to be supplied or a credentialDataSupplier`)\n      }\n      let credential: CredentialIssuanceInput | undefined\n\n      let signerCallback: CredentialSignerCallback | undefined = opts.credentialSignerCallback\n      const session: CredentialOfferSession | undefined = issuerCorrelation.preAuthorizedCode && preAuthSession ? preAuthSession : authSession\n      if (opts.credential) {\n        credential = opts.credential\n      } else {\n        const credentialDataSupplier: CredentialDataSupplier | undefined =\n          typeof opts.credentialDataSupplier === 'function' ? opts.credentialDataSupplier : this._credentialDataSupplier\n        if (typeof credentialDataSupplier !== 'function') {\n          throw Error('Data supplier is mandatory if no credential is supplied')\n        }\n        if (!session) {\n          throw Error('Either a preAuth or Auth session is required, none found')\n        }\n        const credentialOffer = session.credentialOffer\n        if (!credentialOffer) {\n          throw Error('Credential Offer missing')\n        }\n        const credentialDataSupplierInput = opts.credentialDataSupplierInput ?? session.credentialDataSupplierInput\n\n        const result = await credentialDataSupplier({\n          ...(cNonceState ? { ...cNonceState } : { ...authSession }),\n          credentialRequest: opts.credentialRequest,\n          credentialSupplierConfig: this._issuerMetadata.credential_supplier_config,\n          format,\n          credentialOffer /*todo: clientId: */,\n          ...(credentialDataSupplierInput && { credentialDataSupplierInput }),\n        } as CredentialDataSupplierArgs)\n        credential = result.credential\n        if (result.format) {\n          format = result.format\n        }\n        if (typeof result.signCallback === 'function') {\n          signerCallback = result.signCallback\n        }\n      }\n      if (!credential) {\n        throw Error('A credential needs to be supplied at this point')\n      }\n      // Bind credential to the provided proof of possession\n      if (CredentialMapper.isSdJwtDecodedCredentialPayload(credential) && (kid || jwk) && !credential.cnf) {\n        if (kid) {\n          credential.cnf = {\n            kid,\n          }\n        }\n        // else  TODO temp workaround IATAB2B-57\n        if (jwk) {\n          credential.cnf = {\n            jwk,\n          }\n        }\n      } else if (did && !CredentialMapper.isSdJwtDecodedCredentialPayload(credential) && credential.credentialSubject !== undefined) {\n        const credentialSubjects = Array.isArray(credential.credentialSubject) ? credential.credentialSubject : [credential.credentialSubject]\n        credentialSubjects.map((subject) => {\n          if (!subject.id) {\n            subject.id = did\n          }\n          return subject\n        })\n        credential.credentialSubject = Array.isArray(credential.credentialSubject) ? credentialSubjects : credentialSubjects[0]\n      } else {\n        // Mdoc Format\n        // Nothing to do here\n      }\n\n      let issuer: string | undefined = undefined\n      if (credential.iss) {\n        issuer = credential.iss\n      } else if (credential.issuer) {\n        if (typeof credential.issuer === 'string') {\n          issuer = credential.issuer\n        } else if (typeof credential.issuer === 'object' && 'id' in credential.issuer && typeof credential.issuer.id === 'string') {\n          issuer = credential.issuer.id\n        }\n      }\n\n      const verifiableCredential = await this.issueCredentialImpl(\n        {\n          credentialRequest: opts.credentialRequest,\n          format,\n          credential,\n          jwtVerifyResult,\n          issuer,\n          ...(session && { statusLists: session.statusLists }),\n        },\n        signerCallback,\n      )\n      // TODO implement acceptance_token (deferred response)\n      // TODO update verification accordingly\n      if (!verifiableCredential) {\n        // credential: OPTIONAL. Contains issued Credential. MUST be present when acceptance_token is not returned. MAY be a JSON string or a JSON object, depending on the Credential format. See Appendix E for the Credential format specific encoding requirements\n        throw new Error(CREDENTIAL_MISSING_ERROR)\n      }\n      if (cNonceState) {\n        // remove the previous nonce\n        await this.cNonces.delete(cNonceState.cNonce)\n      }\n\n      let notification_id: string | undefined\n\n      if (issuerCorrelation.preAuthorizedCode && preAuthSession) {\n        preAuthSession.lastUpdatedAt = +new Date()\n        preAuthSession.status = IssueStatus.CREDENTIAL_ISSUED\n        notification_id = preAuthSession.notification_id\n        await this._credentialOfferSessions.set(issuerCorrelation.preAuthorizedCode, preAuthSession)\n      } else if (issuerCorrelation.issuerState && authSession) {\n        // If both were set we used the pre auth flow above as well, hence the else if\n        authSession.lastUpdatedAt = +new Date()\n        authSession.status = IssueStatus.CREDENTIAL_ISSUED\n        notification_id = authSession.notification_id\n        await this._credentialOfferSessions.set(issuerCorrelation.issuerState, authSession)\n      }\n\n      const response: CredentialResponse = {\n        credentials: [{ credential: verifiableCredential }],\n        // format: credentialRequest.format,\n        c_nonce: newcNonce,\n        c_nonce_expires_in: this._cNonceExpiresIn,\n        ...(notification_id && { notification_id }),\n      }\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      const experimentalSubjectIssuance = opts.credentialRequest.credential_subject_issuance\n      if (experimentalSubjectIssuance?.subject_proof_mode) {\n        if (experimentalSubjectIssuance.subject_proof_mode !== 'proof_replace') {\n          throw Error('Only proof replace is supported currently')\n        }\n        response.transaction_id = authSession?.issuerState\n        response.credential_subject_issuance = experimentalSubjectIssuance\n      }\n      return response\n    } catch (error: unknown) {\n      await this.updateSession({ preAuthorizedCode: issuerCorrelation.preAuthorizedCode, issuerState: issuerCorrelation.issuerState, error })\n      throw error\n    }\n  }\n\n  private lookupCredentialFormat(credentialRequest: CredentialRequestV1_0_15): OID4VCICredentialFormat | undefined {\n    let format: OID4VCICredentialFormat | undefined\n\n    if ('credential_configuration_id' in credentialRequest && credentialRequest.credential_configuration_id) {\n      const credentialConfig = this._issuerMetadata.credential_configurations_supported?.[credentialRequest.credential_configuration_id]\n      format = credentialConfig?.format as OID4VCICredentialFormat\n    } else if ('credential_identifier' in credentialRequest && credentialRequest.credential_identifier) {\n      const credentialIdentifier: any = credentialRequest.credential_identifier\n      const matchedConfig = Object.values(this._issuerMetadata.credential_configurations_supported || {}).find(\n        (config) => credentialIdentifier === config.id || credentialIdentifier === config.vct,\n      )\n\n      return matchedConfig?.format as OID4VCICredentialFormat\n    }\n    return format\n  }\n\n  private async updateSession({\n    preAuthorizedCode,\n    error,\n    issuerState,\n    notification,\n  }: {\n    preAuthorizedCode?: string\n    issuerState?: string\n    error?: unknown\n    notification?: NotificationRequest\n  }) {\n    let issueState: IssueStatus | undefined = undefined\n    if (error) {\n      issueState = IssueStatus.ERROR\n    } else if (notification) {\n      if (notification.event == 'credential_accepted') {\n        issueState = IssueStatus.NOTIFICATION_CREDENTIAL_ACCEPTED\n      } else if (notification.event == 'credential_deleted') {\n        issueState = IssueStatus.NOTIFICATION_CREDENTIAL_DELETED\n      } else if (notification.event == 'credential_failure') {\n        issueState = IssueStatus.NOTIFICATION_CREDENTIAL_FAILURE\n      }\n    }\n\n    if (preAuthorizedCode) {\n      const preAuthSession = await this._credentialOfferSessions.get(preAuthorizedCode)\n      if (preAuthSession) {\n        preAuthSession.lastUpdatedAt = +new Date()\n        if (issueState) {\n          preAuthSession.status = issueState\n        }\n        if (error) {\n          preAuthSession.error = error instanceof Error ? error.message : error?.toString()\n        }\n        preAuthSession.notification_id\n        if (notification) {\n          preAuthSession.notification = notification\n        }\n        await this._credentialOfferSessions.set(preAuthorizedCode, preAuthSession)\n      }\n    }\n    if (issuerState) {\n      const authSession = await this._credentialOfferSessions.get(issuerState)\n      if (authSession) {\n        authSession.lastUpdatedAt = +new Date()\n        if (issueState) {\n          authSession.status = issueState\n        }\n        if (error) {\n          authSession.error = error instanceof Error ? error.message : error?.toString()\n        }\n        if (notification) {\n          authSession.notification = notification\n        }\n        await this._credentialOfferSessions.set(issuerState, authSession)\n      }\n    }\n  }\n\n  /*\n    private async retrieveGrantsAndCredentialOfferSession(id: string): Promise<{\n      clientId?: string;\n      grants?: Grant,\n      session: CredentialOfferSession\n    }> {\n      const session: CredentialOfferSession | undefined = await this._credentialOfferSessions.getAsserted(id)\n      const clientId = session?.clientId\n      const grants = session?.credentialOffer?.credential_offer?.grants\n      if (!grants?.authorization_code?.issuer_state && !grants?.[PRE_AUTH_GRANT_LITERAL]?.[PRE_AUTH_CODE_LITERAL]) {\n        throw new Error(GRANTS_MUST_NOT_BE_UNDEFINED)\n      }\n      return { session, clientId, grants }\n    }*/\n\n  private async validateCredentialRequestProof({\n    credentialRequest,\n    issuerCorrelation,\n    format,\n    jwtVerifyCallback,\n    tokenExpiresIn,\n  }: {\n    credentialRequest: CredentialRequest\n    issuerCorrelation: IssuerCorrelation\n    format?: OID4VCICredentialFormat\n    tokenExpiresIn: number // expiration duration in seconds\n    // grants?: Grant,\n    clientId?: string\n    jwtVerifyCallback?: JWTVerifyCallback\n  }) {\n    let issuerState: string | undefined\n\n    const supportedIssuanceFormats = ['jwt_vc_json', 'jwt_vc_json-ld', 'dc+sd-jwt', 'ldp_vc', 'mso_mdoc']\n    try {\n      if (format && !supportedIssuanceFormats.includes(format)) {\n        throw Error(`Format ${format} not supported yet`)\n      }\n\n      const verifyFn: JWTVerifyCallback | undefined = jwtVerifyCallback ?? this._jwtVerifyCallback\n      if (typeof verifyFn !== 'function') {\n        throw Error(JWT_VERIFY_CONFIG_ERROR)\n      }\n\n      const credReq = credentialRequest as CredentialRequestV1_0_15\n\n      // Validate request structure (mutually exclusive)\n      if (credReq.proof && credReq.proofs) {\n        throw Error('Credential request may not contain both proof and proofs parameters')\n      }\n\n      // Normalize candidates into a single array of ProofOfPossession objects\n      const proofCandidates: Array<ProofOfPossession> = []\n\n      if (credReq.proof) {\n        proofCandidates.push(credReq.proof)\n      } else if (credReq.proofs) {\n        // Handle \"proofs\": prioritize 'jwt' as it's the only fully supported type\n        if (Array.isArray(credReq.proofs.jwt)) {\n          // Map to ProofOfPossession objects, handling both string and object formats\n          for (const jwtProof of credReq.proofs.jwt) {\n            if (typeof jwtProof === 'string') {\n              // Handle case where jwt array contains strings instead of ProofOfPossession objects\n              proofCandidates.push({\n                proof_type: 'jwt',\n                jwt: jwtProof,\n              })\n            } else if (jwtProof && typeof jwtProof === 'object' && 'jwt' in jwtProof) {\n              // Handle proper ProofOfPossession object\n              proofCandidates.push(jwtProof)\n            }\n          }\n        }\n\n        // Check if there are no supported proofs found\n        if (proofCandidates.length === 0) {\n          const availableTypes = Object.keys(credReq.proofs).join(', ')\n          throw Error(`No supported proof types found in request. Available: [${availableTypes}]`)\n        }\n      } else {\n        throw Error('Proof of possession is required. No proof or proofs value present in credential request')\n      }\n\n      // Execute verification\n      let jwtVerifyResult: JwtVerifyResult | undefined\n      const validationErrors: string[] = []\n\n      for (const proof of proofCandidates) {\n        try {\n          jwtVerifyResult = await verifyFn({ jwt: proof.jwt })\n          break\n        } catch (error) {\n          const msg = error instanceof Error ? error.message : String(error)\n          validationErrors.push(msg)\n        }\n      }\n\n      // Check success\n      if (!jwtVerifyResult) {\n        throw Error(`Unable to verify any provided proofs. Errors: ${validationErrors.join('; ')}`)\n      }\n\n      const { didDocument, did, jwt } = jwtVerifyResult\n      const { header, payload } = jwt\n      const { iss, aud, iat, nonce } = payload\n      const issuer_state =\n        'issuer_state' in credentialRequest && credentialRequest.issuer_state ? credentialRequest.issuer_state : issuerCorrelation.issuerState\n      if (!nonce && !issuer_state) {\n        throw Error('No nonce or issuer_state was found in the Proof of Possession')\n      }\n\n      let createdAt: number = +new Date()\n      let cNonceState: CNonceState | undefined\n      if (nonce) {\n        cNonceState = await this.cNonces.getAsserted(nonce)\n        createdAt = cNonceState.createdAt\n      }\n      if (issuer_state) {\n        const session = await this._credentialOfferSessions.getAsserted(issuer_state as string)\n        issuerState = issuer_state as string | undefined\n        createdAt = session.createdAt\n      }\n\n      // The verify callback should set the correct values, but let's look at the JWT ourselves to to be sure\n      const alg = jwtVerifyResult.alg ?? header.alg\n      const kid = jwtVerifyResult.kid ?? header.kid\n      const jwk = jwtVerifyResult.jwk ?? header.jwk\n      const x5c = jwtVerifyResult.x5c ?? header.x5c\n      const typ = header.typ\n\n      if (typ !== 'openid4vci-proof+jwt') {\n        throw Error(TYP_ERROR)\n      } else if (!alg) {\n        throw Error(ALG_ERROR)\n      } else if (x5c && (kid || jwk)) {\n        // x5c cannot be used together with kid or jwk\n        throw Error(KID_JWK_X5C_ERROR)\n      } else if (kid && !did) {\n        if (!jwk && !x5c) {\n          // Make sure the callback function extracts the DID from the kid\n          throw Error(KID_DID_NO_DID_ERROR)\n        } else {\n          // If JWK or x5c is present, log the information and proceed\n          console.log(`KID present but no DID, using JWK or x5c`)\n        }\n      } else if (did && !didDocument) {\n        // Make sure the callback function does DID resolution when a did is present\n        throw Error(DID_NO_DIDDOC_ERROR)\n      }\n\n      const preAuthSession = issuerCorrelation.preAuthorizedCode\n        ? await this.credentialOfferSessions.get(issuerCorrelation.preAuthorizedCode)\n        : undefined\n      const authSession = issuerState ? await this.credentialOfferSessions.get(issuerState) : undefined\n      if (!preAuthSession && !authSession) {\n        throw Error('Either a pre-authorized code or issuer state needs to be present')\n      }\n      if (preAuthSession) {\n        if (!preAuthSession.preAuthorizedCode || preAuthSession.preAuthorizedCode !== issuerCorrelation.preAuthorizedCode) {\n          throw Error('Invalid pre-authorized code')\n        }\n        preAuthSession.lastUpdatedAt = +new Date()\n        preAuthSession.status = IssueStatus.CREDENTIAL_REQUEST_RECEIVED\n        await this._credentialOfferSessions.set(issuerCorrelation.preAuthorizedCode, preAuthSession)\n      }\n      if (authSession) {\n        if (!authSession.issuerState || authSession.issuerState !== issuerState) {\n          throw Error('Invalid issuer state')\n        }\n        authSession.lastUpdatedAt = +new Date()\n        authSession.status = IssueStatus.CREDENTIAL_REQUEST_RECEIVED\n      }\n\n      // https://www.rfc-editor.org/rfc/rfc6749.html#section-3.2.1\n      // A client MAY use the \"client_id\" request parameter to identify itself\n      // when sending requests to the token endpoint.  In the\n      // \"authorization_code\" \"grant_type\" request to the token endpoint, an\n      // unauthenticated client MUST send its \"client_id\" to prevent itself\n      // from inadvertently accepting a code intended for a client with a\n      // different \"client_id\".  This protects the client from substitution of\n      // the authentication code.  (It provides no additional security for the\n      // protected resource.)\n      if (!iss && authSession?.credentialOffer.credential_offer?.grants?.authorization_code) {\n        throw new Error(NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT)\n      }\n      // iss: OPTIONAL (string). The value of this claim MUST be the client_id of the client making the credential request.\n      // This claim MUST be omitted if the Access Token authorizing the issuance call was obtained from a Pre-Authorized Code Flow through anonymous access to the Token Endpoint.\n      // TODO We need to investigate further what the comment above means, because it's not clear if the client or the user may be authorized anonymously\n      // if (iss && grants && grants[PRE_AUTH_GRANT_LITERAL]) {\n      //   throw new Error(ISS_PRESENT_IN_PRE_AUTHORIZED_CODE_CONTEXT)\n      // }\n      /*if (iss && iss !== clientId) {\n        throw new Error(ISS_MUST_BE_CLIENT_ID + `iss: ${iss}, client_id: ${clientId}`)\n      }*/\n      if (!aud || aud !== this._issuerMetadata.credential_issuer) {\n        throw new Error(AUD_ERROR)\n      }\n      if (!iat) {\n        throw new Error(IAT_ERROR)\n      } else if (iat > Math.round(createdAt / 1000) + tokenExpiresIn) {\n        // createdAt is in milliseconds whilst iat and tokenExpiresIn are in seconds\n        throw new Error(IAT_ERROR)\n      }\n      // todo: Add a check of iat against current TS on server with a skew\n\n      return { jwtVerifyResult, preAuthorizedCode: issuerCorrelation.preAuthorizedCode, preAuthSession, issuerState, authSession, cNonceState }\n    } catch (error: unknown) {\n      await this.updateSession({ preAuthorizedCode: issuerCorrelation.preAuthorizedCode, issuerState, error })\n      throw error\n    }\n  }\n\n  private async issueCredentialImpl(\n    opts: {\n      credentialRequest: CredentialRequest\n      credential: CredentialIssuanceInput\n      jwtVerifyResult: JwtVerifyResult\n      format?: OID4VCICredentialFormat\n      issuer?: string\n      statusLists?: Array<StatusListOpts>\n    },\n    issuerCallback?: CredentialSignerCallback,\n  ): Promise<W3CVerifiableCredential | CompactSdJwtVc> {\n    if ((!opts.credential && !opts.credentialRequest) || !this._credentialSignerCallback) {\n      throw new Error(ISSUER_CONFIG_ERROR)\n    }\n    const credential = issuerCallback ? await issuerCallback(opts) : await this._credentialSignerCallback(opts)\n\n    // TODO: Create builder\n    EVENTS.emit(CredentialEventNames.OID4VCI_CREDENTIAL_ISSUED, {\n      eventName: CredentialEventNames.OID4VCI_CREDENTIAL_ISSUED,\n      id: uuidv4(),\n      data: credential,\n      // TODO: Format, request etc\n      initiator: opts.issuer ?? '<unknown>',\n      initiatorType: InitiatorType.EXTERNAL,\n      system: System.OID4VCI,\n      subsystem: SubSystem.VC_ISSUER,\n    })\n\n    return credential\n  }\n\n  get credentialSignerCallback(): CredentialSignerCallback | undefined {\n    return this._credentialSignerCallback\n  }\n\n  get jwtVerifyCallback(): JWTVerifyCallback | undefined {\n    return this._jwtVerifyCallback\n  }\n\n  get credentialDataSupplier(): CredentialDataSupplier | undefined {\n    return this._credentialDataSupplier\n  }\n\n  get uris(): IStateManager<URIState> {\n    return this._uris\n  }\n\n  get cNonceExpiresIn(): number {\n    return this._cNonceExpiresIn\n  }\n\n  public get credentialOfferSessions(): IStateManager<CredentialOfferSession> {\n    return this._credentialOfferSessions\n  }\n\n  public get cNonces(): IStateManager<CNonceState> {\n    return this._cNonces\n  }\n\n  get defaultCredentialOfferBaseUri(): string | undefined {\n    return this._defaultCredentialOfferBaseUri\n  }\n\n  public get issuerMetadata() {\n    return this._issuerMetadata\n  }\n\n  // TODO SSISDK-87 create proper solution to update issuer metadata\n  public set issuerMetadata(value: CredentialIssuerMetadataOptsV1_0_15) {\n    this._issuerMetadata = value;\n  }\n\n  public get authorizationServerMetadata() {\n    return this._authorizationServerMetadata\n  }\n\n  get asClientOpts() {\n    return this._asClientOpts\n  }\n}\n","import { uuidv4 } from '@sphereon/oid4vc-common'\nimport {\n  AssertedUniformCredentialOffer,\n  AuthorizationDetailsV1_0_15,\n  CredentialIssuerMetadataOptsV1_0_15,\n  CredentialOfferMode,\n  CredentialOfferPayloadV1_0_15,\n  CredentialOfferSession,\n  CredentialOfferV1_0_15,\n  Grant,\n  GrantAuthorizationCode,\n  GrantUrnIetf,\n  IssuerMetadataV1_0_15,\n  PIN_NOT_MATCH_ERROR,\n  PRE_AUTH_GRANT_LITERAL,\n  UniformCredentialOffer,\n} from '@sphereon/oid4vci-common'\n\nexport interface CredentialOfferGrantInput {\n  authorization_code?: Partial<GrantAuthorizationCode>\n  [PRE_AUTH_GRANT_LITERAL]?: Partial<GrantUrnIetf>\n  'urn:ietf:params:oauth:grant-type:pre-authorized_code'?: Partial<GrantUrnIetf> // FIXME? Getting typscript errors when only PRE_AUTH_GRANT_LITERAL is there\n}\n\nfunction createCredentialOfferGrants(inputGrants?: CredentialOfferGrantInput) {\n  // Grants is optional\n  if (!inputGrants || Object.keys(inputGrants).length === 0) {\n    return undefined\n  }\n\n  const grants: Grant = {}\n  if (inputGrants?.[PRE_AUTH_GRANT_LITERAL]) {\n    const grant = {\n      ...inputGrants[PRE_AUTH_GRANT_LITERAL],\n      'pre-authorized_code': inputGrants[PRE_AUTH_GRANT_LITERAL]['pre-authorized_code'] ?? uuidv4(),\n    }\n\n    if (grant.tx_code && !grant.tx_code.length) {\n      grant.tx_code.length = 4\n    }\n\n    grants[PRE_AUTH_GRANT_LITERAL] = grant\n  }\n\n  if (inputGrants?.authorization_code) {\n    grants.authorization_code = {\n      ...inputGrants.authorization_code,\n\n      // TODO: it should be possible to create offer without issuer_state\n      // this is added to avoid breaking changes.\n      issuer_state: inputGrants.authorization_code.issuer_state ?? uuidv4(),\n    }\n  }\n\n  return grants\n}\n\nfunction parseCredentialOfferSchemeAndBaseUri(scheme?: string, baseUri?: string, credentialIssuer?: string): { scheme: string; baseUri: string } {\n  const newScheme = scheme?.replace('://', '') ?? (baseUri?.includes('://') ? baseUri.split('://')[0] : 'openid-credential-offer')\n  let newBaseUri: string\n\n  if (baseUri) {\n    newBaseUri = baseUri\n  } else if (newScheme.startsWith('http')) {\n    if (credentialIssuer) {\n      newBaseUri = credentialIssuer\n      if (!newBaseUri.startsWith(`${newScheme}://`)) {\n        throw Error(`scheme ${newScheme} is different from base uri ${newBaseUri}`)\n      }\n    } else {\n      throw Error(`A '${newScheme}' scheme requires a URI to be present as baseUri`)\n    }\n  } else {\n    newBaseUri = ''\n  }\n  newBaseUri = newBaseUri?.replace(`${newScheme}://`, '')\n\n  return { scheme: newScheme, baseUri: newBaseUri }\n}\n\nexport function createCredentialOfferObject(\n  issuerMetadata?: CredentialIssuerMetadataOptsV1_0_15,\n  // todo: probably it's wise to create another builder for CredentialOfferPayload that will generate different kinds of CredentialOfferPayload\n  opts?: {\n    credentialOffer?: CredentialOfferPayloadV1_0_15\n    credentialOfferUri?: string\n    grants?: CredentialOfferGrantInput\n    client_id?: string\n  },\n): AssertedUniformCredentialOffer {\n  if (!issuerMetadata && !opts?.credentialOffer && !opts?.credentialOfferUri) {\n    throw new Error('You have to provide issuerMetadata or credentialOffer object for creating a deeplink')\n  }\n\n  const grants = createCredentialOfferGrants(opts?.grants)\n\n  let credential_offer: CredentialOfferPayloadV1_0_15\n  if (opts?.credentialOffer) {\n    credential_offer = {\n      ...opts.credentialOffer,\n    }\n  } else {\n    if (!issuerMetadata?.credential_configurations_supported) {\n      throw new Error('credential_configurations_supported is mandatory in the metadata')\n    }\n    credential_offer = {\n      credential_issuer: issuerMetadata.credential_issuer,\n      credential_configuration_ids: Object.keys(issuerMetadata.credential_configurations_supported),\n    }\n  }\n\n  if (grants) {\n    credential_offer.grants = grants\n  }\n  if (opts?.client_id) {\n    credential_offer.client_id = opts.client_id\n  }\n\n  // todo: check payload against issuer metadata. Especially strings in the credentials array: When processing, the Wallet MUST resolve this string value to the respective object.\n  return { credential_offer, credential_offer_uri: opts?.credentialOfferUri }\n}\n\nexport function createCredentialOfferURIFromObject(\n  credentialOffer: CredentialOfferV1_0_15 | UniformCredentialOffer,\n  offerMode: CredentialOfferMode,\n  opts?: { scheme?: string; baseUri?: string },\n) {\n  const { scheme, baseUri } = parseCredentialOfferSchemeAndBaseUri(opts?.scheme, opts?.baseUri, credentialOffer.credential_offer?.credential_issuer)\n\n  if (offerMode === 'REFERENCE') {\n    if (!credentialOffer.credential_offer_uri) {\n      throw Error(`credential_offer_uri must be set for offerMode ${offerMode}`)\n    }\n    if (credentialOffer.credential_offer_uri.includes('credential_offer_uri=')) {\n      // discard the scheme. Apparently a URI is set and it already contains the actual uri, so assume that takes priority\n      return credentialOffer.credential_offer_uri\n    }\n    return `${scheme}://${baseUri}?credential_offer_uri=${encodeURIComponent(credentialOffer.credential_offer_uri)}`\n  } else if (offerMode === 'VALUE') {\n    return `${scheme}://${baseUri}?credential_offer=${encodeURIComponent(JSON.stringify(credentialOffer.credential_offer))}`\n  }\n  throw Error(`unsupported offerMode ${offerMode}`)\n}\n\nexport function createCredentialOfferURI(\n  offerMode: CredentialOfferMode,\n  issuerMetadata?: IssuerMetadataV1_0_15,\n  // todo: probably it's wise to create another builder for CredentialOfferPayload that will generate different kinds of CredentialOfferPayload\n  opts?: {\n    credentialOffer?: CredentialOfferPayloadV1_0_15\n    credentialOfferUri?: string\n    scheme?: string\n    baseUri?: string\n    grants?: CredentialOfferGrantInput\n  },\n): string {\n  const credentialOffer = createCredentialOfferObject(issuerMetadata, opts)\n  return createCredentialOfferURIFromObject(credentialOffer, offerMode, opts)\n}\n\nexport const isPreAuthorizedCodeExpired = (state: CredentialOfferSession, expirationDurationInSeconds: number) => {\n  const now = +new Date()\n  const expirationTime = state.createdAt + expirationDurationInSeconds * 1000\n  return now >= expirationTime\n}\n\nexport const assertValidPinNumber = (pin?: string, pinLength?: number) => {\n  if (pin && !RegExp(`[\\\\d\\\\D]{${pinLength ?? 6}}`).test(pin)) {\n    throw Error(`${PIN_NOT_MATCH_ERROR}`)\n  }\n}\n\n/**\n * Generates unique credential identifiers for authorization details\n * Each identifier represents a specific credential instance that can be issued\n */\nexport const generateCredentialIdentifiers = (authDetail: AuthorizationDetailsV1_0_15, session: CredentialOfferSession): string[] => {\n  if (typeof authDetail === 'string') {\n    return [uuidv4()]\n  }\n\n  const identifiers: string[] = []\n\n  if (authDetail.credential_configuration_id) {\n    const configId = authDetail.credential_configuration_id\n    const hasConfig = session.credentialOffer.credential_offer.credential_configuration_ids?.includes(configId)\n\n    if (hasConfig) {\n      identifiers.push(`${configId}_${Date.now()}_${uuidv4()}`)\n    }\n  }\n\n  if (identifiers.length === 0 && authDetail.format) {\n    identifiers.push(`${authDetail.format}_${Date.now()}_${uuidv4()}`)\n  }\n\n  // Ultimate fallback\n  if (identifiers.length === 0) {\n    identifiers.push(uuidv4())\n  }\n\n  return identifiers\n}\n","import { decodeJwt, decodeProtectedHeader } from '@sphereon/oid4vc-common'\nimport { ClientMetadata, JWTHeader, JWTVerifyCallback, JwtVerifyResult } from '@sphereon/oid4vci-common'\nimport { oidcDiscoverIssuer, oidcGetClient } from '@sphereon/ssi-express-support'\n\nexport function oidcAccessTokenVerifyCallback(opts: {\n  credentialIssuer: string\n  authorizationServer: string\n  clientMetadata?: ClientMetadata\n}): JWTVerifyCallback {\n  const clientMetadata = opts.clientMetadata ?? { client_id: opts.credentialIssuer }\n\n  return async (args: { jwt: string; kid?: string }): Promise<JwtVerifyResult> => {\n    const oidcIssuer = await oidcDiscoverIssuer({ issuerUrl: opts.authorizationServer })\n    const oidcClient = await oidcGetClient(oidcIssuer.issuer, clientMetadata)\n    const introspection = await oidcClient.introspect(args.jwt)\n    if (!introspection.active) {\n      return Promise.reject(Error('Access token is not active or invalid'))\n    }\n    const jwt = { header: decodeProtectedHeader(args.jwt) as JWTHeader, payload: decodeJwt(args.jwt) }\n\n    return {\n      jwt,\n      alg: jwt.header.alg,\n      ...(jwt.header.jwk && { jwk: jwt.header.jwk }),\n      ...(jwt.header.x5c && { x5c: jwt.header.x5c }),\n      ...(jwt.header.kid && { kid: jwt.header.kid }),\n      // We could resolve the did document here if the kid is a VM\n    }\n  }\n}\n","import { IStateManager, STATE_MISSING_ERROR, StateType } from '@sphereon/oid4vci-common'\n\nexport class MemoryStates<T extends StateType> implements IStateManager<T> {\n  private readonly expiresInMS: number\n  private readonly states: Map<string, T>\n  private cleanupIntervalId?: number | NodeJS.Timeout\n\n  constructor(opts?: { expiresInSec?: number }) {\n    this.expiresInMS = opts?.expiresInSec !== undefined ? opts?.expiresInSec * 1000 : 180000\n    this.states = new Map()\n  }\n\n  async clearAll(): Promise<void> {\n    this.states.clear()\n  }\n\n  async clearExpired(timestamp?: number): Promise<void> {\n    const states = Array.from(this.states.entries())\n    const ts = timestamp ?? +new Date()\n    for (const [id, state] of states) {\n      if (state.expiresAt && state.expiresAt < ts) {\n        this.states.delete(id)\n      } else if (!state.expiresAt) {\n        // If there is no expiration set on the state itself, we will use the state manager expiresInMS value\n        if (state.createdAt + this.expiresInMS < ts) {\n          this.states.delete(id)\n        }\n      }\n    }\n  }\n\n  async delete(id: string): Promise<boolean> {\n    if (!id) {\n      throw Error('No id supplied')\n    }\n    return this.states.delete(id)\n  }\n\n  async getAsserted(id: string): Promise<T> {\n    if (!id) {\n      throw Error('No id supplied')\n    }\n    let result: T | undefined\n    if (await this.has(id)) {\n      result = (await this.get(id)) as T\n    }\n    if (!result) {\n      throw new Error(STATE_MISSING_ERROR + ` (${id})`)\n    }\n    return result\n  }\n\n  async get(id: string): Promise<T | undefined> {\n    return this.states.get(id)\n  }\n\n  async has(id: string): Promise<boolean> {\n    if (!id) {\n      throw Error('No id supplied')\n    }\n    return this.states.has(id)\n  }\n\n  async set(id: string, stateValue: T): Promise<void> {\n    if (!id) {\n      throw Error('No id supplied')\n    }\n    this.states.set(id, stateValue)\n  }\n\n  async startCleanupRoutine(timeout?: number): Promise<void> {\n    if (!this.cleanupIntervalId) {\n      this.cleanupIntervalId = setInterval(() => this.clearExpired(), timeout ?? 30000)\n    }\n  }\n\n  async stopCleanupRoutine(): Promise<void> {\n    if (this.cleanupIntervalId) {\n      clearInterval(this.cleanupIntervalId)\n    }\n  }\n}\n","// noinspection ES6MissingAwait\n\nimport { IStateManager, StateType } from '@sphereon/oid4vci-common'\n\nexport async function lookupStateManagerMultiGetAsserted<K extends StateType, V extends StateType>(args: {\n  id: string\n  lookups: string[]\n  keyValueMapper: IStateManager<K>\n  valueStateManager: IStateManager<V>\n}) {\n  const value = await lookupStateManagerMultiGet(args)\n  if (value) {\n    return value\n  }\n  return Promise.reject(Error(`no value found for id ${args.id}`))\n}\nexport async function lookupStateManagerMultiGet<K extends StateType, V extends StateType>({\n  id,\n  lookups,\n  keyValueMapper,\n  valueStateManager,\n}: {\n  id: string\n  lookups: string[]\n  keyValueMapper: IStateManager<K>\n  valueStateManager: IStateManager<V>\n}) {\n  for (const lookup of lookups) {\n    try {\n      const value = await new LookupStateManager(keyValueMapper, valueStateManager, lookup).get(id)\n      if (value) {\n        return value\n      }\n    } catch (e) {\n      // intentionally ignore the error\n    }\n  }\n  return valueStateManager.get(id)\n}\n\nexport class LookupStateManager<K extends StateType, V extends StateType> implements IStateManager<V> {\n  constructor(\n    private keyValueMapper: IStateManager<K>,\n    private valueStateManager: IStateManager<V>,\n    private lookup: string,\n  ) {}\n\n  startCleanupRoutine(timeout?: number | undefined): Promise<void> {\n    this.keyValueMapper.startCleanupRoutine(timeout)\n    return this.valueStateManager.startCleanupRoutine(timeout)\n  }\n\n  stopCleanupRoutine(): Promise<void> {\n    this.keyValueMapper.stopCleanupRoutine()\n    return this.valueStateManager.stopCleanupRoutine()\n  }\n\n  async clearAll(): Promise<void> {\n    this.keyValueMapper.clearAll()\n    this.valueStateManager.clearAll()\n  }\n\n  async clearExpired(timestamp?: number): Promise<void> {\n    this.keyValueMapper.clearExpired(timestamp)\n    this.valueStateManager.clearExpired(timestamp)\n  }\n\n  private async assertedValueId(key: string): Promise<string> {\n    const prop = this.lookup\n    const valueId = await this.keyValueMapper\n      .getAsserted(key)\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      .then((keyState) => (keyState && prop in keyState ? keyState[prop] : undefined))\n    if (typeof valueId !== 'string') {\n      throw Error('no value id could be derived for key' + key)\n    }\n    return valueId\n  }\n\n  private async valueId(key: string): Promise<string | undefined> {\n    const prop = this.lookup\n    return (await this.keyValueMapper\n      .get(key)\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      .then((keyState) => (keyState && prop in keyState ? keyState[prop] : undefined))) as string\n  }\n\n  async delete(id: string): Promise<boolean> {\n    return await this.assertedValueId(id).then(async (value) => {\n      await this.keyValueMapper.delete(id)\n      return await this.valueStateManager.delete(value)\n    })\n  }\n\n  async get(id: string): Promise<V | undefined> {\n    return this.valueId(id).then((value) => (value ? this.valueStateManager.get(value) : undefined))\n  }\n\n  async has(id: string): Promise<boolean> {\n    return this.valueId(id).then((value) => (value ? this.valueStateManager.has(value) : false))\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  async set(_id: string, _stateValue: V): Promise<void> {\n    throw Error(`Please use the setMappedMethod that accepts both and id, value and object`)\n  }\n\n  async setMapped(valueKey: string, keyObject: K, stateValue: V): Promise<void> {\n    const keys = keyObject as any\n    if (!(this.lookup in keys) || !keys[this.lookup]) {\n      return Promise.reject(new Error(`keyValue ${keyObject} does not contain the lookup property ${this.lookup}`))\n    }\n    const key = keys[this.lookup]\n    await this.keyValueMapper.set(key, keyObject)\n    await this.valueStateManager.set(valueKey, stateValue)\n  }\n\n  async getAsserted(id: string): Promise<V> {\n    return this.assertedValueId(id).then((value) => this.valueStateManager.getAsserted(value))\n  }\n}\n","import { AssertedUniformCredentialOffer, CredentialOfferSession } from '@sphereon/oid4vci-common'\n\nexport class CredentialOfferStateBuilder {\n  private readonly credentialOfferState: Partial<CredentialOfferSession>\n  constructor() {\n    this.credentialOfferState = {}\n  }\n\n  credentialOffer(credentialOffer: AssertedUniformCredentialOffer): CredentialOfferStateBuilder {\n    this.credentialOfferState.credentialOffer = credentialOffer\n    return this\n  }\n\n  createdAt(timestamp: number): CredentialOfferStateBuilder {\n    this.credentialOfferState.createdAt = timestamp\n    return this\n  }\n\n  build(): CredentialOfferSession {\n    if (!this.credentialOfferState.createdAt) {\n      this.credentialOfferState.createdAt = +new Date()\n    }\n    if (!this.credentialOfferState.credentialOffer) {\n      throw new Error('Not all properties are present to build an IssuerState object')\n    }\n    return this.credentialOfferState as CredentialOfferSession\n  }\n}\n","import { ImageInfo, MetadataDisplay } from '@sphereon/oid4vci-common'\n\nexport class DisplayBuilder {\n  name?: string\n  locale?: string\n  additionalProperties: Record<string, unknown> = {}\n\n  logo?: ImageInfo\n  backgroundColor?: string\n  textColor?: string\n\n  withName(name: string) {\n    this.name = name\n    return this\n  }\n\n  withLocale(locale: string) {\n    this.locale = locale\n    return this\n  }\n\n  withLogo(logo: ImageInfo) {\n    if (logo) {\n      if (!logo.uri) {\n        throw Error(`logo without url will not work`)\n      }\n    }\n    this.logo = logo\n    return this\n  }\n\n  withBackgroundColor(backgroundColor: string) {\n    this.backgroundColor = backgroundColor\n    return this\n  }\n\n  withTextColor(textColor: string) {\n    this.textColor = textColor\n    return this\n  }\n\n  withAdditionalProperties(properties: Record<string, unknown>) {\n    this.additionalProperties = properties ?? {}\n    return this\n  }\n\n  addAdditionalProperty(key: string, value: unknown) {\n    this.additionalProperties[key] = value\n    return this\n  }\n\n  build(): MetadataDisplay {\n    return {\n      ...this.additionalProperties,\n      ...(this.name && { name: this.name }),\n      ...(this.locale && { locale: this.locale }),\n      ...(this.logo && { logo: this.logo }),\n      ...(this.backgroundColor && { background_color: this.backgroundColor }),\n      ...(this.textColor && { text_color: this.textColor }),\n    }\n  }\n}\n","import {\n  BatchCredentialIssuance,\n  CredentialConfigurationSupportedV1_0_15,\n  IssuerMetadataV1_0_15,\n  MetadataDisplay,\n  ResponseEncryption,\n} from '@sphereon/oid4vci-common'\n\nimport { CredentialSupportedBuilderV1_15 } from './CredentialSupportedBuilderV1_15'\nimport { DisplayBuilder } from './DisplayBuilder'\n\nexport class IssuerMetadataBuilderV1_15 {\n  credentialEndpoint?: string\n  nonceEndpoint?: string // New in v15\n  credentialIssuer?: string\n  supportedBuilders: CredentialSupportedBuilderV1_15[] = []\n  credentialConfigurationsSupported: Record<string, CredentialConfigurationSupportedV1_0_15> = {}\n  displayBuilders: DisplayBuilder[] = []\n  display: MetadataDisplay[] = []\n  batchCredentialIssuance?: BatchCredentialIssuance // Changed from batchCredentialEndpoint in v15\n  authorizationServers?: string[]\n  tokenEndpoint?: string\n  authorizationChallengeEndpoint?: string\n  credentialResponseEncryption?: ResponseEncryption\n  signedMetadata?: string\n  credentialIdentifiersSupported?: boolean\n\n  // Removed withBatchCredentialEndpoint - replaced with batch issuance metadata\n  public withBatchCredentialIssuance(batchCredentialIssuance: BatchCredentialIssuance) {\n    this.batchCredentialIssuance = batchCredentialIssuance\n    return this\n  }\n\n  public withAuthorizationServers(authorizationServers: string[]) {\n    this.authorizationServers = authorizationServers\n    return this\n  }\n\n  public withAuthorizationServer(authorizationServer: string) {\n    if (this.authorizationServers === undefined) {\n      this.authorizationServers = []\n    }\n    this.authorizationServers.push(authorizationServer)\n    return this\n  }\n\n  public withAuthorizationChallengeEndpoint(authorizationChallengeEndpoint: string) {\n    this.authorizationChallengeEndpoint = authorizationChallengeEndpoint\n    return this\n  }\n\n  public withTokenEndpoint(tokenEndpoint: string) {\n    this.tokenEndpoint = tokenEndpoint\n    return this\n  }\n\n  public withCredentialEndpoint(credentialEndpoint: string): IssuerMetadataBuilderV1_15 {\n    this.credentialEndpoint = credentialEndpoint\n    return this\n  }\n\n  // New in v15: Nonce endpoint support\n  public withNonceEndpoint(nonceEndpoint: string): IssuerMetadataBuilderV1_15 {\n    this.nonceEndpoint = nonceEndpoint\n    return this\n  }\n\n  public withCredentialIssuer(credentialIssuer: string): IssuerMetadataBuilderV1_15 {\n    this.credentialIssuer = credentialIssuer\n    return this\n  }\n\n  // New in v15: Credential response encryption support\n  public withCredentialResponseEncryption(credentialResponseEncryption: ResponseEncryption): IssuerMetadataBuilderV1_15 {\n    this.credentialResponseEncryption = credentialResponseEncryption\n    return this\n  }\n\n  // New in v15: Signed metadata support\n  public withSignedMetadata(signedMetadata: string): IssuerMetadataBuilderV1_15 {\n    this.signedMetadata = signedMetadata\n    return this\n  }\n\n  // New in v15: Credential identifiers support\n  public withCredentialIdentifiersSupported(credentialIdentifiersSupported: boolean): IssuerMetadataBuilderV1_15 {\n    this.credentialIdentifiersSupported = credentialIdentifiersSupported\n    return this\n  }\n\n  public newSupportedCredentialBuilder(): CredentialSupportedBuilderV1_15 {\n    const builder = new CredentialSupportedBuilderV1_15()\n    this.addSupportedCredentialBuilder(builder)\n    return builder\n  }\n\n  public addSupportedCredentialBuilder(supportedCredentialBuilder: CredentialSupportedBuilderV1_15) {\n    this.supportedBuilders.push(supportedCredentialBuilder)\n    return this\n  }\n\n  public addCredentialConfigurationsSupported(id: string, supportedCredential: CredentialConfigurationSupportedV1_0_15) {\n    this.credentialConfigurationsSupported[id] = supportedCredential\n    return this\n  }\n\n  public withIssuerDisplay(issuerDisplay: MetadataDisplay[] | MetadataDisplay): IssuerMetadataBuilderV1_15 {\n    this.display = Array.isArray(issuerDisplay) ? issuerDisplay : [issuerDisplay]\n    return this\n  }\n\n  public addDisplay(display: MetadataDisplay) {\n    this.display.push(display)\n  }\n\n  public addDisplayBuilder(displayBuilder: DisplayBuilder) {\n    this.displayBuilders.push(displayBuilder)\n  }\n\n  public newDisplayBuilder(): DisplayBuilder {\n    const builder = new DisplayBuilder()\n    this.addDisplayBuilder(builder)\n    return builder\n  }\n\n  public build(): IssuerMetadataV1_0_15 {\n    if (!this.credentialIssuer) {\n      throw Error('No credential issuer supplied')\n    } else if (!this.credentialEndpoint) {\n      throw Error('No credential endpoint supplied')\n    }\n    const credential_configurations_supported: Record<string, CredentialConfigurationSupportedV1_0_15> = this.credentialConfigurationsSupported\n    const configurationsEntryList: Record<string, CredentialConfigurationSupportedV1_0_15>[] = this.supportedBuilders.map((builder) =>\n      builder.build(),\n    )\n    configurationsEntryList.forEach((configRecord) => {\n      Object.keys(configRecord).forEach((key) => {\n        credential_configurations_supported[key] = configRecord[key]\n      })\n    })\n    if (Object.keys(credential_configurations_supported).length === 0) {\n      throw Error('No supported credentials supplied')\n    }\n\n    const display: MetadataDisplay[] = []\n    display.push(...this.display)\n    display.push(...this.displayBuilders.map((builder) => builder.build()))\n\n    const issuerMetadata: IssuerMetadataV1_0_15 = {\n      credential_issuer: this.credentialIssuer,\n      credential_endpoint: this.credentialEndpoint,\n      credential_configurations_supported,\n      ...(this.nonceEndpoint && { nonce_endpoint: this.nonceEndpoint }),\n      ...(this.batchCredentialIssuance && { batch_credential_issuance: this.batchCredentialIssuance }),\n      ...(this.authorizationServers && { authorization_servers: this.authorizationServers }),\n      ...(this.tokenEndpoint && { token_endpoint: this.tokenEndpoint }),\n      ...(this.authorizationChallengeEndpoint && { authorization_challenge_endpoint: this.authorizationChallengeEndpoint }),\n      ...(this.credentialResponseEncryption && { credential_response_encryption: this.credentialResponseEncryption }),\n      ...(this.signedMetadata && { signed_metadata: this.signedMetadata }),\n      ...(this.credentialIdentifiersSupported !== undefined && { credential_identifiers_supported: this.credentialIdentifiersSupported }),\n      ...(display.length > 0 && { display }),\n    }\n\n    return issuerMetadata\n  }\n}\n","import { SigningAlgo } from '@sphereon/oid4vc-common'\nimport {\n  AuthorizationServerMetadata,\n  OAuthGrantType,\n  OAuthResponseMode,\n  OAuthResponseType,\n  OAuthScope,\n  PKCECodeChallengeMethod,\n  RevocationEndpointAuthMethod,\n  RevocationEndpointAuthSigningAlg,\n  TokenEndpointAuthMethod,\n  TokenEndpointAuthSigningAlg,\n} from '@sphereon/oid4vci-common'\n\nexport class AuthorizationServerMetadataBuilder {\n  private metadata: Partial<AuthorizationServerMetadata> = {}\n\n  public withIssuer(issuer: string): AuthorizationServerMetadataBuilder {\n    this.metadata.issuer = issuer\n    return this\n  }\n\n  public withAuthorizationEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.authorization_endpoint = endpoint\n    return this\n  }\n\n  public withAuthorizationChallengeEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.authorization_challenge_endpoint = endpoint\n    return this\n  }\n\n  public withTokenEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.token_endpoint = endpoint\n    return this\n  }\n\n  public withNonceEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.nonce_endpoint = endpoint\n    return this\n  }\n\n  public withTokenEndpointAuthMethodsSupported(methods: Array<TokenEndpointAuthMethod>): AuthorizationServerMetadataBuilder {\n    this.metadata.token_endpoint_auth_methods_supported = methods\n    return this\n  }\n\n  public withTokenEndpointAuthSigningAlgValuesSupported(algs: Array<TokenEndpointAuthSigningAlg>): AuthorizationServerMetadataBuilder {\n    this.metadata.token_endpoint_auth_signing_alg_values_supported = algs\n    return this\n  }\n\n  public withRegistrationEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.registration_endpoint = endpoint\n    return this\n  }\n\n  public withScopesSupported(scopes: Array<OAuthScope | string>): AuthorizationServerMetadataBuilder {\n    this.metadata.scopes_supported = scopes\n    return this\n  }\n\n  public withResponseTypesSupported(types: Array<OAuthResponseType>): AuthorizationServerMetadataBuilder {\n    this.metadata.response_types_supported = types\n    return this\n  }\n\n  public withResponseModesSupported(modes: Array<OAuthResponseMode>): AuthorizationServerMetadataBuilder {\n    this.metadata.response_modes_supported = modes\n    return this\n  }\n\n  public withGrantTypesSupported(types: Array<OAuthGrantType>): AuthorizationServerMetadataBuilder {\n    this.metadata.grant_types_supported = types\n    return this\n  }\n\n  public withServiceDocumentation(url: string): AuthorizationServerMetadataBuilder {\n    this.metadata.service_documentation = url\n    return this\n  }\n\n  public withUILocalesSupported(locales: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.ui_locales_supported = locales\n    return this\n  }\n\n  public withOpPolicyUri(uri: string): AuthorizationServerMetadataBuilder {\n    this.metadata.op_policy_uri = uri\n    return this\n  }\n\n  public withOpTosUri(uri: string): AuthorizationServerMetadataBuilder {\n    this.metadata.op_tos_uri = uri\n    return this\n  }\n\n  public withRevocationEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.revocation_endpoint = endpoint\n    return this\n  }\n\n  public withRevocationEndpointAuthMethodsSupported(methods: Array<RevocationEndpointAuthMethod>): AuthorizationServerMetadataBuilder {\n    this.metadata.revocation_endpoint_auth_methods_supported = methods\n    return this\n  }\n\n  public withRevocationEndpointAuthSigningAlgValuesSupported(algs: Array<RevocationEndpointAuthSigningAlg>): AuthorizationServerMetadataBuilder {\n    this.metadata.revocation_endpoint_auth_signing_alg_values_supported = algs\n    return this\n  }\n\n  public withIntrospectionEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.introspection_endpoint = endpoint\n    return this\n  }\n\n  public withCodeChallengeMethodsSupported(methods: Array<PKCECodeChallengeMethod>): AuthorizationServerMetadataBuilder {\n    this.metadata.code_challenge_methods_supported = methods\n    return this\n  }\n\n  public withPushedAuthorizationRequestEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.pushed_authorization_request_endpoint = endpoint\n    return this\n  }\n\n  public withRequirePushedAuthorizationRequests(required: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.require_pushed_authorization_requests = required\n    return this\n  }\n\n  public withPreAuthorizedGrantAnonymousAccessSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata['pre-authorized_grant_anonymous_access_supported'] = supported\n    return this\n  }\n\n  public withDPoPSigningAlgValuesSupported(algs: (string | SigningAlgo)[]): AuthorizationServerMetadataBuilder {\n    this.metadata.dpop_signing_alg_values_supported = algs\n    return this\n  }\n\n  // OIDC specific methods\n  public withFrontchannelLogoutSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.frontchannel_logout_supported = supported\n    return this\n  }\n\n  public withFrontchannelLogoutSessionSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.frontchannel_logout_session_supported = supported\n    return this\n  }\n\n  public withBackchannelLogoutSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.backchannel_logout_supported = supported\n    return this\n  }\n\n  public withBackchannelLogoutSessionSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.backchannel_logout_session_supported = supported\n    return this\n  }\n\n  public withUserinfoEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.userinfo_endpoint = endpoint\n    return this\n  }\n\n  public withCheckSessionIframe(url: string): AuthorizationServerMetadataBuilder {\n    this.metadata.check_session_iframe = url\n    return this\n  }\n\n  public withEndSessionEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.end_session_endpoint = endpoint\n    return this\n  }\n\n  public withAcrValuesSupported(values: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.acr_values_supported = values\n    return this\n  }\n\n  public withSubjectTypesSupported(types: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.subject_types_supported = types\n    return this\n  }\n\n  public withRequestObjectSigningAlgValuesSupported(algs: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.request_object_signing_alg_values_supported = algs\n    return this\n  }\n\n  public withDisplayValuesSupported(values: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.display_values_supported = values\n    return this\n  }\n\n  public withClaimTypesSupported(types: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.claim_types_supported = types\n    return this\n  }\n\n  public withClaimsSupported(claims: string[]): AuthorizationServerMetadataBuilder {\n    this.metadata.claims_supported = claims\n    return this\n  }\n\n  public withClaimsParameterSupported(supported: boolean): AuthorizationServerMetadataBuilder {\n    this.metadata.claims_parameter_supported = supported\n    return this\n  }\n\n  // VCI specific methods\n  public withCredentialEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.credential_endpoint = endpoint\n    return this\n  }\n\n  public withDeferredCredentialEndpoint(endpoint: string): AuthorizationServerMetadataBuilder {\n    this.metadata.deferred_credential_endpoint = endpoint\n    return this\n  }\n\n  public build(): AuthorizationServerMetadata {\n    if (!this.metadata.issuer) {\n      throw new Error('Issuer is required')\n    }\n\n    if (!this.metadata.response_types_supported) {\n      throw new Error('Response types supported is required')\n    }\n\n    return this.metadata as AuthorizationServerMetadata\n  }\n}\n","import { calculateJwkThumbprint, JWK, uuidv4 } from '@sphereon/oid4vc-common'\nimport {\n  AccessTokenRequest,\n  AccessTokenResponse,\n  Alg,\n  AuthorizationRequest,\n  CNonceState,\n  CredentialOfferSession,\n  EXPIRED_PRE_AUTHORIZED_CODE,\n  GrantTypes,\n  INVALID_PRE_AUTHORIZED_CODE,\n  IssueStatus,\n  IStateManager,\n  Jwt,\n  JWTSignerCallback,\n  JWTVerifyCallback,\n  PIN_NOT_MATCH_ERROR,\n  PIN_VALIDATION_ERROR,\n  PRE_AUTH_CODE_LITERAL,\n  PRE_AUTHORIZED_CODE_REQUIRED_ERROR,\n  TokenError,\n  TokenErrorResponse,\n  UNSUPPORTED_GRANT_TYPE_ERROR,\n  USER_PIN_NOT_REQUIRED_ERROR,\n  USER_PIN_REQUIRED_ERROR,\n  USER_PIN_TX_CODE_SPEC_ERROR,\n} from '@sphereon/oid4vci-common'\n\nimport { generateCredentialIdentifiers, isPreAuthorizedCodeExpired } from '../functions'\n\nexport interface ITokenEndpointOpts {\n  tokenEndpointDisabled?: boolean // Disable if used in an existing OAuth2/OIDC environment and have the AS handle tokens\n  tokenPath?: string // token path can either be defined here, or will be deduced from issuer metadata\n  interval?: number\n  cNonceExpiresIn?: number\n  tokenExpiresIn?: number\n  preAuthorizedCodeExpirationDuration?: number\n  accessTokenSignerCallback?: JWTSignerCallback\n  accessTokenVerificationCallback?: JWTVerifyCallback\n  accessTokenIssuer?: string\n  accessTokenProvider?: AccessTokenProvider\n}\n\nexport type AccessTokenProvider = 'internal' | 'oidc' | 'oauth2'\n\nexport const generateAccessToken = async (\n  opts: Required<Pick<ITokenEndpointOpts, 'accessTokenSignerCallback' | 'tokenExpiresIn' | 'accessTokenIssuer' | 'accessTokenProvider'>> & {\n    additionalClaims?: Record<string, unknown>\n    preAuthorizedCode?: string\n    alg?: Alg\n    dPoPJwk?: JWK\n  },\n): Promise<string> => {\n  const {\n    dPoPJwk,\n    accessTokenIssuer,\n    alg,\n    accessTokenSignerCallback,\n    tokenExpiresIn,\n    preAuthorizedCode,\n    additionalClaims,\n    accessTokenProvider = 'internal',\n  } = opts\n  // JWT uses seconds for iat and exp\n  if (accessTokenProvider !== 'internal') {\n    throw new TokenError(\n      400,\n      TokenErrorResponse.invalid_request,\n      `Access token provider ${accessTokenProvider} is an external access token provider. We cannot generate tokens ourselves in this case`,\n    )\n  }\n  const iat = new Date().getTime() / 1000\n  const exp = iat + tokenExpiresIn\n  const cnf = dPoPJwk ? { cnf: { jkt: await calculateJwkThumbprint(dPoPJwk, 'sha256') } } : undefined\n  const jwt: Jwt = {\n    header: { typ: 'JWT', alg: alg ?? Alg.ES256 },\n    payload: {\n      iat,\n      exp,\n      iss: accessTokenIssuer,\n      ...cnf,\n      ...(preAuthorizedCode && { preAuthorizedCode }),\n      // Protected resources simultaneously supporting both the DPoP and Bearer schemes need to update how the\n      // evaluation process is performed for bearer tokens to prevent downgraded usage of a DPoP-bound access token.\n      // Specifically, such a protected resource MUST reject a DPoP-bound access token received as a bearer token per [RFC6750].\n      token_type: dPoPJwk ? 'DPoP' : 'Bearer',\n      ...additionalClaims,\n    },\n  }\n  return await accessTokenSignerCallback(jwt)\n}\n\nexport const isValidGrant = (assertedState: CredentialOfferSession, grantType: string): boolean => {\n  if (assertedState.credentialOffer?.credential_offer?.grants) {\n    // TODO implement authorization_code\n    return (\n      Object.keys(assertedState.credentialOffer?.credential_offer?.grants).includes(GrantTypes.PRE_AUTHORIZED_CODE) &&\n      grantType === GrantTypes.PRE_AUTHORIZED_CODE\n    )\n  }\n  return false\n}\n\nexport const assertValidAccessTokenRequest = async (\n  request: AccessTokenRequest,\n  opts: {\n    credentialOfferSessions: IStateManager<CredentialOfferSession>\n    expirationDuration: number\n    authRequestsData?: Map<string, any>\n  },\n) => {\n  const { credentialOfferSessions, expirationDuration, authRequestsData } = opts\n\n  // Handle authorization code flow\n  if (request.grant_type === GrantTypes.AUTHORIZATION_CODE) {\n    if (!request.code || !authRequestsData) {\n      throw new TokenError(400, TokenErrorResponse.invalid_request, 'Authorization code required')\n    }\n\n    // Find the authorization request data by code\n    // This is simplified - you'll need to implement proper code->request mapping\n    const authRequestData: AuthorizationRequest | undefined = Array.from(authRequestsData.values()).find(\n      (data) => data.authorization_code === request.code,\n    )\n\n    if (!authRequestData) {\n      throw new TokenError(400, TokenErrorResponse.invalid_grant, 'Invalid authorization code')\n    }\n\n    // Create or update credential offer session with authorization_details\n    const sessionId = request.code // or generate a proper session ID\n    let credentialOfferSession = await credentialOfferSessions.get(sessionId)\n\n    if (!credentialOfferSession) {\n      // Create new session for authorization code flow\n      credentialOfferSession = {\n        createdAt: Date.now(),\n        lastUpdatedAt: Date.now(),\n        status: IssueStatus.ACCESS_TOKEN_REQUESTED,\n        notification_id: uuidv4(),\n        credentialOffer: {\n          credential_offer: {\n            credential_issuer: '', // Set appropriately\n            credential_configuration_ids: [], // Set from authorization_details\n            grants: {},\n          },\n        },\n        authorizationDetails: authRequestData?.authorization_details,\n        authorizationCode: request.code,\n      }\n      await credentialOfferSessions.set(sessionId, credentialOfferSession)\n    } else {\n      credentialOfferSession.authorizationDetails = authRequestData?.authorization_details\n      credentialOfferSession.authorizationCode = request.code\n      credentialOfferSession.status = IssueStatus.ACCESS_TOKEN_REQUESTED\n      credentialOfferSession.lastUpdatedAt = Date.now()\n      await credentialOfferSessions.set(sessionId, credentialOfferSession)\n    }\n\n    return { preAuthSession: credentialOfferSession }\n  }\n\n  // Handle pre-authorized code flow (existing logic)\n  if (request.grant_type !== GrantTypes.PRE_AUTHORIZED_CODE) {\n    throw new TokenError(400, TokenErrorResponse.invalid_grant, UNSUPPORTED_GRANT_TYPE_ERROR)\n  }\n\n  // Pre-auth flow\n  if (!request[PRE_AUTH_CODE_LITERAL]) {\n    throw new TokenError(400, TokenErrorResponse.invalid_request, PRE_AUTHORIZED_CODE_REQUIRED_ERROR)\n  }\n\n  const credentialOfferSession = await credentialOfferSessions.getAsserted(request[PRE_AUTH_CODE_LITERAL])\n  credentialOfferSession.status = IssueStatus.ACCESS_TOKEN_REQUESTED\n  credentialOfferSession.lastUpdatedAt = +new Date()\n  await credentialOfferSessions.set(request[PRE_AUTH_CODE_LITERAL], credentialOfferSession)\n  if (!isValidGrant(credentialOfferSession, request.grant_type)) {\n    throw new TokenError(400, TokenErrorResponse.invalid_grant, UNSUPPORTED_GRANT_TYPE_ERROR)\n  }\n\n  /*\n invalid_request:\n the Authorization Server does not expect a PIN in the pre-authorized flow but the client provides a PIN\n  */\n  if (\n    !credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.tx_code &&\n    request.tx_code &&\n    !request.user_pin\n  ) {\n    // >= v13\n    throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_NOT_REQUIRED_ERROR)\n  } else if (\n    !credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.user_pin_required &&\n    request.user_pin &&\n    !request.tx_code\n  ) {\n    // <= v12\n    throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_NOT_REQUIRED_ERROR)\n  }\n  /*\n  invalid_request:\n  the Authorization Server expects a PIN in the pre-authorized flow but the client does not provide a PIN\n   */\n  if (\n    // >= v13\n    !!credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.tx_code &&\n    !request.tx_code\n  ) {\n    if (request.user_pin) {\n      throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_TX_CODE_SPEC_ERROR)\n    }\n    throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_REQUIRED_ERROR)\n  } else if (\n    // <= v12\n    credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.user_pin_required &&\n    !credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.tx_code &&\n    !request.user_pin\n  ) {\n    if (request.tx_code) {\n      throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_TX_CODE_SPEC_ERROR)\n    }\n    throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_REQUIRED_ERROR)\n  }\n\n  if (isPreAuthorizedCodeExpired(credentialOfferSession, expirationDuration)) {\n    throw new TokenError(400, TokenErrorResponse.invalid_grant, EXPIRED_PRE_AUTHORIZED_CODE)\n  } else if (\n    request[PRE_AUTH_CODE_LITERAL] !==\n    credentialOfferSession.credentialOffer?.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.[PRE_AUTH_CODE_LITERAL]\n  ) {\n    throw new TokenError(400, TokenErrorResponse.invalid_grant, INVALID_PRE_AUTHORIZED_CODE)\n  }\n  /*\n  invalid_grant:\n  the Authorization Server expects a PIN in the pre-authorized flow but the client provides the wrong PIN\n  the End-User provides the wrong Pre-Authorized Code or the Pre-Authorized Code has expired\n   */\n  if (request.tx_code) {\n    const txCodeOffer = credentialOfferSession.credentialOffer.credential_offer?.grants?.[GrantTypes.PRE_AUTHORIZED_CODE]?.tx_code\n    if (!txCodeOffer) {\n      throw new TokenError(400, TokenErrorResponse.invalid_request, USER_PIN_NOT_REQUIRED_ERROR)\n    } else if (txCodeOffer.input_mode === 'text') {\n      if (!RegExp(`[\\\\D]{${txCodeOffer.length}`).test(request.tx_code)) {\n        throw new TokenError(400, TokenErrorResponse.invalid_grant, `${PIN_VALIDATION_ERROR} ${txCodeOffer.length}`)\n      }\n    } else {\n      if (!RegExp(`[\\\\d]{${txCodeOffer.length}}`).test(request.tx_code)) {\n        throw new TokenError(400, TokenErrorResponse.invalid_grant, `${PIN_VALIDATION_ERROR} ${txCodeOffer.length}`)\n      }\n    }\n    if (request.tx_code !== credentialOfferSession.txCode) {\n      throw new TokenError(400, TokenErrorResponse.invalid_grant, PIN_NOT_MATCH_ERROR)\n    }\n  } else if (request.user_pin) {\n    if (!/[\\\\d]{1,8}/.test(request.user_pin)) {\n      throw new TokenError(400, TokenErrorResponse.invalid_grant, `${PIN_VALIDATION_ERROR} 1-8`)\n    } else if (request.user_pin !== credentialOfferSession.txCode) {\n      throw new TokenError(400, TokenErrorResponse.invalid_grant, PIN_NOT_MATCH_ERROR)\n    }\n  }\n\n  return { preAuthSession: credentialOfferSession }\n}\n\nexport const createAccessTokenResponse = async (\n  request: AccessTokenRequest,\n  opts: {\n    credentialOfferSessions: IStateManager<CredentialOfferSession>\n    cNonces: IStateManager<CNonceState>\n    cNonce?: string\n    cNonceExpiresIn?: number // expiration in seconds\n    tokenExpiresIn: number // expiration in seconds\n    // preAuthorizedCodeExpirationDuration?: number\n    accessTokenSignerCallback: JWTSignerCallback\n    accessTokenIssuer: string\n    accessTokenProvider?: AccessTokenProvider\n    interval?: number\n    dPoPJwk?: JWK\n  },\n) => {\n  const {\n    dPoPJwk,\n    credentialOfferSessions,\n    cNonces,\n    cNonceExpiresIn,\n    tokenExpiresIn,\n    accessTokenIssuer,\n    accessTokenSignerCallback,\n    interval,\n    accessTokenProvider = 'internal',\n  } = opts\n\n  let sessionKey: string\n  let credentialOfferSession: CredentialOfferSession\n\n  if (request.grant_type === GrantTypes.AUTHORIZATION_CODE) {\n    sessionKey = request.code!\n    credentialOfferSession = await credentialOfferSessions.getAsserted(sessionKey)\n  } else {\n    sessionKey = request[PRE_AUTH_CODE_LITERAL] as string\n    credentialOfferSession = await credentialOfferSessions.getAsserted(sessionKey)\n  }\n\n  const cNonce = opts.cNonce ?? uuidv4()\n  await cNonces.set(cNonce, { cNonce, createdAt: +new Date() })\n\n  const access_token = await generateAccessToken({\n    tokenExpiresIn,\n    accessTokenSignerCallback,\n    preAuthorizedCode: sessionKey,\n    accessTokenIssuer,\n    dPoPJwk,\n    accessTokenProvider,\n  })\n\n  credentialOfferSession.status = IssueStatus.ACCESS_TOKEN_CREATED\n  credentialOfferSession.lastUpdatedAt = +new Date()\n\n  const response: AccessTokenResponse = {\n    access_token,\n    token_type: dPoPJwk ? 'DPoP' : 'bearer',\n    expires_in: tokenExpiresIn,\n    c_nonce: cNonce,\n    c_nonce_expires_in: cNonceExpiresIn,\n    interval,\n    ...(credentialOfferSession.authorizationDetails && {\n      authorization_details: credentialOfferSession.authorizationDetails.map((detail) => {\n        if (typeof detail === 'string') {\n          return detail\n        }\n        return {\n          ...detail,\n          credential_identifiers: generateCredentialIdentifiers(detail, credentialOfferSession),\n        }\n      }),\n    }),\n  }\n  await credentialOfferSessions.set(sessionKey, credentialOfferSession)\n  return response\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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AMyF,WAAgC;IACpCF;IACAzE,YAAY1B,UAAU,SAAS;IAC/BsG,YAAYlG;IACZmG,SAASL;IACTM,oBAAoBT;IACpBC;IACA,GAAIzC,uBAAuBY,wBAAwB;MACjDC,uBAAuBb,uBAAuBY,qBAAqBsC,IAAI,CAACC,WAAAA;AACtE,YAAI,OAAOA,WAAW,UAAU;AAC9B,iBAAOA;QACT;AACA,eAAO;UACL,GAAGA;UACHC,wBAAwBC,8BAA8BF,QAAQnD,sBAAAA;QAChE;MACF,CAAA;IACF;EACF;AACA,QAAMf,wBAAwB8B,IAAI2B,YAAY1C,sBAAAA;AAC9C,SAAO8C;AACT,GA3EyC;;;AZrQlC,IAAMQ,MAAuCC,mCAAYC,IAAI,yBAAA;","names":["import_oid4vci_common","CredentialSupportedBuilderV1_15","format","scope","credentialName","credentialDefinition","cryptographicBindingMethodsSupported","credentialSigningAlgValuesSupported","proofTypesSupported","display","claims","vct","doctype","withFormat","credentialFormat","withCredentialName","withCredentialDefinition","type","Error","withScope","withVct","withDoctype","addCryptographicBindingMethod","method","Array","isArray","withCryptographicBindingMethod","addCredentialSigningAlgValuesSupported","algValues","withCredentialSigningAlgValuesSupported","addProofTypesSupported","keyProofType","proofType","withProofTypesSupported","addCredentialSupportedDisplay","credentialDisplay","withCredentialSupportedDisplay","withClaims","addClaim","claim","push","build","TokenErrorResponse","invalid_request","credentialSupported","credential_definition","credential_signing_alg_values_supported","cryptographic_binding_methods_supported","supportedConfiguration","import_oid4vci_common","import_oid4vc_common","import_oid4vci_common","import_oid4vci_common","createCredentialOfferGrants","inputGrants","Object","keys","length","undefined","grants","PRE_AUTH_GRANT_LITERAL","grant","uuidv4","tx_code","authorization_code","issuer_state","parseCredentialOfferSchemeAndBaseUri","scheme","baseUri","credentialIssuer","newScheme","replace","includes","split","newBaseUri","startsWith","Error","createCredentialOfferObject","issuerMetadata","opts","credentialOffer","credentialOfferUri","credential_offer","credential_configurations_supported","credential_issuer","credential_configuration_ids","client_id","credential_offer_uri","createCredentialOfferURIFromObject","offerMode","encodeURIComponent","JSON","stringify","createCredentialOfferURI","isPreAuthorizedCodeExpired","state","expirationDurationInSeconds","now","Date","expirationTime","createdAt","assertValidPinNumber","pin","pinLength","RegExp","test","PIN_NOT_MATCH_ERROR","generateCredentialIdentifiers","authDetail","session","identifiers","credential_configuration_id","configId","hasConfig","push","format","import_oid4vc_common","oidcAccessTokenVerifyCallback","opts","clientMetadata","client_id","credentialIssuer","args","oidcIssuer","oidcDiscoverIssuer","issuerUrl","authorizationServer","oidcClient","oidcGetClient","issuer","introspection","introspect","jwt","active","Promise","reject","Error","header","decodeProtectedHeader","payload","decodeJwt","alg","jwk","x5c","kid","import_oid4vci_common","MemoryStates","expiresInMS","states","cleanupIntervalId","opts","expiresInSec","undefined","Map","clearAll","clear","clearExpired","timestamp","Array","from","entries","ts","Date","id","state","expiresAt","delete","createdAt","Error","getAsserted","result","has","get","STATE_MISSING_ERROR","set","stateValue","startCleanupRoutine","timeout","setInterval","stopCleanupRoutine","clearInterval","lookupStateManagerMultiGetAsserted","args","value","lookupStateManagerMultiGet","Promise","reject","Error","id","lookups","keyValueMapper","valueStateManager","lookup","LookupStateManager","get","e","startCleanupRoutine","timeout","stopCleanupRoutine","clearAll","clearExpired","timestamp","assertedValueId","key","prop","valueId","getAsserted","then","keyState","undefined","delete","has","set","_id","_stateValue","setMapped","valueKey","keyObject","stateValue","keys","CredentialOfferStateBuilder","credentialOfferState","credentialOffer","createdAt","timestamp","build","Date","Error","shortUUID","ShortUUID","VcIssuer","_issuerMetadata","_authorizationServerMetadata","_defaultCredentialOfferBaseUri","_credentialSignerCallback","_jwtVerifyCallback","_credentialDataSupplier","_credentialOfferSessions","_cNonces","_uris","_cNonceExpiresIn","_asClientOpts","issuerMetadata","authorizationServerMetadata","args","defaultCredentialOfferBaseUri","credentialOfferSessions","MemoryStates","uris","cNonces","credentialSignerCallback","jwtVerifyCallback","credentialDataSupplier","cNonceExpiresIn","process","env","C_NONCE_EXPIRES_IN","parseInt","asClientOpts","getCredentialOfferSessionById","id","lookups","Array","isArray","length","Promise","reject","Error","lookupStateManagerMultiGetAsserted","keyValueMapper","valueStateManager","session","get","deleteCredentialOfferSessionById","preAuthorizedCode","has","delete","issuerState","processNotification","notification","sessionId","undefined","LOG","error","notification_id","info","updateSession","createCredentialOfferURI","opts","offerMode","correlationId","generate","credential_configuration_ids","statusListOpts","credentialOfferUri","redirectUri","grants","pinLength","PRE_AUTH_GRANT_LITERAL","tx_code","baseUri","credentialOfferObject","createCredentialOfferObject","credentialOffer","credential_issuer","preAuthGrant","credential_offer","authGrant","authorization_code","issuer_state","txCode","userPin","Math","round","pow","random","padStart","assertValidPinNumber","createdAt","Date","lastUpdatedAt","expirationInMs","sessionLifeTimeInSec","expiresAt","abs","offerUri","replace","credential_offer_uri","set","uri","toUniformCredentialOfferRequest","version","OpenId4VCIVersion","VER_1_0_15","resolve","status","IssueStatus","OFFER_CREATED","uuidv4","client_id","clientId","credentialDataSupplierInput","statusLists","createCredentialOfferURIFromObject","lookupManager","LookupStateManager","setMapped","qrCodeDataUri","qrCodeOpts","AwesomeQR","qrCode","text","draw","toString","credentialOfferResult","EVENTS","emit","CredentialOfferEventNames","OID4VCI_OFFER_CREATED","eventName","data","initiator","initiatorType","InitiatorType","EXTERNAL","system","System","OID4VCI","issuer","subsystem","SubSystem","API","issueCredential","credentialRequest","issuerCorrelation","credential_configuration_id","credential_configurations_supported","TokenErrorResponse","invalid_request","credential_identifier","authorizationDetails","validIdentifiers","flatMap","detail","credential_identifiers","includes","format","lookupCredentialFormat","validated","validateCredentialRequestProof","tokenExpiresIn","preAuthSession","authSession","cNonceState","jwtVerifyResult","did","jwk","kid","newcNonce","newCNonce","newcNonceState","cNonce","credential","signerCallback","result","credentialSupplierConfig","credential_supplier_config","signCallback","CredentialMapper","isSdJwtDecodedCredentialPayload","cnf","credentialSubject","credentialSubjects","map","subject","iss","verifiableCredential","issueCredentialImpl","CREDENTIAL_MISSING_ERROR","CREDENTIAL_ISSUED","response","credentials","c_nonce","c_nonce_expires_in","experimentalSubjectIssuance","credential_subject_issuance","subject_proof_mode","transaction_id","credentialConfig","credentialIdentifier","matchedConfig","Object","values","find","config","vct","issueState","ERROR","event","NOTIFICATION_CREDENTIAL_ACCEPTED","NOTIFICATION_CREDENTIAL_DELETED","NOTIFICATION_CREDENTIAL_FAILURE","message","supportedIssuanceFormats","verifyFn","JWT_VERIFY_CONFIG_ERROR","credReq","proof","proofs","proofCandidates","push","jwt","jwtProof","proof_type","availableTypes","keys","join","validationErrors","msg","String","didDocument","header","payload","aud","iat","nonce","getAsserted","alg","x5c","typ","TYP_ERROR","ALG_ERROR","KID_JWK_X5C_ERROR","KID_DID_NO_DID_ERROR","console","log","DID_NO_DIDDOC_ERROR","CREDENTIAL_REQUEST_RECEIVED","NO_ISS_IN_AUTHORIZATION_CODE_CONTEXT","AUD_ERROR","IAT_ERROR","issuerCallback","ISSUER_CONFIG_ERROR","CredentialEventNames","OID4VCI_CREDENTIAL_ISSUED","VC_ISSUER","value","VcIssuerBuilder","issuerMetadataBuilder","issuerMetadata","authorizationServerMetadata","asClientOpts","txCode","defaultCredentialOfferBaseUri","userPinRequired","cNonceExpiresIn","credentialOfferStateManager","credentialOfferURIManager","cNonceStateManager","credentialSignerCallback","jwtVerifyCallback","credentialDataSupplier","withIssuerMetadata","credential_configurations_supported","Error","withASClientMetadata","clientMetadata","withASClientMetadataParams","client_id","client_secret","redirect_uris","response_types","other","withAuthorizationMetadata","withIssuerMetadataBuilder","builder","withDefaultCredentialOfferBaseUri","baseUri","withCredentialIssuer","issuer","credential_issuer","withAuthorizationServers","authorizationServers","authorization_servers","withCredentialEndpoint","credentialEndpoint","credential_endpoint","withTokenEndpoint","tokenEndpoint","token_endpoint","withNonceEndpoint","nonceEndpoint","nonce_endpoint","withIssuerDisplay","issuerDisplay","display","Array","isArray","addIssuerDisplay","withCredentialConfigurationsSupported","credentialConfigurationsSupported","addCredentialConfigurationsSupported","id","supportedCredential","withTXCode","withCredentialOfferURIStateManager","withInMemoryCredentialOfferURIState","MemoryStates","withCredentialOfferStateManager","credentialOfferManager","withInMemoryCredentialOfferState","withCNonceStateManager","cNonceManager","withInMemoryCNonceState","withCNonceExpiresIn","withCredentialSignerCallback","cb","withJWTVerifyCallback","verifyCallback","withCredentialDataSupplier","build","TokenErrorResponse","invalid_request","Object","keys","length","metadata","oidcAccessTokenVerifyCallback","credentialIssuer","authorizationServer","VcIssuer","credentialOfferSessions","cNonces","uris","DisplayBuilder","name","locale","additionalProperties","logo","backgroundColor","textColor","withName","withLocale","withLogo","uri","Error","withBackgroundColor","withTextColor","withAdditionalProperties","properties","addAdditionalProperty","key","value","build","background_color","text_color","IssuerMetadataBuilderV1_15","credentialEndpoint","nonceEndpoint","credentialIssuer","supportedBuilders","credentialConfigurationsSupported","displayBuilders","display","batchCredentialIssuance","authorizationServers","tokenEndpoint","authorizationChallengeEndpoint","credentialResponseEncryption","signedMetadata","credentialIdentifiersSupported","withBatchCredentialIssuance","withAuthorizationServers","withAuthorizationServer","authorizationServer","undefined","push","withAuthorizationChallengeEndpoint","withTokenEndpoint","withCredentialEndpoint","withNonceEndpoint","withCredentialIssuer","withCredentialResponseEncryption","withSignedMetadata","withCredentialIdentifiersSupported","newSupportedCredentialBuilder","builder","CredentialSupportedBuilderV1_15","addSupportedCredentialBuilder","supportedCredentialBuilder","addCredentialConfigurationsSupported","id","supportedCredential","withIssuerDisplay","issuerDisplay","Array","isArray","addDisplay","addDisplayBuilder","displayBuilder","newDisplayBuilder","DisplayBuilder","build","Error","credential_configurations_supported","configurationsEntryList","map","forEach","configRecord","Object","keys","key","length","issuerMetadata","credential_issuer","credential_endpoint","nonce_endpoint","batch_credential_issuance","authorization_servers","token_endpoint","authorization_challenge_endpoint","credential_response_encryption","signed_metadata","credential_identifiers_supported","AuthorizationServerMetadataBuilder","metadata","withIssuer","issuer","withAuthorizationEndpoint","endpoint","authorization_endpoint","withAuthorizationChallengeEndpoint","authorization_challenge_endpoint","withTokenEndpoint","token_endpoint","withNonceEndpoint","nonce_endpoint","withTokenEndpointAuthMethodsSupported","methods","token_endpoint_auth_methods_supported","withTokenEndpointAuthSigningAlgValuesSupported","algs","token_endpoint_auth_signing_alg_values_supported","withRegistrationEndpoint","registration_endpoint","withScopesSupported","scopes","scopes_supported","withResponseTypesSupported","types","response_types_supported","withResponseModesSupported","modes","response_modes_supported","withGrantTypesSupported","grant_types_supported","withServiceDocumentation","url","service_documentation","withUILocalesSupported","locales","ui_locales_supported","withOpPolicyUri","uri","op_policy_uri","withOpTosUri","op_tos_uri","withRevocationEndpoint","revocation_endpoint","withRevocationEndpointAuthMethodsSupported","revocation_endpoint_auth_methods_supported","withRevocationEndpointAuthSigningAlgValuesSupported","revocation_endpoint_auth_signing_alg_values_supported","withIntrospectionEndpoint","introspection_endpoint","withCodeChallengeMethodsSupported","code_challenge_methods_supported","withPushedAuthorizationRequestEndpoint","pushed_authorization_request_endpoint","withRequirePushedAuthorizationRequests","required","require_pushed_authorization_requests","withPreAuthorizedGrantAnonymousAccessSupported","supported","withDPoPSigningAlgValuesSupported","dpop_signing_alg_values_supported","withFrontchannelLogoutSupported","frontchannel_logout_supported","withFrontchannelLogoutSessionSupported","frontchannel_logout_session_supported","withBackchannelLogoutSupported","backchannel_logout_supported","withBackchannelLogoutSessionSupported","backchannel_logout_session_supported","withUserinfoEndpoint","userinfo_endpoint","withCheckSessionIframe","check_session_iframe","withEndSessionEndpoint","end_session_endpoint","withAcrValuesSupported","values","acr_values_supported","withSubjectTypesSupported","subject_types_supported","withRequestObjectSigningAlgValuesSupported","request_object_signing_alg_values_supported","withDisplayValuesSupported","display_values_supported","withClaimTypesSupported","claim_types_supported","withClaimsSupported","claims","claims_supported","withClaimsParameterSupported","claims_parameter_supported","withCredentialEndpoint","credential_endpoint","withDeferredCredentialEndpoint","deferred_credential_endpoint","build","Error","import_oid4vc_common","import_oid4vci_common","generateAccessToken","opts","dPoPJwk","accessTokenIssuer","alg","accessTokenSignerCallback","tokenExpiresIn","preAuthorizedCode","additionalClaims","accessTokenProvider","TokenError","TokenErrorResponse","invalid_request","iat","Date","getTime","exp","cnf","jkt","calculateJwkThumbprint","undefined","jwt","header","typ","Alg","ES256","payload","iss","token_type","isValidGrant","assertedState","grantType","credentialOffer","credential_offer","grants","Object","keys","includes","GrantTypes","PRE_AUTHORIZED_CODE","assertValidAccessTokenRequest","request","credentialOfferSessions","expirationDuration","authRequestsData","grant_type","AUTHORIZATION_CODE","code","authRequestData","Array","from","values","find","data","authorization_code","invalid_grant","sessionId","credentialOfferSession","get","createdAt","now","lastUpdatedAt","status","IssueStatus","ACCESS_TOKEN_REQUESTED","notification_id","uuidv4","credential_issuer","credential_configuration_ids","authorizationDetails","authorization_details","authorizationCode","set","preAuthSession","UNSUPPORTED_GRANT_TYPE_ERROR","PRE_AUTH_CODE_LITERAL","PRE_AUTHORIZED_CODE_REQUIRED_ERROR","getAsserted","tx_code","user_pin","USER_PIN_NOT_REQUIRED_ERROR","user_pin_required","USER_PIN_TX_CODE_SPEC_ERROR","USER_PIN_REQUIRED_ERROR","isPreAuthorizedCodeExpired","EXPIRED_PRE_AUTHORIZED_CODE","INVALID_PRE_AUTHORIZED_CODE","txCodeOffer","input_mode","RegExp","length","test","PIN_VALIDATION_ERROR","txCode","PIN_NOT_MATCH_ERROR","createAccessTokenResponse","cNonces","cNonceExpiresIn","interval","sessionKey","cNonce","access_token","ACCESS_TOKEN_CREATED","response","expires_in","c_nonce","c_nonce_expires_in","map","detail","credential_identifiers","generateCredentialIdentifiers","LOG","VCI_LOGGERS","get"]}