{"version":3,"sources":["../src/localization/translations/en.json","../src/localization/translations/nl.json","../plugin.schema.json","../src/index.ts","../src/agent/DidAuthSiopOpAuthenticator.ts","../src/session/functions.ts","../src/session/OID4VP.ts","../src/types/IDidAuthSiopOpAuthenticator.ts","../src/types/siop-service/index.ts","../src/types/machine/index.ts","../src/types/identifier/index.ts","../src/session/OpSession.ts","../src/machine/Siopv2Machine.ts","../src/localization/Localization.ts","../src/services/Siopv2MachineService.ts","../src/utils/dcql.ts","../src/utils/CredentialUtils.ts","../src/machine/CallbackStateListener.ts","../src/link-handler/index.ts"],"sourcesContent":["{\n  \"siopv2_machine_identifier_error_title\": \"Getting identifier\",\n  \"siopv2_machine_create_config_error_title\": \"Creating siopV2 config\",\n  \"siopv2_machine_get_request_error_title\": \"Getting siopV2 request\",\n  \"siopv2_machine_get_selectable_credentials_error_title\": \"Getting siopV2 selectable credentials\",\n  \"siopv2_machine_retrieve_contact_error_title\": \"Retrieve contact\",\n  \"siopv2_machine_add_contact_identity_error_title\": \"Add contact identity\",\n  \"siopv2_machine_send_response_error_title\": \"Sending siopV2 response\"\n}\n","{\n  \"siopv2_machine_identifier_error_title\": \"Identifier ophalen\",\n  \"siopv2_machine_create_config_error_title\": \"SiopV2 configuratie maken\",\n  \"siopv2_machine_get_request_error_title\": \"SiopV2 verzoek ophalen\",\n  \"siopv2_machine_retrieve_contact_error_title\": \"Ophalen credential\",\n  \"siopv2_machine_add_contact_identity_error_title\": \"Toevoegen identiteit contact\",\n  \"siopv2_machine_send_response_error_title\": \"SiopV2 antwoord verzenden\"\n}\n","{\n  \"IDidAuthSiopOpAuthenticator\": {\n    \"components\": {\n      \"schemas\": {\n        \"IGetSiopSessionArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.getSessionForSiop } \"\n        },\n        \"IRegisterSiopSessionArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"identifier\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"did\": {\n                  \"type\": \"string\"\n                },\n                \"alias\": {\n                  \"type\": \"string\"\n                },\n                \"provider\": {\n                  \"type\": \"string\"\n                },\n                \"controllerKeyId\": {\n                  \"type\": \"string\"\n                },\n                \"keys\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"additionalProperties\": true\n                    }\n                  }\n                },\n                \"services\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"additionalProperties\": true\n                    }\n                  }\n                }\n              },\n              \"additionalProperties\": false,\n              \"required\": [\"did\", \"provider\", \"keys\", \"services\"]\n            },\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"expiresIn\": {\n              \"type\": \"number\"\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"identifier\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.registerSessionForSiop } \"\n        },\n        \"IRemoveSiopSessionArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.removeSessionForSiop } \"\n        },\n        \"IAuthenticateWithSiopArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"stateId\": {\n              \"type\": \"string\"\n            },\n            \"redirectUrl\": {\n              \"type\": \"string\"\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\", \"stateId\", \"redirectUrl\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.authenticateWithSiop } \"\n        },\n        \"IResponse\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"status\": {\n              \"type\": \"number\"\n            },\n            \"additionalProperties\": true\n          },\n          \"required\": [\"status\"],\n          \"description\": \"Result of {@link DidAuthSiopOpAuthenticator.authenticateWithSiop & DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } \"\n        },\n        \"IGetSiopAuthenticationRequestFromRpArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"stateId\": {\n              \"type\": \"string\"\n            },\n            \"redirectUrl\": {\n              \"type\": \"string\"\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\", \"stateId\", \"redirectUrl\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } \"\n        },\n        \"ParsedAuthenticationRequestURI\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"jwt\": {\n              \"type\": \"string\"\n            },\n            \"requestPayload\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"registration\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"jwt\", \"requestPayload\", \"registration\"],\n          \"description\": \"Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } \"\n        },\n        \"IGetSiopAuthenticationRequestDetailsArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"verifiedAuthenticationRequest\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"credentialFilter\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\", \"verifiedAuthenticationRequest\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } \"\n        },\n        \"IAuthRequestDetails\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"id\": {\n              \"type\": \"string\"\n            },\n            \"alsoKnownAs\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            },\n            \"vpResponseOpts\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"id\", \"vpResponseOpts\"],\n          \"description\": \"Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } \"\n        },\n        \"IVerifySiopAuthenticationRequestUriArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"ParsedAuthenticationRequestURI\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\", \"ParsedAuthenticationRequestURI\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } \"\n        },\n        \"VerifiedAuthorizationRequest\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"payload\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"presentationDefinitions\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"verifyOpts\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"payload\", \"verifyOpts\"],\n          \"description\": \"Result of {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } \"\n        },\n        \"ISendSiopAuthenticationResponseArgs\": {\n          \"type\": \"object\",\n          \"properties\": {\n            \"sessionId\": {\n              \"type\": \"string\"\n            },\n            \"verifiedAuthenticationRequest\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"verifiablePresentationResponse\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"additionalProperties\": true\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"required\": [\"sessionId\", \"verifiedAuthenticationRequest\"],\n          \"description\": \"Arguments needed for {@link DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } \"\n        }\n      },\n      \"methods\": {\n        \"getSessionForSiop\": {\n          \"description\": \"Get SIOP session\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IGetSiopSessionArgs\"\n          },\n          \"returnType\": \"object\"\n        },\n        \"registerSessionForSiop\": {\n          \"description\": \"Register SIOP session\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IRegisterSiopSessionArgs\"\n          },\n          \"returnType\": \"object\"\n        },\n        \"removeSessionForSiop\": {\n          \"description\": \"Remove SIOP session\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IRemoveSiopSessionArgs\"\n          },\n          \"returnType\": \"boolean\"\n        },\n        \"authenticateWithSiop\": {\n          \"description\": \"Authenticate using DID Auth SIOP\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IAuthenticateWithSiopArgs\"\n          },\n          \"returnType\": {\n            \"$ref\": \"#/components/schemas/Response\"\n          }\n        },\n        \"getSiopAuthenticationRequestFromRP\": {\n          \"description\": \"Get authentication request from RP\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IGetSiopAuthenticationRequestFromRpArgs\"\n          },\n          \"returnType\": {\n            \"$ref\": \"#/components/schemas/ParsedAuthenticationRequestURI\"\n          }\n        },\n        \"getSiopAuthenticationRequestDetails\": {\n          \"description\": \"Get authentication request details\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IGetSiopAuthenticationRequestDetailsArgs\"\n          },\n          \"returnType\": {\n            \"$ref\": \"#/components/schemas/IAuthRequestDetails\"\n          }\n        },\n        \"verifySiopAuthenticationRequestURI\": {\n          \"description\": \"Verify authentication request URI\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/IVerifySiopAuthenticationRequestUriArgs\"\n          },\n          \"returnType\": {\n            \"$ref\": \"#/components/schemas/VerifiedAuthorizationRequest\"\n          }\n        },\n        \"sendSiopAuthenticationResponse\": {\n          \"description\": \"Send authentication response\",\n          \"arguments\": {\n            \"$ref\": \"#/components/schemas/ISendSiopAuthenticationResponseArgs\"\n          },\n          \"returnType\": {\n            \"$ref\": \"#/components/schemas/IRequiredContext\"\n          }\n        }\n      }\n    }\n  }\n}\n","/**\n * @public\n */\nconst schema = require('../plugin.schema.json')\nexport { schema }\nexport { DidAuthSiopOpAuthenticator, didAuthSiopOpAuthenticatorMethods } from './agent/DidAuthSiopOpAuthenticator'\nexport { Siopv2Machine } from './machine/Siopv2Machine'\nexport * from './machine/CallbackStateListener'\nexport * from './session'\nexport * from './types'\nexport * from './link-handler'\n","import { decodeUriAsJson, PresentationSignCallback, SupportedVersion, VerifiedAuthorizationRequest } from '@sphereon/did-auth-siop'\nimport {\n  ConnectionType,\n  CorrelationIdentifierType,\n  CredentialDocumentFormat,\n  CredentialRole,\n  DocumentType,\n  Identity,\n  IdentityOrigin,\n  NonPersistedIdentity,\n  Party,\n} from '@sphereon/ssi-sdk.data-store'\nimport { HasherSync, Loggers, SdJwtDecodedVerifiableCredential } from '@sphereon/ssi-types'\nimport { IAgentPlugin } from '@veramo/core'\nimport { v4 as uuidv4 } from 'uuid'\n\nimport { OpSession } from '../session'\nimport { PEX, Status } from '@sphereon/pex'\nimport { computeEntryHash } from '@veramo/utils'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { EventEmitter } from 'events'\nimport {\n  DidAuthSiopOpAuthenticatorOptions,\n  GetSelectableCredentialsArgs,\n  IDidAuthSiopOpAuthenticator,\n  IGetSiopSessionArgs,\n  IOpSessionArgs,\n  IRegisterCustomApprovalForSiopArgs,\n  IRemoveCustomApprovalForSiopArgs,\n  IRemoveSiopSessionArgs,\n  IRequiredContext,\n  Json,\n  LOGGER_NAMESPACE,\n  RequiredContext,\n  SelectableCredentialsMap,\n  Siopv2AuthorizationResponseData,\n  VerifiableCredentialsWithDefinition,\n} from '../types'\n\nimport {\n  AddIdentityArgs,\n  CreateConfigArgs,\n  CreateConfigResult,\n  GetSiopRequestArgs,\n  OnContactIdentityCreatedArgs,\n  OnIdentifierCreatedArgs,\n  RetrieveContactArgs,\n  SendResponseArgs,\n  Siopv2AuthorizationRequestData,\n  Siopv2HolderEvent,\n  Siopv2Machine as Siopv2MachineId,\n  Siopv2MachineInstanceOpts,\n} from '../types'\nimport { DcqlCredential, DcqlPresentation, DcqlQuery, DcqlSdJwtVcCredential } from 'dcql'\nimport { Siopv2Machine } from '../machine/Siopv2Machine'\nimport { getSelectableCredentials, siopSendAuthorizationResponse, translateCorrelationIdToName } from '../services/Siopv2MachineService'\nimport { schema } from '..'\n\nconst logger = Loggers.DEFAULT.options(LOGGER_NAMESPACE, {}).get(LOGGER_NAMESPACE)\n\n// Exposing the methods here for any REST implementation\nexport const didAuthSiopOpAuthenticatorMethods: Array<string> = [\n  'cmGetContacts',\n  'cmGetContact',\n  'cmAddContact',\n  'cmAddIdentity',\n  'didManagerFind',\n  'didManagerGet',\n  'keyManagerSign',\n  'didManagerGetProviders',\n  'dataStoreORMGetVerifiableCredentials',\n  'createVerifiablePresentation',\n]\n\nexport class DidAuthSiopOpAuthenticator implements IAgentPlugin {\n  readonly schema = schema.IDidAuthSiopOpAuthenticator\n  readonly methods: IDidAuthSiopOpAuthenticator = {\n    siopGetOPSession: this.siopGetOPSession.bind(this),\n    siopRegisterOPSession: this.siopRegisterOPSession.bind(this),\n    siopRemoveOPSession: this.siopRemoveOPSession.bind(this),\n    siopRegisterOPCustomApproval: this.siopRegisterOPCustomApproval.bind(this),\n    siopRemoveOPCustomApproval: this.siopRemoveOPCustomApproval.bind(this),\n\n    siopGetMachineInterpreter: this.siopGetMachineInterpreter.bind(this),\n    siopCreateConfig: this.siopCreateConfig.bind(this),\n    siopGetSiopRequest: this.siopGetSiopRequest.bind(this),\n    siopRetrieveContact: this.siopRetrieveContact.bind(this),\n    siopAddIdentity: this.siopAddContactIdentity.bind(this),\n    siopSendResponse: this.siopSendResponse.bind(this),\n    siopGetSelectableCredentials: this.siopGetSelectableCredentials.bind(this),\n  }\n\n  private readonly sessions: Map<string, OpSession>\n  private readonly customApprovals: Record<string, (verifiedAuthorizationRequest: VerifiedAuthorizationRequest, sessionId: string) => Promise<void>>\n  private readonly presentationSignCallback?: PresentationSignCallback\n  private readonly onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n  private readonly onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n  private readonly eventEmitter?: EventEmitter\n  private readonly hasher?: HasherSync\n\n  constructor(options?: DidAuthSiopOpAuthenticatorOptions) {\n    const { onContactIdentityCreated, onIdentifierCreated, hasher, customApprovals = {}, presentationSignCallback } = { ...options }\n\n    this.hasher = hasher\n    this.onContactIdentityCreated = onContactIdentityCreated\n    this.onIdentifierCreated = onIdentifierCreated\n    this.presentationSignCallback = presentationSignCallback\n    this.sessions = new Map<string, OpSession>()\n    this.customApprovals = customApprovals\n  }\n\n  public async onEvent(event: any, context: RequiredContext): Promise<void> {\n    switch (event.type) {\n      case Siopv2HolderEvent.CONTACT_IDENTITY_CREATED:\n        this.onContactIdentityCreated?.(event.data)\n        break\n      case Siopv2HolderEvent.IDENTIFIER_CREATED:\n        this.onIdentifierCreated?.(event.data)\n        break\n      default:\n        return Promise.reject(Error(`Event type ${event.type} not supported`))\n    }\n  }\n\n  private async siopGetOPSession(args: IGetSiopSessionArgs, context: IRequiredContext): Promise<OpSession> {\n    // TODO add cleaning up sessions https://sphereon.atlassian.net/browse/MYC-143\n    if (!this.sessions.has(args.sessionId)) {\n      throw Error(`No session found for id: ${args.sessionId}`)\n    }\n\n    return this.sessions.get(args.sessionId)!\n  }\n\n  private async siopRegisterOPSession(args: Omit<IOpSessionArgs, 'context'>, context: IRequiredContext): Promise<OpSession> {\n    const sessionId = args.sessionId || uuidv4()\n    if (this.sessions.has(sessionId)) {\n      return Promise.reject(new Error(`Session with id: ${args.sessionId} already present`))\n    }\n    const opts = { ...args, sessionId, context } as Required<IOpSessionArgs>\n    if (!opts.op?.presentationSignCallback) {\n      opts.op = { ...opts.op, presentationSignCallback: this.presentationSignCallback }\n    }\n    const session = await OpSession.init(opts)\n    this.sessions.set(sessionId, session)\n    return session\n  }\n\n  private async siopRemoveOPSession(args: IRemoveSiopSessionArgs, context: IRequiredContext): Promise<boolean> {\n    return this.sessions.delete(args.sessionId)\n  }\n\n  private async siopRegisterOPCustomApproval(args: IRegisterCustomApprovalForSiopArgs, context: IRequiredContext): Promise<void> {\n    if (this.customApprovals[args.key] !== undefined) {\n      return Promise.reject(new Error(`Custom approval with key: ${args.key} already present`))\n    }\n\n    this.customApprovals[args.key] = args.customApproval\n  }\n\n  private async siopRemoveOPCustomApproval(args: IRemoveCustomApprovalForSiopArgs, context: IRequiredContext): Promise<boolean> {\n    return delete this.customApprovals[args.key]\n  }\n\n  private async siopGetMachineInterpreter(opts: Siopv2MachineInstanceOpts, context: RequiredContext): Promise<Siopv2MachineId> {\n    const { stateNavigationListener, url } = opts\n    const services = {\n      createConfig: (args: CreateConfigArgs) => this.siopCreateConfig(args),\n      getSiopRequest: (args: GetSiopRequestArgs) => this.siopGetSiopRequest(args, context),\n      getSelectableCredentials: (args: GetSelectableCredentialsArgs) => this.siopGetSelectableCredentials(args, context),\n      retrieveContact: (args: RetrieveContactArgs) => this.siopRetrieveContact(args, context),\n      addContactIdentity: (args: AddIdentityArgs) => this.siopAddContactIdentity(args, context),\n      sendResponse: (args: SendResponseArgs) => this.siopSendResponse(args, context),\n      ...opts?.services,\n    }\n\n    const siopv2MachineOpts: Siopv2MachineInstanceOpts = {\n      ...opts,\n      url,\n      stateNavigationListener,\n      services: {\n        ...services,\n        ...opts.services,\n      },\n    }\n\n    return Siopv2Machine.newInstance(siopv2MachineOpts)\n  }\n\n  private async siopCreateConfig<TContext extends CreateConfigArgs>(context: TContext): Promise<CreateConfigResult> {\n    const { url } = context\n\n    if (!url) {\n      return Promise.reject(Error('Missing request uri in context'))\n    }\n\n    return {\n      id: uuidv4(),\n      // FIXME: Update these values in SSI-SDK. Only the URI (not a redirectURI) would be available at this point\n      sessionId: uuidv4(),\n      redirectUrl: url,\n    }\n  }\n\n  private async siopGetSiopRequest(args: GetSiopRequestArgs, context: RequiredContext): Promise<Siopv2AuthorizationRequestData> {\n    const { agent } = context\n    const { didAuthConfig } = args\n\n    if (args.url === undefined) {\n      return Promise.reject(Error('Missing request uri in context'))\n    }\n\n    if (didAuthConfig === undefined) {\n      return Promise.reject(Error('Missing config in context'))\n    }\n    const { sessionId, redirectUrl } = didAuthConfig\n\n    const session: OpSession = await agent.siopGetOPSession({ sessionId }).catch(\n      async () =>\n        await agent.siopRegisterOPSession({\n          requestJwtOrUri: redirectUrl,\n          sessionId,\n          op: { eventEmitter: this.eventEmitter, hasher: this.hasher },\n        }),\n    )\n\n    logger.debug(`session: ${JSON.stringify(session.id, null, 2)}`)\n    const verifiedAuthorizationRequest = await session.getAuthorizationRequest()\n    // logger.trace('Request: ' + JSON.stringify(verifiedAuthorizationRequest, null, 2))\n    const clientName = verifiedAuthorizationRequest.registrationMetadataPayload?.client_name\n    const url =\n      verifiedAuthorizationRequest.responseURI ??\n      (args.url.includes('request_uri')\n        ? decodeURIComponent(args.url.split('?request_uri=')[1].trim())\n        : (verifiedAuthorizationRequest.issuer ?? verifiedAuthorizationRequest.registrationMetadataPayload?.client_id))\n    const uri: URL | undefined = url.includes('://') ? new URL(url) : undefined\n    const correlationId: string = uri?.hostname ?? (await this.determineCorrelationId(uri, verifiedAuthorizationRequest, clientName, context))\n    const clientId: string | undefined = await verifiedAuthorizationRequest.authorizationRequest.getMergedProperty<string>('client_id')\n\n    return {\n      issuer: verifiedAuthorizationRequest.issuer,\n      correlationId,\n      registrationMetadataPayload: verifiedAuthorizationRequest.registrationMetadataPayload,\n      uri,\n      name: clientName,\n      clientId,\n      presentationDefinitions:\n        (await verifiedAuthorizationRequest.authorizationRequest.containsResponseType('vp_token')) ||\n        (verifiedAuthorizationRequest.versions.every((version) => version <= SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1) &&\n          verifiedAuthorizationRequest.presentationDefinitions &&\n          verifiedAuthorizationRequest.presentationDefinitions.length > 0)\n          ? verifiedAuthorizationRequest.presentationDefinitions\n          : undefined,\n      dcqlQuery: verifiedAuthorizationRequest.dcqlQuery,\n    }\n  }\n\n  private async determineCorrelationId(\n    uri: URL | undefined,\n    verifiedAuthorizationRequest: any,\n    clientName: string | undefined,\n    context: RequiredContext,\n  ): Promise<string> {\n    if (uri) {\n      return (await translateCorrelationIdToName(uri.hostname, context)) ?? uri.hostname\n    }\n\n    if (verifiedAuthorizationRequest.issuer) {\n      const issuerHostname = verifiedAuthorizationRequest.issuer.split('://')[1]\n      return (await translateCorrelationIdToName(issuerHostname, context)) ?? issuerHostname\n    }\n\n    if (clientName) {\n      return clientName\n    }\n\n    throw new Error(\"Can't determine correlationId from request\")\n  }\n\n  private async siopRetrieveContact(args: RetrieveContactArgs, context: RequiredContext): Promise<Party | undefined> {\n    const { authorizationRequestData } = args\n    const { agent } = context\n\n    if (authorizationRequestData === undefined) {\n      return Promise.reject(Error('Missing authorization request data in context'))\n    }\n\n    return agent\n      .cmGetContacts({\n        filter: [\n          {\n            identities: {\n              identifier: {\n                correlationId: authorizationRequestData.correlationId,\n              },\n            },\n          },\n        ],\n      })\n      .then((contacts: Array<Party>): Party | undefined => (contacts.length === 1 ? contacts[0] : undefined))\n  }\n\n  private async siopAddContactIdentity(args: AddIdentityArgs, context: RequiredContext): Promise<void> {\n    const { agent } = context\n    const { contact, authorizationRequestData } = args\n\n    if (contact === undefined) {\n      return Promise.reject(Error('Missing contact in context'))\n    }\n\n    if (authorizationRequestData === undefined) {\n      return Promise.reject(Error('Missing authorization request data in context'))\n    }\n\n    // TODO: Makes sense to move these types of common queries/retrievals to the SIOP auth request object\n    const clientId: string | undefined = authorizationRequestData.clientId ?? authorizationRequestData.issuer\n    const correlationId: string | undefined = clientId\n      ? clientId.startsWith('did:')\n        ? clientId\n        : `${new URL(clientId).protocol}//${new URL(clientId).hostname}`\n      : undefined\n\n    if (correlationId) {\n      const identity: NonPersistedIdentity = {\n        alias: correlationId,\n        origin: IdentityOrigin.EXTERNAL,\n        roles: [CredentialRole.ISSUER],\n        identifier: {\n          type: correlationId.startsWith('did:') ? CorrelationIdentifierType.DID : CorrelationIdentifierType.URL,\n          correlationId,\n        },\n      }\n      const addedIdentity: Identity = await agent.cmAddIdentity({ contactId: contact.id, identity })\n      await context.agent.emit(Siopv2HolderEvent.CONTACT_IDENTITY_CREATED, {\n        contactId: contact.id,\n        identity: addedIdentity,\n      })\n      logger.info(`Contact identity created: ${JSON.stringify(addedIdentity)}`)\n    }\n  }\n\n  private async siopSendResponse(args: SendResponseArgs, context: RequiredContext): Promise<Siopv2AuthorizationResponseData> {\n    const { didAuthConfig, authorizationRequestData, selectedCredentials, isFirstParty } = args\n\n    if (didAuthConfig === undefined) {\n      return Promise.reject(Error('Missing config in context'))\n    }\n\n    if (authorizationRequestData === undefined) {\n      return Promise.reject(Error('Missing authorization request data in context'))\n    }\n\n    const pex = new PEX({ hasher: this.hasher })\n    const verifiableCredentialsWithDefinition: Array<VerifiableCredentialsWithDefinition> = []\n    const dcqlCredentialsWithCredentials: Map<DcqlCredential, UniqueDigitalCredential> = new Map()\n\n    if (Array.isArray(authorizationRequestData.presentationDefinitions) && authorizationRequestData?.presentationDefinitions.length > 0) {\n      try {\n        authorizationRequestData.presentationDefinitions?.forEach((presentationDefinition) => {\n          const { areRequiredCredentialsPresent, verifiableCredential: verifiableCredentials } = pex.selectFrom(\n            presentationDefinition.definition,\n            selectedCredentials.map((udc) => udc.originalVerifiableCredential!),\n          )\n\n          if (areRequiredCredentialsPresent !== Status.ERROR && verifiableCredentials) {\n            let uniqueDigitalCredentials: UniqueDigitalCredential[] = []\n            uniqueDigitalCredentials = verifiableCredentials.map((vc) => {\n              // @ts-ignore FIXME Funke\n              const hash = typeof vc === 'string' ? computeEntryHash(vc.split('~'[0])) : computeEntryHash(vc)\n              const udc = selectedCredentials.find((udc) => udc.hash == hash || udc.originalVerifiableCredential == vc)\n\n              if (!udc) {\n                throw Error(\n                  `UniqueDigitalCredential could not be found in store. Either the credential is not present in the store or the hash is not correct.`,\n                )\n              }\n              return udc\n            })\n            verifiableCredentialsWithDefinition.push({\n              definition: presentationDefinition,\n              credentials: uniqueDigitalCredentials,\n            })\n          }\n        })\n      } catch (e) {\n        return Promise.reject(e)\n      }\n\n      if (verifiableCredentialsWithDefinition.length === 0) {\n        return Promise.reject(Error('None of the selected credentials match any of the presentation definitions.'))\n      }\n    } else if (authorizationRequestData.dcqlQuery) {\n      //TODO Only SD-JWT and MSO MDOC are supported at the moment\n      if (this.hasMDocCredentials(selectedCredentials) || this.hasSdJwtCredentials(selectedCredentials)) {\n        try {\n          selectedCredentials.forEach((vc) => {\n            if (this.isSdJwtCredential(vc)) {\n              const payload = (vc.originalVerifiableCredential as SdJwtDecodedVerifiableCredential).decodedPayload\n              const result: DcqlSdJwtVcCredential = {\n                claims: payload as { [x: string]: Json },\n                vct: payload.vct,\n                credential_format: 'vc+sd-jwt',\n              }\n              dcqlCredentialsWithCredentials.set(result, vc)\n              //FIXME MDoc namespaces are incompatible: array of strings vs complex object - https://sphereon.atlassian.net/browse/SPRIND-143\n            } else {\n              throw Error(`Invalid credential format: ${vc.digitalCredential.documentFormat}`)\n            }\n          })\n        } catch (e) {\n          return Promise.reject(e)\n        }\n\n        const dcqlPresentationRecord: DcqlPresentation.Output = {}\n        const queryResult = DcqlQuery.query(authorizationRequestData.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()))\n        for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n          if (value.success) {\n            dcqlPresentationRecord[key] = this.retrieveEncodedCredential(dcqlCredentialsWithCredentials.get(value.output)!) as\n              | string\n              | { [x: string]: Json }\n          }\n        }\n      }\n    }\n\n    const response = await siopSendAuthorizationResponse(\n      ConnectionType.SIOPv2_OpenID4VP,\n      {\n        sessionId: didAuthConfig.sessionId,\n        ...(args.idOpts && { idOpts: args.idOpts }),\n        ...(authorizationRequestData.presentationDefinitions !== undefined && { verifiableCredentialsWithDefinition }),\n        isFirstParty,\n        hasher: this.hasher,\n      },\n      context,\n    )\n\n    const contentType = response.headers.get('content-type') || ''\n    let responseBody: any = null\n\n    const text = await response.text()\n    if (text) {\n      responseBody = contentType.includes('application/json') || text.startsWith('{') ? JSON.parse(text) : text\n    }\n\n    return {\n      body: responseBody,\n      url: response?.url,\n      queryParams: decodeUriAsJson(response?.url),\n    }\n  }\n\n  private hasMDocCredentials = (credentials: UniqueDigitalCredential[]): boolean => {\n    return credentials.some(this.isMDocCredential)\n  }\n\n  private isMDocCredential = (credential: UniqueDigitalCredential) => {\n    return (\n      credential.digitalCredential.documentFormat === CredentialDocumentFormat.MSO_MDOC &&\n      credential.digitalCredential.documentType === DocumentType.VC\n    )\n  }\n\n  private hasSdJwtCredentials = (credentials: UniqueDigitalCredential[]): boolean => {\n    return credentials.some(this.isSdJwtCredential)\n  }\n\n  private isSdJwtCredential = (credential: UniqueDigitalCredential) => {\n    return (\n      credential.digitalCredential.documentFormat === CredentialDocumentFormat.SD_JWT && credential.digitalCredential.documentType === DocumentType.VC\n    )\n  }\n\n  private retrieveEncodedCredential = (credential: UniqueDigitalCredential) => {\n    return credential.originalVerifiableCredential !== undefined &&\n      credential.originalVerifiableCredential !== null &&\n      (credential?.originalVerifiableCredential as SdJwtDecodedVerifiableCredential)?.compactSdJwtVc !== undefined &&\n      (credential?.originalVerifiableCredential as SdJwtDecodedVerifiableCredential)?.compactSdJwtVc !== null\n      ? (credential.originalVerifiableCredential as SdJwtDecodedVerifiableCredential).compactSdJwtVc\n      : credential.originalVerifiableCredential\n  }\n\n  private async siopGetSelectableCredentials(args: GetSelectableCredentialsArgs, context: RequiredContext): Promise<SelectableCredentialsMap> {\n    const { authorizationRequestData } = args\n\n    if (\n      !authorizationRequestData ||\n      !authorizationRequestData.presentationDefinitions ||\n      authorizationRequestData.presentationDefinitions.length === 0\n    ) {\n      return Promise.reject(Error('Missing required fields in arguments or context'))\n    }\n    if (authorizationRequestData.presentationDefinitions.length > 1) {\n      return Promise.reject(Error('Multiple presentation definitions present'))\n    }\n\n    return getSelectableCredentials(authorizationRequestData.presentationDefinitions[0].definition, context)\n  }\n}\n","import { OP, OPBuilder, PassBy, PresentationSignCallback, ResponseMode, SupportedVersion, VerifyJwtCallback } from '@sphereon/did-auth-siop'\nimport { CreateJwtCallback, JwtHeader, JwtIssuer, SigningAlgo } from '@sphereon/oid4vc-common'\nimport { Format } from '@sphereon/pex-models'\nimport { isManagedIdentifierDidOpts, isManagedIdentifierX5cOpts, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { JwsHeader, JwsPayload, JwtCompactResult } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { createPEXPresentationSignCallback } from '@sphereon/ssi-sdk.presentation-exchange'\nimport { IVerifyCallbackArgs, IVerifyCredentialResult, VerifyCallback } from '@sphereon/wellknown-dids-client'\nimport { TKeyType } from '@veramo/core'\nimport { JWTVerifyOptions } from 'did-jwt'\nimport { Resolvable } from 'did-resolver'\nimport { EventEmitter } from 'events'\nimport { IOPOptions, IRequiredContext } from '../types'\nimport { OriginalVerifiableCredential } from '@sphereon/ssi-types'\n\nexport async function createOID4VPPresentationSignCallback({\n  presentationSignCallback,\n  idOpts,\n  domain,\n  fetchRemoteContexts,\n  challenge,\n  format,\n  context,\n  skipDidResolution,\n}: {\n  presentationSignCallback?: PresentationSignCallback\n  idOpts: ManagedIdentifierOptsOrResult\n  domain?: string\n  challenge?: string\n  fetchRemoteContexts?: boolean\n  skipDidResolution?: boolean\n  format?: Format\n  context: IRequiredContext\n}): Promise<PresentationSignCallback> {\n  if (typeof presentationSignCallback === 'function') {\n    return presentationSignCallback\n  }\n\n  return createPEXPresentationSignCallback(\n    {\n      idOpts,\n      fetchRemoteContexts,\n      domain,\n      challenge,\n      format,\n      skipDidResolution,\n    },\n    context,\n  )\n}\n\nexport async function createOPBuilder({\n  opOptions,\n  idOpts,\n  context,\n}: {\n  opOptions: IOPOptions\n  idOpts?: ManagedIdentifierOptsOrResult\n  context: IRequiredContext\n}): Promise<OPBuilder> {\n  const eventEmitter = opOptions.eventEmitter ?? new EventEmitter()\n  const builder = OP.builder()\n    .withResponseMode(opOptions.responseMode ?? ResponseMode.DIRECT_POST)\n    .withSupportedVersions(\n      opOptions.supportedVersions ?? [\n        SupportedVersion.SIOPv2_ID1,\n        SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1,\n        SupportedVersion.SIOPv2_D11,\n        SupportedVersion.SIOPv2_D12_OID4VP_D18,\n      ],\n    )\n    .withExpiresIn(opOptions.expiresIn ?? 300)\n    .withEventEmitter(eventEmitter)\n    .withRegistration({\n      passBy: PassBy.VALUE,\n    })\n\n  const wellknownDIDVerifyCallback = opOptions.wellknownDIDVerifyCallback\n    ? opOptions.wellknownDIDVerifyCallback\n    : async (args: IVerifyCallbackArgs): Promise<IVerifyCredentialResult> => {\n        const result = await context.agent.cvVerifyCredential({\n          credential: args.credential as OriginalVerifiableCredential,\n          fetchRemoteContexts: true,\n        })\n        return { verified: result.result }\n      }\n  builder.withVerifyJwtCallback(\n    opOptions.verifyJwtCallback\n      ? opOptions.verifyJwtCallback\n      : getVerifyJwtCallback(\n          {\n            verifyOpts: {\n              wellknownDIDVerifyCallback,\n              checkLinkedDomain: 'if_present',\n            },\n          },\n          context,\n        ),\n  )\n  if (idOpts) {\n    if (opOptions.skipDidResolution && isManagedIdentifierDidOpts(idOpts)) {\n      idOpts.offlineWhenNoDIDRegistered = true\n    }\n    const createJwtCallback = createJwtCallbackWithIdOpts(idOpts, context)\n    builder.withCreateJwtCallback(createJwtCallback as CreateJwtCallback<any>)\n    builder.withPresentationSignCallback(\n      await createOID4VPPresentationSignCallback({\n        presentationSignCallback: opOptions.presentationSignCallback,\n        skipDidResolution: opOptions.skipDidResolution ?? false,\n        idOpts,\n        context,\n      }),\n    )\n  } else {\n    const createJwtCallback = createJwtCallbackWithOpOpts(opOptions, context)\n    builder.withCreateJwtCallback(createJwtCallback as CreateJwtCallback<any>)\n  }\n  return builder\n}\n\nexport function createJwtCallbackWithIdOpts(\n  idOpts: ManagedIdentifierOptsOrResult,\n  context: IRequiredContext,\n): (jwtIssuer: JwtIssuer, jwt: { header: JwtHeader; payload: JwsPayload }) => Promise<string> {\n  return async (jwtIssuer: JwtIssuer, jwt: { header: JwtHeader; payload: JwsPayload }) => {\n    let issuer: ManagedIdentifierOptsOrResult & { noIdentifierInHeader: false }\n\n    if (isManagedIdentifierDidOpts(idOpts)) {\n      issuer = {\n        ...idOpts,\n        method: idOpts.method,\n        noIdentifierInHeader: false,\n      }\n    } else if (isManagedIdentifierX5cOpts(idOpts)) {\n      issuer = {\n        ...idOpts,\n        method: idOpts.method,\n        noIdentifierInHeader: false,\n      }\n    } else {\n      return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`))\n    }\n\n    const result: JwtCompactResult = await context.agent.jwtCreateJwsCompactSignature({\n      issuer,\n      protectedHeader: jwt.header as JwsHeader,\n      payload: jwt.payload,\n    })\n    return result.jwt\n  }\n}\n\nexport function createJwtCallbackWithOpOpts(\n  opOpts: IOPOptions,\n  context: IRequiredContext,\n): (jwtIssuer: JwtIssuer, jwt: { header: JwtHeader; payload: JwsPayload }) => Promise<string> {\n  return async (jwtIssuer: JwtIssuer, jwt: { header: JwtHeader; payload: JwsPayload }) => {\n    let identifier: string | Array<string>\n    if (jwtIssuer.method == 'did') {\n      identifier = jwtIssuer.didUrl\n    } else if (jwtIssuer.method == 'x5c') {\n      identifier = jwtIssuer.x5c\n    } else {\n      return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`))\n    }\n\n    const result: JwtCompactResult = await context.agent.jwtCreateJwsCompactSignature({\n      // FIXME fix cose-key inference\n      // @ts-ignore\n      issuer: { identifier: identifier, kmsKeyRef: idOpts.kmsKeyRef, noIdentifierInHeader: false },\n      // FIXME fix JWK key_ops\n      // @ts-ignore\n      protectedHeader: jwt.header,\n      payload: jwt.payload,\n    })\n    return result.jwt\n  }\n}\n\nfunction getVerifyJwtCallback(\n  _opts: {\n    resolver?: Resolvable\n    verifyOpts?: JWTVerifyOptions & {\n      checkLinkedDomain: 'never' | 'if_present' | 'always'\n      wellknownDIDVerifyCallback?: VerifyCallback\n    }\n  },\n  context: IRequiredContext,\n): VerifyJwtCallback {\n  return async (_jwtVerifier, jwt) => {\n    const result = await context.agent.jwtVerifyJwsSignature({ jws: jwt.raw })\n    console.log(result.message)\n    return !result.error\n  }\n}\n\nexport async function createOP({\n  opOptions,\n  idOpts,\n  context,\n}: {\n  opOptions: IOPOptions\n  idOpts?: ManagedIdentifierOptsOrResult\n  context: IRequiredContext\n}): Promise<OP> {\n  return (await createOPBuilder({ opOptions, idOpts, context })).build()\n}\n\nexport function getSigningAlgo(type: TKeyType): SigningAlgo {\n  switch (type) {\n    case 'Ed25519':\n      return SigningAlgo.EDDSA\n    case 'Secp256k1':\n      return SigningAlgo.ES256K\n    case 'Secp256r1':\n      return SigningAlgo.ES256\n    // @ts-ignore\n    case 'RSA':\n      return SigningAlgo.RS256\n    default:\n      throw Error('Key type not yet supported')\n  }\n}\n","import { PresentationDefinitionWithLocation, PresentationExchange } from '@sphereon/did-auth-siop'\nimport { SelectResults, Status, SubmissionRequirementMatch } from '@sphereon/pex'\nimport { Format } from '@sphereon/pex-models'\nimport {\n  isManagedIdentifierDidResult,\n  isOID4VCIssuerIdentifier,\n  ManagedIdentifierOptsOrResult,\n  ManagedIdentifierResult,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { defaultHasher, ProofOptions } from '@sphereon/ssi-sdk.core'\nimport { UniqueDigitalCredential, verifiableCredentialForRoleFilter } from '@sphereon/ssi-sdk.credential-store'\nimport { CredentialRole, FindDigitalCredentialArgs } from '@sphereon/ssi-sdk.data-store'\nimport { CompactJWT, HasherSync, IProof, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport {\n  DEFAULT_JWT_PROOF_TYPE,\n  IGetPresentationExchangeArgs,\n  IOID4VPArgs,\n  VerifiableCredentialsWithDefinition,\n  VerifiablePresentationWithDefinition,\n} from '../types'\nimport { createOID4VPPresentationSignCallback } from './functions'\nimport { OpSession } from './OpSession'\n\nexport class OID4VP {\n  private readonly session: OpSession\n  private readonly allIdentifiers: string[]\n  private readonly hasher?: HasherSync\n\n  private constructor(args: IOID4VPArgs) {\n    const { session, allIdentifiers, hasher = defaultHasher } = args\n\n    this.session = session\n    this.allIdentifiers = allIdentifiers ?? []\n    this.hasher = hasher\n  }\n\n  public static async init(session: OpSession, allIdentifiers: string[], hasher?: HasherSync): Promise<OID4VP> {\n    return new OID4VP({ session, allIdentifiers: allIdentifiers ?? (await session.getSupportedDIDs()), hasher })\n  }\n\n  public async getPresentationDefinitions(): Promise<PresentationDefinitionWithLocation[] | undefined> {\n    const definitions = await this.session.getPresentationDefinitions()\n    if (definitions) {\n      PresentationExchange.assertValidPresentationDefinitionWithLocations(definitions)\n    }\n    return definitions\n  }\n\n  private getPresentationExchange(args: IGetPresentationExchangeArgs): PresentationExchange {\n    const { verifiableCredentials, allIdentifiers, hasher } = args\n\n    return new PresentationExchange({\n      allDIDs: allIdentifiers ?? this.allIdentifiers,\n      allVerifiableCredentials: verifiableCredentials,\n      hasher: hasher ?? this.hasher,\n    })\n  }\n\n  public async createVerifiablePresentations(\n    credentialRole: CredentialRole,\n    credentialsWithDefinitions: VerifiableCredentialsWithDefinition[],\n    opts?: {\n      forceNoCredentialsInVP?: boolean // Allow to create a VP without credentials, like EBSI is using it. Defaults to false\n      restrictToFormats?: Format\n      restrictToDIDMethods?: string[]\n      proofOpts?: ProofOptions\n      idOpts?: ManagedIdentifierOptsOrResult\n      skipDidResolution?: boolean\n      holderDID?: string\n      subjectIsHolder?: boolean\n      hasher?: HasherSync\n      applyFilter?: boolean\n    },\n  ): Promise<VerifiablePresentationWithDefinition[]> {\n    return await Promise.all(credentialsWithDefinitions.map((cred) => this.createVerifiablePresentation(credentialRole, cred, opts)))\n  }\n\n  public async createVerifiablePresentation(\n    credentialRole: CredentialRole,\n    selectedVerifiableCredentials: VerifiableCredentialsWithDefinition,\n    opts?: {\n      forceNoCredentialsInVP?: boolean // Allow to create a VP without credentials, like EBSI is using it. Defaults to false\n      restrictToFormats?: Format\n      restrictToDIDMethods?: string[]\n      proofOpts?: ProofOptions\n      idOpts?: ManagedIdentifierOptsOrResult\n      skipDidResolution?: boolean\n      holder?: string\n      subjectIsHolder?: boolean\n      applyFilter?: boolean\n      hasher?: HasherSync\n    },\n  ): Promise<VerifiablePresentationWithDefinition> {\n    const { subjectIsHolder, holder, forceNoCredentialsInVP = false } = { ...opts }\n    if (subjectIsHolder && holder) {\n      throw Error('Cannot both have subject is holder and a holderDID value at the same time (programming error)')\n    }\n    if (forceNoCredentialsInVP) {\n      selectedVerifiableCredentials.credentials = []\n    } else if (!selectedVerifiableCredentials?.credentials || selectedVerifiableCredentials.credentials.length === 0) {\n      throw Error('No verifiable verifiableCredentials provided for presentation definition')\n    }\n\n    const proofOptions: ProofOptions = {\n      ...opts?.proofOpts,\n      challenge: opts?.proofOpts?.nonce ?? opts?.proofOpts?.challenge ?? this.session.nonce,\n      domain: opts?.proofOpts?.domain ?? (await this.session.getRedirectUri()),\n    }\n\n    let idOpts = opts?.idOpts\n    if (!idOpts) {\n      if (opts?.subjectIsHolder) {\n        if (forceNoCredentialsInVP) {\n          return Promise.reject(\n            Error(\n              `Cannot have subject is holder, when force no credentials is being used, as we could never determine the holder then. Please provide holderDID`,\n            ),\n          )\n        }\n        const firstUniqueDC = selectedVerifiableCredentials.credentials[0]\n        //        const firstVC = firstUniqueDC.uniformVerifiableCredential!\n        if (typeof firstUniqueDC !== 'object' || !('digitalCredential' in firstUniqueDC)) {\n          return Promise.reject(Error('If no opts provided, credentials should be of type UniqueDigitalCredential'))\n        }\n\n        idOpts = isOID4VCIssuerIdentifier(firstUniqueDC.digitalCredential.kmsKeyRef)\n          ? await this.session.context.agent.identifierManagedGetByIssuer({\n              identifier: firstUniqueDC.digitalCredential.kmsKeyRef,\n            })\n          : await this.session.context.agent.identifierManagedGetByKid({\n              identifier: firstUniqueDC.digitalCredential.kmsKeyRef,\n              kmsKeyRef: firstUniqueDC.digitalCredential.kmsKeyRef,\n            })\n\n        /*\n        const holder = CredentialMapper.isSdJwtDecodedCredential(firstVC)\n          ? firstVC.decodedPayload.cnf?.jwk\n            ? //TODO SDK-19: convert the JWK to hex and search for the appropriate key and associated DID\n              //doesn't apply to did:jwk only, as you can represent any DID key as a JWK. So whenever you encounter a JWK it doesn't mean it had to come from a did:jwk in the system. It just can always be represented as a did:jwk\n              `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0`\n            : firstVC.decodedPayload.sub\n          : Array.isArray(firstVC.credentialSubject)\n            ? firstVC.credentialSubject[0].id\n            : firstVC.credentialSubject.id\n        if (holder) {\n          idOpts = { identifier: holder }\n        }\n*/\n      } else if (opts?.holder) {\n        idOpts = { identifier: opts.holder }\n      }\n    }\n\n    // We are making sure to filter, in case the user submitted all verifiableCredentials in the wallet/agent. We also make sure to get original formats back\n    const vcs = forceNoCredentialsInVP\n      ? selectedVerifiableCredentials\n      : opts?.applyFilter\n        ? await this.filterCredentials(credentialRole, selectedVerifiableCredentials.definition, {\n            restrictToFormats: opts?.restrictToFormats,\n            restrictToDIDMethods: opts?.restrictToDIDMethods,\n            filterOpts: {\n              verifiableCredentials: selectedVerifiableCredentials.credentials,\n            },\n          })\n        : {\n            definition: selectedVerifiableCredentials.definition,\n            credentials: selectedVerifiableCredentials.credentials,\n          }\n\n    if (!idOpts) {\n      return Promise.reject(Error(`No identifier options present at this point`))\n    }\n\n    const signCallback = await createOID4VPPresentationSignCallback({\n      presentationSignCallback: this.session.options.presentationSignCallback,\n      idOpts,\n      context: this.session.context,\n      domain: proofOptions.domain,\n      challenge: proofOptions.challenge,\n      format: opts?.restrictToFormats ?? selectedVerifiableCredentials.definition.definition.format,\n      skipDidResolution: opts?.skipDidResolution ?? false,\n    })\n    const identifier: ManagedIdentifierResult = await this.session.context.agent.identifierManagedGet(idOpts)\n    const verifiableCredentials = vcs.credentials.map((credential) =>\n      typeof credential === 'object' && 'digitalCredential' in credential ? credential.originalVerifiableCredential! : credential,\n    )\n    const presentationResult = await this.getPresentationExchange({\n      verifiableCredentials: verifiableCredentials,\n      allIdentifiers: this.allIdentifiers,\n      hasher: opts?.hasher,\n    }).createVerifiablePresentation(vcs.definition.definition, verifiableCredentials, signCallback, {\n      proofOptions,\n      // fixme: Update to newer siop-vp to not require dids here. But when Veramo is creating the VP it's still looking at this field to pass into didManagerGet\n      ...(identifier && isManagedIdentifierDidResult(identifier) && { holderDID: identifier.did }),\n    })\n\n    const verifiablePresentations = presentationResult.verifiablePresentations.map((verifiablePresentation) =>\n      typeof verifiablePresentation !== 'string' &&\n      'proof' in verifiablePresentation &&\n      'jwt' in verifiablePresentation.proof &&\n      verifiablePresentation.proof.jwt\n        ? verifiablePresentation.proof.jwt\n        : verifiablePresentation,\n    )\n\n    return {\n      ...presentationResult,\n      verifiablePresentations,\n      verifiableCredentials: verifiableCredentials,\n      definition: selectedVerifiableCredentials.definition,\n      idOpts,\n    }\n  }\n\n  public async filterCredentialsAgainstAllDefinitions(\n    credentialRole: CredentialRole,\n    opts?: {\n      filterOpts?: {\n        verifiableCredentials?: UniqueDigitalCredential[]\n        filter?: FindDigitalCredentialArgs\n      }\n      holderDIDs?: string[]\n      restrictToFormats?: Format\n      restrictToDIDMethods?: string[]\n    },\n  ): Promise<VerifiableCredentialsWithDefinition[]> {\n    const defs = await this.getPresentationDefinitions()\n    const result: VerifiableCredentialsWithDefinition[] = []\n    if (defs) {\n      for (const definition of defs) {\n        result.push(await this.filterCredentials(credentialRole, definition, opts))\n      }\n    }\n    return result\n  }\n\n  public async filterCredentials(\n    credentialRole: CredentialRole,\n    presentationDefinition: PresentationDefinitionWithLocation,\n    opts?: {\n      filterOpts?: { verifiableCredentials?: (UniqueDigitalCredential | OriginalVerifiableCredential)[]; filter?: FindDigitalCredentialArgs }\n      holderDIDs?: string[]\n      restrictToFormats?: Format\n      restrictToDIDMethods?: string[]\n    },\n  ): Promise<VerifiableCredentialsWithDefinition> {\n    const udcMap = new Map<OriginalVerifiableCredential, UniqueDigitalCredential | OriginalVerifiableCredential>()\n    opts?.filterOpts?.verifiableCredentials?.forEach((credential) => {\n      if (typeof credential === 'object' && 'digitalCredential' in credential) {\n        udcMap.set(credential.originalVerifiableCredential!, credential)\n      } else {\n        udcMap.set(credential, credential)\n      }\n    })\n\n    const credentials = (\n      await this.filterCredentialsWithSelectionStatus(credentialRole, presentationDefinition, {\n        ...opts,\n        filterOpts: {\n          verifiableCredentials: opts?.filterOpts?.verifiableCredentials?.map((credential) => {\n            if (typeof credential === 'object' && 'digitalCredential' in credential) {\n              return credential.originalVerifiableCredential!\n            } else {\n              return credential\n            }\n          }),\n        },\n      })\n    ).verifiableCredential\n    return {\n      definition: presentationDefinition,\n      credentials: credentials?.map((vc) => udcMap.get(vc)!) ?? [],\n    }\n  }\n\n  public async filterCredentialsWithSelectionStatus(\n    credentialRole: CredentialRole,\n    presentationDefinition: PresentationDefinitionWithLocation,\n    opts?: {\n      filterOpts?: { verifiableCredentials?: OriginalVerifiableCredential[]; filter?: FindDigitalCredentialArgs }\n      holderDIDs?: string[]\n      restrictToFormats?: Format\n      restrictToDIDMethods?: string[]\n    },\n  ): Promise<SelectResults> {\n    const selectionResults: SelectResults = await this.getPresentationExchange({\n      verifiableCredentials: await this.getCredentials(credentialRole, opts?.filterOpts),\n    }).selectVerifiableCredentialsForSubmission(presentationDefinition.definition, opts)\n    if (selectionResults.errors && selectionResults.errors.length > 0) {\n      throw Error(JSON.stringify(selectionResults.errors))\n    } else if (selectionResults.areRequiredCredentialsPresent === Status.ERROR) {\n      throw Error(`Not all required credentials are available to satisfy the relying party's request`)\n    }\n\n    const matches: SubmissionRequirementMatch[] | undefined = selectionResults.matches\n    if (!matches || matches.length === 0 || !selectionResults.verifiableCredential || selectionResults.verifiableCredential.length === 0) {\n      throw Error(JSON.stringify(selectionResults.errors))\n    }\n    return selectionResults\n  }\n\n  private async getCredentials(\n    credentialRole: CredentialRole,\n    filterOpts?: {\n      verifiableCredentials?: OriginalVerifiableCredential[]\n      filter?: FindDigitalCredentialArgs\n    },\n  ): Promise<OriginalVerifiableCredential[]> {\n    if (filterOpts?.verifiableCredentials && filterOpts.verifiableCredentials.length > 0) {\n      return filterOpts.verifiableCredentials\n    }\n\n    const filter = verifiableCredentialForRoleFilter(credentialRole, filterOpts?.filter)\n    const uniqueCredentials = await this.session.context.agent.crsGetUniqueCredentials({ filter })\n    return uniqueCredentials.map((uniqueVC: UniqueDigitalCredential) => {\n      const vc = uniqueVC.uniformVerifiableCredential!\n      const proof = Array.isArray(vc.proof) ? vc.proof : [vc.proof]\n      const jwtProof = proof.find((p: IProof) => p?.type === DEFAULT_JWT_PROOF_TYPE)\n      return jwtProof ? (jwtProof.jwt as CompactJWT) : vc\n    })\n  }\n}\n","import {\n  DcqlResponseOpts,\n  PresentationDefinitionWithLocation,\n  PresentationSignCallback,\n  ResponseMode,\n  SupportedVersion,\n  URI,\n  VerifiablePresentationTypeFormat,\n  VerifiedAuthorizationRequest,\n  VerifyJwtCallback,\n  VPTokenLocation,\n} from '@sphereon/did-auth-siop'\nimport { CheckLinkedDomain, ResolveOpts } from '@sphereon/did-auth-siop-adapter'\nimport { DIDDocument } from '@sphereon/did-uni-client'\nimport { VerifiablePresentationResult } from '@sphereon/pex'\nimport { IIdentifierResolution, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { ICredentialStore, UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { Party } from '@sphereon/ssi-sdk.data-store'\nimport { IPDManager } from '@sphereon/ssi-sdk.pd-manager'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\nimport { HasherSync, OriginalVerifiableCredential, PresentationSubmission, W3CVerifiablePresentation } from '@sphereon/ssi-types'\nimport { VerifyCallback } from '@sphereon/wellknown-dids-client'\nimport {\n  IAgentContext,\n  ICredentialIssuer,\n  ICredentialVerifier,\n  IDataStoreORM,\n  IDIDManager,\n  IKeyManager,\n  IPluginMethodMap,\n  IResolver,\n} from '@veramo/core'\nimport { EventEmitter } from 'events'\nimport { OpSession } from '../session'\nimport { Siopv2Machine as Siopv2MachineId } from './machine'\nimport {\n  AddIdentityArgs,\n  CreateConfigArgs,\n  CreateConfigResult,\n  GetMachineArgs,\n  GetSelectableCredentialsArgs,\n  GetSiopRequestArgs,\n  RequiredContext,\n  RetrieveContactArgs,\n  SelectableCredentialsMap,\n  SendResponseArgs,\n  Siopv2AuthorizationRequestData,\n  Siopv2AuthorizationResponseData,\n} from './siop-service'\nimport { ICredentialValidation } from '@sphereon/ssi-sdk.credential-validation'\n\nexport const LOGGER_NAMESPACE = 'sphereon:siopv2-oid4vp:op-auth'\n\nexport interface IDidAuthSiopOpAuthenticator extends IPluginMethodMap {\n  siopGetOPSession(args: IGetSiopSessionArgs, context: IRequiredContext): Promise<OpSession>\n\n  siopRegisterOPSession(args: Omit<IOpSessionArgs, 'context'>, context: IRequiredContext): Promise<OpSession>\n\n  siopRemoveOPSession(args: IRemoveSiopSessionArgs, context: IRequiredContext): Promise<boolean>\n\n  siopRegisterOPCustomApproval(args: IRegisterCustomApprovalForSiopArgs, context: IRequiredContext): Promise<void>\n\n  siopRemoveOPCustomApproval(args: IRemoveCustomApprovalForSiopArgs, context: IRequiredContext): Promise<boolean>\n\n  siopGetMachineInterpreter(args: GetMachineArgs, context: RequiredContext): Promise<Siopv2MachineId>\n\n  siopCreateConfig(args: CreateConfigArgs): Promise<CreateConfigResult>\n\n  siopGetSiopRequest(args: GetSiopRequestArgs, context: RequiredContext): Promise<Siopv2AuthorizationRequestData>\n\n  siopRetrieveContact(args: RetrieveContactArgs, context: RequiredContext): Promise<Party | undefined>\n\n  siopAddIdentity(args: AddIdentityArgs, context: RequiredContext): Promise<void>\n\n  siopSendResponse(args: SendResponseArgs, context: RequiredContext): Promise<Siopv2AuthorizationResponseData>\n\n  siopGetSelectableCredentials(args: GetSelectableCredentialsArgs, context: RequiredContext): Promise<SelectableCredentialsMap>\n}\n\nexport interface IOpSessionArgs {\n  sessionId?: string\n  requestJwtOrUri: string | URI\n  providedPresentationDefinitions?: Array<PresentationDefinitionWithLocation>\n  identifierOptions?: ManagedIdentifierOptsOrResult\n  context: IRequiredContext\n  op?: IOPOptions\n}\n\nexport interface IAuthRequestDetails {\n  rpDIDDocument?: DIDDocument\n  id: string\n  verifiablePresentationMatches: IPresentationWithDefinition[]\n  alsoKnownAs?: string[]\n}\n\nexport interface IPresentationWithDefinition {\n  location: VPTokenLocation\n  definition: PresentationDefinitionWithLocation\n  format: VerifiablePresentationTypeFormat\n  presentation: W3CVerifiablePresentation\n}\n\nexport interface IGetSiopSessionArgs {\n  sessionId: string\n}\n\nexport interface IRemoveSiopSessionArgs {\n  sessionId: string\n}\n\nexport interface IRegisterCustomApprovalForSiopArgs {\n  key: string\n  customApproval: (verifiedAuthorizationRequest: VerifiedAuthorizationRequest, sessionId: string) => Promise<void>\n}\n\nexport interface IRemoveCustomApprovalForSiopArgs {\n  key: string\n}\n\nexport interface IOpsSendSiopAuthorizationResponseArgs {\n  responseSignerOpts: ManagedIdentifierOptsOrResult\n  // verifiedAuthorizationRequest: VerifiedAuthorizationRequest\n  presentationSubmission?: PresentationSubmission\n  verifiablePresentations?: W3CVerifiablePresentation[]\n  dcqlResponse?: DcqlResponseOpts\n  hasher?: HasherSync\n  isFirstParty?: boolean\n}\n\nexport enum events {\n  DID_SIOP_AUTHENTICATED = 'didSiopAuthenticated',\n}\n\nexport type IRequiredContext = IAgentContext<\n  IDataStoreORM &\n    IResolver &\n    IDIDManager &\n    IKeyManager &\n    IIdentifierResolution &\n    ICredentialIssuer &\n    ICredentialValidation &\n    ICredentialVerifier &\n    ICredentialStore &\n    IPDManager &\n    ISDJwtPlugin &\n    IJwtService\n>\n\nexport interface IOPOptions {\n  responseMode?: ResponseMode\n  supportedVersions?: SupportedVersion[]\n  expiresIn?: number\n  checkLinkedDomains?: CheckLinkedDomain\n  skipDidResolution?: boolean\n  eventEmitter?: EventEmitter\n  supportedDIDMethods?: string[]\n\n  verifyJwtCallback?: VerifyJwtCallback\n  wellknownDIDVerifyCallback?: VerifyCallback\n\n  presentationSignCallback?: PresentationSignCallback\n\n  resolveOpts?: ResolveOpts\n  hasher?: HasherSync\n}\n\n/*\nexport interface IIdentifierOpts {\n  identifier: IIdentifier\n  verificationMethodSection?: DIDDocumentSection\n  kid?: string\n}*/\n\nexport interface VerifiableCredentialsWithDefinition {\n  definition: PresentationDefinitionWithLocation\n  credentials: (UniqueDigitalCredential | OriginalVerifiableCredential)[]\n}\n\nexport interface VerifiablePresentationWithDefinition extends VerifiablePresentationResult {\n  definition: PresentationDefinitionWithLocation\n  verifiableCredentials: OriginalVerifiableCredential[]\n  idOpts: ManagedIdentifierOptsOrResult\n}\n\nexport interface IOpSessionGetOID4VPArgs {\n  allIdentifiers?: string[]\n  hasher?: HasherSync\n}\n\nexport interface IOID4VPArgs {\n  session: OpSession\n  allIdentifiers?: string[]\n  hasher?: HasherSync\n}\n\nexport interface IGetPresentationExchangeArgs {\n  verifiableCredentials: OriginalVerifiableCredential[]\n  allIdentifiers?: string[]\n  hasher?: HasherSync\n}\n\n// It was added here because it's not exported from DCQL anymore\nexport type Json =\n  | string\n  | number\n  | boolean\n  | null\n  | {\n      [key: string]: Json\n    }\n  | Json[]\n\nexport const DEFAULT_JWT_PROOF_TYPE = 'JwtProof2020'\n","import {\n  PresentationDefinitionWithLocation,\n  PresentationSignCallback,\n  RPRegistrationMetadataPayload,\n  VerifiedAuthorizationRequest,\n} from '@sphereon/did-auth-siop'\nimport { IIdentifierResolution, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IContactManager } from '@sphereon/ssi-sdk.contact-manager'\nimport { ICredentialStore, UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { DidAuthConfig, ICredentialLocaleBranding, Identity, Party } from '@sphereon/ssi-sdk.data-store'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { IAgentContext, IDIDManager, IIdentifier, IResolver } from '@veramo/core'\nimport { IDidAuthSiopOpAuthenticator } from '../IDidAuthSiopOpAuthenticator'\nimport { Siopv2MachineContext, Siopv2MachineInterpreter, Siopv2MachineState } from '../machine'\nimport { DcqlQuery } from 'dcql'\nimport { HasherSync } from '@sphereon/ssi-types'\n\nexport type DidAuthSiopOpAuthenticatorOptions = {\n  presentationSignCallback?: PresentationSignCallback\n  customApprovals?: Record<string, (verifiedAuthorizationRequest: VerifiedAuthorizationRequest, sessionId: string) => Promise<void>>\n  onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n  onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n  hasher?: HasherSync\n}\n\nexport type GetMachineArgs = {\n  url: string | URL\n  idOpts?: ManagedIdentifierOptsOrResult\n  stateNavigationListener?: (siopv2Machine: Siopv2MachineInterpreter, state: Siopv2MachineState, navigation?: any) => Promise<void>\n}\n\nexport type CreateConfigArgs = { url: string }\nexport type CreateConfigResult = Omit<DidAuthConfig, 'stateId' | 'idOpts'>\nexport type GetSiopRequestArgs = { didAuthConfig?: Omit<DidAuthConfig, 'identifier'>; url: string }\n// FIXME it would be nicer if these function are not tied to a certain machine so that we can start calling them for anywhere\nexport type RetrieveContactArgs = Pick<Siopv2MachineContext, 'url' | 'authorizationRequestData'>\n// FIXME it would be nicer if these function are not tied to a certain machine so that we can start calling them for anywhere\nexport type AddIdentityArgs = Pick<Siopv2MachineContext, 'contact' | 'authorizationRequestData'>\nexport type SendResponseArgs = {\n  didAuthConfig?: Omit<DidAuthConfig, 'identifier'>\n  authorizationRequestData?: Siopv2AuthorizationRequestData\n  selectedCredentials: Array<UniqueDigitalCredential>\n  idOpts?: ManagedIdentifierOptsOrResult\n  isFirstParty?: boolean\n}\n// FIXME it would be nicer if these function are not tied to a certain machine so that we can start calling them for anywhere\nexport type GetSelectableCredentialsArgs = Pick<Siopv2MachineContext, 'authorizationRequestData'>\n\nexport enum Siopv2HolderEvent {\n  CONTACT_IDENTITY_CREATED = 'contact_identity_created',\n  IDENTIFIER_CREATED = 'identifier_created',\n}\n\nexport enum SupportedLanguage {\n  ENGLISH = 'en',\n  DUTCH = 'nl',\n}\n\nexport type Siopv2AuthorizationResponseData = {\n  body?: string | Record<string, any>\n  url?: string\n  queryParams?: Record<string, any>\n}\n\nexport type Siopv2AuthorizationRequestData = {\n  correlationId: string\n  registrationMetadataPayload: RPRegistrationMetadataPayload\n  issuer?: string\n  name?: string\n  uri?: URL\n  clientId?: string\n  presentationDefinitions?: PresentationDefinitionWithLocation[]\n  dcqlQuery?: DcqlQuery\n}\n\nexport type SelectableCredentialsMap = Map<string, Array<SelectableCredential>>\n\nexport type SelectableCredential = {\n  credential: UniqueDigitalCredential\n  credentialBranding: Array<ICredentialLocaleBranding>\n  issuerParty?: Party\n  subjectParty?: Party\n}\n\nexport type OnContactIdentityCreatedArgs = {\n  contactId: string\n  identity: Identity\n}\n\nexport type OnIdentifierCreatedArgs = {\n  identifier: IIdentifier\n}\n\nexport type RequiredContext = IAgentContext<\n  IContactManager & IDidAuthSiopOpAuthenticator & IDIDManager & IResolver & IIdentifierResolution & ICredentialStore & IIssuanceBranding\n>\n","import { VerifiedAuthorizationRequest } from '@sphereon/did-auth-siop'\nimport { ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { DidAuthConfig, Party } from '@sphereon/ssi-sdk.data-store'\nimport { BaseActionObject, Interpreter, ResolveTypegenMeta, ServiceMap, State, StateMachine, TypegenDisabled } from 'xstate'\nimport { ErrorDetails } from '../error'\nimport { SelectableCredentialsMap, Siopv2AuthorizationRequestData, Siopv2AuthorizationResponseData } from '../siop-service'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\n\nexport type Siopv2MachineContext = {\n  url: string\n  idOpts?: ManagedIdentifierOptsOrResult\n  didAuthConfig?: Omit<DidAuthConfig, 'identifier'>\n  authorizationRequestData?: Siopv2AuthorizationRequestData\n  authorizationResponseData?: Siopv2AuthorizationResponseData\n  verifiedAuthorizationRequest?: VerifiedAuthorizationRequest\n  contact?: Party\n  hasContactConsent: boolean\n  contactAlias: string\n  selectableCredentialsMap?: SelectableCredentialsMap\n  selectedCredentials: Array<UniqueDigitalCredential>\n  isFirstParty?: boolean\n  error?: ErrorDetails\n}\n\nexport enum Siopv2MachineStates {\n  createConfig = 'createConfig',\n  getSiopRequest = 'getSiopRequest',\n  getSelectableCredentials = 'getSelectableCredentials',\n  retrieveContact = 'retrieveContact',\n  transitionFromSetup = 'transitionFromSetup',\n  addContact = 'addContact',\n  addContactIdentity = 'addContactIdentity',\n  selectCredentials = 'selectCredentials',\n  sendResponse = 'sendResponse',\n  handleError = 'handleError',\n  aborted = 'aborted',\n  declined = 'declined',\n  error = 'error',\n  done = 'done',\n}\n\nexport enum Siopv2MachineAddContactStates {\n  idle = 'idle',\n  executing = 'executing',\n  next = 'next',\n}\n\nexport type Siopv2MachineInterpreter = Interpreter<\n  Siopv2MachineContext,\n  any,\n  Siopv2MachineEventTypes,\n  { value: any; context: Siopv2MachineContext },\n  any\n>\n\nexport type Siopv2MachineState = State<\n  Siopv2MachineContext,\n  Siopv2MachineEventTypes,\n  any,\n  {\n    value: any\n    context: Siopv2MachineContext\n  },\n  any\n>\n\nexport type Siopv2StateMachine = StateMachine<\n  Siopv2MachineContext,\n  any,\n  Siopv2MachineEventTypes,\n  { value: any; context: Siopv2MachineContext },\n  BaseActionObject,\n  ServiceMap,\n  ResolveTypegenMeta<TypegenDisabled, Siopv2MachineEventTypes, BaseActionObject, ServiceMap>\n>\n\nexport type CreateSiopv2MachineOpts = {\n  url: string | URL\n  idOpts?: ManagedIdentifierOptsOrResult\n  machineId?: string\n}\n\nexport type Siopv2MachineInstanceOpts = {\n  services?: any\n  guards?: any\n  subscription?: () => void\n  requireCustomNavigationHook?: boolean\n  stateNavigationListener?: (siopv2Machine: Siopv2MachineInterpreter, state: Siopv2MachineState, navigation?: any) => Promise<void>\n} & CreateSiopv2MachineOpts\n\nexport enum Siopv2MachineEvents {\n  NEXT = 'NEXT',\n  PREVIOUS = 'PREVIOUS',\n  DECLINE = 'DECLINE',\n  SET_CONTACT_ALIAS = 'SET_CONTACT_ALIAS',\n  SET_CONTACT_CONSENT = 'SET_CONTACT_CONSENT',\n  CREATE_CONTACT = 'CREATE_CONTACT',\n  SET_SELECTED_CREDENTIALS = 'SET_SELECTED_CREDENTIALS',\n}\n\nexport enum Siopv2MachineGuards {\n  hasNoContactGuard = 'Siopv2HasNoContactGuard',\n  createContactGuard = 'Siopv2CreateContactGuard',\n  hasContactGuard = 'Siopv2HasContactGuard',\n  hasAuthorizationRequestGuard = 'Siopv2HasAuthorizationRequestGuard',\n  hasSelectableCredentialsAndContactGuard = 'Siopv2HasSelectableCredentialsAndContactGuard',\n  hasSelectedRequiredCredentialsGuard = 'Siopv2HasSelectedRequiredCredentialsGuard',\n  siopOnlyGuard = 'Siopv2IsSiopOnlyGuard',\n  siopWithOID4VPGuard = 'Siopv2IsSiopWithOID4VPGuard',\n}\n\nexport enum Siopv2MachineServices {\n  getSiopRequest = 'getSiopRequest',\n  getSelectableCredentials = 'getSelectableCredentials',\n  retrieveContact = 'retrieveContact',\n  addContactIdentity = 'addContactIdentity',\n  sendResponse = 'sendResponse',\n  createConfig = 'createConfig',\n}\n\nexport type Siopv2MachineEventTypes =\n  | NextEvent\n  | PreviousEvent\n  | DeclineEvent\n  | CreateContactEvent\n  | ContactConsentEvent\n  | ContactAliasEvent\n  | SelectCredentialsEvent\n\nexport type NextEvent = { type: Siopv2MachineEvents.NEXT }\nexport type PreviousEvent = { type: Siopv2MachineEvents.PREVIOUS }\nexport type DeclineEvent = { type: Siopv2MachineEvents.DECLINE }\nexport type ContactConsentEvent = { type: Siopv2MachineEvents.SET_CONTACT_CONSENT; data: boolean }\nexport type ContactAliasEvent = { type: Siopv2MachineEvents.SET_CONTACT_ALIAS; data: string }\nexport type CreateContactEvent = { type: Siopv2MachineEvents.CREATE_CONTACT; data: Party }\nexport type SelectCredentialsEvent = {\n  type: Siopv2MachineEvents.SET_SELECTED_CREDENTIALS\n  data: Array<UniqueDigitalCredential>\n}\n\nexport type Siopv2Machine = {\n  interpreter: Siopv2MachineInterpreter\n}\n","import { IDIDManager, IIdentifier, IResolver, TAgent, TKeyType } from '@veramo/core'\nimport { _ExtendedIKey } from '@veramo/utils'\nimport { RequiredContext } from '../siop-service'\nimport { SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport { IContactManager } from '@sphereon/ssi-sdk.contact-manager'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { ICredentialStore } from '@sphereon/ssi-sdk.credential-store'\n\nexport const DID_PREFIX = 'did'\n\nexport type CreateOrGetIdentifierOpts = {\n  method: SupportedDidMethodEnum\n  createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type CreateIdentifierCreateOpts = {\n  kms?: string\n  alias?: string\n  options?: IdentifierProviderOpts\n}\n\nexport type IdentifierProviderOpts = {\n  type?: TKeyType\n  use?: string\n  [x: string]: any\n}\n\nexport type KeyOpts = {\n  didMethod: SupportedDidMethodEnum\n  keyType: TKeyType\n  codecName?: string\n  kid?: string\n  identifier: IIdentifier\n}\n\nexport type GetIdentifierArgs = {\n  keyOpts: KeyOpts // TODO was IssuanceOpts, check if ok like this\n  context: RequiredContext\n}\n\nexport type IdentifierWithKey = {\n  identifier: IIdentifier\n  key: _ExtendedIKey\n  kid: string\n}\n\nexport type GetAuthenticationKeyArgs = {\n  identifier: IIdentifier\n  context: RequiredContext\n}\n\nexport type CreateIdentifierArgs = {\n  context: RequiredContext\n  opts?: CreateIdentifierOpts\n}\n\nexport type CreateIdentifierOpts = {\n  method: SupportedDidMethodEnum\n  createOpts?: CreateIdentifierCreateOpts\n}\n\nexport type DidAgents = TAgent<IResolver & IDIDManager>\nexport type SuitableCredentialAgents = TAgent<IContactManager & ICredentialStore & IIssuanceBranding>\n","import {\n  AuthorizationResponsePayload,\n  JwksMetadataParams,\n  OP,\n  PresentationDefinitionWithLocation,\n  PresentationExchangeResponseOpts,\n  PresentationVerificationResult,\n  RequestObjectPayload,\n  ResponseIss,\n  SupportedVersion,\n  URI,\n  Verification,\n  VerifiedAuthorizationRequest,\n} from '@sphereon/did-auth-siop'\nimport { ResolveOpts } from '@sphereon/did-auth-siop-adapter'\nimport { JwtIssuer } from '@sphereon/oid4vc-common'\nimport { getAgentDIDMethods, getAgentResolver } from '@sphereon/ssi-sdk-ext.did-utils'\nimport { JweAlg, JweEnc } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { encodeBase64url } from '@sphereon/ssi-sdk.core'\nimport {\n  CompactSdJwtVc,\n  CredentialMapper,\n  HasherSync,\n  OriginalVerifiableCredential,\n  parseDid,\n  PresentationSubmission,\n  W3CVerifiablePresentation,\n} from '@sphereon/ssi-types'\nimport { IIdentifier, IVerifyResult, TKeyType } from '@veramo/core'\nimport { v4 } from 'uuid'\nimport { IOPOptions, IOpSessionArgs, IOpSessionGetOID4VPArgs, IOpsSendSiopAuthorizationResponseArgs, IRequiredContext } from '../types'\nimport { createOP } from './functions'\nimport { OID4VP } from './OID4VP'\nimport { PEX } from '@sphereon/pex'\nimport { Loggers } from '@sphereon/ssi-types'\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vp:OpSession')\n\nexport class OpSession {\n  public readonly ts = new Date().getDate()\n  public readonly id: string\n  public readonly options: IOPOptions\n  public readonly context: IRequiredContext\n  private readonly requestJwtOrUri: string | URI\n  private verifiedAuthorizationRequest?: VerifiedAuthorizationRequest | undefined\n  private _nonce?: string\n  private _state?: string\n  private readonly _providedPresentationDefinitions?: PresentationDefinitionWithLocation[]\n\n  private constructor(options: Required<IOpSessionArgs>) {\n    this.id = options.sessionId\n    this.options = options.op\n    this.context = options.context\n    this.requestJwtOrUri = options.requestJwtOrUri\n    this._providedPresentationDefinitions = options.providedPresentationDefinitions\n  }\n\n  public static async init(options: Required<IOpSessionArgs>): Promise<OpSession> {\n    return new OpSession(options)\n  }\n\n  public async getAuthorizationRequest(): Promise<VerifiedAuthorizationRequest> {\n    if (!this.verifiedAuthorizationRequest) {\n      const op = await createOP({ opOptions: this.options, context: this.context })\n      this.verifiedAuthorizationRequest = await op.verifyAuthorizationRequest(this.requestJwtOrUri)\n      this._nonce = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty('nonce')\n      this._state = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty('state')\n\n      // only used to ensure that we have DID methods supported\n      await this.getSupportedDIDMethods()\n    }\n    return this.verifiedAuthorizationRequest\n  }\n\n  public async getAuthorizationRequestURI(): Promise<URI> {\n    return await URI.fromAuthorizationRequest((await this.getAuthorizationRequest()).authorizationRequest)\n  }\n\n  get nonce() {\n    if (!this._nonce) {\n      throw Error('No nonce available. Please get authorization request first')\n    }\n    return this._nonce\n  }\n\n  get state() {\n    if (!this._state) {\n      throw Error('No state available. Please get authorization request first')\n    }\n    return this._state\n  }\n\n  public clear(): OpSession {\n    this._nonce = undefined\n    this._state = undefined\n    this.verifiedAuthorizationRequest = undefined\n    return this\n  }\n\n  public async getSupportedDIDMethods(didPrefix?: boolean): Promise<string[]> {\n    const agentMethods = this.getAgentDIDMethodsSupported({ didPrefix })\n    let rpMethods = await this.getRPDIDMethodsSupported({ didPrefix, agentMethods })\n    logger.debug(`RP supports subject syntax types: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`)\n    if (rpMethods.dids.length === 0) {\n      logger.debug(`RP does not support DIDs. Supported: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`)\n      return []\n    }\n\n    let intersection: string[]\n    if (rpMethods.dids.includes('did')) {\n      intersection =\n        agentMethods && agentMethods.length > 0\n          ? agentMethods\n          : (await getAgentDIDMethods(this.context)).map((method) => convertDidMethod(method, didPrefix)) // fallback to the agent in case the agent methods are undefined\n    } else if (!agentMethods || agentMethods.length === 0) {\n      intersection = rpMethods.dids?.map((method) => convertDidMethod(method, didPrefix))\n    } else {\n      intersection = agentMethods.filter((value) => rpMethods.dids.includes(value))\n    }\n    if (intersection.length === 0) {\n      throw Error('No matching DID methods between agent and relying party')\n    }\n    return intersection.map((value) => convertDidMethod(value, didPrefix))\n  }\n\n  private getAgentDIDMethodsSupported(opts: { didPrefix?: boolean }) {\n    const agentMethods = this.options.supportedDIDMethods?.map((method) => convertDidMethod(method, opts.didPrefix))\n    logger.debug(`agent methods: ${JSON.stringify(agentMethods)}`)\n    return agentMethods\n  }\n\n  private async getSubjectSyntaxTypesSupported(): Promise<string[]> {\n    const authReq = await this.getAuthorizationRequest()\n    const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported\n    return subjectSyntaxTypesSupported ?? []\n  }\n\n  private async getRPDIDMethodsSupported(opts: { didPrefix?: boolean; agentMethods?: string[] }) {\n    let keyType: TKeyType | undefined\n    const agentMethods =\n      (opts.agentMethods ?? this.getAgentDIDMethodsSupported(opts))?.map((method) => convertDidMethod(method, opts.didPrefix)) ?? []\n    logger.debug(`agent methods supported: ${JSON.stringify(agentMethods)}`)\n    const authReq = await this.getAuthorizationRequest()\n    const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported\n      ?.map((method) => convertDidMethod(method, opts.didPrefix))\n      .filter((val) => !val.startsWith('did'))\n    logger.debug(`subject syntax types supported in rp method supported: ${JSON.stringify(subjectSyntaxTypesSupported)}`)\n    const aud = await authReq.authorizationRequest.getMergedProperty<string>('aud')\n    let rpMethods: string[] = []\n    if (aud && aud.startsWith('did:')) {\n      const didMethod = convertDidMethod(parseDid(aud).method, opts.didPrefix)\n      logger.debug(`aud did method: ${didMethod}`)\n\n      // The RP knows our DID, so we can use it to determine the supported DID methods\n      // If the aud did:method is not in the supported types, there still is something wrong, unless the RP signals to support all did methods\n      if (\n        subjectSyntaxTypesSupported &&\n        subjectSyntaxTypesSupported.length > 0 &&\n        !subjectSyntaxTypesSupported.includes('did') &&\n        !subjectSyntaxTypesSupported.includes(didMethod)\n      ) {\n        throw Error(`The aud DID method ${didMethod} is not in the supported types ${subjectSyntaxTypesSupported}`)\n      }\n      rpMethods = [didMethod]\n    } else if (subjectSyntaxTypesSupported) {\n      rpMethods = (Array.isArray(subjectSyntaxTypesSupported) ? subjectSyntaxTypesSupported : [subjectSyntaxTypesSupported]).map((method) =>\n        convertDidMethod(method, opts.didPrefix),\n      )\n    }\n    const isEBSI =\n      rpMethods.length === 0 &&\n      (authReq.issuer?.includes('.ebsi.eu') || (await authReq.authorizationRequest.getMergedProperty<string>('client_id'))?.includes('.ebsi.eu'))\n    let codecName: string | undefined = undefined\n    if (isEBSI && (!aud || !aud.startsWith('http'))) {\n      logger.debug(`EBSI detected, adding did:key to supported DID methods for RP`)\n      const didKeyMethod = convertDidMethod('did:key', opts.didPrefix)\n      if (!agentMethods?.includes(didKeyMethod)) {\n        throw Error(`EBSI detected, but agent did not support did:key. Please reconfigure agent`)\n      }\n      rpMethods = [didKeyMethod]\n      keyType = 'Secp256r1'\n      codecName = 'jwk_jcs-pub'\n    }\n    return { dids: rpMethods, codecName, keyType }\n  }\n\n  public async getSupportedIdentifiers(opts?: { createInCaseNoDIDFound?: boolean }): Promise<IIdentifier[]> {\n    // todo: we also need to check signature algo\n    const methods = await this.getSupportedDIDMethods(true)\n    logger.debug(`supported DID methods (did: prefix = true): ${JSON.stringify(methods)}`)\n    if (methods.length === 0) {\n      throw Error(`No DID methods are supported`)\n    }\n    const identifiers: IIdentifier[] = await this.context.agent\n      .didManagerFind()\n      .then((ids: IIdentifier[]) => ids.filter((id) => methods.includes(id.provider)))\n    if (identifiers.length === 0) {\n      logger.debug(`No identifiers available in agent supporting methods ${JSON.stringify(methods)}`)\n      if (opts?.createInCaseNoDIDFound !== false) {\n        const { codecName, keyType } = await this.getRPDIDMethodsSupported({\n          didPrefix: true,\n          agentMethods: methods,\n        })\n        const identifier = await this.context.agent.didManagerCreate({\n          provider: methods[0],\n          options: { codecName, keyType, type: keyType }, // both keyType and type, because not every did provider has the same param\n        })\n        logger.debug(`Created a new identifier for the SIOP interaction: ${identifier.did}`)\n        identifiers.push(identifier)\n      }\n    }\n    logger.debug(`supported identifiers: ${JSON.stringify(identifiers.map((id) => id.did))}`)\n    return identifiers\n  }\n\n  public async getSupportedDIDs(): Promise<string[]> {\n    return (await this.getSupportedIdentifiers()).map((id) => id.did)\n  }\n\n  public async getRedirectUri(): Promise<string> {\n    return Promise.resolve(this.verifiedAuthorizationRequest!.responseURI!)\n  }\n\n  public async hasPresentationDefinitions(): Promise<boolean> {\n    const defs = this._providedPresentationDefinitions ?? (await this.getAuthorizationRequest()).presentationDefinitions\n    return defs !== undefined && defs.length > 0\n  }\n\n  public async getPresentationDefinitions(): Promise<Array<PresentationDefinitionWithLocation> | undefined> {\n    if (!(await this.hasPresentationDefinitions())) {\n      throw Error(`No presentation definitions found`)\n    }\n    return this._providedPresentationDefinitions ?? (await this.getAuthorizationRequest()).presentationDefinitions\n  }\n\n  public async getOID4VP(args: IOpSessionGetOID4VPArgs): Promise<OID4VP> {\n    return await OID4VP.init(this, args.allIdentifiers ?? [], args.hasher)\n  }\n\n  private createPresentationVerificationCallback(context: IRequiredContext) {\n    async function presentationVerificationCallback(\n      args: W3CVerifiablePresentation | CompactSdJwtVc,\n      presentationSubmission?: PresentationSubmission,\n    ): Promise<PresentationVerificationResult> {\n      let result: IVerifyResult\n      if (CredentialMapper.isSdJwtEncoded(args)) {\n        try {\n          const sdJwtResult = await context.agent.verifySdJwtPresentation({ presentation: args })\n          result = {\n            verified: 'header' in sdJwtResult,\n            error: 'header' in sdJwtResult ? undefined : { message: 'could not verify SD JWT presentation' },\n          }\n        } catch (error: any) {\n          result = {\n            verified: false,\n            error: { message: error.message },\n          }\n        }\n      } else {\n        // @ts-ignore TODO IVerifiablePresentation has too many union types for Veramo\n        result = await context.agent.verifyPresentation({ presentation: args })\n      }\n      return result\n    }\n\n    return presentationVerificationCallback\n  }\n\n  private async createJarmResponseCallback({\n    responseOpts,\n  }: {\n    responseOpts: {\n      jwtIssuer?: JwtIssuer\n      version?: SupportedVersion\n      correlationId?: string\n      audience?: string\n      issuer?: ResponseIss | string\n      verification?: Verification\n    }\n  }) {\n    const agent = this.context.agent\n    return async function jarmResponse(opts: {\n      authorizationResponsePayload: AuthorizationResponsePayload\n      requestObjectPayload: RequestObjectPayload\n      clientMetadata: JwksMetadataParams\n    }): Promise<{ response: string }> {\n      const { clientMetadata, requestObjectPayload, authorizationResponsePayload: authResponse } = opts\n      const jwk = await OP.extractEncJwksFromClientMetadata(clientMetadata)\n      // @ts-ignore // FIXME: Fix jwk inference\n      const recipientKey = await agent.identifierExternalResolveByJwk({ identifier: jwk })\n\n      return await agent\n        .jwtEncryptJweCompactJwt({\n          recipientKey,\n          protectedHeader: {},\n          alg: (requestObjectPayload.client_metadata.authorization_encrypted_response_alg as JweAlg | undefined) ?? 'ECDH-ES',\n          enc: (requestObjectPayload.client_metadata.authorization_encrypted_response_enc as JweEnc | undefined) ?? 'A256GCM',\n          apv: encodeBase64url(opts.requestObjectPayload.nonce),\n          apu: encodeBase64url(v4()),\n          payload: authResponse,\n          issuer: responseOpts.issuer,\n          audience: responseOpts.audience,\n        })\n        .then((result) => {\n          return { response: result.jwt }\n        })\n    }\n  }\n\n  public async sendAuthorizationResponse(args: IOpsSendSiopAuthorizationResponseArgs): Promise<Response> {\n    const resolveOpts: ResolveOpts = this.options.resolveOpts ?? {\n      resolver: getAgentResolver(this.context, {\n        uniresolverResolution: true,\n        localResolution: true,\n        resolverResolution: true,\n      }),\n    }\n    if (!resolveOpts.subjectSyntaxTypesSupported || resolveOpts.subjectSyntaxTypesSupported.length === 0) {\n      resolveOpts.subjectSyntaxTypesSupported = await this.getSupportedDIDMethods(true)\n    }\n    //todo: populate with the right verification params. In did-auth-siop we don't have any test that actually passes this parameter\n    const verification: Verification = {\n      presentationVerificationCallback: this.createPresentationVerificationCallback(this.context),\n    }\n    const request = await this.getAuthorizationRequest()\n    const hasDefinitions = await this.hasPresentationDefinitions()\n    if (hasDefinitions) {\n      const totalInputDescriptors = request.presentationDefinitions?.reduce((sum, pd) => {\n        return sum + pd.definition.input_descriptors.length\n      }, 0)\n      const totalVCs = args.verifiablePresentations ? this.countVCsInAllVPs(args.verifiablePresentations, args.hasher) : 0\n\n      if (!request.presentationDefinitions || !args.verifiablePresentations || totalVCs !== totalInputDescriptors) {\n        throw Error(\n          `Amount of presentations ${args.verifiablePresentations?.length}, doesn't match expected ${request.presentationDefinitions?.length}`,\n        )\n      } else if (!args.presentationSubmission) {\n        throw Error(`Presentation submission is required when verifiable presentations are required`)\n      }\n    }\n\n    const verifiablePresentations = args.verifiablePresentations\n      ? args.verifiablePresentations.map((vp) => CredentialMapper.storedPresentationToOriginalFormat(vp))\n      : []\n    const op = await createOP({\n      opOptions: {\n        ...this.options,\n        resolveOpts: { ...this.options.resolveOpts },\n        eventEmitter: this.options.eventEmitter,\n        presentationSignCallback: this.options.presentationSignCallback,\n        wellknownDIDVerifyCallback: this.options.wellknownDIDVerifyCallback,\n        supportedVersions: request.versions,\n      },\n      idOpts: args.responseSignerOpts,\n      context: this.context,\n    })\n\n    //TODO change this to use the new functionalities by identifier-resolver and get the jwkIssuer for the responseOpts\n    let issuer = args.responseSignerOpts.issuer\n    const responseOpts = {\n      verification,\n      issuer,\n      ...(args.isFirstParty && { isFirstParty: args.isFirstParty }),\n      ...(args.verifiablePresentations && {\n        presentationExchange: {\n          verifiablePresentations,\n          presentationSubmission: args.presentationSubmission,\n        } as PresentationExchangeResponseOpts,\n      }),\n      dcqlQuery: args.dcqlResponse,\n    }\n\n    const authResponse = await op.createAuthorizationResponse(request, responseOpts)\n    const response = await op.submitAuthorizationResponse(authResponse, await this.createJarmResponseCallback({ responseOpts }))\n\n    if (response.status >= 400) {\n      throw Error(`Error ${response.status}: ${response.statusText || (await response.text())}`)\n    } else {\n      return response\n    }\n  }\n\n  private countVCsInAllVPs(verifiablePresentations: W3CVerifiablePresentation[], hasher?: HasherSync) {\n    return verifiablePresentations.reduce((sum, vp) => {\n      if (CredentialMapper.isMsoMdocDecodedPresentation(vp) || CredentialMapper.isMsoMdocOid4VPEncoded(vp)) {\n        return sum + 1\n      }\n\n      const uvp = CredentialMapper.toUniformPresentation(vp, { hasher: hasher ?? this.options.hasher })\n      if (uvp.verifiableCredential?.length) {\n        return sum + uvp.verifiableCredential?.length\n      }\n      const isSdJWT = CredentialMapper.isSdJwtDecodedCredential(uvp)\n      if (\n        isSdJWT ||\n        (uvp.verifiableCredential && !PEX.allowMultipleVCsPerPresentation(uvp.verifiableCredential as Array<OriginalVerifiableCredential>))\n      ) {\n        return sum + 1\n      }\n      return sum\n    }, 0)\n  }\n}\n\nfunction convertDidMethod(didMethod: string, didPrefix?: boolean): string {\n  if (didPrefix === false) {\n    return didMethod.startsWith('did:') ? didMethod.toLowerCase().replace('did:', '') : didMethod.toLowerCase()\n  }\n  return didMethod.startsWith('did:') ? didMethod.toLowerCase() : `did:${didMethod.toLowerCase().replace('did:', '')}`\n}\n","import { VerifiedAuthorizationRequest } from '@sphereon/did-auth-siop'\nimport { DidAuthConfig, Identity, Party } from '@sphereon/ssi-sdk.data-store'\nimport { assign, createMachine, DoneInvokeEvent, interpret } from 'xstate'\nimport { translate } from '../localization/Localization'\nimport { ErrorDetails } from '../types'\nimport {\n  ContactAliasEvent,\n  ContactConsentEvent,\n  CreateContactEvent,\n  CreateSiopv2MachineOpts,\n  SelectCredentialsEvent,\n  Siopv2MachineAddContactStates,\n  Siopv2MachineContext,\n  Siopv2MachineEvents,\n  Siopv2MachineEventTypes,\n  Siopv2MachineGuards,\n  Siopv2MachineInstanceOpts,\n  Siopv2MachineInterpreter,\n  Siopv2MachineServices,\n  Siopv2MachineState,\n  Siopv2MachineStates,\n  Siopv2StateMachine,\n} from '../types'\nimport { LOGGER_NAMESPACE, SelectableCredentialsMap, Siopv2AuthorizationRequestData, Siopv2AuthorizationResponseData } from '../types'\nimport { Loggers } from '@sphereon/ssi-types'\n\nexport const logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\nconst Siopv2HasNoContactGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { contact } = _ctx\n  return contact === undefined\n}\n\nconst Siopv2HasContactGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { contact } = _ctx\n  return contact !== undefined\n}\n\nconst Siopv2HasAuthorizationRequestGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { authorizationRequestData } = _ctx\n  return authorizationRequestData !== undefined\n}\n\nconst Siopv2HasSelectableCredentialsAndContactGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { authorizationRequestData, contact } = _ctx\n\n  if (!authorizationRequestData) {\n    throw new Error('Missing authorization request data in context')\n  }\n  if (!contact) {\n    throw new Error('Missing contact request data in context')\n  }\n\n  return authorizationRequestData.presentationDefinitions !== undefined\n}\n\nconst Siopv2CreateContactGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { contactAlias, hasContactConsent } = _ctx\n\n  return hasContactConsent && contactAlias !== undefined && contactAlias.length > 0\n}\n\nconst Siopv2HasSelectedRequiredCredentialsGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { authorizationRequestData } = _ctx\n\n  if (authorizationRequestData === undefined) {\n    throw new Error('Missing authorization request data in context')\n  }\n\n  if (authorizationRequestData.presentationDefinitions === undefined || authorizationRequestData.presentationDefinitions.length === 0) {\n    throw Error('No presentation definitions present')\n  }\n\n  // FIXME: Return _ctx.selectedCredentials.length > 0 for now, given this is a really expensive operation and will be called in the next phase anyway\n  return _ctx.selectedCredentials.length > 0\n  /*const definitionWithLocation: PresentationDefinitionWithLocation = authorizationRequestData.presentationDefinitions[0];\n        const pex: PEX = new PEX();\n        const evaluationResults: EvaluationResults = pex.evaluateCredentials(definitionWithLocation.definition, selectedCredentials);\n\n        return evaluationResults.areRequiredCredentialsPresent === Status.INFO;*/\n}\n\nconst Siopv2IsSiopOnlyGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { authorizationRequestData } = _ctx\n\n  if (authorizationRequestData === undefined) {\n    throw new Error('Missing authorization request data in context')\n  }\n\n  return authorizationRequestData.presentationDefinitions === undefined\n}\n\nconst Siopv2IsSiopWithOID4VPGuard = (_ctx: Siopv2MachineContext, _event: Siopv2MachineEventTypes): boolean => {\n  const { authorizationRequestData, selectableCredentialsMap } = _ctx\n\n  if (!authorizationRequestData) {\n    throw new Error('Missing authorization request data in context')\n  }\n\n  if (!selectableCredentialsMap) {\n    throw new Error('Missing selectableCredentialsMap in context')\n  }\n\n  return authorizationRequestData.presentationDefinitions !== undefined\n}\n\nconst createSiopv2Machine = (opts: CreateSiopv2MachineOpts): Siopv2StateMachine => {\n  const { url, idOpts } = opts\n  const initialContext: Siopv2MachineContext = {\n    url: new URL(url).toString(),\n    hasContactConsent: true,\n    contactAlias: '',\n    selectedCredentials: [],\n    idOpts: idOpts,\n  }\n\n  return createMachine<Siopv2MachineContext, Siopv2MachineEventTypes>({\n    id: opts?.machineId ?? 'Siopv2',\n    predictableActionArguments: true,\n    initial: Siopv2MachineStates.createConfig,\n    schema: {\n      events: {} as Siopv2MachineEventTypes,\n      guards: {} as\n        | { type: Siopv2MachineGuards.hasNoContactGuard }\n        | { type: Siopv2MachineGuards.hasContactGuard }\n        | { type: Siopv2MachineGuards.createContactGuard }\n        | { type: Siopv2MachineGuards.hasAuthorizationRequestGuard }\n        | { type: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard }\n        | { type: Siopv2MachineGuards.hasSelectedRequiredCredentialsGuard },\n      services: {} as {\n        [Siopv2MachineServices.createConfig]: {\n          data: DidAuthConfig\n        }\n        [Siopv2MachineServices.getSiopRequest]: {\n          data: VerifiedAuthorizationRequest\n        }\n        [Siopv2MachineServices.getSelectableCredentials]: {\n          data: SelectableCredentialsMap\n        }\n        [Siopv2MachineServices.retrieveContact]: {\n          data: Party | undefined\n        }\n        [Siopv2MachineServices.addContactIdentity]: {\n          data: void\n        }\n        [Siopv2MachineServices.sendResponse]: {\n          data: void\n        }\n      },\n    },\n    context: initialContext,\n    states: {\n      [Siopv2MachineStates.createConfig]: {\n        id: Siopv2MachineStates.createConfig,\n        invoke: {\n          src: Siopv2MachineServices.createConfig,\n          onDone: {\n            target: Siopv2MachineStates.getSiopRequest,\n            actions: assign({\n              didAuthConfig: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<DidAuthConfig>) => _event.data,\n            }),\n          },\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_create_config_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n      [Siopv2MachineStates.getSiopRequest]: {\n        id: Siopv2MachineStates.getSiopRequest,\n        invoke: {\n          src: Siopv2MachineServices.getSiopRequest,\n          onDone: {\n            target: Siopv2MachineStates.retrieveContact,\n            actions: assign({\n              authorizationRequestData: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Siopv2AuthorizationRequestData>) => _event.data,\n            }),\n          },\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_get_request_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n      [Siopv2MachineStates.retrieveContact]: {\n        id: Siopv2MachineStates.retrieveContact,\n        invoke: {\n          src: Siopv2MachineServices.retrieveContact,\n          onDone: {\n            target: Siopv2MachineStates.transitionFromSetup,\n            actions: assign({ contact: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Party>) => _event.data }),\n          },\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_retrieve_contact_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n      [Siopv2MachineStates.transitionFromSetup]: {\n        id: Siopv2MachineStates.transitionFromSetup,\n        always: [\n          {\n            target: Siopv2MachineStates.addContact,\n            cond: Siopv2MachineGuards.hasNoContactGuard,\n          },\n          {\n            target: Siopv2MachineStates.sendResponse,\n            cond: Siopv2MachineGuards.siopOnlyGuard,\n          },\n          {\n            target: Siopv2MachineStates.getSelectableCredentials,\n            cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard,\n          },\n          {\n            target: Siopv2MachineStates.selectCredentials,\n            cond: Siopv2MachineGuards.siopWithOID4VPGuard,\n          },\n        ],\n      },\n      [Siopv2MachineStates.addContact]: {\n        id: Siopv2MachineStates.addContact,\n        initial: Siopv2MachineAddContactStates.idle,\n        on: {\n          [Siopv2MachineEvents.SET_CONTACT_CONSENT]: {\n            actions: assign({ hasContactConsent: (_ctx: Siopv2MachineContext, _event: ContactConsentEvent) => _event.data }),\n          },\n          [Siopv2MachineEvents.SET_CONTACT_ALIAS]: {\n            actions: assign({ contactAlias: (_ctx: Siopv2MachineContext, _event: ContactAliasEvent) => _event.data }),\n          },\n          [Siopv2MachineEvents.CREATE_CONTACT]: {\n            target: `.${Siopv2MachineAddContactStates.next}`,\n            actions: assign({ contact: (_ctx: Siopv2MachineContext, _event: CreateContactEvent) => _event.data }),\n            cond: Siopv2MachineGuards.createContactGuard,\n          },\n          [Siopv2MachineEvents.DECLINE]: {\n            target: Siopv2MachineStates.declined,\n          },\n          [Siopv2MachineEvents.PREVIOUS]: {\n            target: Siopv2MachineStates.aborted,\n          },\n        },\n        states: {\n          [Siopv2MachineAddContactStates.idle]: {},\n          [Siopv2MachineAddContactStates.next]: {\n            always: {\n              target: `#${Siopv2MachineStates.transitionFromSetup}`,\n              cond: Siopv2MachineGuards.hasContactGuard,\n            },\n          },\n        },\n      },\n      [Siopv2MachineStates.addContactIdentity]: {\n        id: Siopv2MachineStates.addContactIdentity,\n        invoke: {\n          src: Siopv2MachineServices.addContactIdentity,\n          onDone: [\n            {\n              target: Siopv2MachineStates.getSelectableCredentials,\n              actions: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Identity>): void => {\n                _ctx.contact?.identities.push(_event.data)\n              },\n              cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard,\n            },\n            {\n              target: Siopv2MachineStates.sendResponse,\n              actions: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Identity>): void => {\n                _ctx.contact?.identities.push(_event.data)\n              },\n              cond: Siopv2MachineGuards.siopOnlyGuard,\n            },\n          ],\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_add_contact_identity_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n      [Siopv2MachineStates.getSelectableCredentials]: {\n        id: Siopv2MachineStates.getSelectableCredentials,\n        invoke: {\n          src: Siopv2MachineServices.getSelectableCredentials,\n          onDone: {\n            target: Siopv2MachineStates.selectCredentials,\n            actions: assign({\n              selectableCredentialsMap: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<SelectableCredentialsMap>) => _event.data,\n            }),\n          },\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_get_selectable_credentials_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n\n      [Siopv2MachineStates.selectCredentials]: {\n        id: Siopv2MachineStates.selectCredentials,\n        on: {\n          [Siopv2MachineEvents.SET_SELECTED_CREDENTIALS]: {\n            actions: assign({ selectedCredentials: (_ctx: Siopv2MachineContext, _event: SelectCredentialsEvent) => _event.data }),\n          },\n          [Siopv2MachineEvents.NEXT]: {\n            target: Siopv2MachineStates.sendResponse,\n            cond: Siopv2MachineGuards.hasSelectedRequiredCredentialsGuard,\n          },\n          [Siopv2MachineEvents.DECLINE]: {\n            target: Siopv2MachineStates.declined,\n          },\n          [Siopv2MachineEvents.PREVIOUS]: {\n            target: Siopv2MachineStates.aborted,\n          },\n        },\n      },\n      [Siopv2MachineStates.sendResponse]: {\n        id: Siopv2MachineStates.sendResponse,\n        invoke: {\n          src: Siopv2MachineServices.sendResponse,\n          onDone: {\n            target: Siopv2MachineStates.done,\n            actions: assign({\n              authorizationResponseData: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Siopv2AuthorizationResponseData>) => _event.data,\n            }),\n          },\n          onError: {\n            target: Siopv2MachineStates.handleError,\n            actions: assign({\n              error: (_ctx: Siopv2MachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n                title: translate('siopv2_machine_send_response_error_title'),\n                message: _event.data.message,\n                stack: _event.data.stack,\n              }),\n            }),\n          },\n        },\n      },\n      [Siopv2MachineStates.handleError]: {\n        id: Siopv2MachineStates.handleError,\n        on: {\n          [Siopv2MachineEvents.NEXT]: {\n            target: Siopv2MachineStates.error,\n          },\n          [Siopv2MachineEvents.PREVIOUS]: {\n            target: Siopv2MachineStates.error,\n          },\n        },\n      },\n      [Siopv2MachineStates.aborted]: {\n        id: Siopv2MachineStates.aborted,\n        type: 'final',\n      },\n      [Siopv2MachineStates.declined]: {\n        id: Siopv2MachineStates.declined,\n        type: 'final',\n      },\n      [Siopv2MachineStates.error]: {\n        id: Siopv2MachineStates.error,\n        type: 'final',\n      },\n      [Siopv2MachineStates.done]: {\n        id: Siopv2MachineStates.done,\n        type: 'final',\n      },\n    },\n  })\n}\n\nexport class Siopv2Machine {\n  static newInstance(opts: Siopv2MachineInstanceOpts): { interpreter: Siopv2MachineInterpreter } {\n    logger.info('New Siopv2Machine instance')\n    const interpreter: Siopv2MachineInterpreter = interpret(\n      createSiopv2Machine(opts).withConfig({\n        services: {\n          ...opts?.services,\n        },\n        guards: {\n          Siopv2HasNoContactGuard,\n          Siopv2HasContactGuard,\n          Siopv2HasAuthorizationRequestGuard,\n          Siopv2HasSelectableCredentialsAndContactGuard,\n          Siopv2HasSelectedRequiredCredentialsGuard,\n          Siopv2IsSiopOnlyGuard,\n          Siopv2IsSiopWithOID4VPGuard,\n          Siopv2CreateContactGuard,\n          ...opts?.guards,\n        },\n      }),\n    )\n\n    if (typeof opts?.subscription === 'function') {\n      interpreter.onTransition(opts.subscription)\n    }\n\n    if (opts?.requireCustomNavigationHook !== true) {\n      interpreter.onTransition((snapshot: Siopv2MachineState): void => {\n        if (opts.stateNavigationListener !== undefined) {\n          void opts.stateNavigationListener(interpreter, snapshot)\n        }\n      })\n    }\n    interpreter.onTransition((snapshot: Siopv2MachineState): void => {\n      logger.info('onTransition to new state', snapshot.value)\n    })\n\n    return { interpreter }\n  }\n}\n","import i18n, { Scope, TranslateOptions } from 'i18n-js'\nimport memoize from 'lodash.memoize'\nimport { SupportedLanguage } from '../types'\n\nclass Localization {\n  private static translationGetters: { [locale: string]: () => object } = {\n    [SupportedLanguage.ENGLISH]: () => require('./translations/en.json'),\n    [SupportedLanguage.DUTCH]: () => require('./translations/nl.json'),\n  }\n\n  public static translate: any = memoize(\n    (key: Scope, config?: TranslateOptions) => {\n      // If no LocaleProvider is used we need to load the default locale as the translations will be empty\n      if (Object.keys(i18n.translations).length === 0) {\n        i18n.translations = {\n          [SupportedLanguage.ENGLISH]: Localization.translationGetters[SupportedLanguage.ENGLISH](),\n        }\n        i18n.locale = SupportedLanguage.ENGLISH\n      } else {\n        i18n.translations = {\n          [i18n.locale]: {\n            ...i18n.translations[i18n.locale],\n            ...Localization.translationGetters[this.findSupportedLanguage(i18n.locale) || SupportedLanguage.ENGLISH](),\n          },\n        }\n      }\n\n      return i18n.t(key, config)\n    },\n    (key: Scope, config?: TranslateOptions) => (config ? key + JSON.stringify(config) : key),\n  )\n\n  private static findSupportedLanguage = (locale: string): string | undefined => {\n    for (const language of Object.values(SupportedLanguage)) {\n      if (language === locale) {\n        return language\n      }\n    }\n\n    return undefined\n  }\n\n  public static getLocale = (): string => {\n    return i18n.locale || SupportedLanguage.ENGLISH\n  }\n}\n\nexport const translate = Localization.translate\nexport default Localization\n","import { AuthorizationRequest, SupportedVersion } from '@sphereon/did-auth-siop'\nimport { IPresentationDefinition, PEX } from '@sphereon/pex'\nimport { InputDescriptorV1, InputDescriptorV2, PresentationDefinitionV1, PresentationDefinitionV2 } from '@sphereon/pex-models'\nimport { isOID4VCIssuerIdentifier, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { UniqueDigitalCredential, verifiableCredentialForRoleFilter } from '@sphereon/ssi-sdk.credential-store'\nimport { ConnectionType, CredentialRole } from '@sphereon/ssi-sdk.data-store'\nimport { CredentialMapper, HasherSync, Loggers, OriginalVerifiableCredential, PresentationSubmission } from '@sphereon/ssi-types'\nimport { OID4VP, OpSession } from '../session'\nimport {\n  DidAgents,\n  LOGGER_NAMESPACE,\n  RequiredContext,\n  SelectableCredential,\n  SelectableCredentialsMap,\n  Siopv2HolderEvent,\n  SuitableCredentialAgents,\n  VerifiableCredentialsWithDefinition,\n  VerifiablePresentationWithDefinition,\n} from '../types'\nimport { IAgentContext, IDIDManager } from '@veramo/core'\nimport { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport { defaultHasher, encodeJoseBlob } from '@sphereon/ssi-sdk.core'\nimport { DcqlCredential, DcqlCredentialPresentation, DcqlPresentation, DcqlQuery } from 'dcql'\nimport { convertToDcqlCredentials } from '../utils/dcql'\nimport { getOriginalVerifiableCredential } from '../utils/CredentialUtils'\n\nexport const logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\nconst createEbsiIdentifier = async (agentContext: IAgentContext<IDIDManager>): Promise<ManagedIdentifierOptsOrResult> => {\n  logger.log(`No EBSI key present yet. Creating a new one...`)\n  const { result: newIdentifier, created } = await getOrCreatePrimaryIdentifier(agentContext, {\n    method: SupportedDidMethodEnum.DID_KEY,\n    createOpts: { options: { codecName: 'jwk_jcs-pub', type: 'Secp256r1' } },\n  })\n  logger.log(`EBSI key created: ${newIdentifier.did}`)\n  if (created) {\n    await agentContext.agent.emit(Siopv2HolderEvent.IDENTIFIER_CREATED, { result: newIdentifier })\n  }\n  return await agentContext.agent.identifierManagedGetByDid({ identifier: newIdentifier.did })\n}\n\nconst hasEbsiClient = async (authorizationRequest: AuthorizationRequest) => {\n  const clientId = await authorizationRequest.getMergedProperty<string>('client_id')\n  const redirectUri = await authorizationRequest.getMergedProperty<string>('redirect_uri')\n  return clientId?.toLowerCase().includes('.ebsi.eu') || redirectUri?.toLowerCase().includes('.ebsi.eu')\n}\n\nexport const siopSendAuthorizationResponse = async (\n  connectionType: ConnectionType,\n  args: {\n    sessionId: string\n    verifiableCredentialsWithDefinition?: VerifiableCredentialsWithDefinition[]\n    idOpts?: ManagedIdentifierOptsOrResult\n    isFirstParty?: boolean\n    hasher?: HasherSync\n    dcqlQuery?: DcqlQuery\n  },\n  context: RequiredContext,\n) => {\n  const { agent } = context\n  const agentContext = { ...context, agent: context.agent as DidAgents }\n  let { idOpts, isFirstParty, hasher = defaultHasher } = args\n\n  if (connectionType !== ConnectionType.SIOPv2_OpenID4VP) {\n    return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`))\n  }\n  const session: OpSession = await agent.siopGetOPSession({ sessionId: args.sessionId })\n  const request = await session.getAuthorizationRequest()\n  const aud = await request.authorizationRequest.getMergedProperty<string>('aud')\n  logger.debug(`AUD: ${aud}`)\n  logger.debug(JSON.stringify(request.authorizationRequest))\n\n  let presentationsAndDefs: VerifiablePresentationWithDefinition[] | undefined\n  let presentationSubmission: PresentationSubmission | undefined\n  if (await session.hasPresentationDefinitions()) {\n    const oid4vp: OID4VP = await session.getOID4VP({ hasher })\n\n    const credentialsAndDefinitions = args.verifiableCredentialsWithDefinition\n      ? args.verifiableCredentialsWithDefinition\n      : await oid4vp.filterCredentialsAgainstAllDefinitions(CredentialRole.HOLDER)\n    const domain =\n      ((await request.authorizationRequest.getMergedProperty('client_id')) as string) ??\n      request.issuer ??\n      (request.versions.includes(SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1)\n        ? 'https://self-issued.me/v2/openid-vc'\n        : 'https://self-issued.me/v2')\n    logger.log(`NONCE: ${session.nonce}, domain: ${domain}`)\n\n    const firstUniqueDC = credentialsAndDefinitions[0].credentials[0]\n    if (typeof firstUniqueDC !== 'object' || !('digitalCredential' in firstUniqueDC)) {\n      return Promise.reject(Error('SiopMachine only supports UniqueDigitalCredentials for now'))\n    }\n\n    let identifier: ManagedIdentifierOptsOrResult\n    const digitalCredential = firstUniqueDC.digitalCredential\n    const firstVC = firstUniqueDC.uniformVerifiableCredential\n    const holder = CredentialMapper.isSdJwtDecodedCredential(firstVC)\n      ? firstVC.decodedPayload.cnf?.jwk\n        ? //TODO SDK-19: convert the JWK to hex and search for the appropriate key and associated DID\n          //doesn't apply to did:jwk only, as you can represent any DID key as a JWK. So whenever you encounter a JWK it doesn't mean it had to come from a did:jwk in the system. It just can always be represented as a did:jwk\n          `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0`\n        : firstVC.decodedPayload.sub\n      : Array.isArray(firstVC.credentialSubject)\n        ? firstVC.credentialSubject[0].id\n        : firstVC.credentialSubject.id\n    if (!digitalCredential.kmsKeyRef) {\n      // In case the store does not have the kmsKeyRef lets search for the holder\n\n      if (!holder) {\n        return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`)\n      }\n      try {\n        identifier = await session.context.agent.identifierManagedGet({ identifier: holder })\n      } catch (e) {\n        logger.debug(`Holder DID not found: ${holder}`)\n        throw e\n      }\n    } else if (isOID4VCIssuerIdentifier(digitalCredential.kmsKeyRef)) {\n      identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({\n        identifier: firstUniqueDC.digitalCredential.kmsKeyRef,\n      })\n    } else {\n      switch (digitalCredential.subjectCorrelationType) {\n        case 'DID':\n          identifier = await session.context.agent.identifierManagedGetByDid({\n            identifier: digitalCredential.subjectCorrelationId ?? holder,\n            kmsKeyRef: digitalCredential.kmsKeyRef,\n          })\n          break\n        // TODO other implementations?\n        default:\n          if (digitalCredential.subjectCorrelationId?.startsWith('did:') || holder?.startsWith('did:')) {\n            identifier = await session.context.agent.identifierManagedGetByDid({\n              identifier: digitalCredential.subjectCorrelationId ?? holder,\n              kmsKeyRef: digitalCredential.kmsKeyRef,\n            })\n          } else {\n            // Since we are using the kmsKeyRef we will find the KID regardless of the identifier. We set it for later access though\n            identifier = await session.context.agent.identifierManagedGetByKid({\n              identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,\n              kmsKeyRef: digitalCredential.kmsKeyRef,\n            })\n          }\n      }\n    }\n\n    if (identifier === undefined && idOpts !== undefined && (await hasEbsiClient(request.authorizationRequest))) {\n      identifier = await createEbsiIdentifier(agentContext)\n    }\n    logger.debug(`Identifier`, identifier)\n\n    // TODO Add mdoc support\n\n    presentationsAndDefs = await oid4vp.createVerifiablePresentations(CredentialRole.HOLDER, credentialsAndDefinitions, {\n      idOpts: identifier,\n      proofOpts: {\n        nonce: session.nonce,\n        domain,\n      },\n    })\n    if (!presentationsAndDefs || presentationsAndDefs.length === 0) {\n      throw Error('No verifiable presentations could be created')\n    } else if (presentationsAndDefs.length > 1) {\n      throw Error(`Only one verifiable presentation supported for now. Got ${presentationsAndDefs.length}`)\n    }\n\n    idOpts = presentationsAndDefs[0].idOpts\n    presentationSubmission = presentationsAndDefs[0].presentationSubmission\n\n    logger.log(`Definitions and locations:`, JSON.stringify(presentationsAndDefs?.[0]?.verifiablePresentations, null, 2))\n    logger.log(`Presentation Submission:`, JSON.stringify(presentationSubmission, null, 2))\n    const mergedVerifiablePresentations = presentationsAndDefs?.flatMap((pd) => pd.verifiablePresentations) || []\n    return await session.sendAuthorizationResponse({\n      ...(presentationsAndDefs && { verifiablePresentations: mergedVerifiablePresentations }),\n      ...(presentationSubmission && { presentationSubmission }),\n      // todo: Change issuer value in case we do not use identifier. Use key.meta.jwkThumbprint then\n      responseSignerOpts: idOpts!,\n      isFirstParty,\n    })\n  } else if (request.dcqlQuery) {\n    if (args.verifiableCredentialsWithDefinition !== undefined && args.verifiableCredentialsWithDefinition !== null) {\n      const vcs = args.verifiableCredentialsWithDefinition.flatMap((vcd) => vcd.credentials)\n      const domain =\n        ((await request.authorizationRequest.getMergedProperty('client_id')) as string) ??\n        request.issuer ??\n        (request.versions.includes(SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1)\n          ? 'https://self-issued.me/v2/openid-vc'\n          : 'https://self-issued.me/v2')\n      logger.debug(`NONCE: ${session.nonce}, domain: ${domain}`)\n\n      const firstUniqueDC = vcs[0]\n      if (typeof firstUniqueDC !== 'object' || !('digitalCredential' in firstUniqueDC)) {\n        return Promise.reject(Error('SiopMachine only supports UniqueDigitalCredentials for now'))\n      }\n\n      let identifier: ManagedIdentifierOptsOrResult\n      const digitalCredential = firstUniqueDC.digitalCredential\n      const firstVC = firstUniqueDC.uniformVerifiableCredential\n      const holder = CredentialMapper.isSdJwtDecodedCredential(firstVC)\n        ? firstVC.decodedPayload.cnf?.jwk\n          ? //TODO SDK-19: convert the JWK to hex and search for the appropriate key and associated DID\n            //doesn't apply to did:jwk only, as you can represent any DID key as a JWK. So whenever you encounter a JWK it doesn't mean it had to come from a did:jwk in the system. It just can always be represented as a did:jwk\n            `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0`\n          : firstVC.decodedPayload.sub\n        : Array.isArray(firstVC.credentialSubject)\n          ? firstVC.credentialSubject[0].id\n          : firstVC.credentialSubject.id\n      if (!digitalCredential.kmsKeyRef) {\n        // In case the store does not have the kmsKeyRef lets search for the holder\n\n        if (!holder) {\n          return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`)\n        }\n        try {\n          identifier = await session.context.agent.identifierManagedGet({ identifier: holder })\n        } catch (e) {\n          logger.debug(`Holder DID not found: ${holder}`)\n          throw e\n        }\n      } else if (isOID4VCIssuerIdentifier(digitalCredential.kmsKeyRef)) {\n        identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({\n          identifier: firstUniqueDC.digitalCredential.kmsKeyRef,\n        })\n      } else {\n        switch (digitalCredential.subjectCorrelationType) {\n          case 'DID':\n            identifier = await session.context.agent.identifierManagedGetByDid({\n              identifier: digitalCredential.subjectCorrelationId ?? holder,\n              kmsKeyRef: digitalCredential.kmsKeyRef,\n            })\n            break\n          // TODO other implementations?\n          default:\n            // Since we are using the kmsKeyRef we will find the KID regardless of the identifier. We set it for later access though\n            identifier = await session.context.agent.identifierManagedGetByKid({\n              identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,\n              kmsKeyRef: digitalCredential.kmsKeyRef,\n            })\n        }\n      }\n      console.log(`Identifier`, identifier)\n\n      const dcqlRepresentations: DcqlCredential[] = []\n      vcs.forEach((vc: UniqueDigitalCredential | OriginalVerifiableCredential) => {\n        const rep = convertToDcqlCredentials(vc, args.hasher)\n        if (rep) {\n          dcqlRepresentations.push(rep)\n        }\n      })\n\n      const queryResult = DcqlQuery.query(request.dcqlQuery, dcqlRepresentations)\n      const presentation: Record<string, DcqlCredentialPresentation> = {}\n\n      for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n        const allMatches = Array.isArray(value) ? value : [value]\n        allMatches.forEach((match) => {\n          if (match.success) {\n            const originalCredential = getOriginalVerifiableCredential(vcs[match.input_credential_index])\n            if (!originalCredential) {\n              throw new Error(`Index ${match.input_credential_index} out of range in credentials array`)\n            }\n            presentation[key] =\n              (originalCredential as any)['compactSdJwtVc'] !== undefined ? (originalCredential as any).compactSdJwtVc : originalCredential\n          }\n        })\n      }\n\n      const response = session.sendAuthorizationResponse({\n        responseSignerOpts: identifier,\n        ...{ dcqlQuery: { dcqlPresentation: DcqlPresentation.parse(presentation) } },\n      })\n\n      logger.debug(`Response: `, response)\n\n      return response\n    }\n  }\n  throw Error('Presentation Definition or DCQL is required')\n}\n\nfunction buildPartialPD(\n  inputDescriptor: InputDescriptorV1 | InputDescriptorV2,\n  presentationDefinition: PresentationDefinitionV1 | PresentationDefinitionV2,\n): IPresentationDefinition {\n  return {\n    ...presentationDefinition,\n    input_descriptors: [inputDescriptor],\n  } as IPresentationDefinition\n}\n\nexport const getSelectableCredentials = async (\n  presentationDefinition: IPresentationDefinition,\n  context: RequiredContext,\n): Promise<SelectableCredentialsMap> => {\n  const agentContext = { ...context, agent: context.agent as SuitableCredentialAgents }\n  const { agent } = agentContext\n  const pex = new PEX()\n\n  const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({\n    filter: verifiableCredentialForRoleFilter(CredentialRole.HOLDER),\n  })\n  const credentialBranding = await agent.ibGetCredentialBranding()\n\n  const selectableCredentialsMap: SelectableCredentialsMap = new Map()\n\n  for (const inputDescriptor of presentationDefinition.input_descriptors) {\n    const partialPD = buildPartialPD(inputDescriptor, presentationDefinition)\n    const originalCredentials = uniqueVerifiableCredentials.map((uniqueVC) => {\n      return CredentialMapper.storedCredentialToOriginalFormat(uniqueVC.originalVerifiableCredential!) // ( ! is valid for verifiableCredentialForRoleFilter )\n    })\n    const selectionResults = pex.selectFrom(partialPD, originalCredentials)\n\n    const selectableCredentials: Array<SelectableCredential> = []\n    for (const selectedCredential of selectionResults.verifiableCredential || []) {\n      const filteredUniqueVC = uniqueVerifiableCredentials.find((uniqueVC) => {\n        const proof = uniqueVC.uniformVerifiableCredential!.proof\n        return Array.isArray(proof) ? proof.some((proofItem) => proofItem.jwt === selectedCredential) : proof.jwt === selectedCredential\n      })\n\n      if (filteredUniqueVC) {\n        const filteredCredentialBrandings = credentialBranding.filter((cb) => cb.vcHash === filteredUniqueVC.hash)\n        const issuerPartyIdentity = await agent.cmGetContacts({\n          filter: [{ identities: { identifier: { correlationId: filteredUniqueVC.uniformVerifiableCredential!.issuerDid } } }],\n        })\n        const subjectPartyIdentity = await agent.cmGetContacts({\n          filter: [{ identities: { identifier: { correlationId: filteredUniqueVC.uniformVerifiableCredential!.subjectDid } } }],\n        })\n\n        selectableCredentials.push({\n          credential: filteredUniqueVC,\n          credentialBranding: filteredCredentialBrandings[0]?.localeBranding,\n          issuerParty: issuerPartyIdentity?.[0],\n          subjectParty: subjectPartyIdentity?.[0],\n        })\n      }\n    }\n    selectableCredentialsMap.set(inputDescriptor.id, selectableCredentials)\n  }\n  return selectableCredentialsMap\n}\n\nexport const translateCorrelationIdToName = async (correlationId: string, context: RequiredContext): Promise<string | undefined> => {\n  const { agent } = context\n\n  const contacts = await agent.cmGetContacts({\n    filter: [{ identities: { identifier: { correlationId } } }],\n  })\n\n  if (contacts.length === 0) {\n    return undefined\n  }\n\n  return contacts[0].contact.displayName\n}\n","import { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { DcqlCredential, DcqlSdJwtVcCredential, DcqlW3cVcCredential } from 'dcql'\nimport { CredentialMapper, HasherSync, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { isUniqueDigitalCredential } from './CredentialUtils'\n\nexport function convertToDcqlCredentials(credential: UniqueDigitalCredential | OriginalVerifiableCredential, hasher?: HasherSync): DcqlCredential {\n  let payload\n  if (isUniqueDigitalCredential(credential)) {\n    if (!credential.originalVerifiableCredential) {\n      throw new Error('originalVerifiableCredential is not defined in UniqueDigitalCredential')\n    }\n    payload = CredentialMapper.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher)\n  } else {\n    payload = CredentialMapper.decodeVerifiableCredential(credential as OriginalVerifiableCredential, hasher)\n  }\n\n  if (!payload) {\n    throw new Error('No payload found')\n  }\n\n  if ('decodedPayload' in payload && payload.decodedPayload) {\n    payload = payload.decodedPayload\n  }\n\n  if ('vct' in payload!) {\n    return { vct: payload.vct, claims: payload, credential_format: 'vc+sd-jwt' } satisfies DcqlSdJwtVcCredential // TODO dc+sd-jwt support?\n  } else if ('docType' in payload! && 'namespaces' in payload) {\n    // mdoc\n    return { docType: payload.docType, namespaces: payload.namespaces, claims: payload }\n  } else {\n    return {\n      claims: payload,\n      credential_format: 'jwt_vc_json', // TODO jwt_vc_json-ld support\n    } as DcqlW3cVcCredential\n  }\n}\n","import { CredentialMapper, HasherSync, ICredential, IVerifiableCredential, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { VerifiableCredential } from '@veramo/core'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\n\n/**\n * Return the type(s) of a VC minus the VerifiableCredential type which should always be present\n * @param credential The input credential\n */\nexport const getCredentialTypeAsString = (credential: ICredential | VerifiableCredential): string => {\n  if (!credential.type) {\n    return 'Verifiable Credential'\n  } else if (typeof credential.type === 'string') {\n    return credential.type\n  }\n  return credential.type.filter((type: string): boolean => type !== 'VerifiableCredential').join(', ')\n}\n\n/**\n * Returns a Unique Verifiable Credential (with hash) as stored in Veramo, based upon matching the id of the input VC or the proof value of the input VC\n * @param uniqueVCs The Unique VCs to search in\n * @param searchVC The VC to search for in the unique VCs array\n */\nexport const getMatchingUniqueDigitalCredential = (\n  uniqueVCs: UniqueDigitalCredential[],\n  searchVC: OriginalVerifiableCredential,\n): UniqueDigitalCredential | undefined => {\n  // Since an ID is optional in a VC according to VCDM, and we really need the matches, we have a fallback match on something which is guaranteed to be unique for any VC (the proof(s))\n  return uniqueVCs.find(\n    (uniqueVC: UniqueDigitalCredential) =>\n      (typeof searchVC !== 'string' &&\n        (uniqueVC.id === (<IVerifiableCredential>searchVC).id ||\n          (uniqueVC.originalVerifiableCredential as VerifiableCredential).proof === (<IVerifiableCredential>searchVC).proof)) ||\n      (typeof searchVC === 'string' && (uniqueVC.uniformVerifiableCredential as VerifiableCredential)?.proof?.jwt === searchVC) ||\n      // We are ignoring the signature of the sd-jwt as PEX signs the vc again and it will not match anymore with the jwt in the proof of the stored jsonld vc\n      (typeof searchVC === 'string' &&\n        CredentialMapper.isSdJwtEncoded(searchVC) &&\n        uniqueVC.uniformVerifiableCredential?.proof &&\n        'jwt' in uniqueVC.uniformVerifiableCredential.proof &&\n        uniqueVC.uniformVerifiableCredential.proof.jwt?.split('.')?.slice(0, 2)?.join('.') === searchVC.split('.')?.slice(0, 2)?.join('.')),\n  )\n}\n\ntype InputCredential = UniqueDigitalCredential | VerifiableCredential | ICredential | OriginalVerifiableCredential\n\n/**\n * Get an original verifiable credential. Maps to wrapped Verifiable Credential first, to get an original JWT as Veramo stores these with a special proof value\n * @param credential The input VC\n */\n\nexport const getOriginalVerifiableCredential = (credential: InputCredential): OriginalVerifiableCredential => {\n  if (isUniqueDigitalCredential(credential)) {\n    if (!credential.originalVerifiableCredential) {\n      throw new Error('originalVerifiableCredential is not defined in UniqueDigitalCredential')\n    }\n    return getCredentialFromProofOrWrapped(credential.originalVerifiableCredential)\n  }\n\n  return getCredentialFromProofOrWrapped(credential)\n}\n\nconst getCredentialFromProofOrWrapped = (cred: any, hasher?: HasherSync): OriginalVerifiableCredential => {\n  if (typeof cred === 'object' && 'proof' in cred && 'jwt' in cred.proof && CredentialMapper.isSdJwtEncoded(cred.proof.jwt)) {\n    return cred.proof.jwt\n  }\n\n  return CredentialMapper.toWrappedVerifiableCredential(cred as OriginalVerifiableCredential, { hasher }).original\n}\n\nexport const isUniqueDigitalCredential = (credential: InputCredential): credential is UniqueDigitalCredential => {\n  return (credential as UniqueDigitalCredential).digitalCredential !== undefined\n}\n","import { Loggers, LogLevel, LogMethod } from '@sphereon/ssi-types'\nimport { Siopv2MachineInterpreter, Siopv2MachineState, Siopv2MachineStates } from '../types'\n\nconst logger = Loggers.DEFAULT.options('sphereon:siopv2-oid4vp:op-auth', {\n  defaultLogLevel: LogLevel.DEBUG,\n  methods: [LogMethod.CONSOLE],\n}).get('sphereon:siopv2-oid4vp:op-auth')\n\nexport const OID4VPCallbackStateListener = (\n  callbacks?: Map<Siopv2MachineStates, (machine: Siopv2MachineInterpreter, state: Siopv2MachineState, opts?: any) => Promise<void>>,\n) => {\n  return async (oid4vciMachine: Siopv2MachineInterpreter, state: Siopv2MachineState): Promise<void> => {\n    if (state._event.type === 'internal') {\n      logger.debug('oid4vpCallbackStateListener: internal event')\n      // Make sure we do not navigate when triggered by an internal event. We need to stay on current screen\n      // Make sure we do not navigate when state has not changed\n      return\n    }\n    logger.info(`VP state listener state: ${JSON.stringify(state.value)}`)\n\n    if (!callbacks || callbacks.size === 0) {\n      logger.info(`VP no callbacks registered for state: ${JSON.stringify(state.value)}`)\n      return\n    }\n\n    for (const [stateKey, callback] of callbacks) {\n      if (state.matches(stateKey)) {\n        logger.log(`VP state callback for state: ${JSON.stringify(state.value)}, will execute...`)\n        await callback(oid4vciMachine, state)\n          .then(() => logger.log(`VP state callback executed for state: ${JSON.stringify(state.value)}`))\n          .catch((error) => {\n            logger.error(\n              `VP state callback failed for state: ${JSON.stringify(state.value)}, error: ${JSON.stringify(error?.message)}, ${JSON.stringify(state.event)}`,\n            )\n            if (error.stack) {\n              logger.error(error.stack)\n            }\n          })\n        break\n      }\n    }\n  }\n}\n","import { ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { contextHasPlugin } from '@sphereon/ssi-sdk.agent-config'\nimport { LinkHandlerAdapter } from '@sphereon/ssi-sdk.core'\nimport { IMachineStatePersistence, interpreterStartOrResume, SerializableState } from '@sphereon/ssi-sdk.xstate-machine-persistence'\nimport { IAgentContext } from '@veramo/core'\nimport { Loggers } from '@sphereon/ssi-types'\nimport { GetMachineArgs, IDidAuthSiopOpAuthenticator, LOGGER_NAMESPACE, Siopv2MachineInterpreter, Siopv2MachineState } from '../types'\n\nconst logger = Loggers.DEFAULT.options(LOGGER_NAMESPACE, {}).get(LOGGER_NAMESPACE)\n\nexport class Siopv2OID4VPLinkHandler extends LinkHandlerAdapter {\n  private readonly context: IAgentContext<IDidAuthSiopOpAuthenticator & IMachineStatePersistence>\n  private readonly stateNavigationListener:\n    | ((oid4vciMachine: Siopv2MachineInterpreter, state: Siopv2MachineState, navigation?: any) => Promise<void>)\n    | undefined\n  private readonly noStateMachinePersistence: boolean\n  private readonly idOpts?: ManagedIdentifierOptsOrResult\n\n  constructor(\n    args: Pick<GetMachineArgs, 'stateNavigationListener'> & {\n      protocols?: Array<string | RegExp>\n      context: IAgentContext<IDidAuthSiopOpAuthenticator & IMachineStatePersistence>\n      noStateMachinePersistence?: boolean\n      idOpts?: ManagedIdentifierOptsOrResult\n    },\n  ) {\n    super({ ...args, id: 'Siopv2' })\n    this.context = args.context\n    this.noStateMachinePersistence = args.noStateMachinePersistence === true\n    this.stateNavigationListener = args.stateNavigationListener\n    this.idOpts = args.idOpts\n  }\n\n  async handle(\n    url: string | URL,\n    opts?: {\n      machineState?: SerializableState\n      idOpts?: ManagedIdentifierOptsOrResult\n    },\n  ): Promise<void> {\n    logger.debug(`handling SIOP link: ${url}`)\n\n    const siopv2Machine = await this.context.agent.siopGetMachineInterpreter({\n      url,\n      idOpts: opts?.idOpts ?? this.idOpts,\n      stateNavigationListener: this.stateNavigationListener,\n    })\n\n    const interpreter = siopv2Machine.interpreter\n    if (!this.noStateMachinePersistence && !opts?.machineState && contextHasPlugin(this.context, 'machineStatesFindActive')) {\n      const init = await interpreterStartOrResume({\n        interpreter,\n        context: this.context,\n        cleanupAllOtherInstances: true,\n        cleanupOnFinalState: true,\n        singletonCheck: true,\n        noRegistration: this.noStateMachinePersistence,\n      })\n      logger.debug(`SIOP machine started for link: ${url}`, init)\n    } else {\n      // @ts-ignore\n      interpreter.start(opts?.machineState)\n      logger.debug(`SIOP machine started for link: ${url}`)\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mDAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,uCAAyC;AAAA,MACzC,0CAA4C;AAAA,MAC5C,wCAA0C;AAAA,MAC1C,uDAAyD;AAAA,MACzD,6CAA+C;AAAA,MAC/C,iDAAmD;AAAA,MACnD,0CAA4C;AAAA,IAC9C;AAAA;AAAA;;;ACRA;AAAA,mDAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,uCAAyC;AAAA,MACzC,0CAA4C;AAAA,MAC5C,wCAA0C;AAAA,MAC1C,6CAA+C;AAAA,MAC/C,iDAAmD;AAAA,MACnD,0CAA4C;AAAA,IAC9C;AAAA;AAAA;;;ACPA;AAAA,gCAAAC,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,6BAA+B;AAAA,QAC7B,YAAc;AAAA,UACZ,SAAW;AAAA,YACT,qBAAuB;AAAA,cACrB,MAAQ;AAAA,cACR,YAAc;AAAA,gBACZ,WAAa;AAAA,kBACX,MAAQ;AAAA,gBACV;AAAA,gBACA,sBAAwB;AAAA,cAC1B;AAAA,cACA,UAAY,CAAC,WAAW;AAAA,cACxB,aAAe;AAAA,YACjB;AAAA,YACA,0BAA4B;AAAA,cAC1B,MAAQ;AAAA,cACR,YAAc;AAAA,gBACZ,YAAc;AAAA,kBACZ,MAAQ;AAAA,kBACR,YAAc;AAAA,oBACZ,KAAO;AAAA,sBACL,MAAQ;AAAA,oBACV;AAAA,oBACA,OAAS;AAAA,sBACP,MAAQ;AAAA,oBACV;AAAA,oBACA,UAAY;AAAA,sBACV,MAAQ;AAAA,oBACV;AAAA,oBACA,iBAAmB;AAAA,sBACjB,MAAQ;AAA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kCAAkCF,GAAAA,EAAK;IACtD;EACF;AACF;;;Af9DA,IAAMgB,SAASC;","names":["module","module","module","import_did_auth_siop","import_ssi_sdk","import_ssi_types","import_uuid","createOID4VPPresentationSignCallback","presentationSignCallback","idOpts","domain","fetchRemoteContexts","challenge","format","context","skipDidResolution","createPEXPresentationSignCallback","createOPBuilder","opOptions","eventEmitter","EventEmitter","builder","OP","withResponseMode","responseMode","ResponseMode","DIRECT_POST","withSupportedVersions","supportedVersions","SupportedVersion","SIOPv2_ID1","JWT_VC_PRESENTATION_PROFILE_v1","SIOPv2_D11","SIOPv2_D12_OID4VP_D18","withExpiresIn","expiresIn","withEventEmitter","withRegistration","passBy","PassBy","VALUE","wellknownDIDVerifyCallback","args","result","agent","cvVerifyCredential","credential","verified","withVerifyJwtCallback","verifyJwtCallback","getVerifyJwtCallback","verifyOpts","checkLinkedDomain","isManagedIdentifierDidOpts","offlineWhenNoDIDRegistered","createJwtCallback","createJwtCallbackWithIdOpts","withCreateJwtCallback","withPresentationSignCallback","createJwtCallbackWithOpOpts","jwtIssuer","jwt","issuer","method","noIdentifierInHeader","isManagedIdentifierX5cOpts","Promise","reject","Error","jwtCreateJwsCompactSignature","protectedHeader","header","payload","opOpts","identifier","didUrl","x5c","kmsKeyRef","_opts","_jwtVerifier","jwtVerifyJwsSignature","jws","raw","console","log","message","error","createOP","build","getSigningAlgo","type","SigningAlgo","EDDSA","ES256K","ES256","RS256","import_did_auth_siop","import_ssi_sdk_ext","import_ssi_sdk","LOGGER_NAMESPACE","events","DEFAULT_JWT_PROOF_TYPE","Siopv2HolderEvent","SupportedLanguage","Siopv2MachineStates","Siopv2MachineAddContactStates","Siopv2MachineEvents","Siopv2MachineGuards","Siopv2MachineServices","DID_PREFIX","OID4VP","session","allIdentifiers","hasher","args","defaultHasher","init","getSupportedDIDs","getPresentationDefinitions","definitions","PresentationExchange","assertValidPresentationDefinitionWithLocations","getPresentationExchange","verifiableCredentials","allDIDs","allVerifiableCredentials","createVerifiablePresentations","credentialRole","credentialsWithDefinitions","opts","Promise","all","map","cred","createVerifiablePresentation","selectedVerifiableCredentials","subjectIsHolder","holder","forceNoCredentialsInVP","Error","credentials","length","proofOptions","proofOpts","challenge","nonce","domain","getRedirectUri","idOpts","reject","firstUniqueDC","isOID4VCIssuerIdentifier","digitalCredential","kmsKeyRef","context","agent","identifierManagedGetByIssuer","identifier","identifierManagedGetByKid","vcs","applyFilter","filterCredentials","definition","restrictToFormats","restrictToDIDMethods","filterOpts","signCallback","createOID4VPPresentationSignCallback","presentationSignCallback","options","format","skipDidResolution","identifierManagedGet","credential","originalVerifiableCredential","presentationResult","isManagedIdentifierDidResult","holderDID","did","verifiablePresentations","verifiablePresentation","proof","jwt","filterCredentialsAgainstAllDefinitions","defs","result","push","presentationDefinition","udcMap","Map","forEach","set","filterCredentialsWithSelectionStatus","verifiableCredential","vc","get","selectionResults","getCredentials","selectVerifiableCredentialsForSubmission","errors","JSON","stringify","areRequiredCredentialsPresent","Status","ERROR","matches","filter","verifiableCredentialForRoleFilter","uniqueCredentials","crsGetUniqueCredentials","uniqueVC","uniformVerifiableCredential","Array","isArray","jwtProof","find","p","type","DEFAULT_JWT_PROOF_TYPE","import_did_auth_siop","import_ssi_sdk_ext","import_ssi_sdk","import_pex","import_ssi_types","logger","Loggers","DEFAULT","get","OpSession","ts","Date","getDate","id","options","context","requestJwtOrUri","verifiedAuthorizationRequest","_nonce","_state","_providedPresentationDefinitions","sessionId","op","providedPresentationDefinitions","init","getAuthorizationRequest","createOP","opOptions","verifyAuthorizationRequest","authorizationRequest","getMergedProperty","getSupportedDIDMethods","getAuthorizationRequestURI","URI","fromAuthorizationRequest","nonce","Error","state","clear","undefined","didPrefix","agentMethods","getAgentDIDMethodsSupported","rpMethods","getRPDIDMethodsSupported","debug","JSON","stringify","getSubjectSyntaxTypesSupported","dids","length","intersection","includes","getAgentDIDMethods","map","method","convertDidMethod","filter","value","opts","supportedDIDMethods","authReq","subjectSyntaxTypesSupported","registrationMetadataPayload","subject_syntax_types_supported","keyType","val","startsWith","aud","didMethod","parseDid","Array","isArray","isEBSI","issuer","codecName","didKeyMethod","getSupportedIdentifiers","methods","identifiers","agent","didManagerFind","then","ids","provider","createInCaseNoDIDFound","identifier","didManagerCreate","type","did","push","getSupportedDIDs","getRedirectUri","Promise","resolve","responseURI","hasPresentationDefinitions","defs","presentationDefinitions","getPresentationDefinitions","getOID4VP","args","OID4VP","allIdentifiers","hasher","createPresentationVerificationCallback","presentationVerificationCallback","presentationSubmission","result","CredentialMapper","isSdJwtEncoded","sdJwtResult","verifySdJwtPresentation","presentation","verified","error","message","verifyPresentation","createJarmResponseCallback","responseOpts","jarmResponse","clientMetadata","requestObjectPayload","authorizationResponsePayload","authResponse","jwk","OP","extractEncJwksFromClientMetadata","recipientKey","identifierExternalResolveByJwk","jwtEncryptJweCompactJwt","protectedHeader","alg","client_metadata","authorization_encrypted_response_alg","enc","authorization_encrypted_response_enc","apv","encodeBase64url","apu","v4","payload","audience","response","jwt","sendAuthorizationResponse","resolveOpts","resolver","getAgentResolver","uniresolverResolution","localResolution","resolverResolution","verification","request","hasDefinitions","totalInputDescriptors","reduce","sum","pd","definition","input_descriptors","totalVCs","verifiablePresentations","countVCsInAllVPs","vp","storedPresentationToOriginalFormat","eventEmitter","presentationSignCallback","wellknownDIDVerifyCallback","supportedVersions","versions","idOpts","responseSignerOpts","isFirstParty","presentationExchange","dcqlQuery","dcqlResponse","createAuthorizationResponse","submitAuthorizationResponse","status","statusText","text","isMsoMdocDecodedPresentation","isMsoMdocOid4VPEncoded","uvp","toUniformPresentation","verifiableCredential","isSdJWT","isSdJwtDecodedCredential","PEX","allowMultipleVCsPerPresentation","toLowerCase","replace","import_pex","import_dcql","Localization","translationGetters","SupportedLanguage","ENGLISH","require","DUTCH","translate","memoize","key","config","Object","keys","i18n","translations","length","locale","findSupportedLanguage","t","JSON","stringify","language","values","undefined","getLocale","import_ssi_types","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","Siopv2HasNoContactGuard","_ctx","_event","contact","undefined","Siopv2HasContactGuard","Siopv2HasAuthorizationRequestGuard","authorizationRequestData","Siopv2HasSelectableCredentialsAndContactGuard","Error","presentationDefinitions","Siopv2CreateContactGuard","contactAlias","hasContactConsent","length","Siopv2HasSelectedRequiredCredentialsGuard","selectedCredentials","Siopv2IsSiopOnlyGuard","Siopv2IsSiopWithOID4VPGuard","selectableCredentialsMap","createSiopv2Machine","opts","url","idOpts","initialContext","URL","toString","createMachine","id","machineId","predictableActionArguments","initial","Siopv2MachineStates","createConfig","schema","events","guards","services","context","states","invoke","src","Siopv2MachineServices","onDone","target","getSiopRequest","actions","assign","didAuthConfig","data","onError","handleError","error","title","translate","message","stack","retrieveContact","transitionFromSetup","always","addContact","cond","Siopv2MachineGuards","hasNoContactGuard","sendResponse","siopOnlyGuard","getSelectableCredentials","hasSelectableCredentialsAndContactGuard","selectCredentials","siopWithOID4VPGuard","Siopv2MachineAddContactStates","idle","on","Siopv2MachineEvents","SET_CONTACT_CONSENT","SET_CONTACT_ALIAS","CREATE_CONTACT","next","createContactGuard","DECLINE","declined","PREVIOUS","aborted","hasContactGuard","addContactIdentity","identities","push","SET_SELECTED_CREDENTIALS","NEXT","hasSelectedRequiredCredentialsGuard","done","authorizationResponseData","type","Siopv2Machine","newInstance","info","interpreter","interpret","withConfig","subscription","onTransition","requireCustomNavigationHook","snapshot","stateNavigationListener","value","import_did_auth_siop","import_pex","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_ssi_types","getOriginalVerifiableCredential","credential","isUniqueDigitalCredential","originalVerifiableCredential","Error","getCredentialFromProofOrWrapped","cred","hasher","proof","CredentialMapper","isSdJwtEncoded","jwt","toWrappedVerifiableCredential","original","digitalCredential","undefined","convertToDcqlCredentials","credential","hasher","payload","isUniqueDigitalCredential","originalVerifiableCredential","Error","CredentialMapper","decodeVerifiableCredential","decodedPayload","vct","claims","credential_format","docType","namespaces","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","createEbsiIdentifier","agentContext","log","result","newIdentifier","created","getOrCreatePrimaryIdentifier","method","SupportedDidMethodEnum","DID_KEY","createOpts","options","codecName","type","did","agent","emit","Siopv2HolderEvent","IDENTIFIER_CREATED","identifierManagedGetByDid","identifier","hasEbsiClient","authorizationRequest","clientId","getMergedProperty","redirectUri","toLowerCase","includes","siopSendAuthorizationResponse","connectionType","args","context","idOpts","isFirstParty","hasher","defaultHasher","ConnectionType","SIOPv2_OpenID4VP","Promise","reject","Error","session","siopGetOPSession","sessionId","request","getAuthorizationRequest","aud","debug","JSON","stringify","presentationsAndDefs","presentationSubmission","hasPresentationDefinitions","oid4vp","getOID4VP","credentialsAndDefinitions","verifiableCredentialsWithDefinition","filterCredentialsAgainstAllDefinitions","CredentialRole","HOLDER","domain","issuer","versions","SupportedVersion","JWT_VC_PRESENTATION_PROFILE_v1","nonce","firstUniqueDC","credentials","digitalCredential","firstVC","uniformVerifiableCredential","holder","CredentialMapper","isSdJwtDecodedCredential","decodedPayload","cnf","jwk","encodeJoseBlob","sub","Array","isArray","credentialSubject","id","kmsKeyRef","identifierManagedGet","e","isOID4VCIssuerIdentifier","identifierManagedGetByOID4VCIssuer","subjectCorrelationType","subjectCorrelationId","startsWith","identifierManagedGetByKid","undefined","createVerifiablePresentations","proofOpts","length","verifiablePresentations","mergedVerifiablePresentations","flatMap","pd","sendAuthorizationResponse","responseSignerOpts","dcqlQuery","vcs","vcd","console","dcqlRepresentations","forEach","vc","rep","convertToDcqlCredentials","push","queryResult","DcqlQuery","query","presentation","key","value","Object","entries","credential_matches","allMatches","match","success","originalCredential","getOriginalVerifiableCredential","input_credential_index","compactSdJwtVc","response","dcqlPresentation","DcqlPresentation","parse","buildPartialPD","inputDescriptor","presentationDefinition","input_descriptors","getSelectableCredentials","pex","PEX","uniqueVerifiableCredentials","crsGetUniqueCredentials","filter","verifiableCredentialForRoleFilter","credentialBranding","ibGetCredentialBranding","selectableCredentialsMap","Map","partialPD","originalCredentials","map","uniqueVC","storedCredentialToOriginalFormat","originalVerifiableCredential","selectionResults","selectFrom","selectableCredentials","selectedCredential","verifiableCredential","filteredUniqueVC","find","proof","some","proofItem","jwt","filteredCredentialBrandings","cb","vcHash","hash","issuerPartyIdentity","cmGetContacts","identities","correlationId","issuerDid","subjectPartyIdentity","subjectDid","credential","localeBranding","issuerParty","subjectParty","set","translateCorrelationIdToName","contacts","contact","displayName","logger","Loggers","DEFAULT","options","LOGGER_NAMESPACE","get","didAuthSiopOpAuthenticatorMethods","DidAuthSiopOpAuthenticator","schema","IDidAuthSiopOpAuthenticator","methods","siopGetOPSession","bind","siopRegisterOPSession","siopRemoveOPSession","siopRegisterOPCustomApproval","siopRemoveOPCustomApproval","siopGetMachineInterpreter","siopCreateConfig","siopGetSiopRequest","siopRetrieveContact","siopAddIdentity","siopAddContactIdentity","siopSendResponse","siopGetSelectableCredentials","sessions","customApprovals","presentationSignCallback","onContactIdentityCreated","onIdentifierCreated","eventEmitter","hasher","constructor","Map","onEvent","event","context","type","Siopv2HolderEvent","CONTACT_IDENTITY_CREATED","data","IDENTIFIER_CREATED","Promise","reject","Error","args","has","sessionId","uuidv4","opts","op","session","OpSession","init","set","delete","key","undefined","customApproval","stateNavigationListener","url","services","createConfig","getSiopRequest","getSelectableCredentials","retrieveContact","addContactIdentity","sendResponse","siopv2MachineOpts","Siopv2Machine","newInstance","id","redirectUrl","agent","didAuthConfig","catch","requestJwtOrUri","debug","JSON","stringify","verifiedAuthorizationRequest","getAuthorizationRequest","clientName","registrationMetadataPayload","client_name","responseURI","includes","decodeURIComponent","split","trim","issuer","client_id","uri","URL","correlationId","hostname","determineCorrelationId","clientId","authorizationRequest","getMergedProperty","name","presentationDefinitions","containsResponseType","versions","every","version","SupportedVersion","JWT_VC_PRESENTATION_PROFILE_v1","length","dcqlQuery","translateCorrelationIdToName","issuerHostname","authorizationRequestData","cmGetContacts","filter","identities","identifier","then","contacts","contact","startsWith","protocol","identity","alias","origin","IdentityOrigin","EXTERNAL","roles","CredentialRole","ISSUER","CorrelationIdentifierType","DID","addedIdentity","cmAddIdentity","contactId","emit","info","selectedCredentials","isFirstParty","pex","PEX","verifiableCredentialsWithDefinition","dcqlCredentialsWithCredentials","Array","isArray","forEach","presentationDefinition","areRequiredCredentialsPresent","verifiableCredential","verifiableCredentials","selectFrom","definition","map","udc","originalVerifiableCredential","Status","ERROR","uniqueDigitalCredentials","vc","hash","computeEntryHash","find","push","credentials","e","hasMDocCredentials","hasSdJwtCredentials","isSdJwtCredential","payload","decodedPayload","result","claims","vct","credential_format","digitalCredential","documentFormat","dcqlPresentationRecord","queryResult","DcqlQuery","query","from","keys","value","Object","entries","credential_matches","success","retrieveEncodedCredential","output","response","siopSendAuthorizationResponse","ConnectionType","SIOPv2_OpenID4VP","idOpts","contentType","headers","responseBody","text","parse","body","queryParams","decodeUriAsJson","some","isMDocCredential","credential","CredentialDocumentFormat","MSO_MDOC","documentType","DocumentType","VC","SD_JWT","compactSdJwtVc","import_ssi_types","logger","Loggers","DEFAULT","options","defaultLogLevel","LogLevel","DEBUG","methods","LogMethod","CONSOLE","get","OID4VPCallbackStateListener","callbacks","oid4vciMachine","state","_event","type","debug","info","JSON","stringify","value","size","stateKey","callback","matches","log","then","catch","error","message","event","stack","import_ssi_sdk","import_ssi_types","logger","Loggers","DEFAULT","options","LOGGER_NAMESPACE","get","Siopv2OID4VPLinkHandler","LinkHandlerAdapter","context","stateNavigationListener","noStateMachinePersistence","idOpts","constructor","args","id","handle","url","opts","debug","siopv2Machine","agent","siopGetMachineInterpreter","interpreter","machineState","contextHasPlugin","init","interpreterStartOrResume","cleanupAllOtherInstances","cleanupOnFinalState","singletonCheck","noRegistration","start","schema","require"]}