@sphereon/ssi-sdk.siopv2-oid4vp-op-auth 0.36.1-next.11 → 0.36.1-next.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/package.json +19 -20
- package/src/session/OID4VP.ts +1 -3
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/localization/translations/en.json","../src/localization/translations/nl.json","../src/index.ts","../plugin.schema.json","../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 * @public\n */\nimport schema from '../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'\nexport * from './utils/dcql'\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","import { decodeUriAsJson, PresentationSignCallback, VerifiedAuthorizationRequest } from '@sphereon/did-auth-siop'\nimport { ConnectionType, CorrelationIdentifierType, Identity, IdentityOrigin, NonPersistedIdentity, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { HasherSync, Loggers, CredentialRole } from '@sphereon/ssi-types'\nimport { IAgentPlugin } from '@veramo/core'\nimport { v4 as uuidv4 } from 'uuid'\nimport { OpSession } from '../session'\nimport { EventEmitter } from 'events'\nimport {\n DidAuthSiopOpAuthenticatorOptions,\n GetSelectableCredentialsArgs,\n IDidAuthSiopOpAuthenticator,\n IGetSiopSessionArgs,\n IOpSessionArgs,\n IRegisterCustomApprovalForSiopArgs,\n IRemoveCustomApprovalForSiopArgs,\n IRemoveSiopSessionArgs,\n IRequiredContext,\n LOGGER_NAMESPACE,\n RequiredContext,\n SelectableCredentialsMap,\n Siopv2AuthorizationResponseData,\n} from '../types'\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 { 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 // TODO do we still need this?\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 = 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 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 response = await siopSendAuthorizationResponse(\n ConnectionType.SIOPv2_OpenID4VP,\n {\n sessionId: didAuthConfig.sessionId,\n ...(args.idOpts && { idOpts: args.idOpts }),\n isFirstParty,\n hasher: this.hasher,\n credentials: selectedCredentials,\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 async siopGetSelectableCredentials(args: GetSelectableCredentialsArgs, context: RequiredContext): Promise<SelectableCredentialsMap> {\n const { authorizationRequestData } = args\n\n if (!authorizationRequestData?.dcqlQuery) {\n return Promise.reject(Error('Missing required dcql query in context'))\n }\n\n return getSelectableCredentials(authorizationRequestData?.dcqlQuery, 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(opOptions.supportedVersions ?? [SupportedVersion.OID4VP_v1, SupportedVersion.SIOPv2_OID4VP_D28])\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 type { PartialSdJwtKbJwt } from '@sphereon/pex/dist/main/lib/index.js'\nimport { calculateSdHash } from '@sphereon/pex/dist/main/lib/utils/index.js'\nimport { isManagedIdentifierDidResult, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { defaultGenerateDigest } from '@sphereon/ssi-sdk.sd-jwt'\nimport {\n CredentialMapper,\n DocumentFormat,\n HasherSync,\n Loggers,\n OriginalVerifiableCredential,\n SdJwtDecodedVerifiableCredential,\n WrappedVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { LOGGER_NAMESPACE, RequiredContext } from '../types'\n\nconst CLOCK_SKEW = 120\nconst logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\nexport interface PresentationBuilderContext {\n nonce: string\n audience: string // clientId or origin\n agent: RequiredContext['agent']\n clockSkew?: number\n hasher?: HasherSync\n}\n\n/**\n * Extracts the original credential from a UniqueDigitalCredential or WrappedVerifiableCredential\n */\nfunction extractOriginalCredential(\n credential: UniqueDigitalCredential | WrappedVerifiableCredential | OriginalVerifiableCredential,\n): OriginalVerifiableCredential {\n if (typeof credential === 'string') {\n return credential\n }\n\n if ('digitalCredential' in credential) {\n // UniqueDigitalCredential\n const udc = credential as UniqueDigitalCredential\n if (udc.originalVerifiableCredential) {\n return udc.originalVerifiableCredential\n }\n return udc.uniformVerifiableCredential as OriginalVerifiableCredential\n }\n\n if ('original' in credential) {\n // WrappedVerifiableCredential\n return credential.original\n }\n\n // Already an OriginalVerifiableCredential\n return credential as OriginalVerifiableCredential\n}\n\n/**\n * Gets the issuer/holder identifier from ManagedIdentifierOptsOrResult\n */\nfunction getIdentifierString(identifier: ManagedIdentifierOptsOrResult): string {\n // Check if it's a result type (has 'method' and 'opts' properties)\n if ('opts' in identifier && 'method' in identifier) {\n // It's a ManagedIdentifierResult\n if (isManagedIdentifierDidResult(identifier)) {\n return identifier.did\n }\n }\n // For opts types or other result types, use issuer if available, otherwise kid\n return identifier.issuer ?? identifier.kid ?? ''\n}\n\n/**\n * Creates a Verifiable Presentation for a given credential in the appropriate format\n * Ensures nonce/aud (or challenge/domain) are set according to OID4VP draft 28\n */\nexport async function createVerifiablePresentationForFormat(\n credential: UniqueDigitalCredential | WrappedVerifiableCredential | OriginalVerifiableCredential,\n identifier: ManagedIdentifierOptsOrResult,\n context: PresentationBuilderContext,\n): Promise<string | object> {\n // FIXME find proper types\n const { nonce, audience, agent, clockSkew = CLOCK_SKEW } = context\n\n const originalCredential = extractOriginalCredential(credential)\n const documentFormat = CredentialMapper.detectDocumentType(originalCredential)\n\n logger.debug(`Creating VP for format: ${documentFormat}`)\n\n switch (documentFormat) {\n case DocumentFormat.SD_JWT_VC: {\n // SD-JWT with KB-JWT\n const decodedSdJwt = await CredentialMapper.decodeSdJwtVcAsync(\n typeof originalCredential === 'string' ? originalCredential : (originalCredential as SdJwtDecodedVerifiableCredential).compactSdJwtVc,\n defaultGenerateDigest,\n )\n\n const hashAlg = decodedSdJwt.signedPayload._sd_alg ?? 'sha-256'\n const sdHash = calculateSdHash(decodedSdJwt.compactSdJwtVc, hashAlg, defaultGenerateDigest)\n\n const kbJwtPayload: PartialSdJwtKbJwt['payload'] = {\n iat: Math.floor(Date.now() / 1000 - clockSkew),\n sd_hash: sdHash,\n nonce, // Always use the Authorization Request nonce\n aud: audience, // Always use the Client Identifier or Origin\n }\n\n const presentationResult = await agent.createSdJwtPresentation({\n presentation: decodedSdJwt.compactSdJwtVc,\n kb: {\n payload: kbJwtPayload as any, // FIXME\n },\n })\n\n return presentationResult.presentation\n }\n\n case DocumentFormat.JSONLD: {\n // JSON-LD VC - create JSON-LD VP with challenge and domain in proof\n const vcObject = typeof originalCredential === 'string' ? JSON.parse(originalCredential) : originalCredential\n\n const vpObject = {\n '@context': ['https://www.w3.org/2018/credentials/v1'],\n type: ['VerifiablePresentation'],\n verifiableCredential: [vcObject],\n }\n\n // Create JSON-LD VP with proof\n return await agent.createVerifiablePresentation({\n presentation: vpObject,\n proofFormat: 'lds',\n challenge: nonce, // Authorization Request nonce as challenge\n domain: audience, // Client Identifier or Origin as domain\n keyRef: identifier.kmsKeyRef || identifier.kid,\n })\n }\n\n case DocumentFormat.MSO_MDOC: {\n // ISO mdoc - create mdoc VP token\n // This is a placeholder implementation\n // Full implementation would require:\n // 1. Decode the mdoc using CredentialMapper or mdoc utilities\n // 2. Build proper mdoc VP token with session transcript\n // 3. Include nonce/audience in the session transcript\n logger.warning('mso_mdoc format has basic support - production use requires proper mdoc VP token implementation')\n\n return originalCredential\n }\n\n default: {\n // JWT VC - create JWT VP with nonce and aud in payload\n const vcJwt = typeof originalCredential === 'string' ? originalCredential : JSON.stringify(originalCredential)\n\n const identifierString = getIdentifierString(identifier)\n\n // Create VP JWT using agent method\n const vpPayload = {\n iss: identifierString,\n aud: audience, // Client Identifier or Origin\n nonce, // Authorization Request nonce\n vp: {\n '@context': ['https://www.w3.org/2018/credentials/v1'],\n type: ['VerifiablePresentation'],\n holder: identifierString,\n verifiableCredential: [vcJwt],\n },\n iat: Math.floor(Date.now() / 1000 - clockSkew),\n exp: Math.floor(Date.now() / 1000 + 600 + clockSkew), // 10 minutes\n }\n\n // Use the agent's JWT creation capability\n const vpJwt = await agent.createVerifiablePresentation({\n presentation: vpPayload.vp,\n proofFormat: 'jwt',\n domain: audience,\n challenge: nonce,\n keyRef: identifier.kmsKeyRef || identifier.kid,\n })\n\n return vpJwt.proof?.jwt || vpJwt\n }\n }\n}\n","import {\n DcqlResponseOpts,\n PresentationSignCallback,\n ResponseMode,\n SupportedVersion,\n URI,\n VerifiedAuthorizationRequest,\n VerifyJwtCallback,\n} from '@sphereon/did-auth-siop'\nimport { CheckLinkedDomain, ResolveOpts } from '@sphereon/did-auth-siop-adapter'\nimport { DIDDocument } from '@sphereon/did-uni-client'\nimport { IIdentifierResolution, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { ICredentialStore } from '@sphereon/ssi-sdk.credential-store'\nimport { Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { IPDManager } from '@sphereon/ssi-sdk.pd-manager'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\nimport { HasherSync, 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'\nimport { DcqlPresentation, DcqlQuery } from 'dcql'\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 dcqlQuery?: DcqlQuery\n identifierOptions?: ManagedIdentifierOptsOrResult\n context: IRequiredContext\n op?: IOPOptions\n}\n\nexport interface IAuthRequestDetails {\n rpDIDDocument?: DIDDocument\n id: string\n verifiablePresentationMatches: DcqlPresentation[]\n alsoKnownAs?: string[]\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 presentationSubmission?: PresentationSubmission\n verifiablePresentations?: W3CVerifiablePresentation[]\n dcqlResponse?: DcqlResponseOpts\n hasher?: HasherSync\n isFirstParty?: boolean\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 verifyJwtCallback?: VerifyJwtCallback\n wellknownDIDVerifyCallback?: VerifyCallback\n presentationSignCallback?: PresentationSignCallback\n resolveOpts?: ResolveOpts\n hasher?: HasherSync\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 const DEFAULT_JWT_PROOF_TYPE = 'JwtProof2020'\n","import { PresentationSignCallback, RPRegistrationMetadataPayload, VerifiedAuthorizationRequest } 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-types'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\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 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 &\n IDidAuthSiopOpAuthenticator &\n IDIDManager &\n IResolver &\n IIdentifierResolution &\n ICredentialStore &\n IIssuanceBranding &\n ISDJwtPlugin\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-types'\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'\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>\n","import {\n AuthorizationResponsePayload,\n JwksMetadataParams,\n OP,\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 { Loggers, parseDid } from '@sphereon/ssi-types'\nimport { IIdentifier, TKeyType } from '@veramo/core'\nimport { v4 } from 'uuid'\nimport { IOPOptions, IOpSessionArgs, IOpsSendSiopAuthorizationResponseArgs, IRequiredContext } from '../types'\nimport { createOP } from './functions'\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\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 }\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') || 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 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 { responseSignerOpts, dcqlResponse, isFirstParty } = args\n\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\n const request = await this.getAuthorizationRequest()\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: 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 = responseSignerOpts.issuer\n const responseOpts = {\n issuer,\n ...(isFirstParty && { isFirstParty }),\n dcqlResponse: 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\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-types'\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.dcqlQuery !== 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.dcqlQuery === undefined) {\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.dcqlQuery === 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.dcqlQuery !== 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 } from '@sphereon/did-auth-siop'\nimport { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport { isOID4VCIssuerIdentifier, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { encodeJoseBlob } from '@sphereon/ssi-sdk.core'\nimport { UniqueDigitalCredential, verifiableCredentialForRoleFilter } from '@sphereon/ssi-sdk.credential-store'\nimport { ConnectionType } from '@sphereon/ssi-sdk.data-store-types'\nimport { CredentialMapper, CredentialRole, HasherSync, Loggers, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { IAgentContext, IDIDManager } from '@veramo/core'\nimport { DcqlPresentation, DcqlQuery } from 'dcql'\nimport { createVerifiablePresentationForFormat, OpSession, PresentationBuilderContext } from '../session'\nimport { LOGGER_NAMESPACE, RequiredContext, SelectableCredential, SelectableCredentialsMap, Siopv2HolderEvent } from '../types'\nimport { convertToDcqlCredentials } from '../utils/dcql'\n\nconst CLOCK_SKEW = 120\n\nexport const logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\n// @ts-ignore\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\n// @ts-ignore\nconst hasEbsiClient = async (authorizationRequest: AuthorizationRequest) => {\n const clientId = authorizationRequest.getMergedProperty<string>('client_id')\n const redirectUri = 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 credentials: Array<UniqueDigitalCredential | OriginalVerifiableCredential>\n idOpts?: ManagedIdentifierOptsOrResult\n isFirstParty?: boolean\n hasher?: HasherSync\n },\n context: RequiredContext,\n) => {\n const { agent } = context\n const { credentials } = args\n if (connectionType !== ConnectionType.SIOPv2_OpenID4VP) {\n return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`))\n }\n\n const session: OpSession = await agent.siopGetOPSession({ sessionId: args.sessionId })\n const request = await session.getAuthorizationRequest()\n const aud = request.authorizationRequest.getMergedProperty<string>('aud')\n logger.debug(`AUD: ${aud}`)\n logger.debug(JSON.stringify(request.authorizationRequest))\n\n const domain = ((await request.authorizationRequest.getMergedProperty('client_id')) as string) ?? request.issuer ?? 'https://self-issued.me/v2'\n\n logger.debug(`NONCE: ${session.nonce}, domain: ${domain}`)\n\n const firstUniqueDC = 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\n // Determine holder DID for identifier resolution\n let holder: string | undefined\n if (CredentialMapper.isSdJwtDecodedCredential(firstVC)) {\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\n holder = firstVC.decodedPayload.cnf?.jwk ? `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0` : firstVC.decodedPayload.sub\n } else {\n holder = Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id\n }\n\n // Resolve identifier\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\n const dcqlCredentialsWithCredentials = new Map(credentials.map((vc) => [convertToDcqlCredentials(vc), vc]))\n\n const queryResult = DcqlQuery.query(request.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()))\n\n if (!queryResult.can_be_satisfied) {\n return Promise.reject(Error('Credentials do not match required query request'))\n }\n\n // Build presentation context for format-aware VP creation\n const presentationContext: PresentationBuilderContext = {\n nonce: request.requestObject?.getPayload()?.nonce ?? session.nonce,\n audience: domain,\n agent: context.agent,\n clockSkew: CLOCK_SKEW,\n hasher: args.hasher,\n }\n\n // Build DCQL presentation with format-aware VPs\n const presentation: DcqlPresentation.Output = {}\n const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values())\n for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n if (value.success) {\n const matchedCredentials = value.valid_credentials.map((cred) => uniqueCredentials[cred.input_credential_index])\n const vc = matchedCredentials[0] // taking the first match for now\n\n if (!vc) {\n continue\n }\n\n try {\n // Use format-aware presentation builder\n const vp = await createVerifiablePresentationForFormat(vc, identifier, presentationContext)\n presentation[key] = vp as any\n } catch (error) {\n logger.error(`Failed to create VP for credential ${key}:`, error)\n throw error\n }\n }\n }\n\n const dcqlPresentation = DcqlPresentation.parse(presentation)\n\n const response = session.sendAuthorizationResponse({\n responseSignerOpts: identifier,\n dcqlResponse: {\n dcqlPresentation,\n },\n })\n\n logger.debug(`Response: `, response)\n return response\n}\n\nexport const getSelectableCredentials = async (dcqlQuery: DcqlQuery, context: RequiredContext): Promise<SelectableCredentialsMap> => {\n const agentContext = { ...context, agent: context.agent }\n const { agent } = agentContext\n const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({\n filter: verifiableCredentialForRoleFilter(CredentialRole.HOLDER),\n })\n const branding = await agent.ibGetCredentialBranding()\n const dcqlCredentialsWithCredentials = new Map(uniqueVerifiableCredentials.map((vc) => [convertToDcqlCredentials(vc), vc]))\n const queryResult = DcqlQuery.query(dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()))\n const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values())\n const selectableCredentialsMap: SelectableCredentialsMap = new Map()\n\n for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n if (!value.valid_credentials) {\n continue\n }\n\n const mapSelectableCredentialPromises = value.valid_credentials.map(async (cred) => {\n const matchedCredential = uniqueCredentials[cred.input_credential_index]\n const credentialBranding = branding.filter((cb) => cb.vcHash === matchedCredential.hash)\n const issuerPartyIdentity = await agent.cmGetContacts({\n filter: [{ identities: { identifier: { correlationId: matchedCredential.uniformVerifiableCredential!.issuerDid } } }],\n })\n const subjectPartyIdentity = await agent.cmGetContacts({\n filter: [{ identities: { identifier: { correlationId: matchedCredential.uniformVerifiableCredential!.subjectDid } } }],\n })\n\n return {\n credential: matchedCredential,\n credentialBranding: credentialBranding[0]?.localeBranding,\n issuerParty: issuerPartyIdentity?.[0],\n subjectParty: subjectPartyIdentity?.[0],\n }\n })\n\n const selectableCredentials: Array<SelectableCredential> = await Promise.all(mapSelectableCredentialPromises)\n selectableCredentialsMap.set(key, selectableCredentials)\n }\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 {\n CredentialMapper,\n HasherSync,\n OriginalVerifiableCredential,\n WrappedMdocCredential,\n type WrappedSdJwtVerifiableCredential,\n type WrappedW3CVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { Dcql } from '@sphereon/did-auth-siop'\nimport { DcqlCredential } from 'dcql'\nimport { isUniqueDigitalCredential } from './CredentialUtils'\n\nexport function convertToDcqlCredentials(credential: UniqueDigitalCredential | OriginalVerifiableCredential, hasher?: HasherSync): DcqlCredential {\n let originalVerifiableCredential\n if (isUniqueDigitalCredential(credential)) {\n if (!credential.originalVerifiableCredential) {\n throw new Error('originalVerifiableCredential is not defined in UniqueDigitalCredential')\n }\n originalVerifiableCredential = CredentialMapper.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher)\n } else {\n originalVerifiableCredential = CredentialMapper.decodeVerifiableCredential(credential as OriginalVerifiableCredential, hasher)\n }\n\n if (!originalVerifiableCredential) {\n throw new Error('No payload found')\n }\n\n if (CredentialMapper.isJwtDecodedCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlJwtCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedW3CVerifiableCredential)\n } else if (CredentialMapper.isSdJwtDecodedCredential(originalVerifiableCredential)) {\n // FIXME: SD-JWT VC vs VCDM2 + SD-JWT would need to be handled here\n return Dcql.toDcqlSdJwtCredential(\n CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedSdJwtVerifiableCredential,\n )\n } else if (CredentialMapper.isMsoMdocDecodedCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlMdocCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedMdocCredential)\n } else if (CredentialMapper.isW3cCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlJsonLdCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedW3CVerifiableCredential)\n }\n\n throw Error(`Unable to map credential to DCQL credential. Credential: ${JSON.stringify(originalVerifiableCredential)}`)\n}\n","import { CredentialMapper, HasherSync, ICredential, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { VerifiableCredential } from '@veramo/core'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\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 as OriginalVerifiableCredential // FIXME SSISDK-59\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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;AAAA,EACE,6BAA+B;AAAA,IAC7B,YAAc;AAAA,MACZ,SAAW;AAAA,QACT,qBAAuB;AAAA,UACrB,MAAQ;AAAA,UACR,YAAc;AAAA,YACZ,WAAa;AAAA,cACX,MAAQ;AAAA,Y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BAA6B,CAACM,MAAMM,oBAAgBC,kCAAiB,KAAKf,SAAS,yBAAA,GAA4B;AACvH,YAAMgB,OAAO,UAAMC,2CAAyB;QAC1CJ;QACAb,SAAS,KAAKA;QACdkB,0BAA0B;QAC1BC,qBAAqB;QACrBC,gBAAgB;QAChBC,gBAAgB,KAAKnB;MACvB,CAAA;AACAV,MAAAA,QAAOiB,MAAM,kCAAkCF,GAAAA,IAAOS,IAAAA;IACxD,OAAO;AAELH,kBAAYS,MAAMd,MAAMM,YAAAA;AACxBtB,MAAAA,QAAOiB,MAAM,kCAAkCF,GAAAA,EAAK;IACtD;EACF;AACF;","names":["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","OID4VP_v1","SIOPv2_OID4VP_D28","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_ssi_sdk_ext","import_ssi_sdk","LOGGER_NAMESPACE","DEFAULT_JWT_PROOF_TYPE","Siopv2HolderEvent","SupportedLanguage","Siopv2MachineStates","Siopv2MachineAddContactStates","Siopv2MachineEvents","Siopv2MachineGuards","Siopv2MachineServices","DID_PREFIX","CLOCK_SKEW","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","extractOriginalCredential","credential","udc","originalVerifiableCredential","uniformVerifiableCredential","original","getIdentifierString","identifier","isManagedIdentifierDidResult","did","issuer","kid","createVerifiablePresentationForFormat","context","nonce","audience","agent","clockSkew","originalCredential","documentFormat","CredentialMapper","detectDocumentType","debug","DocumentFormat","SD_JWT_VC","decodedSdJwt","decodeSdJwtVcAsync","compactSdJwtVc","defaultGenerateDigest","hashAlg","signedPayload","_sd_alg","sdHash","calculateSdHash","kbJwtPayload","iat","Math","floor","Date","now","sd_hash","aud","presentationResult","createSdJwtPresentation","presentation","kb","payload","JSONLD","vcObject","JSON","parse","vpObject","type","verifiableCredential","createVerifiablePresentation","proofFormat","challenge","domain","keyRef","kmsKeyRef","MSO_MDOC","warning","vcJwt","stringify","identifierString","vpPayload","iss","vp","holder","exp","vpJwt","proof","jwt","import_did_auth_siop","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","logger","Loggers","DEFAULT","get","OpSession","ts","Date","getDate","id","options","context","requestJwtOrUri","verifiedAuthorizationRequest","_nonce","_state","sessionId","op","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","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","result","response","jwt","sendAuthorizationResponse","args","responseSignerOpts","dcqlResponse","isFirstParty","resolveOpts","resolver","getAgentResolver","uniresolverResolution","localResolution","resolverResolution","request","eventEmitter","presentationSignCallback","wellknownDIDVerifyCallback","supportedVersions","versions","idOpts","createAuthorizationResponse","submitAuthorizationResponse","status","statusText","text","toLowerCase","replace","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","dcqlQuery","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_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_ssi_types","import_did_auth_siop","import_ssi_types","isUniqueDigitalCredential","credential","digitalCredential","undefined","convertToDcqlCredentials","credential","hasher","originalVerifiableCredential","isUniqueDigitalCredential","Error","CredentialMapper","decodeVerifiableCredential","isJwtDecodedCredential","Dcql","toDcqlJwtCredential","toWrappedVerifiableCredential","isSdJwtDecodedCredential","toDcqlSdJwtCredential","isMsoMdocDecodedCredential","toDcqlMdocCredential","isW3cCredential","toDcqlJsonLdCredential","JSON","stringify","CLOCK_SKEW","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","siopSendAuthorizationResponse","connectionType","args","context","agent","credentials","ConnectionType","SIOPv2_OpenID4VP","Promise","reject","Error","session","siopGetOPSession","sessionId","request","getAuthorizationRequest","aud","authorizationRequest","getMergedProperty","logger","debug","JSON","stringify","domain","issuer","nonce","firstUniqueDC","identifier","digitalCredential","firstVC","uniformVerifiableCredential","holder","CredentialMapper","isSdJwtDecodedCredential","decodedPayload","cnf","jwk","encodeJoseBlob","sub","Array","isArray","credentialSubject","id","kmsKeyRef","identifierManagedGet","e","isOID4VCIssuerIdentifier","identifierManagedGetByOID4VCIssuer","subjectCorrelationType","identifierManagedGetByDid","subjectCorrelationId","identifierManagedGetByKid","dcqlCredentialsWithCredentials","Map","map","vc","convertToDcqlCredentials","queryResult","DcqlQuery","query","dcqlQuery","from","keys","can_be_satisfied","presentationContext","requestObject","getPayload","audience","clockSkew","CLOCK_SKEW","hasher","presentation","uniqueCredentials","values","key","value","Object","entries","credential_matches","success","matchedCredentials","valid_credentials","cred","input_credential_index","vp","createVerifiablePresentationForFormat","error","dcqlPresentation","DcqlPresentation","parse","response","sendAuthorizationResponse","responseSignerOpts","dcqlResponse","getSelectableCredentials","agentContext","uniqueVerifiableCredentials","crsGetUniqueCredentials","filter","verifiableCredentialForRoleFilter","CredentialRole","HOLDER","branding","ibGetCredentialBranding","selectableCredentialsMap","mapSelectableCredentialPromises","matchedCredential","credentialBranding","cb","vcHash","hash","issuerPartyIdentity","cmGetContacts","identities","correlationId","issuerDid","subjectPartyIdentity","subjectDid","credential","localeBranding","issuerParty","subjectParty","selectableCredentials","all","set","translateCorrelationIdToName","contacts","length","undefined","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","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","dcqlQuery","translateCorrelationIdToName","issuerHostname","authorizationRequestData","cmGetContacts","filter","identities","identifier","then","contacts","length","contact","startsWith","protocol","identity","alias","origin","IdentityOrigin","EXTERNAL","roles","CredentialRole","ISSUER","CorrelationIdentifierType","DID","addedIdentity","cmAddIdentity","contactId","emit","info","selectedCredentials","isFirstParty","response","siopSendAuthorizationResponse","ConnectionType","SIOPv2_OpenID4VP","idOpts","credentials","contentType","headers","responseBody","text","parse","body","queryParams","decodeUriAsJson","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","args","id","handle","url","opts","debug","siopv2Machine","agent","siopGetMachineInterpreter","interpreter","machineState","contextHasPlugin","init","interpreterStartOrResume","cleanupAllOtherInstances","cleanupOnFinalState","singletonCheck","noRegistration","start"]}
|
|
1
|
+
{"version":3,"sources":["../src/localization/translations/en.json","../src/localization/translations/nl.json","../src/index.ts","../plugin.schema.json","../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 * @public\n */\nimport schema from '../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'\nexport * from './utils/dcql'\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","import { decodeUriAsJson, PresentationSignCallback, VerifiedAuthorizationRequest } from '@sphereon/did-auth-siop'\nimport { ConnectionType, CorrelationIdentifierType, Identity, IdentityOrigin, NonPersistedIdentity, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { HasherSync, Loggers, CredentialRole } from '@sphereon/ssi-types'\nimport { IAgentPlugin } from '@veramo/core'\nimport { v4 as uuidv4 } from 'uuid'\nimport { OpSession } from '../session'\nimport { EventEmitter } from 'events'\nimport {\n DidAuthSiopOpAuthenticatorOptions,\n GetSelectableCredentialsArgs,\n IDidAuthSiopOpAuthenticator,\n IGetSiopSessionArgs,\n IOpSessionArgs,\n IRegisterCustomApprovalForSiopArgs,\n IRemoveCustomApprovalForSiopArgs,\n IRemoveSiopSessionArgs,\n IRequiredContext,\n LOGGER_NAMESPACE,\n RequiredContext,\n SelectableCredentialsMap,\n Siopv2AuthorizationResponseData,\n} from '../types'\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 { 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 // TODO do we still need this?\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 = 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 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 response = await siopSendAuthorizationResponse(\n ConnectionType.SIOPv2_OpenID4VP,\n {\n sessionId: didAuthConfig.sessionId,\n ...(args.idOpts && { idOpts: args.idOpts }),\n isFirstParty,\n hasher: this.hasher,\n credentials: selectedCredentials,\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 async siopGetSelectableCredentials(args: GetSelectableCredentialsArgs, context: RequiredContext): Promise<SelectableCredentialsMap> {\n const { authorizationRequestData } = args\n\n if (!authorizationRequestData?.dcqlQuery) {\n return Promise.reject(Error('Missing required dcql query in context'))\n }\n\n return getSelectableCredentials(authorizationRequestData?.dcqlQuery, 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(opOptions.supportedVersions ?? [SupportedVersion.OID4VP_v1, SupportedVersion.SIOPv2_OID4VP_D28])\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 { isManagedIdentifierDidResult, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { calculateSdHash, defaultGenerateDigest, PartialSdJwtKbJwt } from '@sphereon/ssi-sdk.sd-jwt'\nimport {\n CredentialMapper,\n DocumentFormat,\n HasherSync,\n Loggers,\n OriginalVerifiableCredential,\n SdJwtDecodedVerifiableCredential,\n WrappedVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { LOGGER_NAMESPACE, RequiredContext } from '../types'\n\nconst CLOCK_SKEW = 120\nconst logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\nexport interface PresentationBuilderContext {\n nonce: string\n audience: string // clientId or origin\n agent: RequiredContext['agent']\n clockSkew?: number\n hasher?: HasherSync\n}\n\n/**\n * Extracts the original credential from a UniqueDigitalCredential or WrappedVerifiableCredential\n */\nfunction extractOriginalCredential(\n credential: UniqueDigitalCredential | WrappedVerifiableCredential | OriginalVerifiableCredential,\n): OriginalVerifiableCredential {\n if (typeof credential === 'string') {\n return credential\n }\n\n if ('digitalCredential' in credential) {\n // UniqueDigitalCredential\n const udc = credential as UniqueDigitalCredential\n if (udc.originalVerifiableCredential) {\n return udc.originalVerifiableCredential\n }\n return udc.uniformVerifiableCredential as OriginalVerifiableCredential\n }\n\n if ('original' in credential) {\n // WrappedVerifiableCredential\n return credential.original\n }\n\n // Already an OriginalVerifiableCredential\n return credential as OriginalVerifiableCredential\n}\n\n/**\n * Gets the issuer/holder identifier from ManagedIdentifierOptsOrResult\n */\nfunction getIdentifierString(identifier: ManagedIdentifierOptsOrResult): string {\n // Check if it's a result type (has 'method' and 'opts' properties)\n if ('opts' in identifier && 'method' in identifier) {\n // It's a ManagedIdentifierResult\n if (isManagedIdentifierDidResult(identifier)) {\n return identifier.did\n }\n }\n // For opts types or other result types, use issuer if available, otherwise kid\n return identifier.issuer ?? identifier.kid ?? ''\n}\n\n/**\n * Creates a Verifiable Presentation for a given credential in the appropriate format\n * Ensures nonce/aud (or challenge/domain) are set according to OID4VP draft 28\n */\nexport async function createVerifiablePresentationForFormat(\n credential: UniqueDigitalCredential | WrappedVerifiableCredential | OriginalVerifiableCredential,\n identifier: ManagedIdentifierOptsOrResult,\n context: PresentationBuilderContext,\n): Promise<string | object> {\n // FIXME find proper types\n const { nonce, audience, agent, clockSkew = CLOCK_SKEW } = context\n\n const originalCredential = extractOriginalCredential(credential)\n const documentFormat = CredentialMapper.detectDocumentType(originalCredential)\n\n logger.debug(`Creating VP for format: ${documentFormat}`)\n\n switch (documentFormat) {\n case DocumentFormat.SD_JWT_VC: {\n // SD-JWT with KB-JWT\n const decodedSdJwt = await CredentialMapper.decodeSdJwtVcAsync(\n typeof originalCredential === 'string' ? originalCredential : (originalCredential as SdJwtDecodedVerifiableCredential).compactSdJwtVc,\n defaultGenerateDigest,\n )\n\n const hashAlg = decodedSdJwt.signedPayload._sd_alg ?? 'sha-256'\n const sdHash = calculateSdHash(decodedSdJwt.compactSdJwtVc, hashAlg, defaultGenerateDigest)\n\n const kbJwtPayload: PartialSdJwtKbJwt['payload'] = {\n iat: Math.floor(Date.now() / 1000 - clockSkew),\n sd_hash: sdHash,\n nonce, // Always use the Authorization Request nonce\n aud: audience, // Always use the Client Identifier or Origin\n }\n\n const presentationResult = await agent.createSdJwtPresentation({\n presentation: decodedSdJwt.compactSdJwtVc,\n kb: {\n payload: kbJwtPayload as any, // FIXME\n },\n })\n\n return presentationResult.presentation\n }\n\n case DocumentFormat.JSONLD: {\n // JSON-LD VC - create JSON-LD VP with challenge and domain in proof\n const vcObject = typeof originalCredential === 'string' ? JSON.parse(originalCredential) : originalCredential\n\n const vpObject = {\n '@context': ['https://www.w3.org/2018/credentials/v1'],\n type: ['VerifiablePresentation'],\n verifiableCredential: [vcObject],\n }\n\n // Create JSON-LD VP with proof\n return await agent.createVerifiablePresentation({\n presentation: vpObject,\n proofFormat: 'lds',\n challenge: nonce, // Authorization Request nonce as challenge\n domain: audience, // Client Identifier or Origin as domain\n keyRef: identifier.kmsKeyRef || identifier.kid,\n })\n }\n\n case DocumentFormat.MSO_MDOC: {\n // ISO mdoc - create mdoc VP token\n // This is a placeholder implementation\n // Full implementation would require:\n // 1. Decode the mdoc using CredentialMapper or mdoc utilities\n // 2. Build proper mdoc VP token with session transcript\n // 3. Include nonce/audience in the session transcript\n logger.warning('mso_mdoc format has basic support - production use requires proper mdoc VP token implementation')\n\n return originalCredential\n }\n\n default: {\n // JWT VC - create JWT VP with nonce and aud in payload\n const vcJwt = typeof originalCredential === 'string' ? originalCredential : JSON.stringify(originalCredential)\n\n const identifierString = getIdentifierString(identifier)\n\n // Create VP JWT using agent method\n const vpPayload = {\n iss: identifierString,\n aud: audience, // Client Identifier or Origin\n nonce, // Authorization Request nonce\n vp: {\n '@context': ['https://www.w3.org/2018/credentials/v1'],\n type: ['VerifiablePresentation'],\n holder: identifierString,\n verifiableCredential: [vcJwt],\n },\n iat: Math.floor(Date.now() / 1000 - clockSkew),\n exp: Math.floor(Date.now() / 1000 + 600 + clockSkew), // 10 minutes\n }\n\n // Use the agent's JWT creation capability\n const vpJwt = await agent.createVerifiablePresentation({\n presentation: vpPayload.vp,\n proofFormat: 'jwt',\n domain: audience,\n challenge: nonce,\n keyRef: identifier.kmsKeyRef || identifier.kid,\n })\n\n return vpJwt.proof?.jwt || vpJwt\n }\n }\n}\n","import {\n DcqlResponseOpts,\n PresentationSignCallback,\n ResponseMode,\n SupportedVersion,\n URI,\n VerifiedAuthorizationRequest,\n VerifyJwtCallback,\n} from '@sphereon/did-auth-siop'\nimport { CheckLinkedDomain, ResolveOpts } from '@sphereon/did-auth-siop-adapter'\nimport { DIDDocument } from '@sphereon/did-uni-client'\nimport { IIdentifierResolution, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { ICredentialStore } from '@sphereon/ssi-sdk.credential-store'\nimport { Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { IPDManager } from '@sphereon/ssi-sdk.pd-manager'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\nimport { HasherSync, 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'\nimport { DcqlPresentation, DcqlQuery } from 'dcql'\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 dcqlQuery?: DcqlQuery\n identifierOptions?: ManagedIdentifierOptsOrResult\n context: IRequiredContext\n op?: IOPOptions\n}\n\nexport interface IAuthRequestDetails {\n rpDIDDocument?: DIDDocument\n id: string\n verifiablePresentationMatches: DcqlPresentation[]\n alsoKnownAs?: string[]\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 presentationSubmission?: PresentationSubmission\n verifiablePresentations?: W3CVerifiablePresentation[]\n dcqlResponse?: DcqlResponseOpts\n hasher?: HasherSync\n isFirstParty?: boolean\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 verifyJwtCallback?: VerifyJwtCallback\n wellknownDIDVerifyCallback?: VerifyCallback\n presentationSignCallback?: PresentationSignCallback\n resolveOpts?: ResolveOpts\n hasher?: HasherSync\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 const DEFAULT_JWT_PROOF_TYPE = 'JwtProof2020'\n","import { PresentationSignCallback, RPRegistrationMetadataPayload, VerifiedAuthorizationRequest } 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-types'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\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 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 &\n IDidAuthSiopOpAuthenticator &\n IDIDManager &\n IResolver &\n IIdentifierResolution &\n ICredentialStore &\n IIssuanceBranding &\n ISDJwtPlugin\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-types'\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'\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>\n","import {\n AuthorizationResponsePayload,\n JwksMetadataParams,\n OP,\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 { Loggers, parseDid } from '@sphereon/ssi-types'\nimport { IIdentifier, TKeyType } from '@veramo/core'\nimport { v4 } from 'uuid'\nimport { IOPOptions, IOpSessionArgs, IOpsSendSiopAuthorizationResponseArgs, IRequiredContext } from '../types'\nimport { createOP } from './functions'\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\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 }\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') || 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 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 { responseSignerOpts, dcqlResponse, isFirstParty } = args\n\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\n const request = await this.getAuthorizationRequest()\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: 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 = responseSignerOpts.issuer\n const responseOpts = {\n issuer,\n ...(isFirstParty && { isFirstParty }),\n dcqlResponse: 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\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-types'\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.dcqlQuery !== 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.dcqlQuery === undefined) {\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.dcqlQuery === 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.dcqlQuery !== 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 } from '@sphereon/did-auth-siop'\nimport { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport { isOID4VCIssuerIdentifier, ManagedIdentifierOptsOrResult } from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { encodeJoseBlob } from '@sphereon/ssi-sdk.core'\nimport { UniqueDigitalCredential, verifiableCredentialForRoleFilter } from '@sphereon/ssi-sdk.credential-store'\nimport { ConnectionType } from '@sphereon/ssi-sdk.data-store-types'\nimport { CredentialMapper, CredentialRole, HasherSync, Loggers, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { IAgentContext, IDIDManager } from '@veramo/core'\nimport { DcqlPresentation, DcqlQuery } from 'dcql'\nimport { createVerifiablePresentationForFormat, OpSession, PresentationBuilderContext } from '../session'\nimport { LOGGER_NAMESPACE, RequiredContext, SelectableCredential, SelectableCredentialsMap, Siopv2HolderEvent } from '../types'\nimport { convertToDcqlCredentials } from '../utils/dcql'\n\nconst CLOCK_SKEW = 120\n\nexport const logger = Loggers.DEFAULT.get(LOGGER_NAMESPACE)\n\n// @ts-ignore\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\n// @ts-ignore\nconst hasEbsiClient = async (authorizationRequest: AuthorizationRequest) => {\n const clientId = authorizationRequest.getMergedProperty<string>('client_id')\n const redirectUri = 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 credentials: Array<UniqueDigitalCredential | OriginalVerifiableCredential>\n idOpts?: ManagedIdentifierOptsOrResult\n isFirstParty?: boolean\n hasher?: HasherSync\n },\n context: RequiredContext,\n) => {\n const { agent } = context\n const { credentials } = args\n if (connectionType !== ConnectionType.SIOPv2_OpenID4VP) {\n return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`))\n }\n\n const session: OpSession = await agent.siopGetOPSession({ sessionId: args.sessionId })\n const request = await session.getAuthorizationRequest()\n const aud = request.authorizationRequest.getMergedProperty<string>('aud')\n logger.debug(`AUD: ${aud}`)\n logger.debug(JSON.stringify(request.authorizationRequest))\n\n const domain = ((await request.authorizationRequest.getMergedProperty('client_id')) as string) ?? request.issuer ?? 'https://self-issued.me/v2'\n\n logger.debug(`NONCE: ${session.nonce}, domain: ${domain}`)\n\n const firstUniqueDC = 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\n // Determine holder DID for identifier resolution\n let holder: string | undefined\n if (CredentialMapper.isSdJwtDecodedCredential(firstVC)) {\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\n holder = firstVC.decodedPayload.cnf?.jwk ? `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0` : firstVC.decodedPayload.sub\n } else {\n holder = Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id\n }\n\n // Resolve identifier\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\n const dcqlCredentialsWithCredentials = new Map(credentials.map((vc) => [convertToDcqlCredentials(vc), vc]))\n\n const queryResult = DcqlQuery.query(request.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()))\n\n if (!queryResult.can_be_satisfied) {\n return Promise.reject(Error('Credentials do not match required query request'))\n }\n\n // Build presentation context for format-aware VP creation\n const presentationContext: PresentationBuilderContext = {\n nonce: request.requestObject?.getPayload()?.nonce ?? session.nonce,\n audience: domain,\n agent: context.agent,\n clockSkew: CLOCK_SKEW,\n hasher: args.hasher,\n }\n\n // Build DCQL presentation with format-aware VPs\n const presentation: DcqlPresentation.Output = {}\n const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values())\n for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n if (value.success) {\n const matchedCredentials = value.valid_credentials.map((cred) => uniqueCredentials[cred.input_credential_index])\n const vc = matchedCredentials[0] // taking the first match for now\n\n if (!vc) {\n continue\n }\n\n try {\n // Use format-aware presentation builder\n const vp = await createVerifiablePresentationForFormat(vc, identifier, presentationContext)\n presentation[key] = vp as any\n } catch (error) {\n logger.error(`Failed to create VP for credential ${key}:`, error)\n throw error\n }\n }\n }\n\n const dcqlPresentation = DcqlPresentation.parse(presentation)\n\n const response = session.sendAuthorizationResponse({\n responseSignerOpts: identifier,\n dcqlResponse: {\n dcqlPresentation,\n },\n })\n\n logger.debug(`Response: `, response)\n return response\n}\n\nexport const getSelectableCredentials = async (dcqlQuery: DcqlQuery, context: RequiredContext): Promise<SelectableCredentialsMap> => {\n const agentContext = { ...context, agent: context.agent }\n const { agent } = agentContext\n const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({\n filter: verifiableCredentialForRoleFilter(CredentialRole.HOLDER),\n })\n const branding = await agent.ibGetCredentialBranding()\n const dcqlCredentialsWithCredentials = new Map(uniqueVerifiableCredentials.map((vc) => [convertToDcqlCredentials(vc), vc]))\n const queryResult = DcqlQuery.query(dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()))\n const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values())\n const selectableCredentialsMap: SelectableCredentialsMap = new Map()\n\n for (const [key, value] of Object.entries(queryResult.credential_matches)) {\n if (!value.valid_credentials) {\n continue\n }\n\n const mapSelectableCredentialPromises = value.valid_credentials.map(async (cred) => {\n const matchedCredential = uniqueCredentials[cred.input_credential_index]\n const credentialBranding = branding.filter((cb) => cb.vcHash === matchedCredential.hash)\n const issuerPartyIdentity = await agent.cmGetContacts({\n filter: [{ identities: { identifier: { correlationId: matchedCredential.uniformVerifiableCredential!.issuerDid } } }],\n })\n const subjectPartyIdentity = await agent.cmGetContacts({\n filter: [{ identities: { identifier: { correlationId: matchedCredential.uniformVerifiableCredential!.subjectDid } } }],\n })\n\n return {\n credential: matchedCredential,\n credentialBranding: credentialBranding[0]?.localeBranding,\n issuerParty: issuerPartyIdentity?.[0],\n subjectParty: subjectPartyIdentity?.[0],\n }\n })\n\n const selectableCredentials: Array<SelectableCredential> = await Promise.all(mapSelectableCredentialPromises)\n selectableCredentialsMap.set(key, selectableCredentials)\n }\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 {\n CredentialMapper,\n HasherSync,\n OriginalVerifiableCredential,\n WrappedMdocCredential,\n type WrappedSdJwtVerifiableCredential,\n type WrappedW3CVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { Dcql } from '@sphereon/did-auth-siop'\nimport { DcqlCredential } from 'dcql'\nimport { isUniqueDigitalCredential } from './CredentialUtils'\n\nexport function convertToDcqlCredentials(credential: UniqueDigitalCredential | OriginalVerifiableCredential, hasher?: HasherSync): DcqlCredential {\n let originalVerifiableCredential\n if (isUniqueDigitalCredential(credential)) {\n if (!credential.originalVerifiableCredential) {\n throw new Error('originalVerifiableCredential is not defined in UniqueDigitalCredential')\n }\n originalVerifiableCredential = CredentialMapper.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher)\n } else {\n originalVerifiableCredential = CredentialMapper.decodeVerifiableCredential(credential as OriginalVerifiableCredential, hasher)\n }\n\n if (!originalVerifiableCredential) {\n throw new Error('No payload found')\n }\n\n if (CredentialMapper.isJwtDecodedCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlJwtCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedW3CVerifiableCredential)\n } else if (CredentialMapper.isSdJwtDecodedCredential(originalVerifiableCredential)) {\n // FIXME: SD-JWT VC vs VCDM2 + SD-JWT would need to be handled here\n return Dcql.toDcqlSdJwtCredential(\n CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedSdJwtVerifiableCredential,\n )\n } else if (CredentialMapper.isMsoMdocDecodedCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlMdocCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedMdocCredential)\n } else if (CredentialMapper.isW3cCredential(originalVerifiableCredential)) {\n return Dcql.toDcqlJsonLdCredential(CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential) as WrappedW3CVerifiableCredential)\n }\n\n throw Error(`Unable to map credential to DCQL credential. Credential: ${JSON.stringify(originalVerifiableCredential)}`)\n}\n","import { CredentialMapper, HasherSync, ICredential, OriginalVerifiableCredential } from '@sphereon/ssi-types'\nimport { VerifiableCredential } from '@veramo/core'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\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 as OriginalVerifiableCredential // FIXME SSISDK-59\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;AAA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KL,UAAUI,KAAKJ;AACpB,SAAKE,4BAA4BE,KAAKF,8BAA8B;AACpE,SAAKD,0BAA0BG,KAAKH;AACpC,SAAKE,SAASC,KAAKD;EACrB;EAEA,MAAMG,OACJC,KACAC,MAIe;AACfhB,IAAAA,QAAOiB,MAAM,uBAAuBF,GAAAA,EAAK;AAEzC,UAAMG,gBAAgB,MAAM,KAAKV,QAAQW,MAAMC,0BAA0B;MACvEL;MACAJ,QAAQK,MAAML,UAAU,KAAKA;MAC7BF,yBAAyB,KAAKA;IAChC,CAAA;AAEA,UAAMY,cAAcH,cAAcG;AAClC,QAAI,CAAC,KAAKX,6BAA6B,CAACM,MAAMM,oBAAgBC,kCAAiB,KAAKf,SAAS,yBAAA,GAA4B;AACvH,YAAMgB,OAAO,UAAMC,2CAAyB;QAC1CJ;QACAb,SAAS,KAAKA;QACdkB,0BAA0B;QAC1BC,qBAAqB;QACrBC,gBAAgB;QAChBC,gBAAgB,KAAKnB;MACvB,CAAA;AACAV,MAAAA,QAAOiB,MAAM,kCAAkCF,GAAAA,IAAOS,IAAAA;IACxD,OAAO;AAELH,kBAAYS,MAAMd,MAAMM,YAAAA;AACxBtB,MAAAA,QAAOiB,MAAM,kCAAkCF,GAAAA,EAAK;IACtD;EACF;AACF;","names":["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","OID4VP_v1","SIOPv2_OID4VP_D28","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_ssi_sdk_ext","import_ssi_sdk","LOGGER_NAMESPACE","DEFAULT_JWT_PROOF_TYPE","Siopv2HolderEvent","SupportedLanguage","Siopv2MachineStates","Siopv2MachineAddContactStates","Siopv2MachineEvents","Siopv2MachineGuards","Siopv2MachineServices","DID_PREFIX","CLOCK_SKEW","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","extractOriginalCredential","credential","udc","originalVerifiableCredential","uniformVerifiableCredential","original","getIdentifierString","identifier","isManagedIdentifierDidResult","did","issuer","kid","createVerifiablePresentationForFormat","context","nonce","audience","agent","clockSkew","originalCredential","documentFormat","CredentialMapper","detectDocumentType","debug","DocumentFormat","SD_JWT_VC","decodedSdJwt","decodeSdJwtVcAsync","compactSdJwtVc","defaultGenerateDigest","hashAlg","signedPayload","_sd_alg","sdHash","calculateSdHash","kbJwtPayload","iat","Math","floor","Date","now","sd_hash","aud","presentationResult","createSdJwtPresentation","presentation","kb","payload","JSONLD","vcObject","JSON","parse","vpObject","type","verifiableCredential","createVerifiablePresentation","proofFormat","challenge","domain","keyRef","kmsKeyRef","MSO_MDOC","warning","vcJwt","stringify","identifierString","vpPayload","iss","vp","holder","exp","vpJwt","proof","jwt","import_did_auth_siop","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","logger","Loggers","DEFAULT","get","OpSession","ts","Date","getDate","id","options","context","requestJwtOrUri","verifiedAuthorizationRequest","_nonce","_state","sessionId","op","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","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","result","response","jwt","sendAuthorizationResponse","args","responseSignerOpts","dcqlResponse","isFirstParty","resolveOpts","resolver","getAgentResolver","uniresolverResolution","localResolution","resolverResolution","request","eventEmitter","presentationSignCallback","wellknownDIDVerifyCallback","supportedVersions","versions","idOpts","createAuthorizationResponse","submitAuthorizationResponse","status","statusText","text","toLowerCase","replace","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","dcqlQuery","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_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_ssi_types","import_did_auth_siop","import_ssi_types","isUniqueDigitalCredential","credential","digitalCredential","undefined","convertToDcqlCredentials","credential","hasher","originalVerifiableCredential","isUniqueDigitalCredential","Error","CredentialMapper","decodeVerifiableCredential","isJwtDecodedCredential","Dcql","toDcqlJwtCredential","toWrappedVerifiableCredential","isSdJwtDecodedCredential","toDcqlSdJwtCredential","isMsoMdocDecodedCredential","toDcqlMdocCredential","isW3cCredential","toDcqlJsonLdCredential","JSON","stringify","CLOCK_SKEW","logger","Loggers","DEFAULT","get","LOGGER_NAMESPACE","siopSendAuthorizationResponse","connectionType","args","context","agent","credentials","ConnectionType","SIOPv2_OpenID4VP","Promise","reject","Error","session","siopGetOPSession","sessionId","request","getAuthorizationRequest","aud","authorizationRequest","getMergedProperty","logger","debug","JSON","stringify","domain","issuer","nonce","firstUniqueDC","identifier","digitalCredential","firstVC","uniformVerifiableCredential","holder","CredentialMapper","isSdJwtDecodedCredential","decodedPayload","cnf","jwk","encodeJoseBlob","sub","Array","isArray","credentialSubject","id","kmsKeyRef","identifierManagedGet","e","isOID4VCIssuerIdentifier","identifierManagedGetByOID4VCIssuer","subjectCorrelationType","identifierManagedGetByDid","subjectCorrelationId","identifierManagedGetByKid","dcqlCredentialsWithCredentials","Map","map","vc","convertToDcqlCredentials","queryResult","DcqlQuery","query","dcqlQuery","from","keys","can_be_satisfied","presentationContext","requestObject","getPayload","audience","clockSkew","CLOCK_SKEW","hasher","presentation","uniqueCredentials","values","key","value","Object","entries","credential_matches","success","matchedCredentials","valid_credentials","cred","input_credential_index","vp","createVerifiablePresentationForFormat","error","dcqlPresentation","DcqlPresentation","parse","response","sendAuthorizationResponse","responseSignerOpts","dcqlResponse","getSelectableCredentials","agentContext","uniqueVerifiableCredentials","crsGetUniqueCredentials","filter","verifiableCredentialForRoleFilter","CredentialRole","HOLDER","branding","ibGetCredentialBranding","selectableCredentialsMap","mapSelectableCredentialPromises","matchedCredential","credentialBranding","cb","vcHash","hash","issuerPartyIdentity","cmGetContacts","identities","correlationId","issuerDid","subjectPartyIdentity","subjectDid","credential","localeBranding","issuerParty","subjectParty","selectableCredentials","all","set","translateCorrelationIdToName","contacts","length","undefined","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","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","dcqlQuery","translateCorrelationIdToName","issuerHostname","authorizationRequestData","cmGetContacts","filter","identities","identifier","then","contacts","length","contact","startsWith","protocol","identity","alias","origin","IdentityOrigin","EXTERNAL","roles","CredentialRole","ISSUER","CorrelationIdentifierType","DID","addedIdentity","cmAddIdentity","contactId","emit","info","selectedCredentials","isFirstParty","response","siopSendAuthorizationResponse","ConnectionType","SIOPv2_OpenID4VP","idOpts","credentials","contentType","headers","responseBody","text","parse","body","queryParams","decodeUriAsJson","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","args","id","handle","url","opts","debug","siopv2Machine","agent","siopGetMachineInterpreter","interpreter","machineState","contextHasPlugin","init","interpreterStartOrResume","cleanupAllOtherInstances","cleanupOnFinalState","singletonCheck","noRegistration","start"]}
|