@sphereon/ssi-sdk.oid4vci-holder 0.36.1-feature.SSISDK.82.and.SSISDK.70.35 → 0.36.1-feature.SSISDK.89.metadata.persistence.103

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/localization/translations/en.json","../src/localization/translations/nl.json","../src/index.ts","../src/agent/OID4VCIHolder.ts","../src/machines/oid4vciMachine.ts","../src/localization/Localization.ts","../src/types/IOID4VCIHolder.ts","../src/types/FirstPartyMachine.ts","../src/services/OID4VCIHolderService.ts","../src/machines/firstPartyMachine.ts","../src/services/FirstPartyMachineServices.ts","../src/mappers/OIDC4VCIBrandingMapper.ts","../src/listeners/headlessStateNavListener.ts","../src/link-handler/index.ts"],"sourcesContent":["{\n \"oid4vci_machine_verify_credentials_error_title\": \"Verify credentials\",\n \"oid4vci_machine_store_credential_branding_error_title\": \"Store credential branding\",\n \"oid4vci_machine_store_credential_error_title\": \"Store credential\",\n \"oid4vci_machine_add_contact_identity_error_title\": \"Add contact identity\",\n \"oid4vci_machine_retrieve_credentials_error_title\": \"Retrieve credentials\",\n \"oid4vci_machine_retrieve_issuer_branding_error_title\": \"Retrieve issuer branding\",\n \"oid4vci_machine_store_issuer_branding_error_title\": \"Store issuer branding\",\n \"oid4vci_machine_retrieve_contact_error_title\": \"Retrieve contact\",\n \"oid4vci_machine_credential_selection_error_title\": \"Credential selection\",\n \"oid4vci_machine_initiation_error_title\": \"Initiate OID4VCI provider\",\n \"oid4vci_machine_credential_verification_failed_message\": \"The credential verification resulted in an error.\",\n \"oid4vci_machine_credential_verification_schema_failed_message\": \"The credential schema verification resulted in an error.\",\n \"oid4vci_machine_retrieve_federation_trust_error_title\": \"Retrieve federation trust\",\n \"oid4vci_machine_first_party_error_title\": \"First party flow\",\n \"oid4vci_machine_send_authorization_challenge_request_error_title\": \"Sending authorization challenge request\",\n \"oid4vci_machine_create_config_error_title\": \"Creating siopV2 config\",\n \"oid4vci_machine_get_request_error_title\": \"Getting siopV2 request\"\n}\n","{\n \"oid4vci_machine_verify_credentials_error_title\": \"Verifiëren credential\",\n \"oid4vci_machine_store_credential_branding_error_title\": \"Opslaan credential branding\",\n \"oid4vci_machine_store_credential_error_title\": \"Opslaan credential\",\n \"oid4vci_machine_add_contact_identity_error_title\": \"Toevoegen identiteit contact\",\n \"oid4vci_machine_retrieve_credentials_error_title\": \"Ophalen credential\",\n \"oid4vci_machine_retrieve_issuer_branding_error_title\": \"Ophalen issuer branding\",\n \"oid4vci_machine_store_issuer_branding_error_title\": \"Opslaan issuer branding\",\n \"oid4vci_machine_retrieve_contact_error_title\": \"Ophalen contact\",\n \"oid4vci_machine_credential_selection_error_title\": \"Credential selectie\",\n \"oid4vci_machine_initiation_error_title\": \"Initiëren OID4VCI provider\",\n \"oid4vci_machine_credential_verification_failed_message\": \"Verificatie van de credential leidde tot een fout.\",\n \"oid4vci_machine_retrieve_federation_trust_error_title\": \"Ophalen federatievertrouwen\",\n \"oid4vci_machine_first_party_error_title\": \"Eerste partijstroom\",\n \"oid4vci_machine_send_authorization_challenge_request_error_title\": \"Versturen autorisatie-uitdaging aanvraag\",\n \"oid4vci_machine_create_config_error_title\": \"SiopV2-configuratie aanmaken\",\n \"oid4vci_machine_get_request_error_title\": \"SiopV2-verzoek ophalen\"\n}\n","/**\n * @public\n */\n\nexport { OID4VCIHolder, oid4vciHolderContextMethods, signCallback } from './agent/OID4VCIHolder'\nexport * from './mappers/OIDC4VCIBrandingMapper'\nexport * from './services/OID4VCIHolderService'\nexport * from './services/FirstPartyMachineServices'\nexport * from './types/IOID4VCIHolder'\nexport * from './types/FirstPartyMachine'\nexport * from './listeners/headlessStateNavListener'\nexport * from './link-handler'\n","import { CredentialOfferClient, MetadataClient, OpenID4VCIClient, OpenID4VCIClientV1_0_15 } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationDetailsV1_0_15,\n AuthorizationRequestOpts,\n AuthorizationServerClientOpts,\n AuthorizationServerOpts,\n CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialOfferRequestWithBaseUrl,\n DefaultURISchemes,\n EndpointMetadataResult,\n getTypesFromObject,\n Jwt,\n NotificationRequest,\n ProofOfPossessionCallbacks,\n} from '@sphereon/oid4vci-common'\nimport { SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n IIdentifierResolution,\n isManagedIdentifierDidOpts,\n isManagedIdentifierDidResult,\n isManagedIdentifierJwkResult,\n isManagedIdentifierKidResult,\n isManagedIdentifierResult,\n isManagedIdentifierX5cOpts,\n isManagedIdentifierX5cResult,\n ManagedIdentifierOptsOrResult,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService, JwsHeader } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { defaultHasher } from '@sphereon/ssi-sdk.core'\nimport {\n ConnectionType,\n CorrelationIdentifierType,\n CredentialCorrelationType,\n ensureRawDocument,\n FindPartyArgs,\n IBasicCredentialLocaleBranding,\n IBasicIssuerLocaleBranding,\n Identity,\n IdentityOrigin,\n IIssuerLocaleBranding,\n NonPersistedIdentity,\n Party,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport {\n CredentialMapper,\n type CredentialProofFormat,\n CredentialRole,\n HasherSync,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n JwtDecodedVerifiableCredential,\n Loggers,\n parseDid,\n SdJwtDecodedVerifiableCredentialPayload,\n WrappedW3CVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport {\n CredentialPayload,\n IAgentContext,\n IAgentPlugin,\n IDIDManager,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n W3CVerifiableCredential,\n} from '@veramo/core'\nimport { asArray, computeEntryHash } from '@veramo/utils'\nimport fetch from 'cross-fetch'\nimport { decodeJWT } from 'did-jwt'\nimport { v4 as uuidv4 } from 'uuid'\nimport { OID4VCIMachine } from '../machines/oid4vciMachine'\nimport {\n extractCredentialFromResponse,\n getBasicIssuerLocaleBranding,\n getCredentialBranding,\n getCredentialConfigsSupportedMerged,\n getIdentifierOpts,\n getIssuanceOpts,\n mapCredentialToAccept,\n selectCredentialLocaleBranding,\n startFirstPartApplicationMachine,\n verifyCredentialToAccept,\n} from '../services/OID4VCIHolderService'\nimport {\n AddContactIdentityArgs,\n AssertValidCredentialsArgs,\n Attribute,\n CreateCredentialsToSelectFromArgs,\n CredentialToAccept,\n CredentialToSelectFromResult,\n GetContactArgs,\n GetCredentialArgs,\n GetCredentialsArgs,\n GetFederationTrustArgs,\n GetIssuerBrandingArgs,\n GetIssuerMetadataArgs,\n IOID4VCIHolder,\n IssuanceOpts,\n MappedCredentialToAccept,\n OID4VCIHolderEvent,\n OID4VCIHolderOptions,\n OID4VCIMachine as OID4VCIMachineId,\n OID4VCIMachineInstanceOpts,\n OID4VCIMachineServiceDefinitions,\n OID4VCIMachineServices,\n OnContactIdentityCreatedArgs,\n OnCredentialStoredArgs,\n OnIdentifierCreatedArgs,\n PrepareAuthorizationRequestArgs,\n PrepareAuthorizationResult,\n PrepareStartArgs,\n RequestType,\n RequiredContext,\n SendNotificationArgs,\n StartFirstPartApplicationMachine,\n StartResult,\n StoreCredentialBrandingArgs,\n StoreCredentialsArgs,\n StoreIssuerBrandingArgs,\n VerificationResult,\n VerifyEBSICredentialIssuerArgs,\n VerifyEBSICredentialIssuerResult,\n WalletType,\n} from '../types/IOID4VCIHolder'\n\n/**\n * {@inheritDoc IOID4VCIHolder}\n */\n\n// Exposing the methods here for any REST implementation\nexport const oid4vciHolderContextMethods: Array<string> = [\n 'cmGetContacts',\n 'cmGetContact',\n 'cmAddContact',\n 'cmAddIdentity',\n 'ibCredentialLocaleBrandingFrom',\n 'ibAddCredentialBranding',\n 'dataStoreSaveVerifiableCredential',\n 'didManagerFind',\n 'didManagerGet',\n 'keyManagerSign',\n 'verifyCredential',\n]\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:holder')\n\nexport function signCallback(\n identifier: ManagedIdentifierOptsOrResult,\n context: IAgentContext<IKeyManager & IDIDManager & IResolver & IIdentifierResolution & IJwtService>,\n nonce?: string,\n) {\n return async (jwt: Jwt, kid?: string, noIssPayloadUpdate?: boolean) => {\n let resolution = await context.agent.identifierManagedGet(identifier)\n const jwk = jwt.header.jwk ?? (resolution.method === 'jwk' ? resolution.jwk : undefined)\n if (!resolution.issuer && !jwt.payload.iss) {\n return Promise.reject(Error(`No issuer could be determined from the JWT ${JSON.stringify(jwt)} or identifier resolution`))\n }\n const header = jwt.header as JwsHeader\n const payload = jwt.payload\n if (nonce) {\n payload.nonce = nonce\n }\n if (jwk && header.kid) {\n console.log(\n `Deleting kid, as we are using a jwk and the oid4vci spec does not allow both to be present (which is not the case in the JOSE spec)`,\n )\n delete header.kid // The OID4VCI spec does not allow a JWK with kid present although the JWS spec does\n }\n return (\n await context.agent.jwtCreateJwsCompactSignature({\n issuer: { ...resolution, noIssPayloadUpdate: noIssPayloadUpdate ?? false },\n protectedHeader: header,\n payload,\n })\n ).jwt\n }\n}\n\nexport async function verifyEBSICredentialIssuer(args: VerifyEBSICredentialIssuerArgs): Promise<VerifyEBSICredentialIssuerResult> {\n const { wrappedVc, issuerType = ['TI'] } = args\n\n const issuer =\n wrappedVc.decoded?.iss ??\n (typeof wrappedVc.decoded?.vc?.issuer === 'string' ? wrappedVc.decoded?.vc?.issuer : wrappedVc.decoded?.vc?.issuer?.existingInstanceId)\n\n if (!issuer) {\n throw Error('The issuer of the VC is required to be present')\n }\n\n const url = `https://api-conformance.ebsi.eu/trusted-issuers-registry/v4/issuers/${issuer}`\n const response = await fetch(url)\n if (response.status !== 200) {\n throw Error('The issuer of the VC cannot be trusted')\n }\n\n const payload = (await response.json()) as VerifyEBSICredentialIssuerResult\n\n if (!payload.attributes.some((a: Attribute) => issuerType.includes(a.issuerType))) {\n throw Error(`The issuer type is required to be one of: ${issuerType.join(', ')}`)\n }\n\n return payload\n}\n\nexport class OID4VCIHolder implements IAgentPlugin {\n private readonly hasher?: HasherSync\n readonly eventTypes: Array<OID4VCIHolderEvent> = [\n OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED,\n OID4VCIHolderEvent.CREDENTIAL_STORED,\n OID4VCIHolderEvent.IDENTIFIER_CREATED,\n ]\n\n readonly methods: IOID4VCIHolder = {\n oid4vciHolderStart: this.oid4vciHolderStart.bind(this),\n oid4vciHolderGetIssuerMetadata: this.oid4vciHolderGetIssuerMetadata.bind(this),\n oid4vciHolderGetMachineInterpreter: this.oid4vciHolderGetMachineInterpreter.bind(this),\n oid4vciHolderPrepareAuthorizationRequest: this.oid4vciHolderPrepareAuthorizationRequest.bind(this),\n oid4vciHolderCreateCredentialsToSelectFrom: this.oid4vciHolderCreateCredentialsToSelectFrom.bind(this),\n oid4vciHolderGetContact: this.oid4vciHolderGetContact.bind(this),\n oid4vciHolderGetCredentials: this.oid4vciHolderGetCredentials.bind(this),\n oid4vciHolderGetCredential: this.oid4vciHolderGetCredential.bind(this),\n oid4vciHolderAddContactIdentity: this.oid4vciHolderAddContactIdentity.bind(this),\n oid4vciHolderAssertValidCredentials: this.oid4vciHolderAssertValidCredentials.bind(this),\n oid4vciHolderStoreCredentialBranding: this.oid4vciHolderStoreCredentialBranding.bind(this),\n oid4vciHolderStoreCredentials: this.oid4vciHolderStoreCredentials.bind(this),\n oid4vciHolderSendNotification: this.oid4vciHolderSendNotification.bind(this),\n oid4vciHolderGetIssuerBranding: this.oid4vciHolderGetIssuerBranding.bind(this),\n oid4vciHolderStoreIssuerBranding: this.oid4vciHolderStoreIssuerBranding.bind(this),\n }\n\n private readonly vcFormatPreferences: Array<string> = ['dc+sd-jwt', 'vc+sd-jwt', 'mso_mdoc', 'jwt_vc_json', 'jwt_vc', 'ldp_vc'] // TODO see SSISDK-52 concerning vc+sd-jwt\n private readonly jsonldCryptographicSuitePreferences: Array<string> = [\n 'Ed25519Signature2018',\n 'EcdsaSecp256k1Signature2019',\n 'Ed25519Signature2020',\n 'JsonWebSignature2020',\n // \"JcsEd25519Signature2020\"\n ]\n private readonly didMethodPreferences: Array<SupportedDidMethodEnum> = [\n SupportedDidMethodEnum.DID_JWK, // FIXME prefer JWK until we devise a method to detect when to use EBSI/jcs for did:key and when not\n SupportedDidMethodEnum.DID_KEY,\n SupportedDidMethodEnum.DID_OYD,\n SupportedDidMethodEnum.DID_EBSI,\n SupportedDidMethodEnum.DID_ION,\n ]\n private readonly jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString> = [\n JoseSignatureAlgorithm.ES256,\n JoseSignatureAlgorithm.ES256K,\n JoseSignatureAlgorithm.EdDSA,\n ]\n private static readonly DEFAULT_MOBILE_REDIRECT_URI = `${DefaultURISchemes.CREDENTIAL_OFFER}://`\n private readonly defaultAuthorizationRequestOpts: AuthorizationRequestOpts = { redirectUri: OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI }\n private readonly onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n private readonly onCredentialStored?: (args: OnCredentialStoredArgs) => Promise<void>\n private readonly onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n private readonly onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n\n constructor(options?: OID4VCIHolderOptions) {\n const {\n onContactIdentityCreated,\n onCredentialStored,\n onIdentifierCreated,\n onVerifyEBSICredentialIssuer,\n vcFormatPreferences,\n jsonldCryptographicSuitePreferences,\n didMethodPreferences,\n jwtCryptographicSuitePreferences,\n defaultAuthorizationRequestOptions,\n hasher = defaultHasher,\n } = { ...options }\n\n this.hasher = hasher\n if (vcFormatPreferences !== undefined && vcFormatPreferences.length > 0) {\n this.vcFormatPreferences = vcFormatPreferences\n }\n if (jsonldCryptographicSuitePreferences !== undefined && jsonldCryptographicSuitePreferences.length > 0) {\n this.jsonldCryptographicSuitePreferences = jsonldCryptographicSuitePreferences\n }\n if (didMethodPreferences !== undefined && didMethodPreferences.length > 0) {\n this.didMethodPreferences = didMethodPreferences\n }\n if (jwtCryptographicSuitePreferences !== undefined && jwtCryptographicSuitePreferences.length > 0) {\n this.jwtCryptographicSuitePreferences = jwtCryptographicSuitePreferences\n }\n if (defaultAuthorizationRequestOptions) {\n this.defaultAuthorizationRequestOpts = defaultAuthorizationRequestOptions\n }\n this.onContactIdentityCreated = onContactIdentityCreated\n this.onCredentialStored = onCredentialStored\n this.onIdentifierCreated = onIdentifierCreated\n this.onVerifyEBSICredentialIssuer = onVerifyEBSICredentialIssuer\n }\n\n public async onEvent(event: any, context: RequiredContext): Promise<void> {\n switch (event.type) {\n case OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED:\n this.onContactIdentityCreated?.(event.data)\n break\n case OID4VCIHolderEvent.CREDENTIAL_STORED:\n this.onCredentialStored?.(event.data)\n break\n case OID4VCIHolderEvent.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 /**\n * FIXME: This method can only be used locally. Creating the interpreter should be local to where the agent is running\n */\n private async oid4vciHolderGetMachineInterpreter(opts: OID4VCIMachineInstanceOpts, context: RequiredContext): Promise<OID4VCIMachineId> {\n const authorizationRequestOpts = { ...this.defaultAuthorizationRequestOpts, ...opts.authorizationRequestOpts }\n const services: OID4VCIMachineServiceDefinitions = {\n [OID4VCIMachineServices.start]: (args: PrepareStartArgs) =>\n this.oid4vciHolderStart(\n {\n ...args,\n authorizationRequestOpts,\n },\n context,\n ),\n [OID4VCIMachineServices.startFirstPartApplicationFlow]: (args: StartFirstPartApplicationMachine) =>\n startFirstPartApplicationMachine({ ...args, stateNavigationListener: opts.firstPartyStateNavigationListener }, context),\n [OID4VCIMachineServices.createCredentialsToSelectFrom]: (args: CreateCredentialsToSelectFromArgs) =>\n this.oid4vciHolderCreateCredentialsToSelectFrom(args, context),\n [OID4VCIMachineServices.prepareAuthorizationRequest]: (args: PrepareAuthorizationRequestArgs) =>\n this.oid4vciHolderPrepareAuthorizationRequest(args, context),\n [OID4VCIMachineServices.getContact]: (args: GetContactArgs) => this.oid4vciHolderGetContact(args, context),\n [OID4VCIMachineServices.getCredentials]: (args: GetCredentialsArgs) =>\n this.oid4vciHolderGetCredentials({ accessTokenOpts: args.accessTokenOpts ?? opts.accessTokenOpts, ...args }, context),\n [OID4VCIMachineServices.addContactIdentity]: (args: AddContactIdentityArgs) => this.oid4vciHolderAddContactIdentity(args, context),\n [OID4VCIMachineServices.getIssuerBranding]: (args: GetIssuerBrandingArgs) => this.oid4vciHolderGetIssuerBranding(args, context),\n [OID4VCIMachineServices.storeIssuerBranding]: (args: StoreIssuerBrandingArgs) => this.oid4vciHolderStoreIssuerBranding(args, context),\n [OID4VCIMachineServices.assertValidCredentials]: (args: AssertValidCredentialsArgs) => this.oid4vciHolderAssertValidCredentials(args, context),\n [OID4VCIMachineServices.storeCredentialBranding]: (args: StoreCredentialBrandingArgs) =>\n this.oid4vciHolderStoreCredentialBranding(args, context),\n [OID4VCIMachineServices.storeCredentials]: (args: StoreCredentialsArgs) => this.oid4vciHolderStoreCredentials(args, context),\n [OID4VCIMachineServices.sendNotification]: (args: SendNotificationArgs) => this.oid4vciHolderSendNotification(args, context),\n [OID4VCIMachineServices.getFederationTrust]: (args: GetFederationTrustArgs) => this.getFederationTrust(args, context),\n }\n\n const oid4vciMachineInstanceArgs: OID4VCIMachineInstanceOpts = {\n ...opts,\n authorizationRequestOpts,\n services: {\n ...services,\n ...opts.services,\n },\n }\n\n const { interpreter } = await OID4VCIMachine.newInstance(oid4vciMachineInstanceArgs, context)\n\n return {\n interpreter,\n }\n }\n\n /**\n * This method is run before the machine starts! So there is no concept of the state machine context or states yet\n *\n * The result of this method can be directly passed into the start method of the state machine\n * @param args\n * @param context\n * @private\n */\n private async oid4vciHolderStart(args: PrepareStartArgs, context: RequiredContext): Promise<StartResult> {\n const { requestData } = args\n if (!requestData) {\n throw Error(`Cannot start the OID4VCI holder flow without request data being provided`)\n }\n const { uri = undefined } = requestData\n if (!uri) {\n return Promise.reject(Error('Missing request URI in context'))\n }\n\n const authorizationRequestOpts = { ...this.defaultAuthorizationRequestOpts, ...args.authorizationRequestOpts } satisfies AuthorizationRequestOpts\n // TODO: Previously we filtered the details first against our vcformat prefs. However auth details does not have the notion of formats anymore\n authorizationRequestOpts.authorizationDetails = authorizationRequestOpts?.authorizationDetails\n ? asArray(authorizationRequestOpts.authorizationDetails)\n : undefined\n\n if (!authorizationRequestOpts.redirectUri) {\n authorizationRequestOpts.redirectUri = OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI\n }\n if (authorizationRequestOpts.redirectUri.startsWith('http') && !authorizationRequestOpts.clientId) {\n // At least set a default for a web based wallet.\n // TODO: We really need (dynamic) client registration support\n authorizationRequestOpts.clientId = authorizationRequestOpts.redirectUri\n }\n\n // TODO: This entire filter and formats population should not work anymore, as the auth details no longer have the format property.\n let formats: string[] = this.vcFormatPreferences\n const authFormats = authorizationRequestOpts?.authorizationDetails\n ?.map((detail: AuthorizationDetailsV1_0_15) => (typeof detail === 'object' && 'format' in detail && detail.format ? detail.format : undefined))\n .filter((format) => !!format)\n .map((format) => format as string)\n if (authFormats && authFormats.length > 0) {\n formats = Array.from(new Set(authFormats))\n }\n let oid4vciClient: OpenID4VCIClientV1_0_15\n let offer: CredentialOfferRequestWithBaseUrl | undefined\n if (requestData.existingClientState) {\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromState({ state: requestData.existingClientState })\n offer = oid4vciClient.credentialOffer\n } else {\n offer = requestData.credentialOffer\n if (\n uri.startsWith(RequestType.OPENID_INITIATE_ISSUANCE) ||\n uri.startsWith(RequestType.OPENID_CREDENTIAL_OFFER) ||\n uri.match(/https?:\\/\\/.*credential_offer(_uri)=?.*/)\n ) {\n if (!offer) {\n // Let's make sure to convert the URI to offer, as it matches the regexes. Normally this should already have happened at this point though\n offer = await CredentialOfferClient.fromURI(uri)\n }\n } else {\n if (!!offer) {\n logger.warning(`Non default URI used for credential offer: ${uri}`)\n }\n }\n\n if (!offer) {\n // else no offer, meaning we have an issuer URL\n logger.log(`Issuer url received (no credential offer): ${uri}`)\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromCredentialIssuer({\n credentialIssuer: uri,\n authorizationRequest: authorizationRequestOpts,\n clientId: authorizationRequestOpts.clientId,\n createAuthorizationRequestURL: false, // requestData.createAuthorizationRequestURL ?? true,\n })\n } else {\n logger.log(`Credential offer received: ${uri}`)\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromURI({\n uri,\n authorizationRequest: authorizationRequestOpts,\n clientId: authorizationRequestOpts.clientId,\n createAuthorizationRequestURL: false, // requestData.createAuthorizationRequestURL ?? true,\n })\n }\n }\n\n let configurationIds: Array<string> = []\n if (offer) {\n configurationIds = offer.original_credential_offer.credential_configuration_ids\n } else {\n configurationIds = asArray(authorizationRequestOpts.authorizationDetails)\n // .filter((authDetails): authDetails is Exclude<AuthorizationDetailsV1_0_15, string> => typeof authDetails !== 'string')\n .map((authReqOpts) => authReqOpts.credential_configuration_id)\n .filter((id): id is string => !!id)\n }\n\n const credentialsSupported = await getCredentialConfigsSupportedMerged({\n client: oid4vciClient,\n vcFormatPreferences: formats,\n configurationIds,\n })\n\n const serverMetadata = await oid4vciClient.retrieveServerMetadata()\n const credentialBranding = await getCredentialBranding({ credentialsSupported, context })\n const oid4vciClientState = JSON.parse(await oid4vciClient.exportState())\n\n return {\n credentialBranding,\n credentialsSupported,\n serverMetadata,\n oid4vciClientState,\n }\n }\n\n private async oid4vciHolderPrepareAuthorizationRequest(\n args: PrepareAuthorizationRequestArgs,\n context: RequiredContext,\n ): Promise<PrepareAuthorizationResult> {\n const { openID4VCIClientState, contact } = args\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n const clientId = contact?.identities\n .map((identity) => {\n const connectionConfig = identity.connection?.config\n if (connectionConfig && 'clientId' in connectionConfig) {\n return connectionConfig.clientId\n }\n return undefined\n })\n .find((clientId) => clientId)\n\n if (!clientId) {\n return Promise.reject(Error(`Missing client id in contact's connectionConfig`))\n }\n const client = await OpenID4VCIClientV1_0_15.fromState({ state: openID4VCIClientState })\n const authorizationCodeURL = await client.createAuthorizationRequestUrl({\n authorizationRequest: {\n clientId: clientId,\n } satisfies AuthorizationRequestOpts,\n })\n if (authorizationCodeURL) {\n logger.log(`authorization code URL ${authorizationCodeURL}`)\n }\n return {\n authorizationCodeURL,\n // Needed, because the above createAuthorizationRequestUrl manipulates the state, adding pkce opts to the state\n oid4vciClientState: JSON.parse(await client.exportState())\n }\n }\n\n private async oid4vciHolderCreateCredentialsToSelectFrom(\n args: CreateCredentialsToSelectFromArgs,\n context: RequiredContext,\n ): Promise<Array<CredentialToSelectFromResult>> {\n const { credentialBranding, locale, selectedCredentials /*, openID4VCIClientState*/, credentialsSupported } = args\n\n // const client = await OpenID4VCIClient.fromState({ state: openID4VCIClientState! }) // TODO see if we need the check openID4VCIClientState defined\n /*const credentialsSupported = await getCredentialConfigsSupportedBySingleTypeOrId({\n client,\n vcFormatPreferences: this.vcFormatPreferences,\n })*/\n logger.info(`Credentials supported ${Object.keys(credentialsSupported).join(', ')}`)\n\n const credentialSelection: Array<CredentialToSelectFromResult> = await Promise.all(\n Object.entries(credentialsSupported).map(async ([id, credentialConfigSupported]): Promise<CredentialToSelectFromResult> => {\n // FIXME this allows for duplicate VerifiableCredential, which the user has no idea which ones those are and we also have a branding map with unique keys, so some branding will not match\n // const defaultCredentialType = 'VerifiableCredential'\n\n const credentialTypes = getTypesFromObject(credentialConfigSupported)\n // const credentialType = id /*?? credentialTypes?.find((type) => type !== defaultCredentialType) ?? defaultCredentialType*/\n const localeBranding = !credentialBranding\n ? undefined\n : (credentialBranding?.[id] ??\n Object.entries(credentialBranding)\n .find(([type, _brandings]) => {\n credentialTypes && type in credentialTypes\n })\n ?.map(([type, supported]) => supported))\n const credentialAlias = (\n await selectCredentialLocaleBranding({\n locale,\n localeBranding,\n })\n )?.alias\n\n return {\n id: uuidv4(),\n credentialId: id,\n credentialTypes: credentialTypes ?? asArray(id),\n credentialAlias: credentialAlias ?? id,\n isSelected: false,\n }\n }),\n )\n\n // TODO find better place to do this, would be nice if the machine does this?\n if (credentialSelection.length >= 1) {\n credentialSelection.map((sel) => selectedCredentials.push(sel.credentialId))\n }\n logger.log(`Credential selection ${JSON.stringify(credentialSelection)}`)\n\n return credentialSelection\n }\n\n private async oid4vciHolderGetContact(args: GetContactArgs, context: RequiredContext): Promise<Party | undefined> {\n const { serverMetadata } = args\n\n if (serverMetadata === undefined) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n const names: Set<string> = new Set(\n serverMetadata.credentialIssuerMetadata?.display\n ?.map((display) => display.name)\n .filter((name) => name != undefined)\n .map((name) => name as string) ?? [],\n )\n const name = names.size > 0 ? Array.from(names)[0] : undefined\n\n const correlationId: string = new URL(serverMetadata.issuer).hostname\n\n const filter: FindPartyArgs = [\n {\n identities: {\n identifier: {\n correlationId,\n },\n },\n },\n ]\n\n if (name) {\n filter.push({\n contact: {\n legalName: name,\n },\n })\n filter.push({\n contact: {\n displayName: name,\n },\n })\n }\n\n const parties: Array<Party> = await context.agent.cmGetContacts({\n filter,\n })\n\n if (parties.length > 1) {\n logger.warning(`Get contacts returned more than one result: ${parties.length}, ${parties.map((party) => party.contact.displayName).join(',')}`)\n }\n const party = parties.length >= 1 ? parties[0] : undefined\n\n logger.log(`Party involved: `, party)\n return party\n }\n\n private async oid4vciHolderGetCredentials(args: GetCredentialsArgs, context: RequiredContext): Promise<Array<MappedCredentialToAccept>> {\n const { verificationCode, openID4VCIClientState, didMethodPreferences, issuanceOpt, accessTokenOpts, walletType } = args\n logger.debug(`Getting credentials`, issuanceOpt, accessTokenOpts)\n\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n const client = await OpenID4VCIClientV1_0_15.fromState({ state: openID4VCIClientState })\n const credentialsSupported = await getCredentialConfigsSupportedMerged({\n client,\n vcFormatPreferences: this.vcFormatPreferences,\n configurationIds: args.selectedCredentials,\n })\n const serverMetadata = await client.retrieveServerMetadata()\n const issuanceOpts = await getIssuanceOpts({\n client,\n credentialsSupported,\n serverMetadata,\n context,\n didMethodPreferences: this.selectDidMethodPreferences(didMethodPreferences, walletType),\n jwtCryptographicSuitePreferences: this.jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences: this.jsonldCryptographicSuitePreferences,\n ...(issuanceOpt && { forceIssuanceOpt: issuanceOpt }),\n })\n\n const getCredentials = issuanceOpts.map(\n async (issuanceOpt: IssuanceOpts): Promise<MappedCredentialToAccept> =>\n await this.oid4vciHolderGetCredential(\n {\n issuanceOpt,\n pin: verificationCode,\n client,\n accessTokenOpts,\n },\n context,\n ),\n )\n\n const allCredentials = await Promise.all(getCredentials)\n logger.log(`Credentials received`, allCredentials)\n\n return allCredentials\n }\n\n private selectDidMethodPreferences(didMethodPreferences: Array<SupportedDidMethodEnum> | undefined, walletType: WalletType) {\n const supportedDidMethodEnums =\n Array.isArray(didMethodPreferences) && didMethodPreferences.length > 0 ? didMethodPreferences : this.didMethodPreferences\n if (walletType === 'ORGANIZATIONAL') {\n return [SupportedDidMethodEnum.DID_WEB, ...supportedDidMethodEnums]\n }\n return supportedDidMethodEnums\n }\n\n private async oid4vciHolderGetCredential(args: GetCredentialArgs, context: RequiredContext): Promise<MappedCredentialToAccept> {\n const { issuanceOpt, pin, client, accessTokenOpts } = args\n logger.info(`Getting credential`, issuanceOpt)\n\n if (!issuanceOpt) {\n return Promise.reject(Error(`Cannot get credential issuance options`))\n }\n\n const identifier = await getIdentifierOpts({ issuanceOpt, context })\n issuanceOpt.identifier = identifier\n logger.info(`ID opts`, identifier)\n const alg: JoseSignatureAlgorithm | JoseSignatureAlgorithmString = await signatureAlgorithmFromKey({ key: identifier.key })\n // The VCI lib either expects a jwk or a kid\n const jwk = isManagedIdentifierJwkResult(identifier) ? identifier.jwk : undefined\n\n const callbacks: ProofOfPossessionCallbacks = {\n signCallback: signCallback(identifier, context),\n }\n\n try {\n // We need to make sure we have acquired the access token\n if (!client.clientId) {\n client.clientId = isManagedIdentifierDidResult(identifier) ? identifier.did : identifier.issuer\n }\n let asOpts: AuthorizationServerOpts | undefined = undefined\n let kid = accessTokenOpts?.clientOpts?.kid ?? identifier.kid\n if (accessTokenOpts?.clientOpts) {\n const clientId = accessTokenOpts.clientOpts.clientId ?? client.clientId ?? identifier.issuer\n if (client.isEBSI() && clientId?.startsWith('http') && kid?.includes('#')) {\n kid = kid.split('#')[1]\n }\n\n //todo: investigate if the jwk should be used here as well if present\n const clientOpts: AuthorizationServerClientOpts = {\n ...accessTokenOpts.clientOpts,\n clientId,\n kid,\n // @ts-ignore\n alg: accessTokenOpts.clientOpts.alg ?? alg,\n signCallbacks: accessTokenOpts.clientOpts.signCallbacks ?? callbacks,\n }\n asOpts = {\n clientOpts,\n }\n }\n\n await client.acquireAccessToken({\n clientId: client.clientId,\n pin,\n authorizationResponse: JSON.parse(await client.exportState()).authorizationCodeResponse,\n additionalRequestParams: accessTokenOpts?.additionalRequestParams,\n ...(asOpts && { asOpts }),\n })\n\n // FIXME: This type mapping is wrong. It should use credential_identifier in case the access token response has authorization details\n const types = getTypesFromObject(issuanceOpt)\n const id: string | undefined = 'id' in issuanceOpt && issuanceOpt.id ? (issuanceOpt.id as string) : undefined\n const credentialTypes = asArray(issuanceOpt.credentialConfigurationId ?? types ?? id)\n if (!credentialTypes || credentialTypes.length === 0) {\n return Promise.reject(Error('cannot determine credential id to request'))\n }\n\n const credentialDefinition = this.getCredentialDefinition(issuanceOpt)\n const credentialResponse = await client.acquireCredentials({\n ...(credentialDefinition && { context: credentialDefinition['@context'] }),\n credentialTypes,\n proofCallbacks: callbacks,\n format: issuanceOpt.format,\n // TODO: We need to update the machine and add notifications support for actual deferred credentials instead of just waiting/retrying\n deferredCredentialAwait: true,\n ...(!jwk && { kid }), // vci client either wants a jwk or kid. If we have used the jwk method do not provide the kid\n jwk,\n alg,\n jti: uuidv4(),\n })\n\n const credential = {\n id: issuanceOpt.credentialConfigurationId ?? id,\n types: types ?? asArray(credentialTypes),\n issuanceOpt,\n credentialResponse,\n } satisfies CredentialToAccept\n return mapCredentialToAccept({ credentialToAccept: credential, hasher: this.hasher })\n } catch (error) {\n return Promise.reject(error)\n }\n }\n\n private async oid4vciHolderAddContactIdentity(args: AddContactIdentityArgs, context: RequiredContext): Promise<Identity> {\n const { credentialsToAccept, contact } = args\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n if (credentialsToAccept === undefined || credentialsToAccept.length === 0) {\n return Promise.reject(Error('Missing credential offers in context'))\n }\n\n let correlationId: string = credentialsToAccept[0].correlationId\n let identifierType = CorrelationIdentifierType.DID\n if (!correlationId.toLowerCase().startsWith('did:')) {\n identifierType = CorrelationIdentifierType.URL\n if (correlationId.startsWith('http')) {\n correlationId = new URL(correlationId).hostname\n }\n }\n const identity: NonPersistedIdentity = {\n alias: credentialsToAccept[0].correlationId,\n origin: IdentityOrigin.EXTERNAL,\n roles: [CredentialRole.ISSUER],\n identifier: {\n type: identifierType,\n correlationId,\n },\n ...(identifierType === CorrelationIdentifierType.URL && {\n connection: {\n type: ConnectionType.OPENID_CONNECT,\n config: {\n clientId: '138d7bf8-c930-4c6e-b928-97d3a4928b01',\n clientSecret: '03b3955f-d020-4f2a-8a27-4e452d4e27a0',\n scopes: ['auth'],\n issuer: 'https://example.com/app-test',\n redirectUrl: 'app:/callback',\n dangerouslyAllowInsecureHttpRequests: true,\n clientAuthMethod: 'post' as const,\n },\n },\n }),\n }\n\n await context.agent.emit(OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED, {\n contactId: contact.id,\n identity,\n })\n logger.log(`Contact added: ${correlationId}`)\n\n return context.agent.cmAddIdentity({ contactId: contact.id, identity })\n }\n\n private async oid4vciHolderGetIssuerBranding(\n args: GetIssuerBrandingArgs,\n context: RequiredContext,\n ): Promise<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>> {\n const { serverMetadata, contact } = args\n\n // Here we are fetching issuer branding for a contact. If no contact is found that means we encounter this contact for the first time. This also means we do not have any branding for the contact.\n const issuerCorrelationId = contact?.identities\n .filter((identity) => identity.roles.includes(CredentialRole.ISSUER))\n .map((identity) => identity.identifier.correlationId)[0]\n\n if (issuerCorrelationId) {\n const branding = await context.agent.ibGetIssuerBranding({ filter: [{ issuerCorrelationId }] })\n if (branding.length > 0) {\n return branding[0].localeBranding\n }\n }\n\n // We should have serverMetadata in the context else something went wrong\n if (!serverMetadata) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n return getBasicIssuerLocaleBranding({\n display: serverMetadata.credentialIssuerMetadata?.display ?? [],\n dynamicRegistrationClientMetadata: serverMetadata.credentialIssuerMetadata,\n context,\n })\n }\n\n private async oid4vciHolderStoreIssuerBranding(args: StoreIssuerBrandingArgs, context: RequiredContext): Promise<void> {\n const { issuerBranding, contact } = args\n if (!issuerBranding || issuerBranding.length === 0 || (<Array<IIssuerLocaleBranding>>issuerBranding)[0].id) {\n // FIXME we need better separation between a contact(issuer) we encountered before and it's branding vs a new contact and it's branding\n return\n }\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n const issuerCorrelationId = contact?.identities\n .filter((identity) => identity.roles.includes(CredentialRole.ISSUER))\n .map((identity) => identity.identifier.correlationId)[0]\n\n // we check for issuer branding as adding an identity might also trigger storing the issuer branding\n const branding = await context.agent.ibGetIssuerBranding({ filter: [{ issuerCorrelationId }] })\n if (branding.length > 0) {\n return\n }\n\n await context.agent.ibAddIssuerBranding({\n localeBranding: issuerBranding as Array<IBasicIssuerLocaleBranding>,\n issuerCorrelationId,\n })\n }\n\n private async oid4vciHolderAssertValidCredentials(args: AssertValidCredentialsArgs, context: RequiredContext): Promise<VerificationResult[]> {\n const { credentialsToAccept, issuanceOpt } = args\n\n return await Promise.all(\n credentialsToAccept.map((credentialToAccept) =>\n verifyCredentialToAccept({\n mappedCredential: credentialToAccept,\n onVerifyEBSICredentialIssuer: this.onVerifyEBSICredentialIssuer,\n hasher: this.hasher,\n schemaValidation: issuanceOpt?.schemaValidation,\n context,\n }),\n ),\n )\n }\n\n private async oid4vciHolderStoreCredentialBranding(args: StoreCredentialBrandingArgs, context: RequiredContext): Promise<void> {\n const { credentialBranding, serverMetadata, selectedCredentials, credentialsToAccept } = args\n\n if (serverMetadata === undefined) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n } else if (selectedCredentials.length === 0) {\n logger.warning(`No credentials selected for issuer: ${serverMetadata.issuer}`)\n return\n }\n\n let counter = 0\n for (const credentialId of selectedCredentials) {\n // The selectedCredential from context is the configurationId, whilst we store the branding by type. We need to map\n const configId = credentialId\n const types =\n credentialsToAccept\n .find((ac) => ac.correlationId === configId || ac.credentialToAccept.id === configId || ac.types.includes(configId))\n ?.types?.filter((type) => type != 'VerifiableCredential') ?? []\n\n const localeBranding: Array<IBasicCredentialLocaleBranding> = credentialBranding?.[configId] ?? []\n if (localeBranding.length === 0) {\n for (const type of types) {\n const branding = credentialBranding?.[type] ?? []\n if (branding.length > 0) {\n localeBranding.push(...branding)\n }\n }\n }\n\n if (localeBranding && localeBranding.length > 0) {\n const credential = credentialsToAccept.find(\n (credAccept) =>\n credAccept.credentialToAccept.id === credentialId ||\n JSON.stringify(credAccept.types) === credentialId ||\n JSON.stringify(credAccept.types.filter((cred) => cred !== 'VerifiableCredential')) === JSON.stringify(types) ||\n credentialsToAccept[counter],\n )!\n counter++\n await context.agent.ibAddCredentialBranding({\n vcHash: computeEntryHash(credential.rawVerifiableCredential as W3CVerifiableCredential),\n issuerCorrelationId: new URL(serverMetadata.issuer).hostname,\n localeBranding,\n })\n logger.log(\n `Credential branding for issuer ${serverMetadata.issuer} and type ${credentialId} stored with locales ${localeBranding.map((b) => b.locale).join(',')}`,\n )\n } else {\n logger.warning(`No credential branding found for issuer: ${serverMetadata.issuer} and type ${credentialId}`)\n }\n }\n }\n\n private async oid4vciHolderStoreCredentials(args: StoreCredentialsArgs, context: RequiredContext): Promise<void> {\n function trimmed(input?: string) {\n const trim = input?.trim()\n if (trim === '') {\n return undefined\n }\n return trim\n }\n\n const { credentialsToAccept, openID4VCIClientState, credentialsSupported, serverMetadata, selectedCredentials } = args\n const mappedCredentialToAccept = credentialsToAccept[0]\n\n if (selectedCredentials && selectedCredentials.length > 1) {\n logger.error(`More than 1 credential selected ${selectedCredentials.join(', ')}, but current service only stores 1 credential!`)\n }\n\n // TODO determine when and how we should store credentials without key kmsKeyRef & id method), this should be tested with the code below\n const issuanceOpt = args.issuanceOpt ?? mappedCredentialToAccept.credentialToAccept.issuanceOpt\n if (!issuanceOpt || !issuanceOpt.identifier) {\n return Promise.reject(Error('issuanceOpt.identifier must me set in order to store a credential'))\n }\n const { kmsKeyRef, method } = issuanceOpt.identifier\n\n let persist = true\n const verifiableCredential = mappedCredentialToAccept.uniformVerifiableCredential as VerifiableCredential\n\n const notificationId = mappedCredentialToAccept.credentialToAccept.credentialResponse.notification_id\n const subjectIssuance = mappedCredentialToAccept.credential_subject_issuance\n const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint\n let holderCredential:\n | IVerifiableCredential\n | JwtDecodedVerifiableCredential\n | SdJwtDecodedVerifiableCredentialPayload\n | W3CVerifiableCredential\n | undefined = undefined\n if (!notificationEndpoint) {\n logger.log(`Notifications not supported by issuer ${serverMetadata?.issuer}. Will not provide a notification`)\n } else if (notificationEndpoint && !notificationId) {\n logger.warning(\n `Notification endpoint available in issuer metadata with value ${notificationEndpoint}, but no ${notificationId} provided. Will not send a notification to issuer ${serverMetadata?.issuer}`,\n )\n } else if (notificationEndpoint && notificationId) {\n logger.log(`Notification id ${notificationId} found, will send back a notification to ${notificationEndpoint}`)\n let event = 'credential_accepted'\n if (Array.isArray(subjectIssuance?.notification_events_supported)) {\n // experimental subject issuance, where a new credential is being created\n event = subjectIssuance.notification_events_supported.includes('credential_accepted_holder_signed')\n ? 'credential_accepted_holder_signed'\n : 'credential_deleted_holder_signed'\n logger.log(`Subject issuance/signing will be used, with event`, event)\n\n const issuerVC = extractCredentialFromResponse(mappedCredentialToAccept.credentialToAccept.credentialResponse)\n const wrappedIssuerVC = CredentialMapper.toWrappedVerifiableCredential(issuerVC, { hasher: this.hasher ?? defaultHasher })\n console.log(`Wrapped VC: ${wrappedIssuerVC.type}, ${wrappedIssuerVC.format}`)\n // We will use the subject of the VCI Issuer (the holder, as the issuer of the new credential, so the below is not a mistake!)\n\n let issuer: string | undefined\n\n if (CredentialMapper.isWrappedSdJwtVerifiableCredential(wrappedIssuerVC)) {\n issuer = trimmed(wrappedIssuerVC.decoded?.sub)\n } else if (CredentialMapper.isWrappedW3CVerifiableCredential(wrappedIssuerVC)) {\n issuer =\n trimmed(wrappedIssuerVC.credential?.sub) ??\n // @ts-ignore\n trimmed(wrappedIssuerVC.credential?.credentialSubject?.id) ??\n trimmed(this.idFromW3cCredentialSubject(wrappedIssuerVC))\n } else if (CredentialMapper.isWrappedMdocCredential(wrappedIssuerVC)) {\n return Promise.reject(Error('mdoc not yet supported'))\n }\n\n if (!issuer) {\n issuer = trimmed(verifiableCredential.credentialSubject?.id)\n }\n if (!issuer && openID4VCIClientState?.kid?.startsWith('did:')) {\n issuer = parseDid(openID4VCIClientState?.kid).did\n }\n if (!issuer && openID4VCIClientState?.jwk?.kid?.startsWith('did:')) {\n issuer = parseDid(openID4VCIClientState!.jwk!.kid!).did\n }\n if (!issuer && openID4VCIClientState?.clientId) {\n issuer = trimmed(openID4VCIClientState.clientId)\n }\n if (!issuer && openID4VCIClientState?.accessTokenResponse) {\n const decodedJwt = decodeJWT(openID4VCIClientState.accessTokenResponse.access_token)\n issuer = decodedJwt.payload.sub\n }\n if (!issuer && mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier) {\n const resolution = await context.agent.identifierManagedGet(mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier)\n issuer = resolution.issuer\n }\n\n if (!issuer) {\n throw Error(`We could not determine the issuer, which means we cannot sign the credential`)\n }\n logger.log(`Issuer for self-issued credential will be: ${issuer}`)\n\n const holderCredentialToSign = wrappedIssuerVC.decoded\n let proofFormat: CredentialProofFormat = 'lds'\n if (wrappedIssuerVC.format.includes('jwt') && !wrappedIssuerVC.format.includes('mso_mdoc')) {\n holderCredentialToSign.iss = issuer\n proofFormat = 'jwt'\n }\n if ('issuer' in holderCredentialToSign && !('iss' in holderCredentialToSign)) {\n holderCredentialToSign.issuer = issuer\n }\n if ('sub' in holderCredentialToSign) {\n holderCredentialToSign.sub = issuer\n }\n if ('credentialSubject' in holderCredentialToSign && !Array.isArray(holderCredentialToSign.credentialSubject)) {\n holderCredentialToSign.credentialSubject.id = issuer\n }\n if ('vc' in holderCredentialToSign) {\n if (holderCredentialToSign.vc.credentialSubject) {\n holderCredentialToSign.vc.credentialSubject.id = issuer\n }\n holderCredentialToSign.vc.issuer = issuer\n delete holderCredentialToSign.vc.proof\n delete holderCredentialToSign.vc.issuanceDate\n }\n delete holderCredentialToSign.proof\n delete holderCredentialToSign.issuanceDate\n delete holderCredentialToSign.iat\n\n logger.log(`Subject issuance/signing will sign credential of type ${proofFormat}:`, holderCredentialToSign)\n const issuedVC = await context.agent.createVerifiableCredential({\n credential: ('vc' in holderCredentialToSign ? holderCredentialToSign.vc : holderCredentialToSign) as CredentialPayload,\n fetchRemoteContexts: true,\n save: false,\n proofFormat,\n })\n if (!issuedVC) {\n throw Error(`Could not issue holder credential from the wallet`)\n }\n logger.log(`Holder ${issuedVC.issuer} issued new credential with id ${issuedVC.id}`, issuedVC)\n holderCredential = CredentialMapper.storedCredentialToOriginalFormat(issuedVC as IVerifiableCredential)\n persist = event === 'credential_accepted_holder_signed'\n }\n\n const notificationRequest: NotificationRequest = {\n notification_id: notificationId,\n ...(holderCredential && { credential: holderCredential }),\n event,\n }\n\n await this.oid4vciHolderSendNotification(\n {\n openID4VCIClientState,\n stored: persist,\n credentialsToAccept,\n credentialsSupported,\n notificationRequest,\n serverMetadata,\n },\n context,\n )\n }\n const persistCredential = holderCredential\n ? CredentialMapper.storedCredentialToOriginalFormat(holderCredential)\n : mappedCredentialToAccept.rawVerifiableCredential\n if (!persist && holderCredential) {\n logger.log(`Will not persist credential, since we are signing as a holder and the issuer asked not to persist`)\n } else {\n logger.log(`Persisting credential`, persistCredential)\n\n const issuer = CredentialMapper.issuerCorrelationIdFromIssuerType(verifiableCredential.issuer)\n const [subjectCorrelationType, subjectCorrelationId] = this.determineSubjectCorrelation(issuanceOpt.identifier, issuer)\n\n const persistedCredential = await context.agent.crsAddCredential({\n credential: {\n rawDocument: ensureRawDocument(persistCredential),\n kmsKeyRef: kmsKeyRef,\n identifierMethod: method,\n credentialRole: CredentialRole.HOLDER,\n issuerCorrelationType: issuer?.startsWith('did:') ? CredentialCorrelationType.DID : CredentialCorrelationType.URL,\n issuerCorrelationId: issuer,\n subjectCorrelationType,\n subjectCorrelationId,\n },\n })\n await context.agent.emit(OID4VCIHolderEvent.CREDENTIAL_STORED, {\n credential: persistedCredential,\n vcHash: persistedCredential.hash,\n } satisfies OnCredentialStoredArgs)\n }\n }\n\n private async oid4vciHolderSendNotification(args: SendNotificationArgs, context: RequiredContext): Promise<void> {\n const { serverMetadata, notificationRequest, openID4VCIClientState } = args\n const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint\n if (!notificationEndpoint) {\n return\n } else if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n } else if (!notificationRequest) {\n return Promise.reject(Error('Missing notification request'))\n }\n\n logger.log(`Will send notification to ${notificationEndpoint}`, notificationRequest)\n\n const client = await OpenID4VCIClient.fromState({ state: openID4VCIClientState })\n await client.sendNotification({ notificationEndpoint }, notificationRequest, openID4VCIClientState?.accessTokenResponse?.access_token)\n logger.log(`Notification to ${notificationEndpoint} has been dispatched`)\n }\n\n private async getFederationTrust(args: GetFederationTrustArgs, context: RequiredContext): Promise<Array<string>> {\n const { requestData, serverMetadata, trustAnchors } = args\n\n if (trustAnchors.length === 0) {\n return Promise.reject(Error('No trust anchors found'))\n }\n\n if (!requestData?.uri) {\n return Promise.reject(Error('Missing request URI in context'))\n }\n\n if (!serverMetadata) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n const url = new URL(requestData?.uri)\n const params = new URLSearchParams(url.search)\n const openidFederation = params.get('openid_federation')\n const entityIdentifier = openidFederation ?? serverMetadata.issuer\n if (entityIdentifier.startsWith('http://')) {\n console.warn(`OpenID federation does not support http://, only https:// allowed; got: (${url.toString()})`)\n // OIDF always needs to be https\n return []\n }\n\n const result = await context.agent.identifierExternalResolveByOIDFEntityId({\n method: 'entity_id',\n trustAnchors: trustAnchors,\n identifier: entityIdentifier,\n })\n\n return result.trustedAnchors\n }\n\n private async oid4vciHolderGetIssuerMetadata(args: GetIssuerMetadataArgs, context: RequiredContext): Promise<EndpointMetadataResult> {\n const { issuer, errorOnNotFound = true } = args\n return MetadataClient.retrieveAllMetadata(issuer, { errorOnNotFound })\n }\n\n private determineSubjectCorrelation(identifier: ManagedIdentifierOptsOrResult, issuer: string): [CredentialCorrelationType, string] {\n switch (identifier.method) {\n case 'did':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierDidResult(identifier)) {\n return [CredentialCorrelationType.DID, identifier.did]\n } else if (isManagedIdentifierDidOpts(identifier)) {\n return [CredentialCorrelationType.DID, typeof identifier.identifier === 'string' ? identifier.identifier : identifier.identifier.did]\n }\n break\n case 'kid':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierKidResult(identifier)) {\n return [CredentialCorrelationType.KID, identifier.kid]\n } else if (isManagedIdentifierDidOpts(identifier)) {\n return [CredentialCorrelationType.KID, identifier.identifier]\n }\n break\n case 'x5c':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierX5cResult(identifier)) {\n return [CredentialCorrelationType.X509_SAN, identifier.x5c.join('\\r\\n')]\n } else if (isManagedIdentifierX5cOpts(identifier)) {\n return [CredentialCorrelationType.X509_SAN, identifier.identifier.join('\\r\\n')]\n }\n break\n }\n return [CredentialCorrelationType.URL, issuer]\n }\n\n private idFromW3cCredentialSubject(wrappedIssuerVC: WrappedW3CVerifiableCredential): string | undefined {\n if (Array.isArray(wrappedIssuerVC.credential?.credentialSubject)) {\n if (wrappedIssuerVC.credential?.credentialSubject.length > 0) {\n return wrappedIssuerVC.credential?.credentialSubject[0].id\n }\n } else {\n return wrappedIssuerVC.credential?.credentialSubject?.id\n }\n return undefined\n }\n\n private getCredentialDefinition(issuanceOpt: IssuanceOpts): CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 | undefined {\n if (issuanceOpt.format == 'ldp_vc' || issuanceOpt.format == 'jwt_vc_json-ld') {\n return (issuanceOpt as CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15).credential_definition\n }\n return undefined\n }\n}\n","import { AuthorizationChallengeCodeResponse, AuthzFlowType, toAuthorizationResponsePayload } from '@sphereon/oid4vci-common'\nimport { IBasicIssuerLocaleBranding, Identity, IIssuerLocaleBranding, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { assign, createMachine, DoneInvokeEvent, interpret } from 'xstate'\nimport { translate } from '../localization/Localization'\nimport {\n AuthorizationResponseEvent,\n ContactAliasEvent,\n ContactConsentEvent,\n CreateContactEvent,\n CreateOID4VCIMachineOpts,\n CredentialToSelectFromResult,\n ErrorDetails,\n StartResult,\n MappedCredentialToAccept,\n OID4VCIMachineAddContactStates,\n OID4VCIMachineContext,\n OID4VCIMachineEvents,\n OID4VCIMachineEventTypes,\n OID4VCIMachineGuards,\n OID4VCIMachineInstanceOpts,\n OID4VCIMachineInterpreter,\n OID4VCIMachineServices,\n OID4VCIMachineState,\n OID4VCIMachineStates,\n OID4VCIMachineVerifyPinStates,\n OID4VCIStateMachine,\n RequiredContext,\n SelectCredentialsEvent,\n SetAuthorizationCodeURLEvent,\n VerificationCodeEvent,\n PrepareAuthorizationResult,\n} from '../types/IOID4VCIHolder'\nimport { FirstPartyMachineStateTypes } from '../types/FirstPartyMachine'\n\nconst oid4vciHasNoContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact } = _ctx\n return contact === undefined\n}\n\nconst oid4vciHasContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact } = _ctx\n return contact !== undefined\n}\n\nconst oid4vciContactHasLowTrustGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact, trustedAnchors } = _ctx\n return contact !== undefined && trustedAnchors !== undefined && trustedAnchors.length === 0\n}\n\nconst oid4vciCredentialsToSelectRequiredGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { credentialToSelectFrom } = _ctx\n return credentialToSelectFrom && credentialToSelectFrom.length > 1\n}\n\nconst oid4vciRequirePinGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { requestData } = _ctx\n return requestData?.credentialOffer?.userPinRequired === true\n}\n\nconst oid4vciHasNoContactIdentityGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact, credentialsToAccept } = _ctx\n let toAcceptId = credentialsToAccept[0].correlationId\n if (toAcceptId.match(/^https?:\\/\\/.*/)) {\n toAcceptId = new URL(toAcceptId).hostname\n }\n return !contact?.identities.some((identity: Identity): boolean => identity.identifier.correlationId === toAcceptId)\n}\n\nconst oid4vciVerificationCodeGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { verificationCode } = _ctx\n return verificationCode !== undefined && verificationCode.length > 0\n}\n\nconst oid4vciCreateContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contactAlias, hasContactConsent } = _ctx\n return hasContactConsent && !!contactAlias && contactAlias.length > 0\n}\n\nconst oid4vciHasSelectedCredentialsGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { selectedCredentials } = _ctx\n return selectedCredentials !== undefined && selectedCredentials.length > 0\n}\n\nconst oid4vciIsOIDFOriginGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n // TODO in the future we need to establish if a origin is a IDF origin. So we need to check if this metadata is on the well-known location\n const { trustAnchors } = _ctx\n return trustAnchors.length > 0\n}\n\nconst oid4vciNoAuthorizationGuard = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !oid4vciHasAuthorizationResponse(ctx, _event)\n}\n\n// FIXME refactor this guard\nconst oid4vciRequireAuthorizationGuard = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { openID4VCIClientState } = ctx\n\n if (!openID4VCIClientState) {\n throw Error('Missing openID4VCI client state in context')\n }\n\n if (openID4VCIClientState.authorizationURL && openID4VCIClientState.authorizationRequestOpts) {\n // We have authz options or there is not credential offer to begin with.\n // We require authz as long as we do not have the authz code response\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {\n return false\n } else if (openID4VCIClientState.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint) {\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n }\n return false\n}\n\nconst oid4vciHasAuthorizationResponse = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !!ctx.openID4VCIClientState?.authorizationCodeResponse\n}\n\nconst oid4vciIsFirstPartyApplication = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !!ctx.serverMetadata?.authorization_challenge_endpoint\n}\n\nconst createOID4VCIMachine = (opts?: CreateOID4VCIMachineOpts): OID4VCIStateMachine => {\n const initialContext: OID4VCIMachineContext = {\n // TODO WAL-671 we need to store the data from OpenIdProvider here in the context and make sure we can restart the machine with it and init the OpenIdProvider\n accessTokenOpts: opts?.accessTokenOpts,\n requestData: opts?.requestData,\n walletType: opts?.walletType ?? 'NATURAL_PERSON',\n trustAnchors: opts?.trustAnchors ?? [],\n issuanceOpt: opts?.issuanceOpt,\n didMethodPreferences: opts?.didMethodPreferences,\n locale: opts?.locale,\n credentialsSupported: {},\n credentialToSelectFrom: [],\n selectedCredentials: [],\n credentialsToAccept: [],\n hasContactConsent: true,\n contactAlias: '',\n }\n\n return createMachine<OID4VCIMachineContext, OID4VCIMachineEventTypes>({\n id: opts?.machineName ?? 'OID4VCIHolder',\n predictableActionArguments: true,\n initial: OID4VCIMachineStates.start,\n schema: {\n events: {} as OID4VCIMachineEventTypes,\n guards: {} as\n | { type: OID4VCIMachineGuards.hasNoContactGuard }\n | { type: OID4VCIMachineGuards.credentialsToSelectRequiredGuard }\n | { type: OID4VCIMachineGuards.requirePinGuard }\n | { type: OID4VCIMachineGuards.requireAuthorizationGuard }\n | { type: OID4VCIMachineGuards.noAuthorizationGuard }\n | { type: OID4VCIMachineGuards.hasNoContactIdentityGuard }\n | { type: OID4VCIMachineGuards.verificationCodeGuard }\n | { type: OID4VCIMachineGuards.hasContactGuard }\n | { type: OID4VCIMachineGuards.createContactGuard }\n | { type: OID4VCIMachineGuards.hasSelectedCredentialsGuard }\n | { type: OID4VCIMachineGuards.hasAuthorizationResponse }\n | { type: OID4VCIMachineGuards.isOIDFOriginGuard }\n | { type: OID4VCIMachineGuards.contactHasLowTrustGuard }\n | { type: OID4VCIMachineGuards.isFirstPartyApplication },\n services: {} as {\n [OID4VCIMachineServices.start]: {\n data: StartResult\n }\n [OID4VCIMachineServices.prepareAuthorizationRequest]: {\n data: PrepareAuthorizationResult\n }\n [OID4VCIMachineServices.createCredentialsToSelectFrom]: {\n data: Array<CredentialToSelectFromResult>\n }\n [OID4VCIMachineServices.getContact]: {\n data: Party | undefined\n }\n [OID4VCIMachineServices.storeIssuerBranding]: {\n data: void\n }\n [OID4VCIMachineServices.getCredentials]: {\n data: Array<MappedCredentialToAccept> | undefined\n }\n [OID4VCIMachineServices.addContactIdentity]: {\n data: void\n }\n [OID4VCIMachineServices.assertValidCredentials]: {\n data: void\n }\n [OID4VCIMachineServices.storeCredentialBranding]: {\n data: void\n }\n [OID4VCIMachineServices.storeCredentials]: {\n data: void\n }\n [OID4VCIMachineServices.getFederationTrust]: {\n data: Array<string>\n }\n [OID4VCIMachineServices.getIssuerBranding]: {\n data: Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>\n }\n [OID4VCIMachineServices.startFirstPartApplicationFlow]: {\n data: void\n }\n },\n },\n context: initialContext,\n states: {\n [OID4VCIMachineStates.start]: {\n id: OID4VCIMachineStates.start,\n invoke: {\n src: OID4VCIMachineServices.start,\n onDone: {\n target: OID4VCIMachineStates.createCredentialsToSelectFrom,\n actions: assign({\n credentialBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.credentialBranding ?? {},\n credentialsSupported: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.credentialsSupported,\n serverMetadata: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.serverMetadata,\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.oid4vciClientState,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_initiation_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.createCredentialsToSelectFrom]: {\n id: OID4VCIMachineStates.createCredentialsToSelectFrom,\n invoke: {\n src: OID4VCIMachineServices.createCredentialsToSelectFrom,\n onDone: {\n target: OID4VCIMachineStates.getContact,\n actions: assign({\n credentialToSelectFrom: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<CredentialToSelectFromResult>>) => _event.data,\n }),\n // TODO WAL-670 would be nice if we can have guard that checks if we have at least 1 item in the selection. not sure if this can occur but it would be more defensive.\n // Still cannot find a nice way to do this inside of an invoke besides adding another transition state\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_credential_selection_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getContact]: {\n id: OID4VCIMachineStates.getContact,\n invoke: {\n src: OID4VCIMachineServices.getContact,\n onDone: {\n target: OID4VCIMachineStates.getIssuerBranding,\n actions: assign({ contact: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Party>) => _event.data }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_contact_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getIssuerBranding]: {\n id: OID4VCIMachineStates.getIssuerBranding,\n invoke: {\n src: OID4VCIMachineServices.getIssuerBranding,\n onDone: [\n {\n target: OID4VCIMachineStates.getFederationTrust,\n cond: OID4VCIMachineGuards.isOIDFOriginGuard,\n actions: assign({\n issuerBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>) =>\n _event.data,\n }),\n },\n {\n target: OID4VCIMachineStates.transitionFromSetup,\n actions: assign({\n issuerBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>) =>\n _event.data,\n }),\n },\n ],\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getFederationTrust]: {\n id: OID4VCIMachineStates.getFederationTrust,\n invoke: {\n src: OID4VCIMachineServices.getFederationTrust,\n onDone: {\n target: OID4VCIMachineStates.transitionFromSetup,\n actions: assign({\n trustedAnchors: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<string>>) => _event.data,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_federation_trust_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromSetup]: {\n id: OID4VCIMachineStates.transitionFromSetup,\n always: [\n {\n target: OID4VCIMachineStates.addContact,\n cond: OID4VCIMachineGuards.hasNoContactGuard,\n },\n {\n target: OID4VCIMachineStates.reviewContact,\n cond: OID4VCIMachineGuards.contactHasLowTrustGuard,\n },\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n on: {\n [OID4VCIMachineEvents.SET_AUTHORIZATION_CODE_URL]: {\n actions: assign({ authorizationCodeURL: (_ctx: OID4VCIMachineContext, _event: SetAuthorizationCodeURLEvent) => _event.data }),\n },\n },\n },\n [OID4VCIMachineStates.addContact]: {\n id: OID4VCIMachineStates.addContact,\n initial: OID4VCIMachineAddContactStates.idle,\n on: {\n [OID4VCIMachineEvents.SET_CONTACT_CONSENT]: {\n actions: assign({ hasContactConsent: (_ctx: OID4VCIMachineContext, _event: ContactConsentEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.SET_CONTACT_ALIAS]: {\n actions: assign({ contactAlias: (_ctx: OID4VCIMachineContext, _event: ContactAliasEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.CREATE_CONTACT]: {\n target: `.${OID4VCIMachineAddContactStates.next}`,\n actions: assign({ contact: (_ctx: OID4VCIMachineContext, _event: CreateContactEvent) => _event.data }),\n cond: OID4VCIMachineGuards.createContactGuard,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n states: {\n [OID4VCIMachineAddContactStates.idle]: {},\n [OID4VCIMachineAddContactStates.next]: {\n always: {\n target: `#${OID4VCIMachineStates.storeIssuerBranding}`,\n cond: OID4VCIMachineGuards.hasContactGuard,\n },\n },\n },\n },\n [OID4VCIMachineStates.reviewContact]: {\n id: OID4VCIMachineStates.reviewContact,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.transitionFromContactSetup,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.storeIssuerBranding]: {\n id: OID4VCIMachineStates.storeIssuerBranding,\n invoke: {\n src: OID4VCIMachineServices.storeIssuerBranding,\n onDone: {\n target: OID4VCIMachineStates.transitionFromContactSetup,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromContactSetup]: {\n id: OID4VCIMachineStates.transitionFromContactSetup,\n always: [\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.startFirstPartApplicationFlow]: {\n id: OID4VCIMachineStates.startFirstPartApplicationFlow,\n invoke: {\n src: OID4VCIMachineServices.startFirstPartApplicationFlow,\n onDone: [\n {\n target: OID4VCIMachineStates.aborted,\n cond: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<FirstPartyMachineStateTypes>): boolean =>\n _event.data === FirstPartyMachineStateTypes.aborted,\n },\n {\n target: OID4VCIMachineStates.declined,\n cond: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<FirstPartyMachineStateTypes>): boolean =>\n _event.data === FirstPartyMachineStateTypes.declined,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n actions: assign({\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeCodeResponse>) => {\n const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data)\n return { ..._ctx.openID4VCIClientState!, authorizationCodeResponse }\n },\n }),\n },\n ],\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<ErrorDetails>): ErrorDetails => ({\n title: _event.data.title ?? translate('oid4vci_machine_first_party_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.selectCredentials]: {\n id: OID4VCIMachineStates.selectCredentials,\n on: {\n [OID4VCIMachineEvents.SET_SELECTED_CREDENTIALS]: {\n actions: assign({ selectedCredentials: (_ctx: OID4VCIMachineContext, _event: SelectCredentialsEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.transitionFromSelectingCredentials,\n cond: OID4VCIMachineGuards.hasSelectedCredentialsGuard,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.transitionFromSelectingCredentials]: {\n id: OID4VCIMachineStates.transitionFromSelectingCredentials,\n always: [\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.prepareAuthorizationRequest]: {\n id: OID4VCIMachineStates.prepareAuthorizationRequest,\n invoke: {\n src: OID4VCIMachineServices.prepareAuthorizationRequest,\n onDone: {\n target: OID4VCIMachineStates.initiateAuthorizationRequest,\n actions: assign({\n authorizationCodeURL: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<PrepareAuthorizationResult>) =>\n _event.data.authorizationCodeURL,\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<PrepareAuthorizationResult>) => _event.data.oid4vciClientState,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_prepare_authorization_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.initiateAuthorizationRequest]: {\n id: OID4VCIMachineStates.initiateAuthorizationRequest,\n on: {\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.selectCredentials,\n },\n [OID4VCIMachineEvents.INVOKED_AUTHORIZATION_CODE_REQUEST]: {\n target: OID4VCIMachineStates.waitForAuthorizationResponse,\n },\n },\n },\n [OID4VCIMachineStates.waitForAuthorizationResponse]: {\n id: OID4VCIMachineStates.waitForAuthorizationResponse,\n on: {\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.initiateAuthorizationRequest,\n },\n [OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE]: {\n actions: assign({\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: AuthorizationResponseEvent) => {\n const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data)\n return { ..._ctx.openID4VCIClientState!, authorizationCodeResponse }\n },\n }),\n },\n },\n always: [\n {\n cond: OID4VCIMachineGuards.hasAuthorizationResponse,\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.verifyPin]: {\n id: OID4VCIMachineStates.verifyPin,\n initial: OID4VCIMachineVerifyPinStates.idle,\n on: {\n [OID4VCIMachineEvents.SET_VERIFICATION_CODE]: {\n target: `.${OID4VCIMachineVerifyPinStates.next}`,\n actions: assign({ verificationCode: (_ctx: OID4VCIMachineContext, _event: VerificationCodeEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.PREVIOUS]: [\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.aborted,\n },\n ],\n },\n states: {\n [OID4VCIMachineVerifyPinStates.idle]: {},\n [OID4VCIMachineVerifyPinStates.next]: {\n always: {\n target: `#${OID4VCIMachineStates.getCredentials}`,\n cond: OID4VCIMachineGuards.verificationCodeGuard,\n },\n },\n },\n },\n [OID4VCIMachineStates.getCredentials]: {\n id: OID4VCIMachineStates.getCredentials,\n invoke: {\n src: OID4VCIMachineServices.getCredentials,\n onDone: {\n target: OID4VCIMachineStates.verifyCredentials,\n actions: assign({\n credentialsToAccept: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<MappedCredentialToAccept>>) => _event.data,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_credentials_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n exit: assign({ verificationCode: undefined }),\n },\n [OID4VCIMachineStates.verifyCredentials]: {\n id: OID4VCIMachineStates.verifyCredentials,\n invoke: {\n src: OID4VCIMachineServices.assertValidCredentials,\n onDone: {\n target: OID4VCIMachineStates.transitionFromWalletInput,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_verify_credentials_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromWalletInput]: {\n id: OID4VCIMachineStates.transitionFromWalletInput,\n always: [\n {\n target: OID4VCIMachineStates.addContactIdentity,\n cond: OID4VCIMachineGuards.hasNoContactIdentityGuard,\n },\n {\n target: OID4VCIMachineStates.reviewCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.addContactIdentity]: {\n id: OID4VCIMachineStates.addContactIdentity,\n invoke: {\n src: OID4VCIMachineServices.addContactIdentity,\n onDone: {\n target: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,\n actions: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Identity>): void => {\n _ctx.contact?.identities.push(_event.data)\n },\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_add_contact_identity_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.addIssuerBrandingAfterIdentity]: {\n id: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,\n invoke: {\n src: OID4VCIMachineServices.storeIssuerBranding,\n onDone: {\n target: OID4VCIMachineStates.reviewCredentials,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.reviewCredentials]: {\n id: OID4VCIMachineStates.reviewCredentials,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.storeCredentialBranding,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.storeCredentialBranding]: {\n id: OID4VCIMachineStates.storeCredentialBranding,\n invoke: {\n src: OID4VCIMachineServices.storeCredentialBranding,\n onDone: {\n target: OID4VCIMachineStates.storeCredentials,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_credential_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.storeCredentials]: {\n id: OID4VCIMachineStates.storeCredentials,\n invoke: {\n src: OID4VCIMachineServices.storeCredentials,\n onDone: {\n target: OID4VCIMachineStates.done,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_credential_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.handleError]: {\n id: OID4VCIMachineStates.handleError,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.error,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.error,\n },\n },\n },\n [OID4VCIMachineStates.aborted]: {\n id: OID4VCIMachineStates.aborted,\n type: 'final',\n },\n [OID4VCIMachineStates.declined]: {\n id: OID4VCIMachineStates.declined,\n type: 'final',\n },\n [OID4VCIMachineStates.error]: {\n id: OID4VCIMachineStates.error,\n type: 'final',\n },\n [OID4VCIMachineStates.done]: {\n id: OID4VCIMachineStates.done,\n type: 'final',\n },\n },\n })\n}\n\nexport class OID4VCIMachine {\n static async newInstance(opts: OID4VCIMachineInstanceOpts, context: RequiredContext): Promise<{ interpreter: OID4VCIMachineInterpreter }> {\n const interpreter: OID4VCIMachineInterpreter = interpret(\n createOID4VCIMachine(opts).withConfig({\n services: {\n ...opts?.services,\n },\n guards: {\n oid4vciHasNoContactGuard,\n oid4vciCredentialsToSelectRequiredGuard,\n oid4vciRequirePinGuard,\n oid4vciHasNoContactIdentityGuard,\n oid4vciVerificationCodeGuard,\n oid4vciHasContactGuard,\n oid4vciCreateContactGuard,\n oid4vciHasSelectedCredentialsGuard,\n oid4vciRequireAuthorizationGuard,\n oid4vciNoAuthorizationGuard,\n oid4vciHasAuthorizationResponse,\n oid4vciIsOIDFOriginGuard,\n oid4vciContactHasLowTrustGuard,\n oid4vciIsFirstPartyApplication,\n ...opts?.guards,\n },\n }),\n )\n\n if (typeof opts?.subscription === 'function') {\n interpreter.onTransition(opts.subscription)\n }\n if (opts?.requireCustomNavigationHook !== true) {\n if (typeof opts?.stateNavigationListener === 'function') {\n interpreter.onTransition((snapshot: OID4VCIMachineState): void => {\n if (opts?.stateNavigationListener) {\n opts.stateNavigationListener(interpreter, snapshot)\n }\n })\n }\n }\n\n return { interpreter }\n }\n}\n","import i18n, { Scope, TranslateOptions } from 'i18n-js'\nimport memoize from 'lodash.memoize'\nimport { SupportedLanguage } from '../types/IOID4VCIHolder'\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 { DynamicRegistrationClientMetadata } from '@sphereon/oid4vc-common'\nimport { OpenID4VCIClientState, OpenID4VCIClientV1_0_15 } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationRequestOpts,\n AuthorizationResponse,\n AuthorizationServerClientOpts,\n AuthzFlowType,\n CredentialConfigurationSupported,\n CredentialOfferRequestWithBaseUrl,\n CredentialResponse,\n CredentialResponseV1_0_15,\n CredentialsSupportedDisplay,\n EndpointMetadataResult,\n ExperimentalSubjectIssuance,\n IssuerCredentialSubject,\n MetadataDisplay,\n NotificationRequest,\n} from '@sphereon/oid4vci-common'\nimport { CreateOrGetIdentifierOpts, IdentifierProviderOpts, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n IIdentifierResolution,\n ManagedIdentifierMethod,\n ManagedIdentifierOptsOrResult,\n ManagedIdentifierResult,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { IContactManager } from '@sphereon/ssi-sdk.contact-manager'\nimport { ICredentialStore } from '@sphereon/ssi-sdk.credential-store'\nimport { ICredentialValidation, SchemaValidation } from '@sphereon/ssi-sdk.credential-validation'\nimport {\n DigitalCredential,\n IBasicCredentialClaim,\n IBasicCredentialLocaleBranding,\n IBasicIssuerLocaleBranding,\n Identity,\n IIssuerLocaleBranding,\n Party,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { ImDLMdoc } from '@sphereon/ssi-sdk.mdl-mdoc'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\nimport { IDidAuthSiopOpAuthenticator } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport {\n HasherSync,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n OriginalVerifiableCredential,\n SdJwtClaimMetadata,\n SdJwtTypeDisplayMetadata,\n W3CVerifiableCredential,\n WrappedVerifiableCredential,\n WrappedVerifiablePresentation,\n} from '@sphereon/ssi-types'\nimport {\n IAgentContext,\n ICredentialIssuer,\n ICredentialVerifier,\n IDIDManager,\n IKeyManager,\n IPluginMethodMap,\n IResolver,\n TAgent,\n TKeyType,\n VerificationPolicies,\n} from '@veramo/core'\nimport { BaseActionObject, Interpreter, ResolveTypegenMeta, ServiceMap, State, StateMachine, TypegenDisabled } from 'xstate'\nimport { FirstPartyMachineStateNavigationListener } from './FirstPartyMachine'\n\nexport interface IOID4VCIHolder extends IPluginMethodMap {\n oid4vciHolderGetIssuerMetadata(args: GetIssuerMetadataArgs, context: RequiredContext): Promise<EndpointMetadataResult>\n\n oid4vciHolderGetMachineInterpreter(args: GetMachineArgs, context: RequiredContext): Promise<OID4VCIMachine> // FIXME is using GetMachineArgs as args but the function uses OID4VCIMachineInstanceOpts\n\n oid4vciHolderStart(args: PrepareStartArgs, context: RequiredContext): Promise<StartResult>\n\n oid4vciHolderCreateCredentialsToSelectFrom(\n args: CreateCredentialsToSelectFromArgs,\n context: RequiredContext,\n ): Promise<Array<CredentialToSelectFromResult>>\n\n oid4vciHolderPrepareAuthorizationRequest(args: PrepareAuthorizationRequestArgs, context: RequiredContext): Promise<PrepareAuthorizationResult>\n oid4vciHolderGetContact(args: GetContactArgs, context: RequiredContext): Promise<Party | undefined>\n\n oid4vciHolderGetCredentials(args: GetCredentialsArgs, context: RequiredContext): Promise<Array<MappedCredentialToAccept>>\n\n oid4vciHolderGetCredential(args: GetCredentialArgs, context: RequiredContext): Promise<MappedCredentialToAccept>\n\n oid4vciHolderAddContactIdentity(args: AddContactIdentityArgs, context: RequiredContext): Promise<Identity>\n\n oid4vciHolderAssertValidCredentials(args: AssertValidCredentialsArgs, context: RequiredContext): Promise<Array<VerificationResult>>\n\n oid4vciHolderGetIssuerBranding(\n args: GetIssuerBrandingArgs,\n context: RequiredContext,\n ): Promise<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>\n\n oid4vciHolderStoreIssuerBranding(args: StoreIssuerBrandingArgs, context: RequiredContext): Promise<void>\n\n oid4vciHolderStoreCredentialBranding(args: StoreCredentialBrandingArgs, context: RequiredContext): Promise<void>\n\n oid4vciHolderStoreCredentials(args: StoreCredentialsArgs, context: RequiredContext): Promise<void>\n}\n\nexport type OID4VCIHolderOptions = {\n onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n onCredentialStored?: (args: OnCredentialStoredArgs) => Promise<void>\n onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n vcFormatPreferences?: Array<string>\n jsonldCryptographicSuitePreferences?: Array<string>\n defaultAuthorizationRequestOptions?: AuthorizationRequestOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n jwtCryptographicSuitePreferences?: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n hasher?: HasherSync\n}\n\nexport type OnContactIdentityCreatedArgs = {\n contactId: string\n identity: Identity\n}\n\nexport type GetIssuerMetadataArgs = {\n issuer: string\n errorOnNotFound?: boolean\n}\n\nexport type OnCredentialStoredArgs = {\n credential: DigitalCredential\n vcHash: string\n}\n\nexport type OnIdentifierCreatedArgs = {\n identifier: ManagedIdentifierResult\n}\n\nexport type GetMachineArgs = {\n requestData: RequestData\n walletType: WalletType\n trustAnchors?: Array<string>\n authorizationRequestOpts?: AuthorizationRequestOpts\n clientOpts?: AuthorizationServerClientOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: Partial<IssuanceOpts>\n stateNavigationListener?: OID4VCIMachineStateNavigationListener\n firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n}\n\nexport type PrepareStartArgs = Pick<\n OID4VCIMachineContext,\n 'requestData' | 'authorizationRequestOpts' | 'didMethodPreferences' | 'issuanceOpt' | 'accessTokenOpts'\n>\nexport type PrepareAuthorizationRequestArgs = Pick<OID4VCIMachineContext, 'openID4VCIClientState' | 'contact'>\nexport type CreateCredentialsToSelectFromArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsSupported' | 'credentialBranding' | 'selectedCredentials' | 'locale' | 'openID4VCIClientState'\n>\nexport type GetContactArgs = Pick<OID4VCIMachineContext, 'serverMetadata'>\nexport type GetCredentialsArgs = Pick<\n OID4VCIMachineContext,\n 'verificationCode' | 'openID4VCIClientState' | 'selectedCredentials' | 'didMethodPreferences' | 'issuanceOpt' | 'accessTokenOpts' | 'walletType'\n>\nexport type AddContactIdentityArgs = Pick<OID4VCIMachineContext, 'credentialsToAccept' | 'contact'>\nexport type GetIssuerBrandingArgs = Pick<OID4VCIMachineContext, 'serverMetadata' | 'contact'>\nexport type StoreIssuerBrandingArgs = Pick<OID4VCIMachineContext, 'issuerBranding' | 'contact'>\nexport type AssertValidCredentialsArgs = Pick<OID4VCIMachineContext, 'credentialsToAccept' | 'issuanceOpt'>\nexport type StoreCredentialBrandingArgs = Pick<\n OID4VCIMachineContext,\n 'serverMetadata' | 'credentialBranding' | 'selectedCredentials' | 'credentialsToAccept'\n>\nexport type StoreCredentialsArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsToAccept' | 'serverMetadata' | 'credentialsSupported' | 'openID4VCIClientState' | 'selectedCredentials' | 'issuanceOpt'\n>\nexport type SendNotificationArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsToAccept' | 'serverMetadata' | 'credentialsSupported' | 'openID4VCIClientState'\n> & { notificationRequest?: NotificationRequest; stored: boolean }\nexport type GetFederationTrustArgs = Pick<OID4VCIMachineContext, 'requestData' | 'trustAnchors' | 'serverMetadata'>\nexport type StartFirstPartApplicationMachine = Pick<OID4VCIMachineContext, 'openID4VCIClientState' | 'contact'> & {\n stateNavigationListener?: FirstPartyMachineStateNavigationListener\n}\n\nexport enum OID4VCIHolderEvent {\n CONTACT_IDENTITY_CREATED = 'contact_identity_created',\n CREDENTIAL_STORED = 'credential_stored',\n IDENTIFIER_CREATED = 'identifier_created',\n}\n\nexport type RequestData = {\n credentialOffer?: CredentialOfferRequestWithBaseUrl // This object needs to be created/prepared with the OID4VCI credential offer client\n code?: string // Authorization code\n uri: string // Either a credential offer URI, or issuer URI. If a credential offer URI. If a credential offer URI it is suggested to include the credential offer, otherwise we try to detect it ourselves\n existingClientState?: string // Allows us to start with an existing client state. Meaning someone had a client instance before starting the flow\n createAuthorizationRequestURL?: boolean // Create or do not create an authorization request URL. The default is true\n flowType?: AuthzFlowType // Force a particular flow type if there is an option.\n [x: string]: any\n}\n\nexport enum SupportedLanguage {\n ENGLISH = 'en',\n DUTCH = 'nl',\n}\n\nexport type VerifyCredentialToAcceptArgs = {\n mappedCredential: MappedCredentialToAccept\n onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n hasher?: HasherSync\n schemaValidation?: SchemaValidation\n context: RequiredContext\n}\n\nexport type MappedCredentialToAccept = ExperimentalSubjectIssuance & {\n correlationId: string\n types: string[]\n credentialToAccept: CredentialToAccept\n uniformVerifiableCredential: IVerifiableCredential\n rawVerifiableCredential: W3CVerifiableCredential\n}\n\nexport type OID4VCIMachineContext = {\n authorizationRequestOpts?: AuthorizationRequestOpts\n accessTokenOpts?: AccessTokenOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: IssuanceOpts\n trustAnchors: Array<string>\n requestData?: RequestData // TODO WAL-673 fix type as this is not always a qr code (deeplink)\n locale?: string\n authorizationCodeURL?: string\n issuerBranding?: Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>\n credentialBranding?: Record<string, Array<IBasicCredentialLocaleBranding>>\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata?: EndpointMetadataResult\n openID4VCIClientState?: OpenID4VCIClientState\n credentialToSelectFrom: Array<CredentialToSelectFromResult>\n contactAlias: string\n walletType: WalletType\n contact?: Party\n selectedCredentials: Array<string>\n credentialsToAccept: Array<MappedCredentialToAccept>\n verificationCode?: string // TODO WAL-672 refactor to not store verificationCode in the context\n hasContactConsent: boolean\n trustedAnchors?: Array<string>\n error?: ErrorDetails\n}\n\nexport enum OID4VCIMachineStates {\n start = 'start',\n createCredentialsToSelectFrom = 'createCredentialsToSelectFrom',\n getContact = 'getContact',\n transitionFromSetup = 'transitionFromSetup',\n getFederationTrust = 'getFederationTrust',\n reviewContact = 'reviewContact',\n addContact = 'addContact',\n getIssuerBranding = 'getIssuerBranding',\n storeIssuerBranding = 'storeIssuerBranding',\n addIssuerBrandingAfterIdentity = 'addIssuerBrandingAfterIdentity',\n transitionFromContactSetup = 'transitionFromContactSetup',\n startFirstPartApplicationFlow = 'startFirstPartApplicationFlow',\n selectCredentials = 'selectCredentials',\n transitionFromSelectingCredentials = 'transitionFromSelectingCredentials',\n verifyPin = 'verifyPin',\n prepareAuthorizationRequest = 'prepareAuthorizationRequest',\n initiateAuthorizationRequest = 'initiateAuthorizationRequest',\n waitForAuthorizationResponse = 'waitForAuthorizationResponse',\n getCredentials = 'getCredentials',\n transitionFromWalletInput = 'transitionFromWalletInput',\n addContactIdentity = 'addContactIdentity',\n reviewCredentials = 'reviewCredentials',\n verifyCredentials = 'verifyCredentials',\n storeCredentialBranding = 'storeCredentialBranding',\n storeCredentials = 'storeCredentials',\n handleError = 'handleError',\n aborted = 'aborted',\n declined = 'declined',\n error = 'error',\n done = 'done',\n}\n\nexport enum OID4VCIMachineAddContactStates {\n idle = 'idle',\n next = 'next',\n}\n\nexport enum OID4VCIMachineVerifyPinStates {\n idle = 'idle',\n next = 'next',\n}\n\nexport type OID4VCIMachineInterpreter = Interpreter<\n OID4VCIMachineContext,\n any,\n OID4VCIMachineEventTypes,\n { value: any; context: OID4VCIMachineContext },\n any\n>\n\nexport type OID4VCIMachineState = State<\n OID4VCIMachineContext,\n OID4VCIMachineEventTypes,\n any,\n {\n value: any\n context: OID4VCIMachineContext\n },\n any\n>\n\nexport type OID4VCIStateMachine = StateMachine<\n OID4VCIMachineContext,\n any,\n OID4VCIMachineEventTypes,\n { value: any; context: OID4VCIMachineContext },\n BaseActionObject,\n ServiceMap,\n ResolveTypegenMeta<TypegenDisabled, OID4VCIMachineEventTypes, BaseActionObject, ServiceMap>\n>\n\nexport type CreateOID4VCIMachineOpts = {\n requestData: RequestData\n walletType: WalletType\n machineName?: string\n locale?: string\n trustAnchors?: Array<string>\n stateDefinition?: OID4VCIMachineState\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n accessTokenOpts?: AccessTokenOpts\n issuanceOpt?: IssuanceOpts\n}\n\nexport type OID4VCIMachineStateNavigationListener = (\n oid4vciMachine: OID4VCIMachineInterpreter,\n state: OID4VCIMachineState,\n navigation?: any,\n) => Promise<void>\n\nexport type OID4VCIMachineInstanceOpts = {\n services?: any\n guards?: any\n subscription?: () => void\n requireCustomNavigationHook?: boolean\n authorizationRequestOpts?: AuthorizationRequestOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: IssuanceOpts // restrict the issuance to these opts\n stateNavigationListener?: OID4VCIMachineStateNavigationListener\n firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n} & CreateOID4VCIMachineOpts\n\nexport type OID4VCIProviderProps = {\n children?: any\n customOID4VCIInstance?: OID4VCIMachineInterpreter\n}\n\nexport type OID4VCIContext = {\n oid4vciInstance?: OID4VCIMachineInterpreter\n}\n\nexport type OID4VCIMachineNavigationArgs = {\n oid4vciMachine: OID4VCIMachineInterpreter\n state: OID4VCIMachineState\n navigation: any\n onNext?: () => void\n onBack?: () => void\n}\n\nexport enum OID4VCIMachineEvents {\n NEXT = 'NEXT',\n PREVIOUS = 'PREVIOUS',\n DECLINE = 'DECLINE',\n CREATE_CONTACT = 'CREATE_CONTACT',\n SET_VERIFICATION_CODE = 'SET_VERIFICATION_CODE',\n SET_CONTACT_ALIAS = 'SET_CONTACT_ALIAS',\n SET_CONTACT_CONSENT = 'SET_CONTACT_CONSENT',\n SET_SELECTED_CREDENTIALS = 'SET_SELECTED_CREDENTIALS',\n SET_AUTHORIZATION_CODE_URL = 'SET_AUTHORIZATION_CODE_URL',\n INVOKED_AUTHORIZATION_CODE_REQUEST = 'INVOKED_AUTHORIZATION_CODE_REQUEST',\n PROVIDE_AUTHORIZATION_CODE_RESPONSE = 'PROVIDE_AUTHORIZATION_CODE_RESPONSE',\n}\n\nexport enum OID4VCIMachineGuards {\n hasContactGuard = 'oid4vciHasContactGuard',\n hasNoContactGuard = 'oid4vciHasNoContactGuard',\n credentialsToSelectRequiredGuard = 'oid4vciCredentialsToSelectRequiredGuard',\n requirePinGuard = 'oid4vciRequirePinGuard',\n requireAuthorizationGuard = 'oid4vciRequireAuthorizationGuard',\n noAuthorizationGuard = 'oid4vciNoAuthorizationGuard',\n hasNonceEndpointGuard = 'oid4vciHasNonceEndpointGuard ',\n hasAuthorizationResponse = 'oid4vciHasAuthorizationResponse',\n hasNoContactIdentityGuard = 'oid4vciHasNoContactIdentityGuard',\n verificationCodeGuard = 'oid4vciVerificationCodeGuard',\n createContactGuard = 'oid4vciCreateContactGuard',\n hasSelectedCredentialsGuard = 'oid4vciHasSelectedCredentialsGuard',\n isOIDFOriginGuard = 'oid4vciIsOIDFOriginGuard',\n contactHasLowTrustGuard = 'oid4vciContactHasLowTrustGuard',\n isFirstPartyApplication = 'oid4vciIsFirstPartyApplication',\n}\n\nexport enum OID4VCIMachineServices {\n start = 'start',\n getContact = 'getContact',\n getFederationTrust = 'getFederationTrust',\n addContactIdentity = 'addContactIdentity',\n createCredentialsToSelectFrom = 'createCredentialsToSelectFrom',\n prepareAuthorizationRequest = 'prepareAuthorizationRequest',\n getIssuerBranding = 'getIssuerBranding',\n storeIssuerBranding = 'storeIssuerBranding',\n getCredentials = 'getCredentials',\n assertValidCredentials = 'assertValidCredentials',\n storeCredentialBranding = 'storeCredentialBranding',\n sendNotification = 'sendNotification',\n storeCredentials = 'storeCredentials',\n startFirstPartApplicationFlow = 'startFirstPartApplicationFlow',\n}\n\nexport type OID4VCIMachineServiceDefinitions = Record<keyof typeof OID4VCIMachineServices, (...args: Array<any>) => any>\n\nexport type NextEvent = { type: OID4VCIMachineEvents.NEXT }\nexport type PreviousEvent = { type: OID4VCIMachineEvents.PREVIOUS }\nexport type DeclineEvent = { type: OID4VCIMachineEvents.DECLINE }\nexport type CreateContactEvent = { type: OID4VCIMachineEvents.CREATE_CONTACT; data: Party }\nexport type SelectCredentialsEvent = { type: OID4VCIMachineEvents.SET_SELECTED_CREDENTIALS; data: Array<string> }\nexport type VerificationCodeEvent = { type: OID4VCIMachineEvents.SET_VERIFICATION_CODE; data: string }\nexport type ContactConsentEvent = { type: OID4VCIMachineEvents.SET_CONTACT_CONSENT; data: boolean }\nexport type ContactAliasEvent = { type: OID4VCIMachineEvents.SET_CONTACT_ALIAS; data: string }\nexport type SetAuthorizationCodeURLEvent = { type: OID4VCIMachineEvents.SET_AUTHORIZATION_CODE_URL; data: string }\nexport type InvokeAuthorizationRequestEvent = { type: OID4VCIMachineEvents.INVOKED_AUTHORIZATION_CODE_REQUEST; data: string }\nexport type AuthorizationResponseEvent = { type: OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE; data: string | AuthorizationResponse }\n\nexport type OID4VCIMachineEventTypes =\n | NextEvent\n | PreviousEvent\n | DeclineEvent\n | CreateContactEvent\n | SelectCredentialsEvent\n | VerificationCodeEvent\n | ContactConsentEvent\n | ContactAliasEvent\n | SetAuthorizationCodeURLEvent\n | InvokeAuthorizationRequestEvent\n | AuthorizationResponseEvent\n\nexport type ErrorDetails = {\n title: string\n message: string\n // TODO WAL-676 would be nice if we can bundle these details fields into a new type so that we can check on this field instead of the 2 separately\n detailsTitle?: string\n detailsMessage?: string\n stack?: string\n}\n\nexport enum RequestType {\n OPENID_INITIATE_ISSUANCE = 'openid-initiate-issuance',\n OPENID_CREDENTIAL_OFFER = 'openid-credential-offer',\n URL = 'URL',\n}\n\nexport type CredentialToSelectFromResult = ExperimentalSubjectIssuance & {\n id: string\n credentialId: string\n credentialTypes: Array<string>\n credentialAlias: string\n isSelected: boolean\n}\n\nexport type OID4VCIMachine = {\n interpreter: OID4VCIMachineInterpreter\n}\n\nexport type StartResult = {\n credentialBranding?: Record<string, Array<IBasicCredentialLocaleBranding>>\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata: EndpointMetadataResult\n oid4vciClientState: OpenID4VCIClientState\n}\n\nexport type PrepareAuthorizationResult = {\n authorizationCodeURL?: string\n oid4vciClientState: OpenID4VCIClientState\n}\n\nexport type SelectAppLocaleBrandingArgs = {\n locale?: string\n localeBranding?: Array<IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding>\n}\n\nexport type IssuanceOpts = CredentialConfigurationSupported & {\n credentialConfigurationId?: string // Explicit ID for a credential\n supportedBindingMethods: ManagedIdentifierMethod[]\n supportedPreferredDidMethod?: SupportedDidMethodEnum\n schemaValidation?: SchemaValidation\n // todo: rename, now we have generic identifiers\n identifier?: ManagedIdentifierOptsOrResult\n // todo: replace by signature alg, so we can determine applicable key types instead of determining up front. Use proof_types_supported\n keyType?: TKeyType\n codecName?: string\n kms?: string\n}\n\nexport type VerificationResult = {\n result: boolean\n source: WrappedVerifiableCredential | WrappedVerifiablePresentation\n subResults: Array<VerificationSubResult>\n error?: string | undefined\n errorDetails?: string\n}\n\nexport type VerificationSubResult = {\n result: boolean\n error?: string\n errorDetails?: string\n}\n\nexport type CredentialToAccept = {\n id?: string\n types: string[]\n issuanceOpt: IssuanceOpts\n credentialResponse: CredentialResponseV1_0_15 | CredentialResponse\n}\n\nexport type GetCredentialConfigsSupportedArgs = {\n client: OpenID4VCIClientV1_0_15\n vcFormatPreferences: Array<string>\n format?: Array<string>\n types?: Array<Array<string>>\n configurationIds?: Array<string>\n}\n\n/**\n * Please note that this method is restricting the results to one set of types or configurationId.\n * It can potentially return multiple results mainly because of different formats.\n */\nexport type GetCredentialConfigsSupportedBySingleTypeOrIdArgs = {\n client: OpenID4VCIClientV1_0_15\n vcFormatPreferences: Array<string>\n format?: string[]\n types?: string[]\n configurationId?: string\n}\n\nexport type GetCredentialBrandingArgs = {\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n context: RequiredContext\n}\n\nexport type GetBasicIssuerLocaleBrandingArgs = {\n display: MetadataDisplay[]\n dynamicRegistrationClientMetadata?: DynamicRegistrationClientMetadataDisplay\n context: RequiredContext\n}\n\nexport type GetPreferredCredentialFormatsArgs = {\n credentials: Record<string, CredentialConfigurationSupported>\n vcFormatPreferences: Array<string>\n}\n\nexport type MapCredentialToAcceptArgs = {\n credentialToAccept: CredentialToAccept\n hasher?: HasherSync\n}\n\nexport type GetDefaultIssuanceOptsArgs = {\n credentialSupported: CredentialConfigurationSupported\n opts: DefaultIssuanceOpts\n context: RequiredContext\n}\n\nexport type DefaultIssuanceOpts = {\n client: OpenID4VCIClientV1_0_15\n}\n\nexport type GetIdentifierArgs = {\n issuanceOpt: IssuanceOpts\n context: RequiredContext\n}\n\nexport type GetAuthenticationKeyArgs = {\n identifier: ManagedIdentifierOptsOrResult\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n context: IAgentContext<IResolver & IDIDManager & IKeyManager>\n}\n\nexport type GetOrCreatePrimaryIdentifierArgs = {\n context: RequiredContext\n opts?: CreateOrGetIdentifierOpts\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 CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type GetIssuanceOptsArgs = {\n client: OpenID4VCIClientV1_0_15\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata: EndpointMetadataResult\n context: RequiredContext\n didMethodPreferences: Array<SupportedDidMethodEnum>\n jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n jsonldCryptographicSuitePreferences: Array<string>\n forceIssuanceOpt?: IssuanceOpts\n}\n\nexport type GetIssuanceDidMethodArgs = {\n credentialSupported: CredentialConfigurationSupported\n client: OpenID4VCIClientV1_0_15\n didMethodPreferences: Array<SupportedDidMethodEnum>\n}\n\nexport type GetIssuanceCryptoSuiteArgs = {\n credentialSupported: CredentialConfigurationSupported\n client: OpenID4VCIClientV1_0_15\n jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n jsonldCryptographicSuitePreferences: Array<string>\n}\n\nexport type GetCredentialArgs = {\n pin?: string\n issuanceOpt: IssuanceOpts\n client: OpenID4VCIClientV1_0_15\n accessTokenOpts?: AccessTokenOpts\n}\n\nexport type AccessTokenOpts = {\n additionalRequestParams?: Record<string, any>\n clientOpts?: AuthorizationServerClientOpts\n}\n\nexport enum IdentifierAliasEnum {\n PRIMARY = 'primary',\n}\n\nexport type CredentialVerificationError = {\n error?: string\n errorDetails?: string\n}\n\nexport type VerifyMdocArgs = { credential: string }\n\nexport type VerifySDJWTCredentialArgs = { credential: string; hasher?: HasherSync }\n\nexport interface VerifyCredentialArgs {\n credential: OriginalVerifiableCredential\n fetchRemoteContexts?: boolean\n policies?: VerificationPolicies\n\n [x: string]: any\n}\n\nexport type IssuerType = 'RootTAO' | 'TAO' | 'TI' | 'Revoked or Undefined'\n\nexport type VerifyEBSICredentialIssuerArgs = {\n wrappedVc: WrappedVerifiableCredential\n issuerType?: IssuerType[]\n}\n\nexport type Attribute = {\n hash: string\n body: string\n issuerType: IssuerType\n tao: string\n rootTao: string\n}\n\nexport type VerifyEBSICredentialIssuerResult = {\n did: string\n attributes: Attribute[]\n}\n\nexport type Oid4vciCredentialLocaleBrandingFromArgs = {\n credentialDisplay: CredentialsSupportedDisplay\n}\n\nexport type SdJwtCredentialLocaleBrandingFromArgs = {\n credentialDisplay: SdJwtTypeDisplayMetadata\n}\n\nexport type SdJwtGetCredentialBrandingFromArgs = {\n credentialDisplay?: Array<SdJwtTypeDisplayMetadata>\n claimsMetadata?: Array<SdJwtClaimMetadata>\n}\n\nexport type SdJwtCredentialClaimLocalesFromArgs = {\n claimsMetadata: Array<SdJwtClaimMetadata>\n}\n\nexport type IssuerLocaleBrandingFromArgs = {\n issuerDisplay: MetadataDisplay\n dynamicRegistrationClientMetadata?: DynamicRegistrationClientMetadataDisplay\n}\n\nexport type Oid4vciGetCredentialBrandingFromArgs = {\n credentialDisplay?: Array<CredentialsSupportedDisplay>\n issuerCredentialSubject?: IssuerCredentialSubject\n}\n\nexport type Oid4vciCredentialDisplayLocalesFromArgs = {\n credentialDisplay: Array<CredentialsSupportedDisplay>\n}\n\nexport type SdJwtCredentialDisplayLocalesFromArgs = {\n credentialDisplay: Array<SdJwtTypeDisplayMetadata>\n}\n\nexport type Oid4vciIssuerCredentialSubjectLocalesFromArgs = {\n issuerCredentialSubject: IssuerCredentialSubject\n}\n\nexport type Oid4vciCombineDisplayLocalesFromArgs = {\n credentialDisplayLocales?: Map<string, CredentialsSupportedDisplay>\n issuerCredentialSubjectLocales?: Map<string, Array<IBasicCredentialClaim>>\n}\n\nexport type SdJwtCombineDisplayLocalesFromArgs = {\n credentialDisplayLocales?: Map<string, SdJwtTypeDisplayMetadata>\n claimsMetadata?: Map<string, Array<IBasicCredentialClaim>>\n}\n\nexport type DynamicRegistrationClientMetadataDisplay = Pick<\n DynamicRegistrationClientMetadata,\n 'client_name' | 'client_uri' | 'contacts' | 'tos_uri' | 'policy_uri' | 'logo_uri'\n>\n\nexport type WalletType = 'NATURAL_PERSON' | 'ORGANIZATIONAL'\n\nexport type DidAgents = TAgent<IResolver & IDIDManager>\n\nexport type RequiredContext = IAgentContext<\n IIssuanceBranding &\n IContactManager &\n ICredentialValidation &\n ICredentialVerifier &\n ICredentialIssuer &\n ICredentialStore &\n IIdentifierResolution &\n IJwtService &\n IDIDManager &\n IResolver &\n IKeyManager &\n ISDJwtPlugin &\n ImDLMdoc &\n IDidAuthSiopOpAuthenticator\n>\n","import { RPRegistrationMetadataPayload } from '@sphereon/did-auth-siop'\nimport { OpenID4VCIClientState } from '@sphereon/oid4vci-client'\nimport { AuthorizationChallengeCodeResponse } from '@sphereon/oid4vci-common'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { DidAuthConfig, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { IIdentifier } from '@veramo/core'\nimport { DcqlQuery } from 'dcql'\nimport { BaseActionObject, Interpreter, ResolveTypegenMeta, ServiceMap, State, StateMachine, StatesConfig, TypegenDisabled } from 'xstate'\nimport { ErrorDetails, RequiredContext } from './IOID4VCIHolder'\n\nexport enum FirstPartyMachineStateTypes {\n sendAuthorizationChallengeRequest = 'sendAuthorizationChallengeRequest',\n sendAuthorizationResponse = 'sendAuthorizationResponse',\n selectCredentials = 'selectCredentials',\n createConfig = 'createConfig',\n getSiopRequest = 'getSiopRequest',\n error = 'error',\n done = 'done',\n aborted = 'aborted',\n declined = 'declined',\n}\n\nexport enum FirstPartyMachineServices {\n sendAuthorizationChallengeRequest = 'sendAuthorizationChallengeRequest',\n sendAuthorizationResponse = 'sendAuthorizationResponse',\n createConfig = 'createConfig',\n getSiopRequest = 'getSiopRequest',\n}\n\nexport type FirstPartyMachineStates = Record<FirstPartyMachineStateTypes, {}>\n\nexport type FirstPartyMachineContext = {\n openID4VCIClientState: OpenID4VCIClientState\n selectedCredentials: Array<UniqueDigitalCredential>\n contact: Party\n authSession?: string\n presentationUri?: string\n identifier?: IIdentifier\n didAuthConfig?: Omit<DidAuthConfig, 'identifier'>\n authorizationRequestData?: SiopV2AuthorizationRequestData\n presentationDuringIssuanceSession?: string\n authorizationCodeResponse?: AuthorizationChallengeCodeResponse\n error?: ErrorDetails\n}\n\nexport enum FirstPartyMachineEvents {\n NEXT = 'NEXT',\n PREVIOUS = 'PREVIOUS',\n DECLINE = 'DECLINE',\n SET_SELECTED_CREDENTIALS = 'SET_SELECTED_CREDENTIALS',\n}\n\nexport type FirstPartyNextEvent = { type: FirstPartyMachineEvents.NEXT }\nexport type FirstPartyPreviousEvent = { type: FirstPartyMachineEvents.PREVIOUS }\nexport type FirstPartyDeclineEvent = { type: FirstPartyMachineEvents.DECLINE }\nexport type FirstPartySelectCredentialsEvent = {\n type: FirstPartyMachineEvents.SET_SELECTED_CREDENTIALS\n data: Array<UniqueDigitalCredential>\n}\n\nexport type FirstPartyMachineEventTypes = FirstPartyNextEvent | FirstPartyPreviousEvent | FirstPartyDeclineEvent | FirstPartySelectCredentialsEvent\n\nexport type FirstPartyMachineStatesConfig = StatesConfig<\n FirstPartyMachineContext,\n {\n states: FirstPartyMachineStates\n },\n FirstPartyMachineEventTypes,\n any\n>\n\nexport type CreateFirstPartyMachineOpts = {\n openID4VCIClientState: OpenID4VCIClientState\n contact: Party\n agentContext: RequiredContext\n machineId?: string\n}\n\nexport type FirstPartyStateMachine = StateMachine<\n FirstPartyMachineContext,\n any,\n FirstPartyMachineEventTypes,\n {\n value: any\n context: FirstPartyMachineContext\n },\n BaseActionObject,\n ServiceMap,\n ResolveTypegenMeta<TypegenDisabled, FirstPartyMachineEventTypes, BaseActionObject, ServiceMap>\n>\n\nexport type FirstPartyMachineInterpreter = Interpreter<\n FirstPartyMachineContext,\n any,\n FirstPartyMachineEventTypes,\n {\n value: any\n context: FirstPartyMachineContext\n },\n any\n>\n\nexport type FirstPartyMachineStateNavigationListener = (\n firstPartyMachine: FirstPartyMachineInterpreter,\n state: FirstPartyMachineState,\n navigation?: any,\n) => Promise<void>\n\nexport type InstanceFirstPartyMachineOpts = {\n services?: any\n guards?: any\n subscription?: () => void\n requireCustomNavigationHook?: boolean\n stateNavigationListener?: FirstPartyMachineStateNavigationListener\n} & CreateFirstPartyMachineOpts\n\nexport type FirstPartyMachineState = State<\n FirstPartyMachineContext,\n FirstPartyMachineEventTypes,\n any,\n {\n value: any\n context: FirstPartyMachineContext\n },\n any\n>\n\nexport type FirstPartyMachineServiceDefinitions = Record<keyof typeof FirstPartyMachineServices, (...args: Array<any>) => any>\n\nexport type SendAuthorizationChallengeRequestArgs = Pick<\n FirstPartyMachineContext,\n 'openID4VCIClientState' | 'authSession' | 'presentationDuringIssuanceSession'\n>\n\nexport type SendAuthorizationResponseArgs = Pick<\n FirstPartyMachineContext,\n 'authSession' | 'presentationUri' | 'didAuthConfig' | 'authorizationRequestData' | 'selectedCredentials'\n>\n\nexport type CreateConfigArgs = Pick<FirstPartyMachineContext, 'presentationUri' | 'identifier'>\n\nexport type GetSiopRequestArgs = Pick<FirstPartyMachineContext, 'didAuthConfig' | 'presentationUri'>\n\nexport type SiopV2AuthorizationRequestData = {\n correlationId: string\n registrationMetadataPayload: RPRegistrationMetadataPayload\n issuer?: string\n name?: string\n uri?: URL\n clientIdScheme?: string\n clientId?: string\n entityId?: string\n dcqlQuery: DcqlQuery\n}\n\nexport type FirstPartyMachineNavigationArgs = {\n firstPartyMachine: FirstPartyMachineInterpreter\n state: FirstPartyMachineState\n navigation: any\n onNext?: () => void\n onBack?: () => void\n}\n","import { LOG } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationChallengeCodeResponse,\n CredentialConfigurationSupported,\n CredentialConfigurationSupportedSdJwtVcV1_0_15,\n CredentialResponse,\n CredentialResponseV1_0_15,\n CredentialSupportedSdJwtVc,\n getSupportedCredentials,\n getTypesFromCredentialSupported,\n getTypesFromObject,\n MetadataDisplay,\n} from '@sphereon/oid4vci-common'\nimport { KeyUse } from '@sphereon/ssi-sdk-ext.did-resolver-jwk'\nimport { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n isIIdentifier,\n isManagedIdentifierDidResult,\n isManagedIdentifierResult,\n ManagedIdentifierMethod,\n ManagedIdentifierResult,\n managedIdentifierToJwk,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { keyTypeFromCryptographicSuite } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { defaultHasher } from '@sphereon/ssi-sdk.core'\nimport { IBasicCredentialLocaleBranding, IBasicIssuerLocaleBranding } from '@sphereon/ssi-sdk.data-store-types'\nimport {\n CredentialMapper,\n Hasher,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n mdocDecodedCredentialToUniformCredential,\n OriginalVerifiableCredential,\n sdJwtDecodedCredentialToUniformCredential,\n SdJwtDecodedVerifiableCredential,\n SdJwtTypeMetadata,\n W3CVerifiableCredential,\n WrappedVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { asArray } from '@veramo/utils'\nimport { translate } from '../localization/Localization'\nimport { FirstPartyMachine } from '../machines/firstPartyMachine'\nimport { issuerLocaleBrandingFrom, oid4vciGetCredentialBrandingFrom, sdJwtGetCredentialBrandingFrom } from '../mappers/OIDC4VCIBrandingMapper'\nimport { FirstPartyMachineState, FirstPartyMachineStateTypes } from '../types/FirstPartyMachine'\nimport {\n DidAgents,\n GetBasicIssuerLocaleBrandingArgs,\n GetCredentialBrandingArgs,\n GetCredentialConfigsSupportedArgs,\n GetCredentialConfigsSupportedBySingleTypeOrIdArgs,\n GetIdentifierArgs,\n GetIssuanceCryptoSuiteArgs,\n GetIssuanceDidMethodArgs,\n GetIssuanceOptsArgs,\n GetPreferredCredentialFormatsArgs,\n IssuanceOpts,\n MapCredentialToAcceptArgs,\n MappedCredentialToAccept,\n OID4VCIHolderEvent,\n RequiredContext,\n SelectAppLocaleBrandingArgs,\n StartFirstPartApplicationMachine,\n VerificationResult,\n VerifyCredentialToAcceptArgs,\n} from '../types/IOID4VCIHolder'\n\nexport const getCredentialBranding = async (args: GetCredentialBrandingArgs): Promise<Record<string, Array<IBasicCredentialLocaleBranding>>> => {\n const { credentialsSupported, context } = args\n const credentialBranding: Record<string, Array<IBasicCredentialLocaleBranding>> = {}\n await Promise.all(\n Object.entries(credentialsSupported).map(async ([configId, credentialsConfigSupported]): Promise<void> => {\n let sdJwtTypeMetadata: SdJwtTypeMetadata | undefined\n if (credentialsConfigSupported.format === 'dc+sd-jwt') {\n const vct = (<CredentialSupportedSdJwtVc | CredentialConfigurationSupportedSdJwtVcV1_0_15>credentialsConfigSupported).vct\n if (vct.startsWith('http')) {\n try {\n sdJwtTypeMetadata = await context.agent.fetchSdJwtTypeMetadataFromVctUrl({ vct })\n } catch {\n // For now, we are just going to ignore and continue without any branding as we still have a fallback\n }\n }\n }\n let mappedLocaleBranding: Array<IBasicCredentialLocaleBranding> = []\n if (sdJwtTypeMetadata) {\n mappedLocaleBranding = await sdJwtGetCredentialBrandingFrom({\n credentialDisplay: sdJwtTypeMetadata.display,\n claimsMetadata: sdJwtTypeMetadata.claims,\n })\n } else {\n mappedLocaleBranding = await oid4vciGetCredentialBrandingFrom({\n credentialDisplay: credentialsConfigSupported.display,\n issuerCredentialSubject:\n // @ts-ignore // FIXME SPRIND-123 add proper support for type recognition as claim display can be located elsewhere for v13\n credentialsSupported.claims !== undefined ? credentialsConfigSupported.claims : credentialsConfigSupported.credentialSubject,\n })\n }\n // TODO we should make the mapper part of the plugin, so that the logic for getting the branding becomes more clear and easier to use\n const localeBranding = await Promise.all(\n mappedLocaleBranding.map(\n async (localeBranding): Promise<IBasicCredentialLocaleBranding> => await context.agent.ibCredentialLocaleBrandingFrom({ localeBranding }),\n ),\n )\n const defaultCredentialType = 'VerifiableCredential'\n const configSupportedTypes = getTypesFromCredentialSupported(credentialsConfigSupported)\n const credentialTypes: Array<string> = configSupportedTypes.length === 0 ? asArray(defaultCredentialType) : configSupportedTypes\n const filteredCredentialTypes = credentialTypes.filter((type: string): boolean => type !== defaultCredentialType)\n credentialBranding[filteredCredentialTypes[0]] = localeBranding // TODO for now taking the first type\n }),\n )\n\n return credentialBranding\n}\n\nexport const getBasicIssuerLocaleBranding = async (args: GetBasicIssuerLocaleBrandingArgs): Promise<Array<IBasicIssuerLocaleBranding>> => {\n const { display, dynamicRegistrationClientMetadata, context } = args\n return await Promise.all(\n display.map(async (issuerDisplay: MetadataDisplay): Promise<IBasicIssuerLocaleBranding> => {\n // FIXME for now we do not have locale support for dynamicRegistrationClientMetadata, so we add all the metadata to every locale\n const branding = await issuerLocaleBrandingFrom({ issuerDisplay, dynamicRegistrationClientMetadata })\n return context.agent.ibIssuerLocaleBrandingFrom({ localeBranding: branding })\n }),\n )\n}\n\nexport const getCredentialConfigsBasedOnFormatPref = async (\n args: GetPreferredCredentialFormatsArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n const { vcFormatPreferences, credentials } = args\n const prefConfigs = {} as Record<string, CredentialConfigurationSupported>\n Object.entries(credentials).forEach(([key, config]) => {\n const result = !config.format || vcFormatPreferences.map((pref) => pref.toLowerCase()).includes(config.format.toLowerCase())\n if (result) {\n prefConfigs[key] = config\n }\n })\n\n return prefConfigs\n}\n\nexport const selectCredentialLocaleBranding = async (\n args: SelectAppLocaleBrandingArgs,\n): Promise<IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding | undefined> => {\n const { locale, localeBranding } = args\n\n return localeBranding?.find(\n (branding: IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding) =>\n locale ? branding.locale?.startsWith(locale) || branding.locale === undefined : branding.locale === undefined, // TODO refactor as we have duplicate code\n )\n}\n\nexport const verifyCredentialToAccept = async (args: VerifyCredentialToAcceptArgs): Promise<VerificationResult> => {\n const { mappedCredential, hasher, onVerifyEBSICredentialIssuer, schemaValidation, context } = args\n\n const credential = extractCredentialFromResponse(mappedCredential.credentialToAccept.credentialResponse)\n\n const wrappedVC = CredentialMapper.toWrappedVerifiableCredential(credential, { hasher: hasher ?? defaultHasher })\n if (\n wrappedVC.decoded?.iss?.includes('did:ebsi:') ||\n (typeof wrappedVC.decoded?.vc?.issuer === 'string'\n ? wrappedVC.decoded?.vc?.issuer?.includes('did:ebsi:')\n : wrappedVC.decoded?.vc?.issuer?.existingInstanceId?.includes('did:ebsi:'))\n ) {\n // TODO: Skipping VC validation for EBSI conformance issued credential, as their Issuer is not present in the ledger (sigh)\n // just calling the verifySchema functionality for ebsi credentials\n await context.agent.cvVerifySchema({ credential, hasher, validationPolicy: schemaValidation })\n if (JSON.stringify(wrappedVC.decoded).includes('vc:ebsi:conformance')) {\n return { source: wrappedVC, error: undefined, result: true, subResults: [] } satisfies VerificationResult\n }\n\n if (onVerifyEBSICredentialIssuer) {\n try {\n await onVerifyEBSICredentialIssuer({\n wrappedVc: wrappedVC,\n })\n } catch (e) {\n return { source: wrappedVC, error: e.message, result: true, subResults: [] } satisfies VerificationResult\n }\n }\n }\n\n const verificationResult: VerificationResult = await context.agent.cvVerifyCredential({\n credential,\n hasher,\n // TODO WAL-675 we might want to allow these types of options as part of the context, now we have state machines. Allows us to pre-determine whether these policies apply and whether remote context should be fetched\n fetchRemoteContexts: true,\n policies: {\n schemaValidation: schemaValidation,\n credentialStatus: false,\n expirationDate: false,\n issuanceDate: false,\n },\n })\n\n if (!verificationResult.result || verificationResult.error) {\n return Promise.reject(Error(verificationResult.error ?? translate('oid4vci_machine_credential_verification_failed_message')))\n }\n return verificationResult\n}\n\nexport const mapCredentialToAccept = async (args: MapCredentialToAcceptArgs): Promise<MappedCredentialToAccept> => {\n const { credentialToAccept, hasher } = args\n\n const verifiableCredential = extractCredentialFromResponse(credentialToAccept.credentialResponse) as W3CVerifiableCredential\n\n const wrappedVerifiableCredential: WrappedVerifiableCredential = CredentialMapper.toWrappedVerifiableCredential(\n verifiableCredential as OriginalVerifiableCredential,\n { hasher },\n )\n let uniformVerifiableCredential: IVerifiableCredential\n if (CredentialMapper.isSdJwtDecodedCredential(wrappedVerifiableCredential.credential)) {\n uniformVerifiableCredential = sdJwtDecodedCredentialToUniformCredential(<SdJwtDecodedVerifiableCredential>wrappedVerifiableCredential.credential)\n } else if (CredentialMapper.isSdJwtEncoded(wrappedVerifiableCredential.credential)) {\n if (!hasher) {\n return Promise.reject('a hasher is required for encoded SD-JWT credentials')\n }\n const asyncHasher: Hasher = (data: string | ArrayBuffer | SharedArrayBuffer, algorithm: string) => Promise.resolve(hasher(data, algorithm))\n const decodedSdJwt = await CredentialMapper.decodeSdJwtVcAsync(wrappedVerifiableCredential.credential, asyncHasher)\n uniformVerifiableCredential = sdJwtDecodedCredentialToUniformCredential(<SdJwtDecodedVerifiableCredential>decodedSdJwt)\n } else if (CredentialMapper.isMsoMdocDecodedCredential(wrappedVerifiableCredential.credential)) {\n uniformVerifiableCredential = mdocDecodedCredentialToUniformCredential(wrappedVerifiableCredential.credential)\n } else {\n uniformVerifiableCredential = <IVerifiableCredential>wrappedVerifiableCredential.credential\n }\n\n const correlationId: string =\n typeof uniformVerifiableCredential.issuer === 'string'\n ? uniformVerifiableCredential.issuer\n : CredentialMapper.isSdJwtDecodedCredential(uniformVerifiableCredential)\n ? uniformVerifiableCredential.decodedPayload.iss\n : uniformVerifiableCredential.issuer.id\n\n const credentialResponse = credentialToAccept.credentialResponse as CredentialResponseV1_0_15\n return {\n correlationId,\n credentialToAccept,\n types: credentialToAccept.types,\n rawVerifiableCredential: verifiableCredential,\n uniformVerifiableCredential,\n ...(credentialResponse.credential_subject_issuance && { credential_subject_issuance: credentialResponse.credential_subject_issuance }),\n }\n}\n\nexport const extractCredentialFromResponse = (credentialResponse: CredentialResponse): OriginalVerifiableCredential => {\n let credential: OriginalVerifiableCredential | undefined\n\n if ('credential' in credentialResponse) {\n credential = credentialResponse.credential as OriginalVerifiableCredential\n } else if (\n 'credentials' in credentialResponse &&\n credentialResponse.credentials &&\n Array.isArray(credentialResponse.credentials) &&\n credentialResponse.credentials.length > 0\n ) {\n credential = credentialResponse.credentials[0].credential as OriginalVerifiableCredential // FIXME SSISDK-13 (no multi-credential support yet)\n }\n\n if (!credential) {\n throw new Error('No credential found in credential response')\n }\n\n return credential\n}\n\nexport const getIdentifierOpts = async (args: GetIdentifierArgs): Promise<ManagedIdentifierResult> => {\n const { issuanceOpt, context } = args\n const { identifier: identifierArg } = issuanceOpt\n if (identifierArg && isManagedIdentifierResult(identifierArg)) {\n return identifierArg\n }\n const {\n supportedPreferredDidMethod,\n supportedBindingMethods,\n keyType = 'Secp256r1',\n kms = await context.agent.keyManagerGetDefaultKeyManagementSystem(),\n } = issuanceOpt\n let identifier: ManagedIdentifierResult\n\n if (identifierArg) {\n if (isIIdentifier(identifierArg.identifier)) {\n identifier = await context.agent.identifierManagedGet(identifierArg)\n } else if (!identifierArg.method && issuanceOpt.supportedBindingMethods.includes('jwk')) {\n identifier = await managedIdentifierToJwk(identifierArg, context)\n } else if (identifierArg.method && !supportedBindingMethods.includes(identifierArg.method)) {\n throw Error(`Supplied identifier method ${identifierArg.method} not supported by the issuer: ${supportedBindingMethods.join(',')}`)\n } else {\n identifier = await context.agent.identifierManagedGet(identifierArg)\n }\n }\n const agentContext = { ...context, agent: context.agent as DidAgents }\n\n if (\n (!identifierArg || isIIdentifier(identifierArg.identifier)) &&\n supportedPreferredDidMethod &&\n (!supportedBindingMethods || supportedBindingMethods.length === 0 || supportedBindingMethods.filter((method) => method.startsWith('did')))\n ) {\n // previous code for managing DIDs only\n const { result, created } = await getOrCreatePrimaryIdentifier(agentContext, {\n method: supportedPreferredDidMethod,\n createOpts: {\n options: {\n type: issuanceOpt.keyType,\n use: KeyUse.Signature,\n codecName: issuanceOpt.codecName,\n kms: issuanceOpt.kms,\n },\n },\n })\n identifier = await context.agent.identifierManagedGetByDid({\n identifier: result,\n keyType,\n offlineWhenNoDIDRegistered: result.did.startsWith('did:ebsi:'),\n })\n if (created) {\n await agentContext.agent.emit(OID4VCIHolderEvent.IDENTIFIER_CREATED, { identifier })\n }\n } else if (supportedBindingMethods.includes('jwk')) {\n // todo: we probably should do something similar as with DIDs for re-use/new keys\n const key = await context.agent.keyManagerCreate({ type: keyType, kms, meta: { keyAlias: `key_${keyType}_${Date.now()}` } })\n // TODO. Create/move this to identifier service await agentContext.agent.emit(OID4VCIHolderEvent.IDENTIFIER_CREATED, { key })\n identifier = await managedIdentifierToJwk({ method: 'key', identifier: key, kmsKeyRef: key.kid }, context)\n // } else if (supportedBindingMethods.includes('cose_key')) {\n // // TODO COSE HERE\n // throw Error(`Holder currently does not support binding method: ${supportedBindingMethods.join(',')}`)\n } else {\n throw Error(`Holder currently does not support binding method: ${supportedBindingMethods.join(',')}`)\n }\n args.issuanceOpt.identifier = identifier\n return identifier\n}\n\nexport const getCredentialConfigsSupportedMerged = async (\n args: GetCredentialConfigsSupportedArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n let result = {} as Record<string, CredentialConfigurationSupported>\n ;(await getCredentialConfigsSupported(args)).forEach((supported: Record<string, CredentialConfigurationSupported>) => {\n result = { ...result, ...supported }\n })\n return result\n}\n\nexport const getCredentialConfigsSupported = async (\n args: GetCredentialConfigsSupportedArgs,\n): Promise<Array<Record<string, CredentialConfigurationSupported>>> => {\n const { types, configurationIds } = args\n if (Array.isArray(types) && types.length > 0) {\n return Promise.all(types.map((type) => getCredentialConfigsSupportedBySingleTypeOrId({ ...args, types: type })))\n } else if (Array.isArray(configurationIds) && configurationIds.length > 0) {\n return Promise.all(\n configurationIds.map((configurationId) =>\n getCredentialConfigsSupportedBySingleTypeOrId({\n ...args,\n configurationId,\n types: undefined,\n }),\n ),\n )\n }\n const configs = await getCredentialConfigsSupportedBySingleTypeOrId({\n ...args,\n types: undefined,\n configurationId: undefined,\n })\n return configs && Object.keys(configs).length > 0 ? [configs] : []\n}\n/**\n * Please note that this method only returns configs supported for a single set of credential types or a single config id.\n * If an offer contains multiple formats/types in an array or multiple config ids, you will have to call this method for all of them\n * @param args\n */\nexport const getCredentialConfigsSupportedBySingleTypeOrId = async (\n args: GetCredentialConfigsSupportedBySingleTypeOrIdArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n const { client, vcFormatPreferences, configurationId } = args\n let { format = undefined, types = undefined } = args\n\n function createIdFromTypes(supported: CredentialConfigurationSupported) {\n const format = supported.format\n const type: string = getTypesFromObject(supported)?.join() ?? ''\n const id = `${type}:${format}`\n return id\n }\n\n if (configurationId) {\n const allSupported = client.getCredentialsSupported(undefined, format)\n return Object.fromEntries(\n Object.entries(allSupported).filter(\n ([id, supported]) => id === configurationId || supported.id === configurationId || createIdFromTypes(supported) === configurationId,\n ),\n )\n }\n\n if (!client.credentialOffer) {\n return Promise.reject(Error('openID4VCIClient has no credentialOffer'))\n }\n if (!types) {\n return Promise.reject(Error('openID4VCIClient has no types'))\n }\n\n const offerSupported = getSupportedCredentials({\n types: [types],\n format,\n version: client.version(),\n issuerMetadata: client.endpointMetadata.credentialIssuerMetadata,\n })\n let allSupported: Record<string, CredentialConfigurationSupported>\n\n if (!Array.isArray(offerSupported)) {\n allSupported = offerSupported\n } else {\n allSupported = {} satisfies Record<string, CredentialConfigurationSupported>\n offerSupported.forEach((supported) => {\n if (supported.id) {\n allSupported[supported.id as string] = supported\n return\n }\n const id = createIdFromTypes(supported)\n allSupported[id] = supported\n })\n }\n\n let credentialConfigsSupported = await getCredentialConfigsBasedOnFormatPref({\n credentials: allSupported,\n vcFormatPreferences,\n })\n if (!credentialConfigsSupported || Object.keys(credentialConfigsSupported).length === 0) {\n LOG.warning(`No matching supported credential found for ${client.getIssuer()}`)\n }\n\n if (client.credentialOffer === undefined) {\n return credentialConfigsSupported\n }\n // Filter configurations based on the credential offer IDs\n const credentialOffer = client.credentialOffer.credential_offer\n\n let credentialsToOffer: Record<string, CredentialConfigurationSupported>\n if ('credential_configuration_ids' in credentialOffer) {\n credentialsToOffer = Object.fromEntries(\n Object.entries(credentialConfigsSupported).filter(([configId, config]) => credentialOffer.credential_configuration_ids.includes(configId)),\n )\n if (Object.keys(credentialsToOffer).length === 0) {\n throw new Error(`No matching supported credential configs found for offer ${credentialOffer.credential_configuration_ids.join(', ')}`)\n }\n } else {\n credentialsToOffer = credentialConfigsSupported\n }\n if (Object.keys(credentialsToOffer).length === 0) {\n // Same check as above, but more generic error message, as it can also apply to below draft 13\n throw new Error(`No matching supported credential configs found for offer`)\n }\n\n return credentialsToOffer\n}\n\nexport const getIssuanceOpts = async (args: GetIssuanceOptsArgs): Promise<Array<IssuanceOpts>> => {\n const {\n client,\n credentialsSupported,\n // serverMetadata,\n context,\n didMethodPreferences,\n jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences,\n forceIssuanceOpt,\n } = args\n\n if (credentialsSupported === undefined || Object.keys(credentialsSupported).length === 0) {\n return Promise.reject(Error('No credentials supported'))\n }\n\n const getIssuanceOpts: Array<Promise<IssuanceOpts>> = Object.values(credentialsSupported).map(async (credentialSupported) => {\n /*if (!serverMetadata?.credentialIssuerMetadata) {\n return await getDefaultIssuanceOpts({ credentialSupported, opts: { client }, context })\n }*/\n\n const cryptographicSuite: string = await getIssuanceCryptoSuite({\n credentialSupported,\n client,\n jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences,\n })\n const { didMethod, methods } = await getIssuanceMethod({\n credentialSupported,\n client,\n didMethodPreferences,\n })\n if (methods.length == 0) {\n console.log(`Could not determine supported cryptographic_binding_methods_supported, will use DIDs`)\n methods.push('did')\n }\n const issuanceOpt = forceIssuanceOpt\n ? { ...credentialSupported, ...forceIssuanceOpt }\n : ({\n ...credentialSupported,\n supportedPreferredDidMethod: didMethod,\n supportedBindingMethods: methods,\n format: credentialSupported.format,\n keyType: client.isEBSI() ? 'Secp256r1' : keyTypeFromCryptographicSuite({ crv: cryptographicSuite }),\n ...(client.isEBSI() && { codecName: 'EBSI' }),\n } satisfies IssuanceOpts)\n const identifier = await getIdentifierOpts({ issuanceOpt, context })\n if (!client.clientId && isManagedIdentifierDidResult(identifier)) {\n // FIXME: We really should fetch server metadata. Have user select required credentials. Take the first cred to determine a kid when no clientId is present and set that.\n // Needs a preference service for crypto, keys, dids, and clientId, with ecosystem support\n client.clientId = identifier.issuer ?? identifier.did\n }\n return { ...issuanceOpt, identifier }\n })\n\n return await Promise.all(getIssuanceOpts)\n}\n\nexport const getIssuanceMethod = async (\n opts: GetIssuanceDidMethodArgs,\n): Promise<{\n methods: ManagedIdentifierMethod[]\n didMethod?: SupportedDidMethodEnum\n}> => {\n const { client, credentialSupported, didMethodPreferences } = opts\n const { format, cryptographic_binding_methods_supported } = credentialSupported\n let methods: ManagedIdentifierMethod[] = [] // we use the external identifier method, as we should be supporting all values in the server metadata anyway\n if (cryptographic_binding_methods_supported && Array.isArray(cryptographic_binding_methods_supported)) {\n methods = cryptographic_binding_methods_supported as ManagedIdentifierMethod[]\n const didMethods: SupportedDidMethodEnum | undefined = didMethodPreferences.find((method: SupportedDidMethodEnum) =>\n cryptographic_binding_methods_supported.includes(`did:${method.toLowerCase() /*.replace('did:', '')*/}`),\n )\n if (didMethods) {\n return { methods, didMethod: didMethods }\n } else if (cryptographic_binding_methods_supported.includes('did')) {\n return { methods, didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0] }\n } else if (methods.length > 0) {\n return { methods }\n }\n console.warn(\n `We should have been able to determine cryptographic_binding_methods_supported, will fall back to legacy behaviour. This is likely a bug`,\n )\n }\n\n if (client.isEBSI()) {\n return { methods: ['did'], didMethod: SupportedDidMethodEnum.DID_KEY }\n }\n\n // legacy fallback\n methods = ['did']\n if (!format || (format.includes('jwt') && !format?.includes('jwt_vc_json_ld'))) {\n return { methods, didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0] }\n } else {\n // JsonLD\n return { methods, didMethod: didMethodPreferences[0] }\n }\n}\n\nexport const getIssuanceCryptoSuite = async (opts: GetIssuanceCryptoSuiteArgs): Promise<string> => {\n const { client, credentialSupported, jwtCryptographicSuitePreferences, jsonldCryptographicSuitePreferences } = opts\n\n let signing_algs_supported: Array<string>\n if ('proof_types_supported' in credentialSupported && credentialSupported.proof_types_supported) {\n if ('jwt' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.jwt) {\n signing_algs_supported = credentialSupported.proof_types_supported.jwt.proof_signing_alg_values_supported\n } else if ('ldp_vp' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.ldp_vp) {\n signing_algs_supported = credentialSupported.proof_types_supported.ldp_vp.proof_signing_alg_values_supported\n } else if ('cwt' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.cwt) {\n signing_algs_supported = credentialSupported.proof_types_supported.cwt.proof_signing_alg_values_supported\n console.error('cwt proof type not supported. Likely that errors will occur after this point')\n } else {\n return Promise.reject(Error(`Unsupported proof_types_supported`))\n }\n } else {\n signing_algs_supported = asArray(\n // @ts-ignore // legacy\n credentialSupported.credential_signing_alg_values_supported ?? credentialSupported.proof_signing_alg_values_supported ?? [],\n )\n }\n\n // TODO: Return array, so the wallet/user could choose\n switch (credentialSupported.format) {\n // @ts-ignore legacy value\n case 'jwt':\n case 'jwt_vc_json':\n case 'jwt_vc':\n case 'vc+sd-jwt':\n case 'dc+sd-jwt':\n case 'mso_mdoc': {\n const supportedPreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString> = jwtCryptographicSuitePreferences.filter(\n (suite: JoseSignatureAlgorithm | JoseSignatureAlgorithmString) => signing_algs_supported.includes(suite),\n )\n\n if (supportedPreferences.length > 0) {\n return supportedPreferences[0]\n } else if (client.isEBSI()) {\n return JoseSignatureAlgorithm.ES256\n }\n\n // if we cannot find supported cryptographic suites, we just try with the first preference\n const fallback = jwtCryptographicSuitePreferences[0]\n console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`)\n return fallback\n }\n // @ts-ignore\n case 'ldp':\n // @ts-ignore\n case 'jwt_vc_json_ld':\n case 'ldp_vc': {\n const supportedPreferences: Array<string> = jsonldCryptographicSuitePreferences.filter((suite: string) =>\n signing_algs_supported.includes(suite),\n )\n if (supportedPreferences.length > 0) {\n return supportedPreferences[0]\n }\n\n // if we cannot find supported cryptographic suites, we just try with the first preference\n const fallback = jsonldCryptographicSuitePreferences[0]\n console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`)\n return fallback\n }\n default:\n return Promise.reject(Error(`Credential format '${credentialSupported.format}' not supported`))\n }\n}\n\nexport const startFirstPartApplicationMachine = async (\n args: StartFirstPartApplicationMachine,\n context: RequiredContext,\n): Promise<AuthorizationChallengeCodeResponse | string> => {\n const { openID4VCIClientState, stateNavigationListener, contact } = args\n\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n const firstPartyMachineInstance = FirstPartyMachine.newInstance({\n openID4VCIClientState,\n contact,\n agentContext: context,\n stateNavigationListener,\n })\n\n return new Promise((resolve, reject) => {\n try {\n firstPartyMachineInstance.onTransition((state: FirstPartyMachineState) => {\n if (state.matches(FirstPartyMachineStateTypes.done)) {\n const authorizationCodeResponse = state.context.authorizationCodeResponse\n if (!authorizationCodeResponse) {\n reject(Error('No authorizationCodeResponse acquired'))\n }\n resolve(authorizationCodeResponse!)\n } else if (state.matches(FirstPartyMachineStateTypes.aborted)) {\n resolve(FirstPartyMachineStateTypes.aborted)\n } else if (state.matches(FirstPartyMachineStateTypes.declined)) {\n resolve(FirstPartyMachineStateTypes.declined)\n } else if (state.matches(FirstPartyMachineStateTypes.error)) {\n reject(state.context.error)\n }\n })\n firstPartyMachineInstance.start()\n } catch (error) {\n reject(error)\n }\n })\n}\n","import { assign, createMachine, DoneInvokeEvent, interpret } from 'xstate'\nimport { AuthorizationChallengeCodeResponse, AuthorizationChallengeError, AuthorizationChallengeErrorResponse } from '@sphereon/oid4vci-common'\nimport { DidAuthConfig } from '@sphereon/ssi-sdk.data-store-types'\nimport { CreateConfigResult } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport { createConfig, getSiopRequest, sendAuthorizationChallengeRequest, sendAuthorizationResponse } from '../services/FirstPartyMachineServices'\nimport { translate } from '../localization/Localization'\nimport { ErrorDetails } from '../types/IOID4VCIHolder'\nimport {\n CreateConfigArgs,\n CreateFirstPartyMachineOpts,\n FirstPartyMachineContext,\n FirstPartyMachineEvents,\n FirstPartyMachineEventTypes,\n FirstPartyMachineInterpreter,\n FirstPartyMachineServices,\n FirstPartyMachineState,\n FirstPartyMachineStatesConfig,\n FirstPartyMachineStateTypes,\n FirstPartyMachineServiceDefinitions,\n FirstPartyStateMachine,\n GetSiopRequestArgs,\n InstanceFirstPartyMachineOpts,\n SiopV2AuthorizationRequestData,\n SendAuthorizationResponseArgs,\n FirstPartySelectCredentialsEvent,\n} from '../types/FirstPartyMachine'\n\nconst firstPartyMachineStates: FirstPartyMachineStatesConfig = {\n [FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest]: {\n id: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n invoke: {\n src: FirstPartyMachineServices.sendAuthorizationChallengeRequest,\n onDone: {\n target: FirstPartyMachineStateTypes.done,\n actions: assign({\n authorizationCodeResponse: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeCodeResponse>) => _event.data,\n }),\n },\n onError: [\n {\n target: FirstPartyMachineStateTypes.createConfig,\n cond: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>): boolean =>\n _event.data.error === AuthorizationChallengeError.insufficient_authorization,\n actions: assign({\n authSession: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>) => _event.data.auth_session,\n presentationUri: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>) =>\n _event.data.presentation,\n }),\n },\n {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_send_authorization_challenge_request_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n ],\n },\n },\n [FirstPartyMachineStateTypes.createConfig]: {\n id: FirstPartyMachineStateTypes.createConfig,\n invoke: {\n src: FirstPartyMachineServices.createConfig,\n onDone: {\n target: FirstPartyMachineStateTypes.getSiopRequest,\n actions: assign({\n didAuthConfig: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<DidAuthConfig>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_create_config_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [FirstPartyMachineStateTypes.getSiopRequest]: {\n id: FirstPartyMachineStateTypes.getSiopRequest,\n invoke: {\n src: FirstPartyMachineServices.getSiopRequest,\n onDone: {\n target: FirstPartyMachineStateTypes.selectCredentials,\n actions: assign({\n authorizationRequestData: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<SiopV2AuthorizationRequestData>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _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 [FirstPartyMachineStateTypes.selectCredentials]: {\n id: FirstPartyMachineStateTypes.selectCredentials,\n on: {\n [FirstPartyMachineEvents.SET_SELECTED_CREDENTIALS]: {\n actions: assign({ selectedCredentials: (_ctx: FirstPartyMachineContext, _event: FirstPartySelectCredentialsEvent) => _event.data }),\n },\n [FirstPartyMachineEvents.NEXT]: {\n target: FirstPartyMachineStateTypes.sendAuthorizationResponse,\n },\n [FirstPartyMachineEvents.DECLINE]: {\n target: FirstPartyMachineStateTypes.declined,\n },\n [FirstPartyMachineEvents.PREVIOUS]: {\n target: FirstPartyMachineStateTypes.aborted,\n },\n },\n },\n [FirstPartyMachineStateTypes.sendAuthorizationResponse]: {\n id: FirstPartyMachineStateTypes.sendAuthorizationResponse,\n invoke: {\n src: FirstPartyMachineServices.sendAuthorizationResponse,\n onDone: {\n target: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n actions: assign({\n presentationDuringIssuanceSession: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<string>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_get_request_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [FirstPartyMachineStateTypes.aborted]: {\n id: FirstPartyMachineStateTypes.aborted,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.declined]: {\n id: FirstPartyMachineStateTypes.declined,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.error]: {\n id: FirstPartyMachineStateTypes.error,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.done]: {\n id: FirstPartyMachineStateTypes.done,\n type: 'final',\n },\n}\n\nconst createFirstPartyActivationMachine = (opts: CreateFirstPartyMachineOpts): FirstPartyStateMachine => {\n const initialContext: FirstPartyMachineContext = {\n openID4VCIClientState: opts.openID4VCIClientState,\n contact: opts.contact,\n selectedCredentials: [],\n }\n\n return createMachine<FirstPartyMachineContext, FirstPartyMachineEventTypes>({\n id: opts?.machineId ?? 'FirstParty',\n predictableActionArguments: true,\n initial: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n context: initialContext,\n states: firstPartyMachineStates,\n schema: {\n events: {} as FirstPartyMachineEventTypes,\n services: {} as {\n [FirstPartyMachineServices.sendAuthorizationChallengeRequest]: {\n data: void\n }\n [FirstPartyMachineServices.createConfig]: {\n data: CreateConfigResult\n }\n [FirstPartyMachineServices.getSiopRequest]: {\n data: SiopV2AuthorizationRequestData\n }\n [FirstPartyMachineServices.sendAuthorizationResponse]: {\n data: string\n }\n },\n },\n })\n}\n\nexport class FirstPartyMachine {\n private static _instance: FirstPartyMachineInterpreter | undefined\n\n static hasInstance(): boolean {\n return FirstPartyMachine._instance !== undefined\n }\n\n static get instance(): FirstPartyMachineInterpreter {\n if (!FirstPartyMachine._instance) {\n throw Error('Please initialize ESIMActivation machine first')\n }\n return FirstPartyMachine._instance\n }\n\n static clearInstance(opts: { stop: boolean }) {\n const { stop } = opts\n if (FirstPartyMachine.hasInstance()) {\n if (stop) {\n FirstPartyMachine.stopInstance()\n }\n }\n FirstPartyMachine._instance = undefined\n }\n\n static stopInstance(): void {\n if (!FirstPartyMachine.hasInstance()) {\n return\n }\n FirstPartyMachine.instance.stop()\n FirstPartyMachine._instance = undefined\n }\n\n public static newInstance(opts: InstanceFirstPartyMachineOpts): FirstPartyMachineInterpreter {\n const { agentContext } = opts\n const services: FirstPartyMachineServiceDefinitions = {\n [FirstPartyMachineServices.sendAuthorizationChallengeRequest]: sendAuthorizationChallengeRequest,\n [FirstPartyMachineServices.createConfig]: (args: CreateConfigArgs) => createConfig(args, agentContext),\n [FirstPartyMachineServices.getSiopRequest]: (args: GetSiopRequestArgs) => getSiopRequest(args, agentContext),\n [FirstPartyMachineServices.sendAuthorizationResponse]: (args: SendAuthorizationResponseArgs) => sendAuthorizationResponse(args, agentContext),\n }\n\n const newInst: FirstPartyMachineInterpreter = interpret(\n createFirstPartyActivationMachine(opts).withConfig({\n services: {\n ...services,\n ...opts?.services,\n },\n guards: {\n ...opts?.guards,\n },\n }),\n )\n\n if (typeof opts?.subscription === 'function') {\n newInst.onTransition(opts.subscription)\n }\n\n if (opts?.requireCustomNavigationHook !== true) {\n newInst.onTransition((snapshot: FirstPartyMachineState): void => {\n if (opts?.stateNavigationListener) {\n void opts.stateNavigationListener(newInst, snapshot)\n }\n })\n }\n\n return newInst\n }\n\n static getInstance(\n opts: InstanceFirstPartyMachineOpts & {\n requireExisting?: boolean\n },\n ): FirstPartyMachineInterpreter {\n if (!FirstPartyMachine._instance) {\n if (opts?.requireExisting === true) {\n throw Error(`Existing FirstPartyMachine instance requested, but none was created at this point!`)\n }\n FirstPartyMachine._instance = FirstPartyMachine.newInstance(opts)\n }\n return FirstPartyMachine._instance\n }\n}\n","import { OpenID4VCIClient } from '@sphereon/oid4vci-client'\nimport { AuthorizationChallengeValidationResponse } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { AuthorizationChallengeCodeResponse } from '@sphereon/oid4vci-common'\nimport { CreateConfigResult } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport { v4 as uuidv4 } from 'uuid'\nimport { RequiredContext } from '../types/IOID4VCIHolder'\nimport {\n CreateConfigArgs,\n GetSiopRequestArgs,\n SendAuthorizationChallengeRequestArgs,\n SendAuthorizationResponseArgs,\n SiopV2AuthorizationRequestData,\n} from '../types/FirstPartyMachine'\n\nexport const sendAuthorizationChallengeRequest = async (args: SendAuthorizationChallengeRequestArgs): Promise<AuthorizationChallengeCodeResponse> => {\n const { openID4VCIClientState, authSession, presentationDuringIssuanceSession } = args\n\n const oid4vciClient = await OpenID4VCIClient.fromState({ state: openID4VCIClientState })\n return oid4vciClient.acquireAuthorizationChallengeCode({\n clientId: oid4vciClient.clientId ?? uuidv4(),\n ...(authSession && { authSession }),\n ...(!authSession &&\n openID4VCIClientState.credentialOffer?.preAuthorizedCode && { issuerState: openID4VCIClientState.credentialOffer?.preAuthorizedCode }),\n ...(!authSession && openID4VCIClientState.credentialOffer?.issuerState && { issuerState: openID4VCIClientState.credentialOffer?.issuerState }),\n ...(presentationDuringIssuanceSession && { presentationDuringIssuanceSession }),\n })\n}\n\nexport const createConfig = async (args: CreateConfigArgs, context: RequiredContext): Promise<CreateConfigResult> => {\n const { presentationUri } = args\n\n if (!presentationUri) {\n return Promise.reject(Error('Missing presentation uri in context'))\n }\n\n return context.agent.siopCreateConfig({ url: presentationUri })\n}\n\nexport const getSiopRequest = async (args: GetSiopRequestArgs, context: RequiredContext): Promise<SiopV2AuthorizationRequestData> => {\n const { didAuthConfig, presentationUri } = args\n\n if (presentationUri === undefined) {\n return Promise.reject(Error('Missing presentation uri in context'))\n }\n\n if (didAuthConfig === undefined) {\n return Promise.reject(Error('Missing did auth config in context'))\n }\n\n return context.agent.siopGetSiopRequest({ didAuthConfig, url: presentationUri })\n}\n\nexport const sendAuthorizationResponse = async (args: SendAuthorizationResponseArgs, context: RequiredContext): Promise<string> => {\n const { didAuthConfig, authorizationRequestData, selectedCredentials } = args\n\n const responseData = await context.agent.siopSendResponse({\n authorizationRequestData,\n selectedCredentials,\n didAuthConfig,\n isFirstParty: true,\n })\n\n return (<AuthorizationChallengeValidationResponse>responseData.body).presentation_during_issuance_session\n}\n","import { CredentialsSupportedDisplay, NameAndLocale } from '@sphereon/oid4vci-common'\nimport { IBasicCredentialClaim, IBasicCredentialLocaleBranding, IBasicIssuerLocaleBranding } from '@sphereon/ssi-sdk.data-store-types'\nimport { SdJwtClaimDisplayMetadata, SdJwtClaimMetadata, SdJwtClaimPath, SdJwtTypeDisplayMetadata } from '@sphereon/ssi-types'\nimport {\n IssuerLocaleBrandingFromArgs,\n Oid4vciCombineDisplayLocalesFromArgs,\n Oid4vciCredentialDisplayLocalesFromArgs,\n Oid4vciCredentialLocaleBrandingFromArgs,\n Oid4vciGetCredentialBrandingFromArgs,\n Oid4vciIssuerCredentialSubjectLocalesFromArgs,\n SdJwtCombineDisplayLocalesFromArgs,\n SdJwtCredentialClaimLocalesFromArgs,\n SdJwtCredentialDisplayLocalesFromArgs,\n SdJwtCredentialLocaleBrandingFromArgs,\n SdJwtGetCredentialBrandingFromArgs,\n} from '../types/IOID4VCIHolder'\n\n// FIXME should we not move this to the branding plugin?\n\nexport const oid4vciGetCredentialBrandingFrom = async (\n args: Oid4vciGetCredentialBrandingFromArgs,\n): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplay, issuerCredentialSubject } = args\n\n return oid4vciCombineDisplayLocalesFrom({\n ...(issuerCredentialSubject && { issuerCredentialSubjectLocales: await oid4vciIssuerCredentialSubjectLocalesFrom({ issuerCredentialSubject }) }),\n ...(credentialDisplay && { credentialDisplayLocales: await oid4vciCredentialDisplayLocalesFrom({ credentialDisplay }) }),\n })\n}\n\nexport const oid4vciCredentialDisplayLocalesFrom = async (\n args: Oid4vciCredentialDisplayLocalesFromArgs,\n): Promise<Map<string, CredentialsSupportedDisplay>> => {\n const { credentialDisplay } = args\n return credentialDisplay.reduce((localeDisplays, display) => {\n const localeKey = display.locale || ''\n localeDisplays.set(localeKey, display)\n return localeDisplays\n }, new Map<string, CredentialsSupportedDisplay>())\n}\n\nexport const oid4vciIssuerCredentialSubjectLocalesFrom = async (\n args: Oid4vciIssuerCredentialSubjectLocalesFromArgs,\n): Promise<Map<string, Array<IBasicCredentialClaim>>> => {\n const { issuerCredentialSubject } = args\n const localeClaims = new Map<string, Array<IBasicCredentialClaim>>()\n\n const processClaimObject = (claim: any, parentKey: string = ''): void => {\n Object.entries(claim).forEach(([key, value]): void => {\n if (key === 'mandatory' || key === 'value_type') {\n return\n }\n\n if (key === 'display' && Array.isArray(value)) {\n value.forEach(({ name, locale = '' }: NameAndLocale): void => {\n if (!name) {\n return\n }\n\n //const localeKey = locale || ''\n if (!localeClaims.has(locale)) {\n localeClaims.set(locale, [])\n }\n localeClaims.get(locale)!.push({ key: parentKey, name })\n })\n } else if (typeof value === 'object' && value !== null) {\n processClaimObject(value, parentKey ? `${parentKey}.${key}` : key)\n }\n })\n }\n\n processClaimObject(issuerCredentialSubject)\n return localeClaims\n}\n\nexport const oid4vciCredentialLocaleBrandingFrom = async (args: Oid4vciCredentialLocaleBrandingFromArgs): Promise<IBasicCredentialLocaleBranding> => {\n const { credentialDisplay } = args\n\n return {\n ...(credentialDisplay.name && {\n alias: credentialDisplay.name,\n }),\n ...(credentialDisplay.locale && {\n locale: credentialDisplay.locale,\n }),\n ...(credentialDisplay.logo && {\n logo: {\n ...((credentialDisplay.logo.url || <string>credentialDisplay.logo.uri) && {\n uri: credentialDisplay.logo?.url ?? <string>credentialDisplay.logo.uri,\n }),\n ...(credentialDisplay.logo.alt_text && {\n alt: credentialDisplay.logo?.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.description && {\n description: credentialDisplay.description,\n }),\n\n ...(credentialDisplay.text_color && {\n text: {\n color: credentialDisplay.text_color,\n },\n }),\n ...((credentialDisplay.background_image || credentialDisplay.background_color) && {\n background: {\n ...(credentialDisplay.background_image && {\n image: {\n ...((credentialDisplay.background_image.url || <string>credentialDisplay.background_image.uri) && {\n uri: credentialDisplay.background_image?.url ?? <string>credentialDisplay.background_image.uri,\n }),\n ...(credentialDisplay.background_image.alt_text && {\n alt: credentialDisplay.background_image?.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.background_color && {\n color: credentialDisplay.background_color,\n }),\n },\n }),\n }\n}\n\nexport const oid4vciCombineDisplayLocalesFrom = async (\n args: Oid4vciCombineDisplayLocalesFromArgs,\n): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const {\n credentialDisplayLocales = new Map<string, CredentialsSupportedDisplay>(),\n issuerCredentialSubjectLocales = new Map<string, Array<IBasicCredentialClaim>>(),\n } = args\n\n const locales: Array<string> = Array.from(new Set([...issuerCredentialSubjectLocales.keys(), ...credentialDisplayLocales.keys()]))\n\n return Promise.all(\n locales.map(async (locale: string): Promise<IBasicCredentialLocaleBranding> => {\n const display = credentialDisplayLocales.get(locale)\n const claims = issuerCredentialSubjectLocales.get(locale)\n\n return {\n ...(display && (await oid4vciCredentialLocaleBrandingFrom({ credentialDisplay: display }))),\n ...(locale.length > 0 && { locale }),\n claims,\n }\n }),\n )\n}\n\nexport const sdJwtGetCredentialBrandingFrom = async (args: SdJwtGetCredentialBrandingFromArgs): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplay, claimsMetadata } = args\n\n return sdJwtCombineDisplayLocalesFrom({\n ...(claimsMetadata && { claimsMetadata: await sdJwtCredentialClaimLocalesFrom({ claimsMetadata }) }),\n ...(credentialDisplay && { credentialDisplayLocales: await sdJwtCredentialDisplayLocalesFrom({ credentialDisplay }) }),\n })\n}\n\nexport const sdJwtCredentialDisplayLocalesFrom = async (\n args: SdJwtCredentialDisplayLocalesFromArgs,\n): Promise<Map<string, SdJwtTypeDisplayMetadata>> => {\n const { credentialDisplay } = args\n return credentialDisplay.reduce((localeDisplays, display) => {\n const localeKey = display.lang || ''\n localeDisplays.set(localeKey, display)\n return localeDisplays\n }, new Map<string, SdJwtTypeDisplayMetadata>())\n}\n\nexport const sdJwtCredentialClaimLocalesFrom = async (\n args: SdJwtCredentialClaimLocalesFromArgs,\n): Promise<Map<string, Array<IBasicCredentialClaim>>> => {\n const { claimsMetadata } = args\n const localeClaims = new Map<string, Array<IBasicCredentialClaim>>()\n\n claimsMetadata.forEach((claim: SdJwtClaimMetadata): void => {\n claim.display?.forEach((display: SdJwtClaimDisplayMetadata): void => {\n const { lang = '', label } = display\n const key = claim.path.map((value: SdJwtClaimPath) => String(value)).join('.')\n if (!localeClaims.has(lang)) {\n localeClaims.set(lang, [])\n }\n localeClaims.get(lang)!.push({ key, name: label })\n })\n })\n\n return localeClaims\n}\n\nexport const sdJwtCredentialLocaleBrandingFrom = async (args: SdJwtCredentialLocaleBrandingFromArgs): Promise<IBasicCredentialLocaleBranding> => {\n const { credentialDisplay } = args\n\n return {\n ...(credentialDisplay.name && {\n alias: credentialDisplay.name,\n }),\n ...(credentialDisplay.lang && {\n locale: credentialDisplay.lang,\n }),\n ...(credentialDisplay.rendering?.simple?.logo && {\n logo: {\n ...(credentialDisplay.rendering.simple.logo.uri && {\n uri: credentialDisplay.rendering.simple.logo.uri,\n }),\n ...(credentialDisplay.rendering.simple.logo.alt_text && {\n alt: credentialDisplay.rendering.simple.logo.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.description && {\n description: credentialDisplay.description,\n }),\n ...(credentialDisplay.rendering?.simple?.text_color && {\n text: {\n color: credentialDisplay.rendering.simple.text_color,\n },\n }),\n ...(credentialDisplay.rendering?.simple?.background_color && {\n background: {\n color: credentialDisplay.rendering.simple.background_color,\n },\n }),\n }\n}\n\nexport const sdJwtCombineDisplayLocalesFrom = async (args: SdJwtCombineDisplayLocalesFromArgs): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplayLocales = new Map<string, SdJwtTypeDisplayMetadata>(), claimsMetadata = new Map<string, Array<IBasicCredentialClaim>>() } =\n args\n\n const locales: Array<string> = Array.from(new Set([...claimsMetadata.keys(), ...credentialDisplayLocales.keys()]))\n\n return Promise.all(\n locales.map(async (locale: string): Promise<IBasicCredentialLocaleBranding> => {\n const display = credentialDisplayLocales.get(locale)\n const claims = claimsMetadata.get(locale)\n\n return {\n ...(display && (await sdJwtCredentialLocaleBrandingFrom({ credentialDisplay: display }))),\n ...(locale.length > 0 && { locale }),\n claims,\n }\n }),\n )\n}\n\n// TODO since dynamicRegistrationClientMetadata can also be on a RP, we should start using this mapper in a more general way\nexport const issuerLocaleBrandingFrom = async (args: IssuerLocaleBrandingFromArgs): Promise<IBasicIssuerLocaleBranding> => {\n const { issuerDisplay, dynamicRegistrationClientMetadata } = args\n\n return {\n ...(dynamicRegistrationClientMetadata?.client_name && {\n alias: dynamicRegistrationClientMetadata.client_name,\n }),\n ...(issuerDisplay.name && {\n alias: issuerDisplay.name,\n }),\n ...(issuerDisplay.locale && {\n locale: issuerDisplay.locale,\n }),\n ...((issuerDisplay.logo || dynamicRegistrationClientMetadata?.logo_uri) && {\n logo: {\n ...(dynamicRegistrationClientMetadata?.logo_uri && {\n uri: dynamicRegistrationClientMetadata?.logo_uri,\n }),\n ...((issuerDisplay.logo?.url || <string>issuerDisplay.logo?.uri) && {\n uri: issuerDisplay.logo?.url ?? <string>issuerDisplay.logo?.uri,\n }),\n ...(issuerDisplay.logo?.alt_text && {\n alt: issuerDisplay.logo?.alt_text,\n }),\n },\n }),\n ...(issuerDisplay.description && {\n description: issuerDisplay.description,\n }),\n ...(issuerDisplay.text_color && {\n text: {\n color: issuerDisplay.text_color,\n },\n }),\n ...(dynamicRegistrationClientMetadata?.client_uri && {\n clientUri: dynamicRegistrationClientMetadata.client_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.tos_uri && {\n tosUri: dynamicRegistrationClientMetadata.tos_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.policy_uri && {\n policyUri: dynamicRegistrationClientMetadata.policy_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.contacts && {\n contacts: dynamicRegistrationClientMetadata.contacts,\n }),\n }\n}\n","import { Loggers, LogLevel, LogMethod } from '@sphereon/ssi-types'\nimport { OID4VCIMachineInterpreter, OID4VCIMachineState, OID4VCIMachineStates } from '../types/IOID4VCIHolder'\n\nconst logger = Loggers.DEFAULT.options('sphereon:oid4vci:holder', { defaultLogLevel: LogLevel.DEBUG, methods: [LogMethod.CONSOLE] }).get(\n 'sphereon:oid4vci:holder',\n)\n\nexport const OID4VCICallbackStateListener = (\n callbacks?: Map<OID4VCIMachineStates, (machine: OID4VCIMachineInterpreter, state: OID4VCIMachineState, opts?: any) => Promise<void>>,\n) => {\n return async (oid4vciMachine: OID4VCIMachineInterpreter, state: OID4VCIMachineState): Promise<void> => {\n if (state._event.type === 'internal') {\n logger.debug('oid4vciCallbackStateListener: 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(`VCI state listener state: ${JSON.stringify(state.value)}`)\n\n if (!callbacks || callbacks.size === 0) {\n logger.info(`VCI 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(`VCI state callback for state: ${JSON.stringify(state.value)}, will execute...`)\n await callback(oid4vciMachine, state)\n .then(() => logger.log(`state callback executed for state: ${JSON.stringify(state.value)}`))\n .catch((error) => {\n logger.error(\n `VCI 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 { CredentialOfferClient } from '@sphereon/oid4vci-client'\nimport { AuthorizationRequestOpts, AuthorizationServerClientOpts, AuthzFlowType, convertURIToJsonObject } from '@sphereon/oid4vci-common'\nimport { DefaultLinkPriorities, LinkHandlerAdapter } from '@sphereon/ssi-sdk.core'\nimport { IMachineStatePersistence, interpreterStartOrResume, SerializableState } from '@sphereon/ssi-sdk.xstate-machine-persistence'\nimport { IAgentContext } from '@veramo/core'\nimport { GetMachineArgs, IOID4VCIHolder, OID4VCIMachineEvents, OID4VCIMachineStateNavigationListener, WalletType } from '../types/IOID4VCIHolder'\nimport { FirstPartyMachineStateNavigationListener } from '../types/FirstPartyMachine'\n\n/**\n * This handler only handles credential offer links (either by value or by reference)\n */\nexport class OID4VCIHolderLinkHandler extends LinkHandlerAdapter {\n private readonly context: IAgentContext<IOID4VCIHolder & IMachineStatePersistence>\n private readonly stateNavigationListener?: OID4VCIMachineStateNavigationListener\n private readonly firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n private readonly noStateMachinePersistence: boolean\n private readonly walletType: WalletType\n private readonly authorizationRequestOpts?: AuthorizationRequestOpts\n private readonly clientOpts?: AuthorizationServerClientOpts\n private readonly trustAnchors?: Array<string>\n\n constructor(\n args: Pick<\n GetMachineArgs,\n 'stateNavigationListener' | 'authorizationRequestOpts' | 'clientOpts' | 'trustAnchors' | 'firstPartyStateNavigationListener' | 'walletType'\n > & {\n priority?: number | DefaultLinkPriorities\n protocols?: Array<string | RegExp>\n noStateMachinePersistence?: boolean\n context: IAgentContext<IOID4VCIHolder & IMachineStatePersistence>\n },\n ) {\n super({ ...args, id: 'OID4VCIHolder' })\n this.authorizationRequestOpts = args.authorizationRequestOpts\n this.clientOpts = args.clientOpts\n this.context = args.context\n this.walletType = args.walletType ?? 'NATURAL_PERSON'\n this.noStateMachinePersistence = args.noStateMachinePersistence === true\n this.stateNavigationListener = args.stateNavigationListener\n this.firstPartyStateNavigationListener = args.firstPartyStateNavigationListener\n this.trustAnchors = args.trustAnchors\n }\n\n async handle(\n url: string | URL,\n opts?: {\n machineState?: SerializableState\n authorizationRequestOpts?: AuthorizationRequestOpts\n createAuthorizationRequestURL?: boolean\n clientOpts?: AuthorizationServerClientOpts\n flowType?: AuthzFlowType\n },\n ): Promise<void> {\n const uri = new URL(url).toString()\n const offerData = convertURIToJsonObject(uri) as Record<string, unknown>\n const hasCode = 'code' in offerData && !!offerData.code && !('issuer' in offerData)\n const code = hasCode ? (offerData.code as string) : undefined\n const clientOpts = { ...this.clientOpts, ...opts?.clientOpts }\n const oid4vciMachine = await this.context.agent.oid4vciHolderGetMachineInterpreter({\n requestData: {\n // We know this can only be invoked with a credential offer, so we convert the URI to offer\n ...(!hasCode && { credentialOffer: await CredentialOfferClient.fromURI(uri) }),\n ...(hasCode && { code: code }),\n createAuthorizationRequestURL: opts?.createAuthorizationRequestURL,\n flowType: opts?.flowType,\n uri,\n },\n trustAnchors: this.trustAnchors,\n authorizationRequestOpts: { ...this.authorizationRequestOpts, ...opts?.authorizationRequestOpts },\n ...((clientOpts.clientId || clientOpts.clientAssertionType) && { clientOpts: clientOpts as AuthorizationServerClientOpts }),\n stateNavigationListener: this.stateNavigationListener,\n firstPartyStateNavigationListener: this.firstPartyStateNavigationListener,\n walletType: this.walletType,\n })\n\n const interpreter = oid4vciMachine.interpreter\n //FIXME we need a better way to check if the state persistence plugin is available in the agent\n if (!opts?.machineState && this.context.agent.availableMethods().includes('machineStatesFindActive')) {\n const stateType = hasCode ? 'existing' : 'new'\n await interpreterStartOrResume({\n stateType,\n interpreter,\n context: this.context,\n cleanupAllOtherInstances: true,\n cleanupOnFinalState: true,\n singletonCheck: true,\n noRegistration: this.noStateMachinePersistence,\n })\n } else {\n // @ts-ignore\n interpreter.start(opts?.machineState)\n }\n\n if (hasCode) {\n interpreter.send(OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE, { data: uri })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mDAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,gDAAkD;AAAA,MAClD,uDAAyD;AAAA,MACzD,8CAAgD;AAAA,MAChD,kDAAoD;AAAA,MACpD,kDAAoD;AAAA,MACpD,sDAAwD;AAAA,MACxD,mDAAqD;AAAA,MACrD,8CAAgD;AAAA,MAChD,kDAAoD;AAAA,MACpD,wCAA0C;AAAA,MAC1C,wDAA0D;AAAA,MAC1D,+DAAiE;AAAA,MACjE,uDAAyD;AAAA,MACz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UF,aAAa,CAAC,CAACA,UAAUG,QAAQ,EAAE,YAAYH;AACzE,UAAMG,OAAOD,UAAWF,UAAUG,OAAkBC;AACpD,UAAMd,aAAa;MAAE,GAAG,KAAKA;MAAY,GAAGM,MAAMN;IAAW;AAC7D,UAAMe,iBAAiB,MAAM,KAAKrB,QAAQsB,MAAMC,mCAAmC;MACjFC,aAAa;;QAEX,GAAI,CAACN,WAAW;UAAEO,iBAAiB,MAAMC,6CAAsBC,QAAQd,GAAAA;QAAK;QAC5E,GAAIK,WAAW;UAAEC;QAAW;QAC5BS,+BAA+BhB,MAAMgB;QACrCC,UAAUjB,MAAMiB;QAChBhB;MACF;MACAN,cAAc,KAAKA;MACnBF,0BAA0B;QAAE,GAAG,KAAKA;QAA0B,GAAGO,MAAMP;MAAyB;MAChG,IAAKC,WAAWwB,YAAYxB,WAAWyB,wBAAwB;QAAEzB;MAAwD;MACzHL,yBAAyB,KAAKA;MAC9BC,mCAAmC,KAAKA;MACxCE,YAAY,KAAKA;IACnB,CAAA;AAEA,UAAM4B,cAAcX,eAAeW;AAEnC,QAAI,CAACpB,MAAMqB,gBAAgB,KAAKjC,QAAQsB,MAAMY,iBAAgB,EAAGC,SAAS,yBAAA,GAA4B;AACpG,YAAMC,YAAYlB,UAAU,aAAa;AACzC,gBAAMmB,0CAAyB;QAC7BD;QACAJ;QACAhC,SAAS,KAAKA;QACdsC,0BAA0B;QAC1BC,qBAAqB;QACrBC,gBAAgB;QAChBC,gBAAgB,KAAKtC;MACvB,CAAA;IACF,OAAO;AAEL6B,kBAAYU,MAAM9B,MAAMqB,YAAAA;IAC1B;AAEA,QAAIf,SAAS;AACXc,kBAAYW,KAAKC,qBAAqBC,qCAAqC;QAAEC,MAAMjC;MAAI,CAAA;IACzF;EACF;AACF;","names":["module","module","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_utils","import_uuid","OID4VCIHolderEvent","SupportedLanguage","OID4VCIMachineStates","OID4VCIMachineAddContactStates","OID4VCIMachineVerifyPinStates","OID4VCIMachineEvents","OID4VCIMachineGuards","OID4VCIMachineServices","RequestType","IdentifierAliasEnum","Localization","translationGetters","SupportedLanguage","ENGLISH","require","DUTCH","translate","memoize","key","config","Object","keys","i18n","translations","length","locale","findSupportedLanguage","t","JSON","stringify","language","values","undefined","getLocale","FirstPartyMachineStateTypes","FirstPartyMachineServices","FirstPartyMachineEvents","oid4vciHasNoContactGuard","_ctx","_event","contact","undefined","oid4vciHasContactGuard","oid4vciContactHasLowTrustGuard","trustedAnchors","length","oid4vciCredentialsToSelectRequiredGuard","credentialToSelectFrom","oid4vciRequirePinGuard","requestData","credentialOffer","userPinRequired","oid4vciHasNoContactIdentityGuard","credentialsToAccept","toAcceptId","correlationId","match","URL","hostname","identities","some","identity","identifier","oid4vciVerificationCodeGuard","verificationCode","oid4vciCreateContactGuard","contactAlias","hasContactConsent","oid4vciHasSelectedCredentialsGuard","selectedCredentials","oid4vciIsOIDFOriginGuard","trustAnchors","oid4vciNoAuthorizationGuard","ctx","oid4vciHasAuthorizationResponse","oid4vciRequireAuthorizationGuard","openID4VCIClientState","Error","authorizationURL","authorizationRequestOpts","authorizationCodeResponse","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","PRE_AUTHORIZED_CODE_FLOW","endpointMetadata","credentialIssuerMetadata","authorization_endpoint","oid4vciIsFirstPartyApplication","serverMetadata","authorization_challenge_endpoint","createOID4VCIMachine","opts","initialContext","accessTokenOpts","walletType","issuanceOpt","didMethodPreferences","locale","credentialsSupported","createMachine","id","machineName","predictableActionArguments","initial","OID4VCIMachineStates","start","schema","events","guards","services","context","states","invoke","src","OID4VCIMachineServices","onDone","target","createCredentialsToSelectFrom","actions","assign","credentialBranding","data","oid4vciClientState","onError","handleError","error","title","translate","message","stack","getContact","getIssuerBranding","getFederationTrust","cond","OID4VCIMachineGuards","isOIDFOriginGuard","issuerBranding","transitionFromSetup","always","addContact","hasNoContactGuard","reviewContact","contactHasLowTrustGuard","selectCredentials","credentialsToSelectRequiredGuard","startFirstPartApplicationFlow","isFirstPartyApplication","prepareAuthorizationRequest","requireAuthorizationGuard","verifyPin","requirePinGuard","getCredentials","on","OID4VCIMachineEvents","SET_AUTHORIZATION_CODE_URL","authorizationCodeURL","OID4VCIMachineAddContactStates","idle","SET_CONTACT_CONSENT","SET_CONTACT_ALIAS","CREATE_CONTACT","next","createContactGuard","DECLINE","declined","PREVIOUS","aborted","storeIssuerBranding","hasContactGuard","NEXT","transitionFromContactSetup","FirstPartyMachineStateTypes","toAuthorizationResponsePayload","SET_SELECTED_CREDENTIALS","transitionFromSelectingCredentials","hasSelectedCredentialsGuard","initiateAuthorizationRequest","INVOKED_AUTHORIZATION_CODE_REQUEST","waitForAuthorizationResponse","PROVIDE_AUTHORIZATION_CODE_RESPONSE","hasAuthorizationResponse","OID4VCIMachineVerifyPinStates","SET_VERIFICATION_CODE","verificationCodeGuard","verifyCredentials","exit","assertValidCredentials","transitionFromWalletInput","addContactIdentity","hasNoContactIdentityGuard","reviewCredentials","addIssuerBrandingAfterIdentity","push","storeCredentialBranding","storeCredentials","done","type","OID4VCIMachine","newInstance","interpreter","interpret","withConfig","subscription","onTransition","requireCustomNavigationHook","stateNavigationListener","snapshot","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk_ext","import_xstate","import_oid4vci_common","sendAuthorizationChallengeRequest","args","openID4VCIClientState","authSession","presentationDuringIssuanceSession","oid4vciClient","OpenID4VCIClient","fromState","state","acquireAuthorizationChallengeCode","clientId","uuidv4","credentialOffer","preAuthorizedCode","issuerState","createConfig","context","presentationUri","Promise","reject","Error","agent","siopCreateConfig","url","getSiopRequest","didAuthConfig","undefined","siopGetSiopRequest","sendAuthorizationResponse","authorizationRequestData","selectedCredentials","responseData","siopSendResponse","isFirstParty","body","presentation_during_issuance_session","firstPartyMachineStates","FirstPartyMachineStateTypes","sendAuthorizationChallengeRequest","id","invoke","src","FirstPartyMachineServices","onDone","target","done","actions","assign","authorizationCodeResponse","_ctx","_event","data","onError","createConfig","cond","error","AuthorizationChallengeError","insufficient_authorization","authSession","auth_session","presentationUri","presentation","title","translate","message","stack","getSiopRequest","didAuthConfig","selectCredentials","authorizationRequestData","on","FirstPartyMachineEvents","SET_SELECTED_CREDENTIALS","selectedCredentials","NEXT","sendAuthorizationResponse","DECLINE","declined","PREVIOUS","aborted","presentationDuringIssuanceSession","type","createFirstPartyActivationMachine","opts","initialContext","openID4VCIClientState","contact","createMachine","machineId","predictableActionArguments","initial","context","states","schema","events","services","FirstPartyMachine","_instance","hasInstance","undefined","instance","Error","clearInstance","stop","stopInstance","newInstance","agentContext","args","newInst","interpret","withConfig","guards","subscription","onTransition","requireCustomNavigationHook","snapshot","stateNavigationListener","getInstance","requireExisting","oid4vciGetCredentialBrandingFrom","args","credentialDisplay","issuerCredentialSubject","oid4vciCombineDisplayLocalesFrom","issuerCredentialSubjectLocales","oid4vciIssuerCredentialSubjectLocalesFrom","credentialDisplayLocales","oid4vciCredentialDisplayLocalesFrom","reduce","localeDisplays","display","localeKey","locale","set","Map","localeClaims","processClaimObject","claim","parentKey","Object","entries","forEach","key","value","Array","isArray","name","has","get","push","oid4vciCredentialLocaleBrandingFrom","alias","logo","url","uri","alt_text","alt","description","text_color","text","color","background_image","background_color","background","image","locales","from","Set","keys","Promise","all","map","claims","length","sdJwtGetCredentialBrandingFrom","claimsMetadata","sdJwtCombineDisplayLocalesFrom","sdJwtCredentialClaimLocalesFrom","sdJwtCredentialDisplayLocalesFrom","lang","label","path","String","join","sdJwtCredentialLocaleBrandingFrom","rendering","simple","issuerLocaleBrandingFrom","issuerDisplay","dynamicRegistrationClientMetadata","client_name","logo_uri","client_uri","clientUri","tos_uri","tosUri","policy_uri","policyUri","contacts","getCredentialBranding","args","credentialsSupported","context","credentialBranding","Promise","all","Object","entries","map","configId","credentialsConfigSupported","sdJwtTypeMetadata","format","vct","startsWith","agent","fetchSdJwtTypeMetadataFromVctUrl","mappedLocaleBranding","sdJwtGetCredentialBrandingFrom","credentialDisplay","display","claimsMetadata","claims","oid4vciGetCredentialBrandingFrom","issuerCredentialSubject","undefined","credentialSubject","localeBranding","ibCredentialLocaleBrandingFrom","defaultCredentialType","configSupportedTypes","getTypesFromCredentialSupported","credentialTypes","length","asArray","filteredCredentialTypes","filter","type","getBasicIssuerLocaleBranding","dynamicRegistrationClientMetadata","issuerDisplay","branding","issuerLocaleBrandingFrom","ibIssuerLocaleBrandingFrom","getCredentialConfigsBasedOnFormatPref","vcFormatPreferences","credentials","prefConfigs","forEach","key","config","result","pref","toLowerCase","includes","selectCredentialLocaleBranding","locale","find","verifyCredentialToAccept","mappedCredential","hasher","onVerifyEBSICredentialIssuer","schemaValidation","credential","extractCredentialFromResponse","credentialToAccept","credentialResponse","wrappedVC","CredentialMapper","toWrappedVerifiableCredential","defaultHasher","decoded","iss","vc","issuer","existingInstanceId","cvVerifySchema","validationPolicy","JSON","stringify","source","error","subResults","wrappedVc","e","message","verificationResult","cvVerifyCredential","fetchRemoteContexts","policies","credentialStatus","expirationDate","issuanceDate","reject","Error","translate","mapCredentialToAccept","verifiableCredential","wrappedVerifiableCredential","uniformVerifiableCredential","isSdJwtDecodedCredential","sdJwtDecodedCredentialToUniformCredential","isSdJwtEncoded","asyncHasher","data","algorithm","resolve","decodedSdJwt","decodeSdJwtVcAsync","isMsoMdocDecodedCredential","mdocDecodedCredentialToUniformCredential","correlationId","decodedPayload","id","types","rawVerifiableCredential","credential_subject_issuance","Array","isArray","getIdentifierOpts","issuanceOpt","identifier","identifierArg","isManagedIdentifierResult","supportedPreferredDidMethod","supportedBindingMethods","keyType","kms","keyManagerGetDefaultKeyManagementSystem","isIIdentifier","identifierManagedGet","method","managedIdentifierToJwk","join","agentContext","created","getOrCreatePrimaryIdentifier","createOpts","options","use","KeyUse","Signature","codecName","identifierManagedGetByDid","offlineWhenNoDIDRegistered","did","emit","OID4VCIHolderEvent","IDENTIFIER_CREATED","keyManagerCreate","meta","keyAlias","Date","now","kmsKeyRef","kid","getCredentialConfigsSupportedMerged","getCredentialConfigsSupported","supported","configurationIds","getCredentialConfigsSupportedBySingleTypeOrId","configurationId","configs","keys","client","createIdFromTypes","getTypesFromObject","allSupported","getCredentialsSupported","fromEntries","credentialOffer","offerSupported","getSupportedCredentials","version","issuerMetadata","endpointMetadata","credentialIssuerMetadata","credentialConfigsSupported","LOG","warning","getIssuer","credential_offer","credentialsToOffer","credential_configuration_ids","getIssuanceOpts","didMethodPreferences","jwtCryptographicSuitePreferences","jsonldCryptographicSuitePreferences","forceIssuanceOpt","values","credentialSupported","cryptographicSuite","getIssuanceCryptoSuite","didMethod","methods","getIssuanceMethod","console","log","push","isEBSI","keyTypeFromCryptographicSuite","crv","clientId","isManagedIdentifierDidResult","opts","cryptographic_binding_methods_supported","didMethods","warn","SupportedDidMethodEnum","DID_KEY","signing_algs_supported","proof_types_supported","jwt","proof_signing_alg_values_supported","ldp_vp","cwt","credential_signing_alg_values_supported","supportedPreferences","suite","JoseSignatureAlgorithm","ES256","fallback","startFirstPartApplicationMachine","openID4VCIClientState","stateNavigationListener","contact","firstPartyMachineInstance","FirstPartyMachine","newInstance","onTransition","state","matches","FirstPartyMachineStateTypes","done","authorizationCodeResponse","aborted","declined","start","oid4vciHolderContextMethods","logger","Loggers","DEFAULT","get","signCallback","identifier","context","nonce","jwt","kid","noIssPayloadUpdate","resolution","agent","identifierManagedGet","jwk","header","method","undefined","issuer","payload","iss","Promise","reject","Error","JSON","stringify","console","log","jwtCreateJwsCompactSignature","protectedHeader","OID4VCIHolder","hasher","eventTypes","OID4VCIHolderEvent","CONTACT_IDENTITY_CREATED","CREDENTIAL_STORED","IDENTIFIER_CREATED","methods","oid4vciHolderStart","bind","oid4vciHolderGetIssuerMetadata","oid4vciHolderGetMachineInterpreter","oid4vciHolderPrepareAuthorizationRequest","oid4vciHolderCreateCredentialsToSelectFrom","oid4vciHolderGetContact","oid4vciHolderGetCredentials","oid4vciHolderGetCredential","oid4vciHolderAddContactIdentity","oid4vciHolderAssertValidCredentials","oid4vciHolderStoreCredentialBranding","oid4vciHolderStoreCredentials","oid4vciHolderSendNotification","oid4vciHolderGetIssuerBranding","oid4vciHolderStoreIssuerBranding","vcFormatPreferences","jsonldCryptographicSuitePreferences","didMethodPreferences","SupportedDidMethodEnum","DID_JWK","DID_KEY","DID_OYD","DID_EBSI","DID_ION","jwtCryptographicSuitePreferences","JoseSignatureAlgorithm","ES256","ES256K","EdDSA","DEFAULT_MOBILE_REDIRECT_URI","DefaultURISchemes","CREDENTIAL_OFFER","defaultAuthorizationRequestOpts","redirectUri","onContactIdentityCreated","onCredentialStored","onIdentifierCreated","onVerifyEBSICredentialIssuer","options","defaultAuthorizationRequestOptions","defaultHasher","undefined","length","onEvent","event","context","type","data","Promise","reject","Error","opts","authorizationRequestOpts","services","OID4VCIMachineServices","start","args","startFirstPartApplicationFlow","startFirstPartApplicationMachine","stateNavigationListener","firstPartyStateNavigationListener","createCredentialsToSelectFrom","prepareAuthorizationRequest","getContact","getCredentials","accessTokenOpts","addContactIdentity","getIssuerBranding","storeIssuerBranding","assertValidCredentials","storeCredentialBranding","storeCredentials","sendNotification","getFederationTrust","oid4vciMachineInstanceArgs","interpreter","OID4VCIMachine","newInstance","requestData","uri","authorizationDetails","asArray","startsWith","clientId","formats","authFormats","map","detail","format","filter","Array","from","Set","oid4vciClient","offer","existingClientState","OpenID4VCIClientV1_0_15","fromState","state","credentialOffer","RequestType","OPENID_INITIATE_ISSUANCE","OPENID_CREDENTIAL_OFFER","match","CredentialOfferClient","fromURI","logger","warning","log","fromCredentialIssuer","credentialIssuer","authorizationRequest","createAuthorizationRequestURL","configurationIds","original_credential_offer","credential_configuration_ids","authReqOpts","credential_configuration_id","id","credentialsSupported","getCredentialConfigsSupportedMerged","client","serverMetadata","retrieveServerMetadata","credentialBranding","getCredentialBranding","oid4vciClientState","JSON","parse","exportState","openID4VCIClientState","contact","identities","identity","connectionConfig","connection","config","find","authorizationCodeURL","createAuthorizationRequestUrl","locale","selectedCredentials","info","Object","keys","join","credentialSelection","all","entries","credentialConfigSupported","credentialTypes","getTypesFromObject","localeBranding","_brandings","supported","credentialAlias","selectCredentialLocaleBranding","alias","uuidv4","credentialId","isSelected","sel","push","stringify","names","credentialIssuerMetadata","display","name","size","correlationId","URL","issuer","hostname","identifier","legalName","displayName","parties","agent","cmGetContacts","party","verificationCode","issuanceOpt","walletType","debug","issuanceOpts","getIssuanceOpts","selectDidMethodPreferences","forceIssuanceOpt","pin","allCredentials","supportedDidMethodEnums","isArray","DID_WEB","getIdentifierOpts","alg","signatureAlgorithmFromKey","key","jwk","isManagedIdentifierJwkResult","callbacks","signCallback","isManagedIdentifierDidResult","did","asOpts","kid","clientOpts","isEBSI","includes","split","signCallbacks","acquireAccessToken","authorizationResponse","authorizationCodeResponse","additionalRequestParams","types","credentialConfigurationId","credentialDefinition","getCredentialDefinition","credentialResponse","acquireCredentials","proofCallbacks","deferredCredentialAwait","jti","credential","mapCredentialToAccept","credentialToAccept","error","credentialsToAccept","identifierType","CorrelationIdentifierType","DID","toLowerCase","origin","IdentityOrigin","EXTERNAL","roles","CredentialRole","ISSUER","ConnectionType","OPENID_CONNECT","clientSecret","scopes","redirectUrl","dangerouslyAllowInsecureHttpRequests","clientAuthMethod","emit","contactId","cmAddIdentity","issuerCorrelationId","branding","ibGetIssuerBranding","getBasicIssuerLocaleBranding","dynamicRegistrationClientMetadata","issuerBranding","ibAddIssuerBranding","verifyCredentialToAccept","mappedCredential","schemaValidation","counter","configId","ac","credAccept","cred","ibAddCredentialBranding","vcHash","computeEntryHash","rawVerifiableCredential","b","trimmed","input","trim","mappedCredentialToAccept","kmsKeyRef","method","persist","verifiableCredential","uniformVerifiableCredential","notificationId","notification_id","subjectIssuance","credential_subject_issuance","notificationEndpoint","notification_endpoint","holderCredential","notification_events_supported","issuerVC","extractCredentialFromResponse","wrappedIssuerVC","CredentialMapper","toWrappedVerifiableCredential","console","isWrappedSdJwtVerifiableCredential","decoded","sub","isWrappedW3CVerifiableCredential","credentialSubject","idFromW3cCredentialSubject","isWrappedMdocCredential","parseDid","accessTokenResponse","decodedJwt","decodeJWT","access_token","payload","resolution","identifierManagedGet","holderCredentialToSign","proofFormat","iss","vc","proof","issuanceDate","iat","issuedVC","createVerifiableCredential","fetchRemoteContexts","save","storedCredentialToOriginalFormat","notificationRequest","stored","persistCredential","issuerCorrelationIdFromIssuerType","subjectCorrelationType","subjectCorrelationId","determineSubjectCorrelation","persistedCredential","crsAddCredential","rawDocument","ensureRawDocument","identifierMethod","credentialRole","HOLDER","issuerCorrelationType","CredentialCorrelationType","hash","OpenID4VCIClient","trustAnchors","url","params","URLSearchParams","search","openidFederation","get","entityIdentifier","warn","toString","result","identifierExternalResolveByOIDFEntityId","trustedAnchors","errorOnNotFound","MetadataClient","retrieveAllMetadata","isManagedIdentifierResult","isManagedIdentifierDidOpts","isManagedIdentifierKidResult","KID","isManagedIdentifierX5cResult","X509_SAN","x5c","isManagedIdentifierX5cOpts","credential_definition","import_ssi_types","logger","Loggers","DEFAULT","options","defaultLogLevel","LogLevel","DEBUG","methods","LogMethod","CONSOLE","get","OID4VCICallbackStateListener","callbacks","oid4vciMachine","state","_event","type","debug","info","JSON","stringify","value","size","stateKey","callback","matches","log","then","catch","error","message","event","stack","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk","OID4VCIHolderLinkHandler","LinkHandlerAdapter","context","stateNavigationListener","firstPartyStateNavigationListener","noStateMachinePersistence","walletType","authorizationRequestOpts","clientOpts","trustAnchors","args","id","handle","url","opts","uri","URL","toString","offerData","convertURIToJsonObject","hasCode","code","undefined","oid4vciMachine","agent","oid4vciHolderGetMachineInterpreter","requestData","credentialOffer","CredentialOfferClient","fromURI","createAuthorizationRequestURL","flowType","clientId","clientAssertionType","interpreter","machineState","availableMethods","includes","stateType","interpreterStartOrResume","cleanupAllOtherInstances","cleanupOnFinalState","singletonCheck","noRegistration","start","send","OID4VCIMachineEvents","PROVIDE_AUTHORIZATION_CODE_RESPONSE","data"]}
1
+ {"version":3,"sources":["../src/localization/translations/en.json","../src/localization/translations/nl.json","../src/index.ts","../src/agent/OID4VCIHolder.ts","../src/machines/oid4vciMachine.ts","../src/localization/Localization.ts","../src/types/IOID4VCIHolder.ts","../src/types/FirstPartyMachine.ts","../src/services/OID4VCIHolderService.ts","../src/machines/firstPartyMachine.ts","../src/services/FirstPartyMachineServices.ts","../src/mappers/OIDC4VCIBrandingMapper.ts","../src/listeners/headlessStateNavListener.ts","../src/link-handler/index.ts"],"sourcesContent":["{\n \"oid4vci_machine_verify_credentials_error_title\": \"Verify credentials\",\n \"oid4vci_machine_store_credential_branding_error_title\": \"Store credential branding\",\n \"oid4vci_machine_store_credential_error_title\": \"Store credential\",\n \"oid4vci_machine_add_contact_identity_error_title\": \"Add contact identity\",\n \"oid4vci_machine_retrieve_credentials_error_title\": \"Retrieve credentials\",\n \"oid4vci_machine_retrieve_issuer_branding_error_title\": \"Retrieve issuer branding\",\n \"oid4vci_machine_store_issuer_branding_error_title\": \"Store issuer branding\",\n \"oid4vci_machine_retrieve_contact_error_title\": \"Retrieve contact\",\n \"oid4vci_machine_credential_selection_error_title\": \"Credential selection\",\n \"oid4vci_machine_initiation_error_title\": \"Initiate OID4VCI provider\",\n \"oid4vci_machine_credential_verification_failed_message\": \"The credential verification resulted in an error.\",\n \"oid4vci_machine_credential_verification_schema_failed_message\": \"The credential schema verification resulted in an error.\",\n \"oid4vci_machine_retrieve_federation_trust_error_title\": \"Retrieve federation trust\",\n \"oid4vci_machine_first_party_error_title\": \"First party flow\",\n \"oid4vci_machine_send_authorization_challenge_request_error_title\": \"Sending authorization challenge request\",\n \"oid4vci_machine_create_config_error_title\": \"Creating siopV2 config\",\n \"oid4vci_machine_get_request_error_title\": \"Getting siopV2 request\"\n}\n","{\n \"oid4vci_machine_verify_credentials_error_title\": \"Verifiëren credential\",\n \"oid4vci_machine_store_credential_branding_error_title\": \"Opslaan credential branding\",\n \"oid4vci_machine_store_credential_error_title\": \"Opslaan credential\",\n \"oid4vci_machine_add_contact_identity_error_title\": \"Toevoegen identiteit contact\",\n \"oid4vci_machine_retrieve_credentials_error_title\": \"Ophalen credential\",\n \"oid4vci_machine_retrieve_issuer_branding_error_title\": \"Ophalen issuer branding\",\n \"oid4vci_machine_store_issuer_branding_error_title\": \"Opslaan issuer branding\",\n \"oid4vci_machine_retrieve_contact_error_title\": \"Ophalen contact\",\n \"oid4vci_machine_credential_selection_error_title\": \"Credential selectie\",\n \"oid4vci_machine_initiation_error_title\": \"Initiëren OID4VCI provider\",\n \"oid4vci_machine_credential_verification_failed_message\": \"Verificatie van de credential leidde tot een fout.\",\n \"oid4vci_machine_retrieve_federation_trust_error_title\": \"Ophalen federatievertrouwen\",\n \"oid4vci_machine_first_party_error_title\": \"Eerste partijstroom\",\n \"oid4vci_machine_send_authorization_challenge_request_error_title\": \"Versturen autorisatie-uitdaging aanvraag\",\n \"oid4vci_machine_create_config_error_title\": \"SiopV2-configuratie aanmaken\",\n \"oid4vci_machine_get_request_error_title\": \"SiopV2-verzoek ophalen\"\n}\n","/**\n * @public\n */\n\nexport { OID4VCIHolder, oid4vciHolderContextMethods, signCallback } from './agent/OID4VCIHolder'\nexport * from './mappers/OIDC4VCIBrandingMapper'\nexport * from './services/OID4VCIHolderService'\nexport * from './services/FirstPartyMachineServices'\nexport * from './types/IOID4VCIHolder'\nexport * from './types/FirstPartyMachine'\nexport * from './listeners/headlessStateNavListener'\nexport * from './link-handler'\n","import { CredentialOfferClient, MetadataClient, OpenID4VCIClient, OpenID4VCIClientV1_0_15 } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationDetailsV1_0_15,\n AuthorizationRequestOpts,\n AuthorizationServerClientOpts,\n AuthorizationServerOpts,\n CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15,\n CredentialOfferRequestWithBaseUrl,\n DefaultURISchemes,\n EndpointMetadataResult,\n getTypesFromObject,\n Jwt,\n NotificationRequest,\n ProofOfPossessionCallbacks,\n} from '@sphereon/oid4vci-common'\nimport { SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n IIdentifierResolution,\n isManagedIdentifierDidOpts,\n isManagedIdentifierDidResult,\n isManagedIdentifierJwkResult,\n isManagedIdentifierKidResult,\n isManagedIdentifierResult,\n isManagedIdentifierX5cOpts,\n isManagedIdentifierX5cResult,\n ManagedIdentifierOptsOrResult,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService, JwsHeader } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { signatureAlgorithmFromKey } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { defaultHasher } from '@sphereon/ssi-sdk.core'\nimport {\n ConnectionType,\n CorrelationIdentifierType,\n CredentialCorrelationType,\n ensureRawDocument,\n FindPartyArgs,\n IBasicCredentialLocaleBranding,\n IBasicIssuerLocaleBranding,\n Identity,\n IdentityOrigin,\n IIssuerLocaleBranding,\n NonPersistedIdentity,\n Party,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport {\n CredentialMapper,\n type CredentialProofFormat,\n CredentialRole,\n HasherSync,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n JwtDecodedVerifiableCredential,\n Loggers,\n parseDid,\n SdJwtDecodedVerifiableCredentialPayload,\n WrappedW3CVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport {\n CredentialPayload,\n IAgentContext,\n IAgentPlugin,\n IDIDManager,\n IKeyManager,\n IResolver,\n VerifiableCredential,\n W3CVerifiableCredential,\n} from '@veramo/core'\nimport { asArray, computeEntryHash } from '@veramo/utils'\nimport fetch from 'cross-fetch'\nimport { decodeJWT } from 'did-jwt'\nimport { v4 as uuidv4 } from 'uuid'\nimport { OID4VCIMachine } from '../machines/oid4vciMachine'\nimport {\n extractCredentialFromResponse,\n getBasicIssuerLocaleBranding,\n getCredentialBranding,\n getCredentialConfigsSupportedMerged,\n getIdentifierOpts,\n getIssuanceOpts,\n mapCredentialToAccept,\n selectCredentialLocaleBranding,\n startFirstPartApplicationMachine,\n verifyCredentialToAccept,\n} from '../services/OID4VCIHolderService'\nimport {\n AddContactIdentityArgs,\n AssertValidCredentialsArgs,\n Attribute,\n CreateCredentialsToSelectFromArgs,\n CredentialToAccept,\n CredentialToSelectFromResult,\n GetContactArgs,\n GetCredentialArgs,\n GetCredentialsArgs,\n GetFederationTrustArgs,\n GetIssuerBrandingArgs,\n GetIssuerMetadataArgs,\n IOID4VCIHolder,\n IssuanceOpts,\n MappedCredentialToAccept,\n OID4VCIHolderEvent,\n OID4VCIHolderOptions,\n OID4VCIMachine as OID4VCIMachineId,\n OID4VCIMachineInstanceOpts,\n OID4VCIMachineServiceDefinitions,\n OID4VCIMachineServices,\n OnContactIdentityCreatedArgs,\n OnCredentialStoredArgs,\n OnIdentifierCreatedArgs,\n PrepareAuthorizationRequestArgs,\n PrepareAuthorizationResult,\n PrepareStartArgs,\n RequestType,\n RequiredContext,\n SendNotificationArgs,\n StartFirstPartApplicationMachine,\n StartResult,\n StoreCredentialBrandingArgs,\n StoreCredentialsArgs,\n StoreIssuerBrandingArgs,\n VerificationResult,\n VerifyEBSICredentialIssuerArgs,\n VerifyEBSICredentialIssuerResult,\n WalletType,\n} from '../types/IOID4VCIHolder'\n\n/**\n * {@inheritDoc IOID4VCIHolder}\n */\n\n// Exposing the methods here for any REST implementation\nexport const oid4vciHolderContextMethods: Array<string> = [\n 'cmGetContacts',\n 'cmGetContact',\n 'cmAddContact',\n 'cmAddIdentity',\n 'ibCredentialLocaleBrandingFrom',\n 'ibAddCredentialBranding',\n 'dataStoreSaveVerifiableCredential',\n 'didManagerFind',\n 'didManagerGet',\n 'keyManagerSign',\n 'verifyCredential',\n]\n\nconst logger = Loggers.DEFAULT.get('sphereon:oid4vci:holder')\n\nexport function signCallback(\n identifier: ManagedIdentifierOptsOrResult,\n context: IAgentContext<IKeyManager & IDIDManager & IResolver & IIdentifierResolution & IJwtService>,\n nonce?: string,\n) {\n return async (jwt: Jwt, kid?: string, noIssPayloadUpdate?: boolean) => {\n let resolution = await context.agent.identifierManagedGet(identifier)\n const jwk = jwt.header.jwk ?? (resolution.method === 'jwk' ? resolution.jwk : undefined)\n if (!resolution.issuer && !jwt.payload.iss) {\n return Promise.reject(Error(`No issuer could be determined from the JWT ${JSON.stringify(jwt)} or identifier resolution`))\n }\n const header = jwt.header as JwsHeader\n const payload = jwt.payload\n if (nonce) {\n payload.nonce = nonce\n }\n if (jwk && header.kid) {\n console.log(\n `Deleting kid, as we are using a jwk and the oid4vci spec does not allow both to be present (which is not the case in the JOSE spec)`,\n )\n delete header.kid // The OID4VCI spec does not allow a JWK with kid present although the JWS spec does\n }\n return (\n await context.agent.jwtCreateJwsCompactSignature({\n issuer: { ...resolution, noIssPayloadUpdate: noIssPayloadUpdate ?? false },\n protectedHeader: header,\n payload,\n })\n ).jwt\n }\n}\n\nexport async function verifyEBSICredentialIssuer(args: VerifyEBSICredentialIssuerArgs): Promise<VerifyEBSICredentialIssuerResult> {\n const { wrappedVc, issuerType = ['TI'] } = args\n\n const issuer =\n wrappedVc.decoded?.iss ??\n (typeof wrappedVc.decoded?.vc?.issuer === 'string' ? wrappedVc.decoded?.vc?.issuer : wrappedVc.decoded?.vc?.issuer?.existingInstanceId)\n\n if (!issuer) {\n throw Error('The issuer of the VC is required to be present')\n }\n\n const url = `https://api-conformance.ebsi.eu/trusted-issuers-registry/v4/issuers/${issuer}`\n const response = await fetch(url)\n if (response.status !== 200) {\n throw Error('The issuer of the VC cannot be trusted')\n }\n\n const payload = (await response.json()) as VerifyEBSICredentialIssuerResult\n\n if (!payload.attributes.some((a: Attribute) => issuerType.includes(a.issuerType))) {\n throw Error(`The issuer type is required to be one of: ${issuerType.join(', ')}`)\n }\n\n return payload\n}\n\nexport class OID4VCIHolder implements IAgentPlugin {\n private readonly hasher?: HasherSync\n readonly eventTypes: Array<OID4VCIHolderEvent> = [\n OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED,\n OID4VCIHolderEvent.CREDENTIAL_STORED,\n OID4VCIHolderEvent.IDENTIFIER_CREATED,\n ]\n\n readonly methods: IOID4VCIHolder = {\n oid4vciHolderStart: this.oid4vciHolderStart.bind(this),\n oid4vciHolderGetIssuerMetadata: this.oid4vciHolderGetIssuerMetadata.bind(this),\n oid4vciHolderGetMachineInterpreter: this.oid4vciHolderGetMachineInterpreter.bind(this),\n oid4vciHolderPrepareAuthorizationRequest: this.oid4vciHolderPrepareAuthorizationRequest.bind(this),\n oid4vciHolderCreateCredentialsToSelectFrom: this.oid4vciHolderCreateCredentialsToSelectFrom.bind(this),\n oid4vciHolderGetContact: this.oid4vciHolderGetContact.bind(this),\n oid4vciHolderGetCredentials: this.oid4vciHolderGetCredentials.bind(this),\n oid4vciHolderGetCredential: this.oid4vciHolderGetCredential.bind(this),\n oid4vciHolderAddContactIdentity: this.oid4vciHolderAddContactIdentity.bind(this),\n oid4vciHolderAssertValidCredentials: this.oid4vciHolderAssertValidCredentials.bind(this),\n oid4vciHolderStoreCredentialBranding: this.oid4vciHolderStoreCredentialBranding.bind(this),\n oid4vciHolderStoreCredentials: this.oid4vciHolderStoreCredentials.bind(this),\n oid4vciHolderSendNotification: this.oid4vciHolderSendNotification.bind(this),\n oid4vciHolderGetIssuerBranding: this.oid4vciHolderGetIssuerBranding.bind(this),\n oid4vciHolderStoreIssuerBranding: this.oid4vciHolderStoreIssuerBranding.bind(this),\n }\n\n private readonly vcFormatPreferences: Array<string> = ['dc+sd-jwt', 'vc+sd-jwt', 'mso_mdoc', 'jwt_vc_json', 'jwt_vc', 'ldp_vc'] // TODO see SSISDK-52 concerning vc+sd-jwt\n private readonly jsonldCryptographicSuitePreferences: Array<string> = [\n 'Ed25519Signature2018',\n 'EcdsaSecp256k1Signature2019',\n 'Ed25519Signature2020',\n 'JsonWebSignature2020',\n // \"JcsEd25519Signature2020\"\n ]\n private readonly didMethodPreferences: Array<SupportedDidMethodEnum> = [\n SupportedDidMethodEnum.DID_JWK, // FIXME prefer JWK until we devise a method to detect when to use EBSI/jcs for did:key and when not\n SupportedDidMethodEnum.DID_KEY,\n SupportedDidMethodEnum.DID_OYD,\n SupportedDidMethodEnum.DID_EBSI,\n SupportedDidMethodEnum.DID_ION,\n ]\n private readonly jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString> = [\n JoseSignatureAlgorithm.ES256,\n JoseSignatureAlgorithm.ES256K,\n JoseSignatureAlgorithm.EdDSA,\n ]\n private static readonly DEFAULT_MOBILE_REDIRECT_URI = `${DefaultURISchemes.CREDENTIAL_OFFER}://`\n private readonly defaultAuthorizationRequestOpts: AuthorizationRequestOpts = { redirectUri: OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI }\n private readonly onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n private readonly onCredentialStored?: (args: OnCredentialStoredArgs) => Promise<void>\n private readonly onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n private readonly onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n\n constructor(options?: OID4VCIHolderOptions) {\n const {\n onContactIdentityCreated,\n onCredentialStored,\n onIdentifierCreated,\n onVerifyEBSICredentialIssuer,\n vcFormatPreferences,\n jsonldCryptographicSuitePreferences,\n didMethodPreferences,\n jwtCryptographicSuitePreferences,\n defaultAuthorizationRequestOptions,\n hasher = defaultHasher,\n } = { ...options }\n\n this.hasher = hasher\n if (vcFormatPreferences !== undefined && vcFormatPreferences.length > 0) {\n this.vcFormatPreferences = vcFormatPreferences\n }\n if (jsonldCryptographicSuitePreferences !== undefined && jsonldCryptographicSuitePreferences.length > 0) {\n this.jsonldCryptographicSuitePreferences = jsonldCryptographicSuitePreferences\n }\n if (didMethodPreferences !== undefined && didMethodPreferences.length > 0) {\n this.didMethodPreferences = didMethodPreferences\n }\n if (jwtCryptographicSuitePreferences !== undefined && jwtCryptographicSuitePreferences.length > 0) {\n this.jwtCryptographicSuitePreferences = jwtCryptographicSuitePreferences\n }\n if (defaultAuthorizationRequestOptions) {\n this.defaultAuthorizationRequestOpts = defaultAuthorizationRequestOptions\n }\n this.onContactIdentityCreated = onContactIdentityCreated\n this.onCredentialStored = onCredentialStored\n this.onIdentifierCreated = onIdentifierCreated\n this.onVerifyEBSICredentialIssuer = onVerifyEBSICredentialIssuer\n }\n\n public async onEvent(event: any, context: RequiredContext): Promise<void> {\n switch (event.type) {\n case OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED:\n this.onContactIdentityCreated?.(event.data)\n break\n case OID4VCIHolderEvent.CREDENTIAL_STORED:\n this.onCredentialStored?.(event.data)\n break\n case OID4VCIHolderEvent.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 /**\n * FIXME: This method can only be used locally. Creating the interpreter should be local to where the agent is running\n */\n private async oid4vciHolderGetMachineInterpreter(opts: OID4VCIMachineInstanceOpts, context: RequiredContext): Promise<OID4VCIMachineId> {\n const authorizationRequestOpts = { ...this.defaultAuthorizationRequestOpts, ...opts.authorizationRequestOpts }\n const services: OID4VCIMachineServiceDefinitions = {\n [OID4VCIMachineServices.start]: (args: PrepareStartArgs) =>\n this.oid4vciHolderStart(\n {\n ...args,\n authorizationRequestOpts,\n },\n context,\n ),\n [OID4VCIMachineServices.startFirstPartApplicationFlow]: (args: StartFirstPartApplicationMachine) =>\n startFirstPartApplicationMachine({ ...args, stateNavigationListener: opts.firstPartyStateNavigationListener }, context),\n [OID4VCIMachineServices.createCredentialsToSelectFrom]: (args: CreateCredentialsToSelectFromArgs) =>\n this.oid4vciHolderCreateCredentialsToSelectFrom(args, context),\n [OID4VCIMachineServices.prepareAuthorizationRequest]: (args: PrepareAuthorizationRequestArgs) =>\n this.oid4vciHolderPrepareAuthorizationRequest(args, context),\n [OID4VCIMachineServices.getContact]: (args: GetContactArgs) => this.oid4vciHolderGetContact(args, context),\n [OID4VCIMachineServices.getCredentials]: (args: GetCredentialsArgs) =>\n this.oid4vciHolderGetCredentials({ accessTokenOpts: args.accessTokenOpts ?? opts.accessTokenOpts, ...args }, context),\n [OID4VCIMachineServices.addContactIdentity]: (args: AddContactIdentityArgs) => this.oid4vciHolderAddContactIdentity(args, context),\n [OID4VCIMachineServices.getIssuerBranding]: (args: GetIssuerBrandingArgs) => this.oid4vciHolderGetIssuerBranding(args, context),\n [OID4VCIMachineServices.storeIssuerBranding]: (args: StoreIssuerBrandingArgs) => this.oid4vciHolderStoreIssuerBranding(args, context),\n [OID4VCIMachineServices.assertValidCredentials]: (args: AssertValidCredentialsArgs) => this.oid4vciHolderAssertValidCredentials(args, context),\n [OID4VCIMachineServices.storeCredentialBranding]: (args: StoreCredentialBrandingArgs) =>\n this.oid4vciHolderStoreCredentialBranding(args, context),\n [OID4VCIMachineServices.storeCredentials]: (args: StoreCredentialsArgs) => this.oid4vciHolderStoreCredentials(args, context),\n [OID4VCIMachineServices.sendNotification]: (args: SendNotificationArgs) => this.oid4vciHolderSendNotification(args, context),\n [OID4VCIMachineServices.getFederationTrust]: (args: GetFederationTrustArgs) => this.getFederationTrust(args, context),\n }\n\n const oid4vciMachineInstanceArgs: OID4VCIMachineInstanceOpts = {\n ...opts,\n authorizationRequestOpts,\n services: {\n ...services,\n ...opts.services,\n },\n }\n\n const { interpreter } = await OID4VCIMachine.newInstance(oid4vciMachineInstanceArgs, context)\n\n return {\n interpreter,\n }\n }\n\n /**\n * This method is run before the machine starts! So there is no concept of the state machine context or states yet\n *\n * The result of this method can be directly passed into the start method of the state machine\n * @param args\n * @param context\n * @private\n */\n private async oid4vciHolderStart(args: PrepareStartArgs, context: RequiredContext): Promise<StartResult> {\n const { requestData } = args\n if (!requestData) {\n throw Error(`Cannot start the OID4VCI holder flow without request data being provided`)\n }\n const { uri = undefined } = requestData\n if (!uri) {\n return Promise.reject(Error('Missing request URI in context'))\n }\n\n const authorizationRequestOpts = { ...this.defaultAuthorizationRequestOpts, ...args.authorizationRequestOpts } satisfies AuthorizationRequestOpts\n // TODO: Previously we filtered the details first against our vcformat prefs. However auth details does not have the notion of formats anymore\n authorizationRequestOpts.authorizationDetails = authorizationRequestOpts?.authorizationDetails\n ? asArray(authorizationRequestOpts.authorizationDetails)\n : undefined\n\n if (!authorizationRequestOpts.redirectUri) {\n authorizationRequestOpts.redirectUri = OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI\n }\n if (authorizationRequestOpts.redirectUri.startsWith('http') && !authorizationRequestOpts.clientId) {\n // At least set a default for a web based wallet.\n // TODO: We really need (dynamic) client registration support\n authorizationRequestOpts.clientId = authorizationRequestOpts.redirectUri\n }\n\n // TODO: This entire filter and formats population should not work anymore, as the auth details no longer have the format property.\n let formats: string[] = this.vcFormatPreferences\n const authFormats = authorizationRequestOpts?.authorizationDetails\n ?.map((detail: AuthorizationDetailsV1_0_15) => (typeof detail === 'object' && 'format' in detail && detail.format ? detail.format : undefined))\n .filter((format) => !!format)\n .map((format) => format as string)\n if (authFormats && authFormats.length > 0) {\n formats = Array.from(new Set(authFormats))\n }\n let oid4vciClient: OpenID4VCIClientV1_0_15\n let offer: CredentialOfferRequestWithBaseUrl | undefined\n if (requestData.existingClientState) {\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromState({ state: requestData.existingClientState })\n offer = oid4vciClient.credentialOffer\n } else {\n offer = requestData.credentialOffer\n if (\n uri.startsWith(RequestType.OPENID_INITIATE_ISSUANCE) ||\n uri.startsWith(RequestType.OPENID_CREDENTIAL_OFFER) ||\n uri.match(/https?:\\/\\/.*credential_offer(_uri)=?.*/)\n ) {\n if (!offer) {\n // Let's make sure to convert the URI to offer, as it matches the regexes. Normally this should already have happened at this point though\n offer = await CredentialOfferClient.fromURI(uri)\n }\n } else {\n if (!!offer) {\n logger.warning(`Non default URI used for credential offer: ${uri}`)\n }\n }\n\n if (!offer) {\n // else no offer, meaning we have an issuer URL\n logger.log(`Issuer url received (no credential offer): ${uri}`)\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromCredentialIssuer({\n credentialIssuer: uri,\n authorizationRequest: authorizationRequestOpts,\n clientId: authorizationRequestOpts.clientId,\n createAuthorizationRequestURL: false, // requestData.createAuthorizationRequestURL ?? true,\n })\n } else {\n logger.log(`Credential offer received: ${uri}`)\n oid4vciClient = await OpenID4VCIClientV1_0_15.fromURI({\n uri,\n authorizationRequest: authorizationRequestOpts,\n clientId: authorizationRequestOpts.clientId,\n createAuthorizationRequestURL: false, // requestData.createAuthorizationRequestURL ?? true,\n })\n }\n }\n\n let configurationIds: Array<string> = []\n if (offer) {\n configurationIds = offer.original_credential_offer.credential_configuration_ids\n } else {\n configurationIds = asArray(authorizationRequestOpts.authorizationDetails)\n // .filter((authDetails): authDetails is Exclude<AuthorizationDetailsV1_0_15, string> => typeof authDetails !== 'string')\n .map((authReqOpts) => authReqOpts.credential_configuration_id)\n .filter((id): id is string => !!id)\n }\n\n const credentialsSupported = await getCredentialConfigsSupportedMerged({\n client: oid4vciClient,\n vcFormatPreferences: formats,\n configurationIds,\n })\n\n const serverMetadata = await oid4vciClient.retrieveServerMetadata()\n const credentialBranding = await getCredentialBranding({ credentialsSupported, context })\n const oid4vciClientState = JSON.parse(await oid4vciClient.exportState())\n\n return {\n credentialBranding,\n credentialsSupported,\n serverMetadata,\n oid4vciClientState,\n }\n }\n\n private async oid4vciHolderPrepareAuthorizationRequest(\n args: PrepareAuthorizationRequestArgs,\n context: RequiredContext,\n ): Promise<PrepareAuthorizationResult> {\n const { openID4VCIClientState, contact } = args\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n const clientId = contact?.identities\n .map((identity) => {\n const connectionConfig = identity.connection?.config\n if (connectionConfig && 'clientId' in connectionConfig) {\n return connectionConfig.clientId\n }\n return undefined\n })\n .find((clientId) => clientId)\n\n if (!clientId) {\n return Promise.reject(Error(`Missing client id in contact's connectionConfig`))\n }\n const client = await OpenID4VCIClientV1_0_15.fromState({ state: openID4VCIClientState })\n const authorizationCodeURL = await client.createAuthorizationRequestUrl({\n authorizationRequest: {\n clientId: clientId,\n } satisfies AuthorizationRequestOpts,\n })\n if (authorizationCodeURL) {\n logger.log(`authorization code URL ${authorizationCodeURL}`)\n }\n return {\n authorizationCodeURL,\n // Needed, because the above createAuthorizationRequestUrl manipulates the state, adding pkce opts to the state\n oid4vciClientState: JSON.parse(await client.exportState()),\n }\n }\n\n private async oid4vciHolderCreateCredentialsToSelectFrom(\n args: CreateCredentialsToSelectFromArgs,\n context: RequiredContext,\n ): Promise<Array<CredentialToSelectFromResult>> {\n const { credentialBranding, locale, selectedCredentials /*, openID4VCIClientState*/, credentialsSupported } = args\n\n // const client = await OpenID4VCIClient.fromState({ state: openID4VCIClientState! }) // TODO see if we need the check openID4VCIClientState defined\n /*const credentialsSupported = await getCredentialConfigsSupportedBySingleTypeOrId({\n client,\n vcFormatPreferences: this.vcFormatPreferences,\n })*/\n logger.info(`Credentials supported ${Object.keys(credentialsSupported).join(', ')}`)\n\n const credentialSelection: Array<CredentialToSelectFromResult> = await Promise.all(\n Object.entries(credentialsSupported).map(async ([id, credentialConfigSupported]): Promise<CredentialToSelectFromResult> => {\n // FIXME this allows for duplicate VerifiableCredential, which the user has no idea which ones those are and we also have a branding map with unique keys, so some branding will not match\n // const defaultCredentialType = 'VerifiableCredential'\n\n const credentialTypes = getTypesFromObject(credentialConfigSupported)\n // const credentialType = id /*?? credentialTypes?.find((type) => type !== defaultCredentialType) ?? defaultCredentialType*/\n const localeBranding = !credentialBranding\n ? undefined\n : (credentialBranding?.[id] ??\n Object.entries(credentialBranding)\n .find(([type, _brandings]) => {\n credentialTypes && type in credentialTypes\n })\n ?.map(([type, supported]) => supported))\n const credentialAlias = (\n await selectCredentialLocaleBranding({\n locale,\n localeBranding,\n })\n )?.alias\n\n return {\n id: uuidv4(),\n credentialId: id,\n credentialTypes: credentialTypes ?? asArray(id),\n credentialAlias: credentialAlias ?? id,\n isSelected: false,\n }\n }),\n )\n\n // TODO find better place to do this, would be nice if the machine does this?\n if (credentialSelection.length >= 1) {\n credentialSelection.map((sel) => selectedCredentials.push(sel.credentialId))\n }\n logger.log(`Credential selection ${JSON.stringify(credentialSelection)}`)\n\n return credentialSelection\n }\n\n private async oid4vciHolderGetContact(args: GetContactArgs, context: RequiredContext): Promise<Party | undefined> {\n const { serverMetadata } = args\n\n if (serverMetadata === undefined) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n const names: Set<string> = new Set(\n serverMetadata.credentialIssuerMetadata?.display\n ?.map((display) => display.name)\n .filter((name) => name != undefined)\n .map((name) => name as string) ?? [],\n )\n const name = names.size > 0 ? Array.from(names)[0] : undefined\n\n const correlationId: string = new URL(serverMetadata.issuer).hostname\n\n const filter: FindPartyArgs = [\n {\n identities: {\n identifier: {\n correlationId,\n },\n },\n },\n ]\n\n if (name) {\n filter.push({\n contact: {\n legalName: name,\n },\n })\n filter.push({\n contact: {\n displayName: name,\n },\n })\n }\n\n const parties: Array<Party> = await context.agent.cmGetContacts({\n filter,\n })\n\n if (parties.length > 1) {\n logger.warning(`Get contacts returned more than one result: ${parties.length}, ${parties.map((party) => party.contact.displayName).join(',')}`)\n }\n const party = parties.length >= 1 ? parties[0] : undefined\n\n logger.log(`Party involved: `, party)\n return party\n }\n\n private async oid4vciHolderGetCredentials(args: GetCredentialsArgs, context: RequiredContext): Promise<Array<MappedCredentialToAccept>> {\n const { verificationCode, openID4VCIClientState, didMethodPreferences, issuanceOpt, accessTokenOpts, walletType } = args\n logger.debug(`Getting credentials`, issuanceOpt, accessTokenOpts)\n\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n const client = await OpenID4VCIClientV1_0_15.fromState({ state: openID4VCIClientState })\n const credentialsSupported = await getCredentialConfigsSupportedMerged({\n client,\n vcFormatPreferences: this.vcFormatPreferences,\n configurationIds: args.selectedCredentials,\n })\n const serverMetadata = await client.retrieveServerMetadata()\n const issuanceOpts = await getIssuanceOpts({\n client,\n credentialsSupported,\n serverMetadata,\n context,\n didMethodPreferences: this.selectDidMethodPreferences(didMethodPreferences, walletType),\n jwtCryptographicSuitePreferences: this.jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences: this.jsonldCryptographicSuitePreferences,\n ...(issuanceOpt && { forceIssuanceOpt: issuanceOpt }),\n })\n\n const getCredentials = issuanceOpts.map(\n async (issuanceOpt: IssuanceOpts): Promise<MappedCredentialToAccept> =>\n await this.oid4vciHolderGetCredential(\n {\n issuanceOpt,\n pin: verificationCode,\n client,\n accessTokenOpts,\n },\n context,\n ),\n )\n\n const allCredentials = await Promise.all(getCredentials)\n logger.log(`Credentials received`, allCredentials)\n\n return allCredentials\n }\n\n private selectDidMethodPreferences(didMethodPreferences: Array<SupportedDidMethodEnum> | undefined, walletType: WalletType) {\n const supportedDidMethodEnums =\n Array.isArray(didMethodPreferences) && didMethodPreferences.length > 0 ? didMethodPreferences : this.didMethodPreferences\n if (walletType === 'ORGANIZATIONAL') {\n return [SupportedDidMethodEnum.DID_WEB, ...supportedDidMethodEnums]\n }\n return supportedDidMethodEnums\n }\n\n private async oid4vciHolderGetCredential(args: GetCredentialArgs, context: RequiredContext): Promise<MappedCredentialToAccept> {\n const { issuanceOpt, pin, client, accessTokenOpts } = args\n logger.info(`Getting credential`, issuanceOpt)\n\n if (!issuanceOpt) {\n return Promise.reject(Error(`Cannot get credential issuance options`))\n }\n\n const identifier = await getIdentifierOpts({ issuanceOpt, context })\n issuanceOpt.identifier = identifier\n logger.info(`ID opts`, identifier)\n const alg: JoseSignatureAlgorithm | JoseSignatureAlgorithmString = await signatureAlgorithmFromKey({ key: identifier.key })\n // The VCI lib either expects a jwk or a kid\n const jwk = isManagedIdentifierJwkResult(identifier) ? identifier.jwk : undefined\n\n const callbacks: ProofOfPossessionCallbacks = {\n signCallback: signCallback(identifier, context),\n }\n\n try {\n // We need to make sure we have acquired the access token\n if (!client.clientId) {\n client.clientId = isManagedIdentifierDidResult(identifier) ? identifier.did : identifier.issuer\n }\n let asOpts: AuthorizationServerOpts | undefined = undefined\n let kid = accessTokenOpts?.clientOpts?.kid ?? identifier.kid\n if (accessTokenOpts?.clientOpts) {\n const clientId = accessTokenOpts.clientOpts.clientId ?? client.clientId ?? identifier.issuer\n if (client.isEBSI() && clientId?.startsWith('http') && kid?.includes('#')) {\n kid = kid.split('#')[1]\n }\n\n //todo: investigate if the jwk should be used here as well if present\n const clientOpts: AuthorizationServerClientOpts = {\n ...accessTokenOpts.clientOpts,\n clientId,\n kid,\n // @ts-ignore\n alg: accessTokenOpts.clientOpts.alg ?? alg,\n signCallbacks: accessTokenOpts.clientOpts.signCallbacks ?? callbacks,\n }\n asOpts = {\n clientOpts,\n }\n }\n\n await client.acquireAccessToken({\n clientId: client.clientId,\n pin,\n authorizationResponse: JSON.parse(await client.exportState()).authorizationCodeResponse,\n additionalRequestParams: accessTokenOpts?.additionalRequestParams,\n ...(asOpts && { asOpts }),\n })\n\n // FIXME: This type mapping is wrong. It should use credential_identifier in case the access token response has authorization details\n const types = getTypesFromObject(issuanceOpt)\n const id: string | undefined = 'id' in issuanceOpt && issuanceOpt.id ? (issuanceOpt.id as string) : undefined\n const credentialTypes = asArray(issuanceOpt.credentialConfigurationId ?? types ?? id)\n if (!credentialTypes || credentialTypes.length === 0) {\n return Promise.reject(Error('cannot determine credential id to request'))\n }\n\n const credentialDefinition = this.getCredentialDefinition(issuanceOpt)\n const credentialResponse = await client.acquireCredentials({\n ...(credentialDefinition && { context: credentialDefinition['@context'] }),\n credentialTypes,\n proofCallbacks: callbacks,\n format: issuanceOpt.format,\n // TODO: We need to update the machine and add notifications support for actual deferred credentials instead of just waiting/retrying\n deferredCredentialAwait: true,\n ...(issuanceOpt.id && typeof issuanceOpt.id === 'string' ? { credentialConfigurationId: issuanceOpt.id } : undefined),\n ...(!jwk && { kid }), // vci client either wants a jwk or kid. If we have used the jwk method do not provide the kid\n jwk,\n alg,\n jti: uuidv4(),\n })\n\n const credential = {\n id: issuanceOpt.credentialConfigurationId ?? id,\n types: types ?? asArray(credentialTypes),\n issuanceOpt,\n credentialResponse,\n } satisfies CredentialToAccept\n return mapCredentialToAccept({ credentialToAccept: credential, hasher: this.hasher })\n } catch (error) {\n return Promise.reject(error)\n }\n }\n\n private async oid4vciHolderAddContactIdentity(args: AddContactIdentityArgs, context: RequiredContext): Promise<Identity> {\n const { credentialsToAccept, contact } = args\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n if (credentialsToAccept === undefined || credentialsToAccept.length === 0) {\n return Promise.reject(Error('Missing credential offers in context'))\n }\n\n let correlationId: string = credentialsToAccept[0].correlationId\n let identifierType = CorrelationIdentifierType.DID\n if (!correlationId.toLowerCase().startsWith('did:')) {\n identifierType = CorrelationIdentifierType.URL\n if (correlationId.startsWith('http')) {\n correlationId = new URL(correlationId).hostname\n }\n }\n const identity: NonPersistedIdentity = {\n alias: credentialsToAccept[0].correlationId,\n origin: IdentityOrigin.EXTERNAL,\n roles: [CredentialRole.ISSUER],\n identifier: {\n type: identifierType,\n correlationId,\n },\n ...(identifierType === CorrelationIdentifierType.URL && {\n connection: {\n type: ConnectionType.OPENID_CONNECT,\n config: {\n clientId: '138d7bf8-c930-4c6e-b928-97d3a4928b01',\n clientSecret: '03b3955f-d020-4f2a-8a27-4e452d4e27a0',\n scopes: ['auth'],\n issuer: 'https://example.com/app-test',\n redirectUrl: 'app:/callback',\n dangerouslyAllowInsecureHttpRequests: true,\n clientAuthMethod: 'post' as const,\n },\n },\n }),\n }\n\n await context.agent.emit(OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED, {\n contactId: contact.id,\n identity,\n })\n logger.log(`Contact added: ${correlationId}`)\n\n return context.agent.cmAddIdentity({ contactId: contact.id, identity })\n }\n\n private async oid4vciHolderGetIssuerBranding(\n args: GetIssuerBrandingArgs,\n context: RequiredContext,\n ): Promise<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>> {\n const { serverMetadata, contact } = args\n\n // Here we are fetching issuer branding for a contact. If no contact is found that means we encounter this contact for the first time. This also means we do not have any branding for the contact.\n const issuerCorrelationId = contact?.identities\n .filter((identity) => identity.roles.includes(CredentialRole.ISSUER))\n .map((identity) => identity.identifier.correlationId)[0]\n\n if (issuerCorrelationId) {\n const branding = await context.agent.ibGetIssuerBranding({ filter: [{ issuerCorrelationId }] })\n if (branding.length > 0) {\n return branding[0].localeBranding\n }\n }\n\n // We should have serverMetadata in the context else something went wrong\n if (!serverMetadata) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n return getBasicIssuerLocaleBranding({\n display: serverMetadata.credentialIssuerMetadata?.display ?? [],\n dynamicRegistrationClientMetadata: serverMetadata.credentialIssuerMetadata,\n context,\n })\n }\n\n private async oid4vciHolderStoreIssuerBranding(args: StoreIssuerBrandingArgs, context: RequiredContext): Promise<void> {\n const { issuerBranding, contact } = args\n if (!issuerBranding || issuerBranding.length === 0 || (<Array<IIssuerLocaleBranding>>issuerBranding)[0].id) {\n // FIXME we need better separation between a contact(issuer) we encountered before and it's branding vs a new contact and it's branding\n return\n }\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n const issuerCorrelationId = contact?.identities\n .filter((identity) => identity.roles.includes(CredentialRole.ISSUER))\n .map((identity) => identity.identifier.correlationId)[0]\n\n // we check for issuer branding as adding an identity might also trigger storing the issuer branding\n const branding = await context.agent.ibGetIssuerBranding({ filter: [{ issuerCorrelationId }] })\n if (branding.length > 0) {\n return\n }\n\n await context.agent.ibAddIssuerBranding({\n localeBranding: issuerBranding as Array<IBasicIssuerLocaleBranding>,\n issuerCorrelationId,\n })\n }\n\n private async oid4vciHolderAssertValidCredentials(args: AssertValidCredentialsArgs, context: RequiredContext): Promise<VerificationResult[]> {\n const { credentialsToAccept, issuanceOpt } = args\n\n return await Promise.all(\n credentialsToAccept.map((credentialToAccept) =>\n verifyCredentialToAccept({\n mappedCredential: credentialToAccept,\n onVerifyEBSICredentialIssuer: this.onVerifyEBSICredentialIssuer,\n hasher: this.hasher,\n schemaValidation: issuanceOpt?.schemaValidation,\n context,\n }),\n ),\n )\n }\n\n private async oid4vciHolderStoreCredentialBranding(args: StoreCredentialBrandingArgs, context: RequiredContext): Promise<void> {\n const { credentialBranding, serverMetadata, selectedCredentials, credentialsToAccept } = args\n\n if (serverMetadata === undefined) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n } else if (selectedCredentials.length === 0) {\n logger.warning(`No credentials selected for issuer: ${serverMetadata.issuer}`)\n return\n }\n\n let counter = 0\n for (const credentialId of selectedCredentials) {\n // The selectedCredential from context is the configurationId, whilst we store the branding by type. We need to map\n const configId = credentialId\n const types =\n credentialsToAccept\n .find((ac) => ac.correlationId === configId || ac.credentialToAccept.id === configId || ac.types.includes(configId))\n ?.types?.filter((type) => type != 'VerifiableCredential') ?? []\n\n const localeBranding: Array<IBasicCredentialLocaleBranding> = credentialBranding?.[configId] ?? []\n if (localeBranding.length === 0) {\n for (const type of types) {\n const branding = credentialBranding?.[type] ?? []\n if (branding.length > 0) {\n localeBranding.push(...branding)\n }\n }\n }\n\n if (localeBranding && localeBranding.length > 0) {\n const credential = credentialsToAccept.find(\n (credAccept) =>\n credAccept.credentialToAccept.id === credentialId ||\n JSON.stringify(credAccept.types) === credentialId ||\n JSON.stringify(credAccept.types.filter((cred) => cred !== 'VerifiableCredential')) === JSON.stringify(types) ||\n credentialsToAccept[counter],\n )!\n counter++\n await context.agent.ibAddCredentialBranding({\n vcHash: computeEntryHash(credential.rawVerifiableCredential as W3CVerifiableCredential),\n issuerCorrelationId: new URL(serverMetadata.issuer).hostname,\n localeBranding,\n })\n logger.log(\n `Credential branding for issuer ${serverMetadata.issuer} and type ${credentialId} stored with locales ${localeBranding.map((b) => b.locale).join(',')}`,\n )\n } else {\n logger.warning(`No credential branding found for issuer: ${serverMetadata.issuer} and type ${credentialId}`)\n }\n }\n }\n\n private async oid4vciHolderStoreCredentials(args: StoreCredentialsArgs, context: RequiredContext): Promise<void> {\n function trimmed(input?: string) {\n const trim = input?.trim()\n if (trim === '') {\n return undefined\n }\n return trim\n }\n\n const { credentialsToAccept, openID4VCIClientState, credentialsSupported, serverMetadata, selectedCredentials } = args\n const mappedCredentialToAccept = credentialsToAccept[0]\n\n if (selectedCredentials && selectedCredentials.length > 1) {\n logger.error(`More than 1 credential selected ${selectedCredentials.join(', ')}, but current service only stores 1 credential!`)\n }\n\n // TODO determine when and how we should store credentials without key kmsKeyRef & id method), this should be tested with the code below\n const issuanceOpt = args.issuanceOpt ?? mappedCredentialToAccept.credentialToAccept.issuanceOpt\n if (!issuanceOpt || !issuanceOpt.identifier) {\n return Promise.reject(Error('issuanceOpt.identifier must me set in order to store a credential'))\n }\n const { kmsKeyRef, method } = issuanceOpt.identifier\n\n let persist = true\n const verifiableCredential = mappedCredentialToAccept.uniformVerifiableCredential as VerifiableCredential\n\n const notificationId = mappedCredentialToAccept.credentialToAccept.credentialResponse.notification_id\n const subjectIssuance = mappedCredentialToAccept.credential_subject_issuance\n const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint\n let holderCredential:\n | IVerifiableCredential\n | JwtDecodedVerifiableCredential\n | SdJwtDecodedVerifiableCredentialPayload\n | W3CVerifiableCredential\n | undefined = undefined\n if (!notificationEndpoint) {\n logger.log(`Notifications not supported by issuer ${serverMetadata?.issuer}. Will not provide a notification`)\n } else if (notificationEndpoint && !notificationId) {\n logger.warning(\n `Notification endpoint available in issuer metadata with value ${notificationEndpoint}, but no ${notificationId} provided. Will not send a notification to issuer ${serverMetadata?.issuer}`,\n )\n } else if (notificationEndpoint && notificationId) {\n logger.log(`Notification id ${notificationId} found, will send back a notification to ${notificationEndpoint}`)\n let event = 'credential_accepted'\n if (Array.isArray(subjectIssuance?.notification_events_supported)) {\n // experimental subject issuance, where a new credential is being created\n event = subjectIssuance.notification_events_supported.includes('credential_accepted_holder_signed')\n ? 'credential_accepted_holder_signed'\n : 'credential_deleted_holder_signed'\n logger.log(`Subject issuance/signing will be used, with event`, event)\n\n const issuerVC = extractCredentialFromResponse(mappedCredentialToAccept.credentialToAccept.credentialResponse)\n const wrappedIssuerVC = CredentialMapper.toWrappedVerifiableCredential(issuerVC, { hasher: this.hasher ?? defaultHasher })\n console.log(`Wrapped VC: ${wrappedIssuerVC.type}, ${wrappedIssuerVC.format}`)\n // We will use the subject of the VCI Issuer (the holder, as the issuer of the new credential, so the below is not a mistake!)\n\n let issuer: string | undefined\n\n if (CredentialMapper.isWrappedSdJwtVerifiableCredential(wrappedIssuerVC)) {\n issuer = trimmed(wrappedIssuerVC.decoded?.sub)\n } else if (CredentialMapper.isWrappedW3CVerifiableCredential(wrappedIssuerVC)) {\n issuer =\n trimmed(wrappedIssuerVC.credential?.sub) ??\n // @ts-ignore\n trimmed(wrappedIssuerVC.credential?.credentialSubject?.id) ??\n trimmed(this.idFromW3cCredentialSubject(wrappedIssuerVC))\n } else if (CredentialMapper.isWrappedMdocCredential(wrappedIssuerVC)) {\n return Promise.reject(Error('mdoc not yet supported'))\n }\n\n if (!issuer) {\n issuer = trimmed(verifiableCredential.credentialSubject?.id)\n }\n if (!issuer && openID4VCIClientState?.kid?.startsWith('did:')) {\n issuer = parseDid(openID4VCIClientState?.kid).did\n }\n if (!issuer && openID4VCIClientState?.jwk?.kid?.startsWith('did:')) {\n issuer = parseDid(openID4VCIClientState!.jwk!.kid!).did\n }\n if (!issuer && openID4VCIClientState?.clientId) {\n issuer = trimmed(openID4VCIClientState.clientId)\n }\n if (!issuer && openID4VCIClientState?.accessTokenResponse) {\n const decodedJwt = decodeJWT(openID4VCIClientState.accessTokenResponse.access_token)\n issuer = decodedJwt.payload.sub\n }\n if (!issuer && mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier) {\n const resolution = await context.agent.identifierManagedGet(mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier)\n issuer = resolution.issuer\n }\n\n if (!issuer) {\n throw Error(`We could not determine the issuer, which means we cannot sign the credential`)\n }\n logger.log(`Issuer for self-issued credential will be: ${issuer}`)\n\n const holderCredentialToSign = wrappedIssuerVC.decoded\n let proofFormat: CredentialProofFormat = 'lds'\n if (wrappedIssuerVC.format.includes('jwt') && !wrappedIssuerVC.format.includes('mso_mdoc')) {\n holderCredentialToSign.iss = issuer\n proofFormat = 'jwt'\n }\n if ('issuer' in holderCredentialToSign && !('iss' in holderCredentialToSign)) {\n holderCredentialToSign.issuer = issuer\n }\n if ('sub' in holderCredentialToSign) {\n holderCredentialToSign.sub = issuer\n }\n if ('credentialSubject' in holderCredentialToSign && !Array.isArray(holderCredentialToSign.credentialSubject)) {\n holderCredentialToSign.credentialSubject.id = issuer\n }\n if ('vc' in holderCredentialToSign) {\n if (holderCredentialToSign.vc.credentialSubject) {\n holderCredentialToSign.vc.credentialSubject.id = issuer\n }\n holderCredentialToSign.vc.issuer = issuer\n delete holderCredentialToSign.vc.proof\n delete holderCredentialToSign.vc.issuanceDate\n }\n delete holderCredentialToSign.proof\n delete holderCredentialToSign.issuanceDate\n delete holderCredentialToSign.iat\n\n logger.log(`Subject issuance/signing will sign credential of type ${proofFormat}:`, holderCredentialToSign)\n const issuedVC = await context.agent.createVerifiableCredential({\n credential: ('vc' in holderCredentialToSign ? holderCredentialToSign.vc : holderCredentialToSign) as CredentialPayload,\n fetchRemoteContexts: true,\n save: false,\n proofFormat,\n })\n if (!issuedVC) {\n throw Error(`Could not issue holder credential from the wallet`)\n }\n logger.log(`Holder ${issuedVC.issuer} issued new credential with id ${issuedVC.id}`, issuedVC)\n holderCredential = CredentialMapper.storedCredentialToOriginalFormat(issuedVC as IVerifiableCredential)\n persist = event === 'credential_accepted_holder_signed'\n }\n\n const notificationRequest: NotificationRequest = {\n notification_id: notificationId,\n ...(holderCredential && { credential: holderCredential }),\n event,\n }\n\n await this.oid4vciHolderSendNotification(\n {\n openID4VCIClientState,\n stored: persist,\n credentialsToAccept,\n credentialsSupported,\n notificationRequest,\n serverMetadata,\n },\n context,\n )\n }\n const persistCredential = holderCredential\n ? CredentialMapper.storedCredentialToOriginalFormat(holderCredential)\n : mappedCredentialToAccept.rawVerifiableCredential\n if (!persist && holderCredential) {\n logger.log(`Will not persist credential, since we are signing as a holder and the issuer asked not to persist`)\n } else {\n logger.log(`Persisting credential`, persistCredential)\n\n const issuer = CredentialMapper.issuerCorrelationIdFromIssuerType(verifiableCredential.issuer)\n const [subjectCorrelationType, subjectCorrelationId] = this.determineSubjectCorrelation(issuanceOpt.identifier, issuer)\n\n const persistedCredential = await context.agent.crsAddCredential({\n credential: {\n rawDocument: ensureRawDocument(persistCredential),\n kmsKeyRef: kmsKeyRef,\n identifierMethod: method,\n credentialRole: CredentialRole.HOLDER,\n issuerCorrelationType: issuer?.startsWith('did:') ? CredentialCorrelationType.DID : CredentialCorrelationType.URL,\n issuerCorrelationId: issuer,\n subjectCorrelationType,\n subjectCorrelationId,\n },\n })\n await context.agent.emit(OID4VCIHolderEvent.CREDENTIAL_STORED, {\n credential: persistedCredential,\n vcHash: persistedCredential.hash,\n } satisfies OnCredentialStoredArgs)\n }\n }\n\n private async oid4vciHolderSendNotification(args: SendNotificationArgs, context: RequiredContext): Promise<void> {\n const { serverMetadata, notificationRequest, openID4VCIClientState } = args\n const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint\n if (!notificationEndpoint) {\n return\n } else if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n } else if (!notificationRequest) {\n return Promise.reject(Error('Missing notification request'))\n }\n\n logger.log(`Will send notification to ${notificationEndpoint}`, notificationRequest)\n\n const client = await OpenID4VCIClient.fromState({ state: openID4VCIClientState })\n await client.sendNotification({ notificationEndpoint }, notificationRequest, openID4VCIClientState?.accessTokenResponse?.access_token)\n logger.log(`Notification to ${notificationEndpoint} has been dispatched`)\n }\n\n private async getFederationTrust(args: GetFederationTrustArgs, context: RequiredContext): Promise<Array<string>> {\n const { requestData, serverMetadata, trustAnchors } = args\n\n if (trustAnchors.length === 0) {\n return Promise.reject(Error('No trust anchors found'))\n }\n\n if (!requestData?.uri) {\n return Promise.reject(Error('Missing request URI in context'))\n }\n\n if (!serverMetadata) {\n return Promise.reject(Error('Missing serverMetadata in context'))\n }\n\n const url = new URL(requestData?.uri)\n const params = new URLSearchParams(url.search)\n const openidFederation = params.get('openid_federation')\n const entityIdentifier = openidFederation ?? serverMetadata.issuer\n if (entityIdentifier.startsWith('http://')) {\n console.warn(`OpenID federation does not support http://, only https:// allowed; got: (${url.toString()})`)\n // OIDF always needs to be https\n return []\n }\n\n const result = await context.agent.identifierExternalResolveByOIDFEntityId({\n method: 'entity_id',\n trustAnchors: trustAnchors,\n identifier: entityIdentifier,\n })\n\n return result.trustedAnchors\n }\n\n private async oid4vciHolderGetIssuerMetadata(args: GetIssuerMetadataArgs, context: RequiredContext): Promise<EndpointMetadataResult> {\n const { issuer, errorOnNotFound = true } = args\n return MetadataClient.retrieveAllMetadata(issuer, { errorOnNotFound })\n }\n\n private determineSubjectCorrelation(identifier: ManagedIdentifierOptsOrResult, issuer: string): [CredentialCorrelationType, string] {\n switch (identifier.method) {\n case 'did':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierDidResult(identifier)) {\n return [CredentialCorrelationType.DID, identifier.did]\n } else if (isManagedIdentifierDidOpts(identifier)) {\n return [CredentialCorrelationType.DID, typeof identifier.identifier === 'string' ? identifier.identifier : identifier.identifier.did]\n }\n break\n case 'kid':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierKidResult(identifier)) {\n return [CredentialCorrelationType.KID, identifier.kid]\n } else if (isManagedIdentifierDidOpts(identifier)) {\n return [CredentialCorrelationType.KID, identifier.identifier]\n }\n break\n case 'x5c':\n if (isManagedIdentifierResult(identifier) && isManagedIdentifierX5cResult(identifier)) {\n return [CredentialCorrelationType.X509_SAN, identifier.x5c.join('\\r\\n')]\n } else if (isManagedIdentifierX5cOpts(identifier)) {\n return [CredentialCorrelationType.X509_SAN, identifier.identifier.join('\\r\\n')]\n }\n break\n }\n return [CredentialCorrelationType.URL, issuer]\n }\n\n private idFromW3cCredentialSubject(wrappedIssuerVC: WrappedW3CVerifiableCredential): string | undefined {\n if (Array.isArray(wrappedIssuerVC.credential?.credentialSubject)) {\n if (wrappedIssuerVC.credential?.credentialSubject.length > 0) {\n return wrappedIssuerVC.credential?.credentialSubject[0].id\n }\n } else {\n return wrappedIssuerVC.credential?.credentialSubject?.id\n }\n return undefined\n }\n\n private getCredentialDefinition(issuanceOpt: IssuanceOpts): CredentialDefinitionJwtVcJsonLdAndLdpVcV1_0_15 | undefined {\n if (issuanceOpt.format == 'ldp_vc' || issuanceOpt.format == 'jwt_vc_json-ld') {\n return (issuanceOpt as CredentialConfigurationSupportedJwtVcJsonLdAndLdpVcV1_0_15).credential_definition\n }\n return undefined\n }\n}\n","import { AuthorizationChallengeCodeResponse, AuthzFlowType, toAuthorizationResponsePayload } from '@sphereon/oid4vci-common'\nimport { IBasicIssuerLocaleBranding, Identity, IIssuerLocaleBranding, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { assign, createMachine, DoneInvokeEvent, interpret } from 'xstate'\nimport { translate } from '../localization/Localization'\nimport {\n AuthorizationResponseEvent,\n ContactAliasEvent,\n ContactConsentEvent,\n CreateContactEvent,\n CreateOID4VCIMachineOpts,\n CredentialToSelectFromResult,\n ErrorDetails,\n StartResult,\n MappedCredentialToAccept,\n OID4VCIMachineAddContactStates,\n OID4VCIMachineContext,\n OID4VCIMachineEvents,\n OID4VCIMachineEventTypes,\n OID4VCIMachineGuards,\n OID4VCIMachineInstanceOpts,\n OID4VCIMachineInterpreter,\n OID4VCIMachineServices,\n OID4VCIMachineState,\n OID4VCIMachineStates,\n OID4VCIMachineVerifyPinStates,\n OID4VCIStateMachine,\n RequiredContext,\n SelectCredentialsEvent,\n SetAuthorizationCodeURLEvent,\n VerificationCodeEvent,\n PrepareAuthorizationResult,\n} from '../types/IOID4VCIHolder'\nimport { FirstPartyMachineStateTypes } from '../types/FirstPartyMachine'\n\nconst oid4vciHasNoContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact } = _ctx\n return contact === undefined\n}\n\nconst oid4vciHasContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact } = _ctx\n return contact !== undefined\n}\n\nconst oid4vciContactHasLowTrustGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact, trustedAnchors } = _ctx\n return contact !== undefined && trustedAnchors !== undefined && trustedAnchors.length === 0\n}\n\nconst oid4vciCredentialsToSelectRequiredGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { credentialToSelectFrom } = _ctx\n return credentialToSelectFrom && credentialToSelectFrom.length > 1\n}\n\nconst oid4vciRequirePinGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { requestData } = _ctx\n return requestData?.credentialOffer?.userPinRequired === true\n}\n\nconst oid4vciHasNoContactIdentityGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contact, credentialsToAccept } = _ctx\n let toAcceptId = credentialsToAccept[0].correlationId\n if (toAcceptId.match(/^https?:\\/\\/.*/)) {\n toAcceptId = new URL(toAcceptId).hostname\n }\n return !contact?.identities.some((identity: Identity): boolean => identity.identifier.correlationId === toAcceptId)\n}\n\nconst oid4vciVerificationCodeGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { verificationCode } = _ctx\n return verificationCode !== undefined && verificationCode.length > 0\n}\n\nconst oid4vciCreateContactGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { contactAlias, hasContactConsent } = _ctx\n return hasContactConsent && !!contactAlias && contactAlias.length > 0\n}\n\nconst oid4vciHasSelectedCredentialsGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { selectedCredentials } = _ctx\n return selectedCredentials !== undefined && selectedCredentials.length > 0\n}\n\nconst oid4vciIsOIDFOriginGuard = (_ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n // TODO in the future we need to establish if a origin is a IDF origin. So we need to check if this metadata is on the well-known location\n const { trustAnchors } = _ctx\n return trustAnchors.length > 0\n}\n\nconst oid4vciNoAuthorizationGuard = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !oid4vciHasAuthorizationResponse(ctx, _event)\n}\n\n// FIXME refactor this guard\nconst oid4vciRequireAuthorizationGuard = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n const { openID4VCIClientState } = ctx\n\n if (!openID4VCIClientState) {\n throw Error('Missing openID4VCI client state in context')\n }\n\n if (openID4VCIClientState.authorizationURL && openID4VCIClientState.authorizationRequestOpts) {\n // We have authz options or there is not credential offer to begin with.\n // We require authz as long as we do not have the authz code response\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {\n return false\n } else if (openID4VCIClientState.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint) {\n return !ctx.openID4VCIClientState?.authorizationCodeResponse\n }\n return false\n}\n\nconst oid4vciHasAuthorizationResponse = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !!ctx.openID4VCIClientState?.authorizationCodeResponse\n}\n\nconst oid4vciIsFirstPartyApplication = (ctx: OID4VCIMachineContext, _event: OID4VCIMachineEventTypes): boolean => {\n return !!ctx.serverMetadata?.authorization_challenge_endpoint\n}\n\nconst createOID4VCIMachine = (opts?: CreateOID4VCIMachineOpts): OID4VCIStateMachine => {\n const initialContext: OID4VCIMachineContext = {\n // TODO WAL-671 we need to store the data from OpenIdProvider here in the context and make sure we can restart the machine with it and init the OpenIdProvider\n accessTokenOpts: opts?.accessTokenOpts,\n requestData: opts?.requestData,\n walletType: opts?.walletType ?? 'NATURAL_PERSON',\n trustAnchors: opts?.trustAnchors ?? [],\n issuanceOpt: opts?.issuanceOpt,\n didMethodPreferences: opts?.didMethodPreferences,\n locale: opts?.locale,\n credentialsSupported: {},\n credentialToSelectFrom: [],\n selectedCredentials: [],\n credentialsToAccept: [],\n hasContactConsent: true,\n contactAlias: '',\n }\n\n return createMachine<OID4VCIMachineContext, OID4VCIMachineEventTypes>({\n id: opts?.machineName ?? 'OID4VCIHolder',\n predictableActionArguments: true,\n initial: OID4VCIMachineStates.start,\n schema: {\n events: {} as OID4VCIMachineEventTypes,\n guards: {} as\n | { type: OID4VCIMachineGuards.hasNoContactGuard }\n | { type: OID4VCIMachineGuards.credentialsToSelectRequiredGuard }\n | { type: OID4VCIMachineGuards.requirePinGuard }\n | { type: OID4VCIMachineGuards.requireAuthorizationGuard }\n | { type: OID4VCIMachineGuards.noAuthorizationGuard }\n | { type: OID4VCIMachineGuards.hasNoContactIdentityGuard }\n | { type: OID4VCIMachineGuards.verificationCodeGuard }\n | { type: OID4VCIMachineGuards.hasContactGuard }\n | { type: OID4VCIMachineGuards.createContactGuard }\n | { type: OID4VCIMachineGuards.hasSelectedCredentialsGuard }\n | { type: OID4VCIMachineGuards.hasAuthorizationResponse }\n | { type: OID4VCIMachineGuards.isOIDFOriginGuard }\n | { type: OID4VCIMachineGuards.contactHasLowTrustGuard }\n | { type: OID4VCIMachineGuards.isFirstPartyApplication },\n services: {} as {\n [OID4VCIMachineServices.start]: {\n data: StartResult\n }\n [OID4VCIMachineServices.prepareAuthorizationRequest]: {\n data: PrepareAuthorizationResult\n }\n [OID4VCIMachineServices.createCredentialsToSelectFrom]: {\n data: Array<CredentialToSelectFromResult>\n }\n [OID4VCIMachineServices.getContact]: {\n data: Party | undefined\n }\n [OID4VCIMachineServices.storeIssuerBranding]: {\n data: void\n }\n [OID4VCIMachineServices.getCredentials]: {\n data: Array<MappedCredentialToAccept> | undefined\n }\n [OID4VCIMachineServices.addContactIdentity]: {\n data: void\n }\n [OID4VCIMachineServices.assertValidCredentials]: {\n data: void\n }\n [OID4VCIMachineServices.storeCredentialBranding]: {\n data: void\n }\n [OID4VCIMachineServices.storeCredentials]: {\n data: void\n }\n [OID4VCIMachineServices.getFederationTrust]: {\n data: Array<string>\n }\n [OID4VCIMachineServices.getIssuerBranding]: {\n data: Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>\n }\n [OID4VCIMachineServices.startFirstPartApplicationFlow]: {\n data: void\n }\n },\n },\n context: initialContext,\n states: {\n [OID4VCIMachineStates.start]: {\n id: OID4VCIMachineStates.start,\n invoke: {\n src: OID4VCIMachineServices.start,\n onDone: {\n target: OID4VCIMachineStates.createCredentialsToSelectFrom,\n actions: assign({\n credentialBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.credentialBranding ?? {},\n credentialsSupported: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.credentialsSupported,\n serverMetadata: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.serverMetadata,\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<StartResult>) => _event.data.oid4vciClientState,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_initiation_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.createCredentialsToSelectFrom]: {\n id: OID4VCIMachineStates.createCredentialsToSelectFrom,\n invoke: {\n src: OID4VCIMachineServices.createCredentialsToSelectFrom,\n onDone: {\n target: OID4VCIMachineStates.getContact,\n actions: assign({\n credentialToSelectFrom: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<CredentialToSelectFromResult>>) => _event.data,\n }),\n // TODO WAL-670 would be nice if we can have guard that checks if we have at least 1 item in the selection. not sure if this can occur but it would be more defensive.\n // Still cannot find a nice way to do this inside of an invoke besides adding another transition state\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_credential_selection_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getContact]: {\n id: OID4VCIMachineStates.getContact,\n invoke: {\n src: OID4VCIMachineServices.getContact,\n onDone: {\n target: OID4VCIMachineStates.getIssuerBranding,\n actions: assign({ contact: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Party>) => _event.data }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_contact_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getIssuerBranding]: {\n id: OID4VCIMachineStates.getIssuerBranding,\n invoke: {\n src: OID4VCIMachineServices.getIssuerBranding,\n onDone: [\n {\n target: OID4VCIMachineStates.getFederationTrust,\n cond: OID4VCIMachineGuards.isOIDFOriginGuard,\n actions: assign({\n issuerBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>) =>\n _event.data,\n }),\n },\n {\n target: OID4VCIMachineStates.transitionFromSetup,\n actions: assign({\n issuerBranding: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>) =>\n _event.data,\n }),\n },\n ],\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.getFederationTrust]: {\n id: OID4VCIMachineStates.getFederationTrust,\n invoke: {\n src: OID4VCIMachineServices.getFederationTrust,\n onDone: {\n target: OID4VCIMachineStates.transitionFromSetup,\n actions: assign({\n trustedAnchors: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<string>>) => _event.data,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_federation_trust_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromSetup]: {\n id: OID4VCIMachineStates.transitionFromSetup,\n always: [\n {\n target: OID4VCIMachineStates.addContact,\n cond: OID4VCIMachineGuards.hasNoContactGuard,\n },\n {\n target: OID4VCIMachineStates.reviewContact,\n cond: OID4VCIMachineGuards.contactHasLowTrustGuard,\n },\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n on: {\n [OID4VCIMachineEvents.SET_AUTHORIZATION_CODE_URL]: {\n actions: assign({ authorizationCodeURL: (_ctx: OID4VCIMachineContext, _event: SetAuthorizationCodeURLEvent) => _event.data }),\n },\n },\n },\n [OID4VCIMachineStates.addContact]: {\n id: OID4VCIMachineStates.addContact,\n initial: OID4VCIMachineAddContactStates.idle,\n on: {\n [OID4VCIMachineEvents.SET_CONTACT_CONSENT]: {\n actions: assign({ hasContactConsent: (_ctx: OID4VCIMachineContext, _event: ContactConsentEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.SET_CONTACT_ALIAS]: {\n actions: assign({ contactAlias: (_ctx: OID4VCIMachineContext, _event: ContactAliasEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.CREATE_CONTACT]: {\n target: `.${OID4VCIMachineAddContactStates.next}`,\n actions: assign({ contact: (_ctx: OID4VCIMachineContext, _event: CreateContactEvent) => _event.data }),\n cond: OID4VCIMachineGuards.createContactGuard,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n states: {\n [OID4VCIMachineAddContactStates.idle]: {},\n [OID4VCIMachineAddContactStates.next]: {\n always: {\n target: `#${OID4VCIMachineStates.storeIssuerBranding}`,\n cond: OID4VCIMachineGuards.hasContactGuard,\n },\n },\n },\n },\n [OID4VCIMachineStates.reviewContact]: {\n id: OID4VCIMachineStates.reviewContact,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.transitionFromContactSetup,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.storeIssuerBranding]: {\n id: OID4VCIMachineStates.storeIssuerBranding,\n invoke: {\n src: OID4VCIMachineServices.storeIssuerBranding,\n onDone: {\n target: OID4VCIMachineStates.transitionFromContactSetup,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromContactSetup]: {\n id: OID4VCIMachineStates.transitionFromContactSetup,\n always: [\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.startFirstPartApplicationFlow]: {\n id: OID4VCIMachineStates.startFirstPartApplicationFlow,\n invoke: {\n src: OID4VCIMachineServices.startFirstPartApplicationFlow,\n onDone: [\n {\n target: OID4VCIMachineStates.aborted,\n cond: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<FirstPartyMachineStateTypes>): boolean =>\n _event.data === FirstPartyMachineStateTypes.aborted,\n },\n {\n target: OID4VCIMachineStates.declined,\n cond: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<FirstPartyMachineStateTypes>): boolean =>\n _event.data === FirstPartyMachineStateTypes.declined,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n actions: assign({\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeCodeResponse>) => {\n const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data)\n return { ..._ctx.openID4VCIClientState!, authorizationCodeResponse }\n },\n }),\n },\n ],\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<ErrorDetails>): ErrorDetails => ({\n title: _event.data.title ?? translate('oid4vci_machine_first_party_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.selectCredentials]: {\n id: OID4VCIMachineStates.selectCredentials,\n on: {\n [OID4VCIMachineEvents.SET_SELECTED_CREDENTIALS]: {\n actions: assign({ selectedCredentials: (_ctx: OID4VCIMachineContext, _event: SelectCredentialsEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.transitionFromSelectingCredentials,\n cond: OID4VCIMachineGuards.hasSelectedCredentialsGuard,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.transitionFromSelectingCredentials]: {\n id: OID4VCIMachineStates.transitionFromSelectingCredentials,\n always: [\n {\n target: OID4VCIMachineStates.startFirstPartApplicationFlow,\n cond: OID4VCIMachineGuards.isFirstPartyApplication,\n },\n {\n target: OID4VCIMachineStates.prepareAuthorizationRequest,\n cond: OID4VCIMachineGuards.requireAuthorizationGuard,\n },\n {\n target: OID4VCIMachineStates.verifyPin,\n cond: OID4VCIMachineGuards.requirePinGuard,\n },\n {\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.prepareAuthorizationRequest]: {\n id: OID4VCIMachineStates.prepareAuthorizationRequest,\n invoke: {\n src: OID4VCIMachineServices.prepareAuthorizationRequest,\n onDone: {\n target: OID4VCIMachineStates.initiateAuthorizationRequest,\n actions: assign({\n authorizationCodeURL: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<PrepareAuthorizationResult>) =>\n _event.data.authorizationCodeURL,\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<PrepareAuthorizationResult>) => _event.data.oid4vciClientState,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_prepare_authorization_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.initiateAuthorizationRequest]: {\n id: OID4VCIMachineStates.initiateAuthorizationRequest,\n on: {\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.selectCredentials,\n },\n [OID4VCIMachineEvents.INVOKED_AUTHORIZATION_CODE_REQUEST]: {\n target: OID4VCIMachineStates.waitForAuthorizationResponse,\n },\n },\n },\n [OID4VCIMachineStates.waitForAuthorizationResponse]: {\n id: OID4VCIMachineStates.waitForAuthorizationResponse,\n on: {\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.initiateAuthorizationRequest,\n },\n [OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE]: {\n actions: assign({\n openID4VCIClientState: (_ctx: OID4VCIMachineContext, _event: AuthorizationResponseEvent) => {\n const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data)\n return { ..._ctx.openID4VCIClientState!, authorizationCodeResponse }\n },\n }),\n },\n },\n always: [\n {\n cond: OID4VCIMachineGuards.hasAuthorizationResponse,\n target: OID4VCIMachineStates.getCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.verifyPin]: {\n id: OID4VCIMachineStates.verifyPin,\n initial: OID4VCIMachineVerifyPinStates.idle,\n on: {\n [OID4VCIMachineEvents.SET_VERIFICATION_CODE]: {\n target: `.${OID4VCIMachineVerifyPinStates.next}`,\n actions: assign({ verificationCode: (_ctx: OID4VCIMachineContext, _event: VerificationCodeEvent) => _event.data }),\n },\n [OID4VCIMachineEvents.PREVIOUS]: [\n {\n target: OID4VCIMachineStates.selectCredentials,\n cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard,\n },\n {\n target: OID4VCIMachineStates.aborted,\n },\n ],\n },\n states: {\n [OID4VCIMachineVerifyPinStates.idle]: {},\n [OID4VCIMachineVerifyPinStates.next]: {\n always: {\n target: `#${OID4VCIMachineStates.getCredentials}`,\n cond: OID4VCIMachineGuards.verificationCodeGuard,\n },\n },\n },\n },\n [OID4VCIMachineStates.getCredentials]: {\n id: OID4VCIMachineStates.getCredentials,\n invoke: {\n src: OID4VCIMachineServices.getCredentials,\n onDone: {\n target: OID4VCIMachineStates.verifyCredentials,\n actions: assign({\n credentialsToAccept: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Array<MappedCredentialToAccept>>) => _event.data,\n }),\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_retrieve_credentials_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n exit: assign({ verificationCode: undefined }),\n },\n [OID4VCIMachineStates.verifyCredentials]: {\n id: OID4VCIMachineStates.verifyCredentials,\n invoke: {\n src: OID4VCIMachineServices.assertValidCredentials,\n onDone: {\n target: OID4VCIMachineStates.transitionFromWalletInput,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_verify_credentials_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.transitionFromWalletInput]: {\n id: OID4VCIMachineStates.transitionFromWalletInput,\n always: [\n {\n target: OID4VCIMachineStates.addContactIdentity,\n cond: OID4VCIMachineGuards.hasNoContactIdentityGuard,\n },\n {\n target: OID4VCIMachineStates.reviewCredentials,\n },\n ],\n },\n [OID4VCIMachineStates.addContactIdentity]: {\n id: OID4VCIMachineStates.addContactIdentity,\n invoke: {\n src: OID4VCIMachineServices.addContactIdentity,\n onDone: {\n target: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,\n actions: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Identity>): void => {\n _ctx.contact?.identities.push(_event.data)\n },\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_add_contact_identity_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.addIssuerBrandingAfterIdentity]: {\n id: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,\n invoke: {\n src: OID4VCIMachineServices.storeIssuerBranding,\n onDone: {\n target: OID4VCIMachineStates.reviewCredentials,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_issuer_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.reviewCredentials]: {\n id: OID4VCIMachineStates.reviewCredentials,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.storeCredentialBranding,\n },\n [OID4VCIMachineEvents.DECLINE]: {\n target: OID4VCIMachineStates.declined,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.aborted,\n },\n },\n },\n [OID4VCIMachineStates.storeCredentialBranding]: {\n id: OID4VCIMachineStates.storeCredentialBranding,\n invoke: {\n src: OID4VCIMachineServices.storeCredentialBranding,\n onDone: {\n target: OID4VCIMachineStates.storeCredentials,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_credential_branding_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.storeCredentials]: {\n id: OID4VCIMachineStates.storeCredentials,\n invoke: {\n src: OID4VCIMachineServices.storeCredentials,\n onDone: {\n target: OID4VCIMachineStates.done,\n },\n onError: {\n target: OID4VCIMachineStates.handleError,\n actions: assign({\n error: (_ctx: OID4VCIMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_store_credential_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [OID4VCIMachineStates.handleError]: {\n id: OID4VCIMachineStates.handleError,\n on: {\n [OID4VCIMachineEvents.NEXT]: {\n target: OID4VCIMachineStates.error,\n },\n [OID4VCIMachineEvents.PREVIOUS]: {\n target: OID4VCIMachineStates.error,\n },\n },\n },\n [OID4VCIMachineStates.aborted]: {\n id: OID4VCIMachineStates.aborted,\n type: 'final',\n },\n [OID4VCIMachineStates.declined]: {\n id: OID4VCIMachineStates.declined,\n type: 'final',\n },\n [OID4VCIMachineStates.error]: {\n id: OID4VCIMachineStates.error,\n type: 'final',\n },\n [OID4VCIMachineStates.done]: {\n id: OID4VCIMachineStates.done,\n type: 'final',\n },\n },\n })\n}\n\nexport class OID4VCIMachine {\n static async newInstance(opts: OID4VCIMachineInstanceOpts, context: RequiredContext): Promise<{ interpreter: OID4VCIMachineInterpreter }> {\n const interpreter: OID4VCIMachineInterpreter = interpret(\n createOID4VCIMachine(opts).withConfig({\n services: {\n ...opts?.services,\n },\n guards: {\n oid4vciHasNoContactGuard,\n oid4vciCredentialsToSelectRequiredGuard,\n oid4vciRequirePinGuard,\n oid4vciHasNoContactIdentityGuard,\n oid4vciVerificationCodeGuard,\n oid4vciHasContactGuard,\n oid4vciCreateContactGuard,\n oid4vciHasSelectedCredentialsGuard,\n oid4vciRequireAuthorizationGuard,\n oid4vciNoAuthorizationGuard,\n oid4vciHasAuthorizationResponse,\n oid4vciIsOIDFOriginGuard,\n oid4vciContactHasLowTrustGuard,\n oid4vciIsFirstPartyApplication,\n ...opts?.guards,\n },\n }),\n )\n\n if (typeof opts?.subscription === 'function') {\n interpreter.onTransition(opts.subscription)\n }\n if (opts?.requireCustomNavigationHook !== true) {\n if (typeof opts?.stateNavigationListener === 'function') {\n interpreter.onTransition((snapshot: OID4VCIMachineState): void => {\n if (opts?.stateNavigationListener) {\n opts.stateNavigationListener(interpreter, snapshot)\n }\n })\n }\n }\n\n return { interpreter }\n }\n}\n","import i18n, { Scope, TranslateOptions } from 'i18n-js'\nimport memoize from 'lodash.memoize'\nimport { SupportedLanguage } from '../types/IOID4VCIHolder'\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 { DynamicRegistrationClientMetadata } from '@sphereon/oid4vc-common'\nimport { OpenID4VCIClientState, OpenID4VCIClientV1_0_15 } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationRequestOpts,\n AuthorizationResponse,\n AuthorizationServerClientOpts,\n AuthzFlowType,\n CredentialConfigurationSupported,\n CredentialOfferRequestWithBaseUrl,\n CredentialResponse,\n CredentialResponseV1_0_15,\n CredentialsSupportedDisplay,\n EndpointMetadataResult,\n ExperimentalSubjectIssuance,\n IssuerCredentialSubject,\n MetadataDisplay,\n NotificationRequest,\n} from '@sphereon/oid4vci-common'\nimport { CreateOrGetIdentifierOpts, IdentifierProviderOpts, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n IIdentifierResolution,\n ManagedIdentifierMethod,\n ManagedIdentifierOptsOrResult,\n ManagedIdentifierResult,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { IJwtService } from '@sphereon/ssi-sdk-ext.jwt-service'\nimport { IContactManager } from '@sphereon/ssi-sdk.contact-manager'\nimport { ICredentialStore } from '@sphereon/ssi-sdk.credential-store'\nimport { ICredentialValidation, SchemaValidation } from '@sphereon/ssi-sdk.credential-validation'\nimport {\n DigitalCredential,\n IBasicCredentialClaim,\n IBasicCredentialLocaleBranding,\n IBasicIssuerLocaleBranding,\n Identity,\n IIssuerLocaleBranding,\n Party,\n} from '@sphereon/ssi-sdk.data-store-types'\nimport { IIssuanceBranding } from '@sphereon/ssi-sdk.issuance-branding'\nimport { ImDLMdoc } from '@sphereon/ssi-sdk.mdl-mdoc'\nimport { ISDJwtPlugin } from '@sphereon/ssi-sdk.sd-jwt'\nimport { IDidAuthSiopOpAuthenticator } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport {\n HasherSync,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n OriginalVerifiableCredential,\n SdJwtClaimMetadata,\n SdJwtTypeDisplayMetadata,\n W3CVerifiableCredential,\n WrappedVerifiableCredential,\n WrappedVerifiablePresentation,\n} from '@sphereon/ssi-types'\nimport {\n IAgentContext,\n ICredentialIssuer,\n ICredentialVerifier,\n IDIDManager,\n IKeyManager,\n IPluginMethodMap,\n IResolver,\n TAgent,\n TKeyType,\n VerificationPolicies,\n} from '@veramo/core'\nimport { BaseActionObject, Interpreter, ResolveTypegenMeta, ServiceMap, State, StateMachine, TypegenDisabled } from 'xstate'\nimport { FirstPartyMachineStateNavigationListener } from './FirstPartyMachine'\n\nexport interface IOID4VCIHolder extends IPluginMethodMap {\n oid4vciHolderGetIssuerMetadata(args: GetIssuerMetadataArgs, context: RequiredContext): Promise<EndpointMetadataResult>\n\n oid4vciHolderGetMachineInterpreter(args: GetMachineArgs, context: RequiredContext): Promise<OID4VCIMachine> // FIXME is using GetMachineArgs as args but the function uses OID4VCIMachineInstanceOpts\n\n oid4vciHolderStart(args: PrepareStartArgs, context: RequiredContext): Promise<StartResult>\n\n oid4vciHolderCreateCredentialsToSelectFrom(\n args: CreateCredentialsToSelectFromArgs,\n context: RequiredContext,\n ): Promise<Array<CredentialToSelectFromResult>>\n\n oid4vciHolderPrepareAuthorizationRequest(args: PrepareAuthorizationRequestArgs, context: RequiredContext): Promise<PrepareAuthorizationResult>\n oid4vciHolderGetContact(args: GetContactArgs, context: RequiredContext): Promise<Party | undefined>\n\n oid4vciHolderGetCredentials(args: GetCredentialsArgs, context: RequiredContext): Promise<Array<MappedCredentialToAccept>>\n\n oid4vciHolderGetCredential(args: GetCredentialArgs, context: RequiredContext): Promise<MappedCredentialToAccept>\n\n oid4vciHolderAddContactIdentity(args: AddContactIdentityArgs, context: RequiredContext): Promise<Identity>\n\n oid4vciHolderAssertValidCredentials(args: AssertValidCredentialsArgs, context: RequiredContext): Promise<Array<VerificationResult>>\n\n oid4vciHolderGetIssuerBranding(\n args: GetIssuerBrandingArgs,\n context: RequiredContext,\n ): Promise<Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>>\n\n oid4vciHolderStoreIssuerBranding(args: StoreIssuerBrandingArgs, context: RequiredContext): Promise<void>\n\n oid4vciHolderStoreCredentialBranding(args: StoreCredentialBrandingArgs, context: RequiredContext): Promise<void>\n\n oid4vciHolderStoreCredentials(args: StoreCredentialsArgs, context: RequiredContext): Promise<void>\n}\n\nexport type OID4VCIHolderOptions = {\n onContactIdentityCreated?: (args: OnContactIdentityCreatedArgs) => Promise<void>\n onCredentialStored?: (args: OnCredentialStoredArgs) => Promise<void>\n onIdentifierCreated?: (args: OnIdentifierCreatedArgs) => Promise<void>\n onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n vcFormatPreferences?: Array<string>\n jsonldCryptographicSuitePreferences?: Array<string>\n defaultAuthorizationRequestOptions?: AuthorizationRequestOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n jwtCryptographicSuitePreferences?: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n hasher?: HasherSync\n}\n\nexport type OnContactIdentityCreatedArgs = {\n contactId: string\n identity: Identity\n}\n\nexport type GetIssuerMetadataArgs = {\n issuer: string\n errorOnNotFound?: boolean\n}\n\nexport type OnCredentialStoredArgs = {\n credential: DigitalCredential\n vcHash: string\n}\n\nexport type OnIdentifierCreatedArgs = {\n identifier: ManagedIdentifierResult\n}\n\nexport type GetMachineArgs = {\n requestData: RequestData\n walletType: WalletType\n trustAnchors?: Array<string>\n authorizationRequestOpts?: AuthorizationRequestOpts\n clientOpts?: AuthorizationServerClientOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: Partial<IssuanceOpts>\n stateNavigationListener?: OID4VCIMachineStateNavigationListener\n firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n}\n\nexport type PrepareStartArgs = Pick<\n OID4VCIMachineContext,\n 'requestData' | 'authorizationRequestOpts' | 'didMethodPreferences' | 'issuanceOpt' | 'accessTokenOpts'\n>\nexport type PrepareAuthorizationRequestArgs = Pick<OID4VCIMachineContext, 'openID4VCIClientState' | 'contact'>\nexport type CreateCredentialsToSelectFromArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsSupported' | 'credentialBranding' | 'selectedCredentials' | 'locale' | 'openID4VCIClientState'\n>\nexport type GetContactArgs = Pick<OID4VCIMachineContext, 'serverMetadata'>\nexport type GetCredentialsArgs = Pick<\n OID4VCIMachineContext,\n 'verificationCode' | 'openID4VCIClientState' | 'selectedCredentials' | 'didMethodPreferences' | 'issuanceOpt' | 'accessTokenOpts' | 'walletType'\n>\nexport type AddContactIdentityArgs = Pick<OID4VCIMachineContext, 'credentialsToAccept' | 'contact'>\nexport type GetIssuerBrandingArgs = Pick<OID4VCIMachineContext, 'serverMetadata' | 'contact'>\nexport type StoreIssuerBrandingArgs = Pick<OID4VCIMachineContext, 'issuerBranding' | 'contact'>\nexport type AssertValidCredentialsArgs = Pick<OID4VCIMachineContext, 'credentialsToAccept' | 'issuanceOpt'>\nexport type StoreCredentialBrandingArgs = Pick<\n OID4VCIMachineContext,\n 'serverMetadata' | 'credentialBranding' | 'selectedCredentials' | 'credentialsToAccept'\n>\nexport type StoreCredentialsArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsToAccept' | 'serverMetadata' | 'credentialsSupported' | 'openID4VCIClientState' | 'selectedCredentials' | 'issuanceOpt'\n>\nexport type SendNotificationArgs = Pick<\n OID4VCIMachineContext,\n 'credentialsToAccept' | 'serverMetadata' | 'credentialsSupported' | 'openID4VCIClientState'\n> & { notificationRequest?: NotificationRequest; stored: boolean }\nexport type GetFederationTrustArgs = Pick<OID4VCIMachineContext, 'requestData' | 'trustAnchors' | 'serverMetadata'>\nexport type StartFirstPartApplicationMachine = Pick<OID4VCIMachineContext, 'openID4VCIClientState' | 'contact'> & {\n stateNavigationListener?: FirstPartyMachineStateNavigationListener\n}\n\nexport enum OID4VCIHolderEvent {\n CONTACT_IDENTITY_CREATED = 'contact_identity_created',\n CREDENTIAL_STORED = 'credential_stored',\n IDENTIFIER_CREATED = 'identifier_created',\n}\n\nexport type RequestData = {\n credentialOffer?: CredentialOfferRequestWithBaseUrl // This object needs to be created/prepared with the OID4VCI credential offer client\n code?: string // Authorization code\n uri: string // Either a credential offer URI, or issuer URI. If a credential offer URI. If a credential offer URI it is suggested to include the credential offer, otherwise we try to detect it ourselves\n existingClientState?: string // Allows us to start with an existing client state. Meaning someone had a client instance before starting the flow\n createAuthorizationRequestURL?: boolean // Create or do not create an authorization request URL. The default is true\n flowType?: AuthzFlowType // Force a particular flow type if there is an option.\n [x: string]: any\n}\n\nexport enum SupportedLanguage {\n ENGLISH = 'en',\n DUTCH = 'nl',\n}\n\nexport type VerifyCredentialToAcceptArgs = {\n mappedCredential: MappedCredentialToAccept\n onVerifyEBSICredentialIssuer?: (args: VerifyEBSICredentialIssuerArgs) => Promise<VerifyEBSICredentialIssuerResult>\n hasher?: HasherSync\n schemaValidation?: SchemaValidation\n context: RequiredContext\n}\n\nexport type MappedCredentialToAccept = ExperimentalSubjectIssuance & {\n correlationId: string\n types: string[]\n credentialToAccept: CredentialToAccept\n uniformVerifiableCredential: IVerifiableCredential\n rawVerifiableCredential: W3CVerifiableCredential\n}\n\nexport type OID4VCIMachineContext = {\n authorizationRequestOpts?: AuthorizationRequestOpts\n accessTokenOpts?: AccessTokenOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: IssuanceOpts\n trustAnchors: Array<string>\n requestData?: RequestData // TODO WAL-673 fix type as this is not always a qr code (deeplink)\n locale?: string\n authorizationCodeURL?: string\n issuerBranding?: Array<IIssuerLocaleBranding | IBasicIssuerLocaleBranding>\n credentialBranding?: Record<string, Array<IBasicCredentialLocaleBranding>>\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata?: EndpointMetadataResult\n openID4VCIClientState?: OpenID4VCIClientState\n credentialToSelectFrom: Array<CredentialToSelectFromResult>\n contactAlias: string\n walletType: WalletType\n contact?: Party\n selectedCredentials: Array<string>\n credentialsToAccept: Array<MappedCredentialToAccept>\n verificationCode?: string // TODO WAL-672 refactor to not store verificationCode in the context\n hasContactConsent: boolean\n trustedAnchors?: Array<string>\n error?: ErrorDetails\n}\n\nexport enum OID4VCIMachineStates {\n start = 'start',\n createCredentialsToSelectFrom = 'createCredentialsToSelectFrom',\n getContact = 'getContact',\n transitionFromSetup = 'transitionFromSetup',\n getFederationTrust = 'getFederationTrust',\n reviewContact = 'reviewContact',\n addContact = 'addContact',\n getIssuerBranding = 'getIssuerBranding',\n storeIssuerBranding = 'storeIssuerBranding',\n addIssuerBrandingAfterIdentity = 'addIssuerBrandingAfterIdentity',\n transitionFromContactSetup = 'transitionFromContactSetup',\n startFirstPartApplicationFlow = 'startFirstPartApplicationFlow',\n selectCredentials = 'selectCredentials',\n transitionFromSelectingCredentials = 'transitionFromSelectingCredentials',\n verifyPin = 'verifyPin',\n prepareAuthorizationRequest = 'prepareAuthorizationRequest',\n initiateAuthorizationRequest = 'initiateAuthorizationRequest',\n waitForAuthorizationResponse = 'waitForAuthorizationResponse',\n getCredentials = 'getCredentials',\n transitionFromWalletInput = 'transitionFromWalletInput',\n addContactIdentity = 'addContactIdentity',\n reviewCredentials = 'reviewCredentials',\n verifyCredentials = 'verifyCredentials',\n storeCredentialBranding = 'storeCredentialBranding',\n storeCredentials = 'storeCredentials',\n handleError = 'handleError',\n aborted = 'aborted',\n declined = 'declined',\n error = 'error',\n done = 'done',\n}\n\nexport enum OID4VCIMachineAddContactStates {\n idle = 'idle',\n next = 'next',\n}\n\nexport enum OID4VCIMachineVerifyPinStates {\n idle = 'idle',\n next = 'next',\n}\n\nexport type OID4VCIMachineInterpreter = Interpreter<\n OID4VCIMachineContext,\n any,\n OID4VCIMachineEventTypes,\n { value: any; context: OID4VCIMachineContext },\n any\n>\n\nexport type OID4VCIMachineState = State<\n OID4VCIMachineContext,\n OID4VCIMachineEventTypes,\n any,\n {\n value: any\n context: OID4VCIMachineContext\n },\n any\n>\n\nexport type OID4VCIStateMachine = StateMachine<\n OID4VCIMachineContext,\n any,\n OID4VCIMachineEventTypes,\n { value: any; context: OID4VCIMachineContext },\n BaseActionObject,\n ServiceMap,\n ResolveTypegenMeta<TypegenDisabled, OID4VCIMachineEventTypes, BaseActionObject, ServiceMap>\n>\n\nexport type CreateOID4VCIMachineOpts = {\n requestData: RequestData\n walletType: WalletType\n machineName?: string\n locale?: string\n trustAnchors?: Array<string>\n stateDefinition?: OID4VCIMachineState\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n accessTokenOpts?: AccessTokenOpts\n issuanceOpt?: IssuanceOpts\n}\n\nexport type OID4VCIMachineStateNavigationListener = (\n oid4vciMachine: OID4VCIMachineInterpreter,\n state: OID4VCIMachineState,\n navigation?: any,\n) => Promise<void>\n\nexport type OID4VCIMachineInstanceOpts = {\n services?: any\n guards?: any\n subscription?: () => void\n requireCustomNavigationHook?: boolean\n authorizationRequestOpts?: AuthorizationRequestOpts\n didMethodPreferences?: Array<SupportedDidMethodEnum>\n issuanceOpt?: IssuanceOpts // restrict the issuance to these opts\n stateNavigationListener?: OID4VCIMachineStateNavigationListener\n firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n} & CreateOID4VCIMachineOpts\n\nexport type OID4VCIProviderProps = {\n children?: any\n customOID4VCIInstance?: OID4VCIMachineInterpreter\n}\n\nexport type OID4VCIContext = {\n oid4vciInstance?: OID4VCIMachineInterpreter\n}\n\nexport type OID4VCIMachineNavigationArgs = {\n oid4vciMachine: OID4VCIMachineInterpreter\n state: OID4VCIMachineState\n navigation: any\n onNext?: () => void\n onBack?: () => void\n}\n\nexport enum OID4VCIMachineEvents {\n NEXT = 'NEXT',\n PREVIOUS = 'PREVIOUS',\n DECLINE = 'DECLINE',\n CREATE_CONTACT = 'CREATE_CONTACT',\n SET_VERIFICATION_CODE = 'SET_VERIFICATION_CODE',\n SET_CONTACT_ALIAS = 'SET_CONTACT_ALIAS',\n SET_CONTACT_CONSENT = 'SET_CONTACT_CONSENT',\n SET_SELECTED_CREDENTIALS = 'SET_SELECTED_CREDENTIALS',\n SET_AUTHORIZATION_CODE_URL = 'SET_AUTHORIZATION_CODE_URL',\n INVOKED_AUTHORIZATION_CODE_REQUEST = 'INVOKED_AUTHORIZATION_CODE_REQUEST',\n PROVIDE_AUTHORIZATION_CODE_RESPONSE = 'PROVIDE_AUTHORIZATION_CODE_RESPONSE',\n}\n\nexport enum OID4VCIMachineGuards {\n hasContactGuard = 'oid4vciHasContactGuard',\n hasNoContactGuard = 'oid4vciHasNoContactGuard',\n credentialsToSelectRequiredGuard = 'oid4vciCredentialsToSelectRequiredGuard',\n requirePinGuard = 'oid4vciRequirePinGuard',\n requireAuthorizationGuard = 'oid4vciRequireAuthorizationGuard',\n noAuthorizationGuard = 'oid4vciNoAuthorizationGuard',\n hasNonceEndpointGuard = 'oid4vciHasNonceEndpointGuard ',\n hasAuthorizationResponse = 'oid4vciHasAuthorizationResponse',\n hasNoContactIdentityGuard = 'oid4vciHasNoContactIdentityGuard',\n verificationCodeGuard = 'oid4vciVerificationCodeGuard',\n createContactGuard = 'oid4vciCreateContactGuard',\n hasSelectedCredentialsGuard = 'oid4vciHasSelectedCredentialsGuard',\n isOIDFOriginGuard = 'oid4vciIsOIDFOriginGuard',\n contactHasLowTrustGuard = 'oid4vciContactHasLowTrustGuard',\n isFirstPartyApplication = 'oid4vciIsFirstPartyApplication',\n}\n\nexport enum OID4VCIMachineServices {\n start = 'start',\n getContact = 'getContact',\n getFederationTrust = 'getFederationTrust',\n addContactIdentity = 'addContactIdentity',\n createCredentialsToSelectFrom = 'createCredentialsToSelectFrom',\n prepareAuthorizationRequest = 'prepareAuthorizationRequest',\n getIssuerBranding = 'getIssuerBranding',\n storeIssuerBranding = 'storeIssuerBranding',\n getCredentials = 'getCredentials',\n assertValidCredentials = 'assertValidCredentials',\n storeCredentialBranding = 'storeCredentialBranding',\n sendNotification = 'sendNotification',\n storeCredentials = 'storeCredentials',\n startFirstPartApplicationFlow = 'startFirstPartApplicationFlow',\n}\n\nexport type OID4VCIMachineServiceDefinitions = Record<keyof typeof OID4VCIMachineServices, (...args: Array<any>) => any>\n\nexport type NextEvent = { type: OID4VCIMachineEvents.NEXT }\nexport type PreviousEvent = { type: OID4VCIMachineEvents.PREVIOUS }\nexport type DeclineEvent = { type: OID4VCIMachineEvents.DECLINE }\nexport type CreateContactEvent = { type: OID4VCIMachineEvents.CREATE_CONTACT; data: Party }\nexport type SelectCredentialsEvent = { type: OID4VCIMachineEvents.SET_SELECTED_CREDENTIALS; data: Array<string> }\nexport type VerificationCodeEvent = { type: OID4VCIMachineEvents.SET_VERIFICATION_CODE; data: string }\nexport type ContactConsentEvent = { type: OID4VCIMachineEvents.SET_CONTACT_CONSENT; data: boolean }\nexport type ContactAliasEvent = { type: OID4VCIMachineEvents.SET_CONTACT_ALIAS; data: string }\nexport type SetAuthorizationCodeURLEvent = { type: OID4VCIMachineEvents.SET_AUTHORIZATION_CODE_URL; data: string }\nexport type InvokeAuthorizationRequestEvent = { type: OID4VCIMachineEvents.INVOKED_AUTHORIZATION_CODE_REQUEST; data: string }\nexport type AuthorizationResponseEvent = { type: OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE; data: string | AuthorizationResponse }\n\nexport type OID4VCIMachineEventTypes =\n | NextEvent\n | PreviousEvent\n | DeclineEvent\n | CreateContactEvent\n | SelectCredentialsEvent\n | VerificationCodeEvent\n | ContactConsentEvent\n | ContactAliasEvent\n | SetAuthorizationCodeURLEvent\n | InvokeAuthorizationRequestEvent\n | AuthorizationResponseEvent\n\nexport type ErrorDetails = {\n title: string\n message: string\n // TODO WAL-676 would be nice if we can bundle these details fields into a new type so that we can check on this field instead of the 2 separately\n detailsTitle?: string\n detailsMessage?: string\n stack?: string\n}\n\nexport enum RequestType {\n OPENID_INITIATE_ISSUANCE = 'openid-initiate-issuance',\n OPENID_CREDENTIAL_OFFER = 'openid-credential-offer',\n URL = 'URL',\n}\n\nexport type CredentialToSelectFromResult = ExperimentalSubjectIssuance & {\n id: string\n credentialId: string\n credentialTypes: Array<string>\n credentialAlias: string\n isSelected: boolean\n}\n\nexport type OID4VCIMachine = {\n interpreter: OID4VCIMachineInterpreter\n}\n\nexport type StartResult = {\n credentialBranding?: Record<string, Array<IBasicCredentialLocaleBranding>>\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata: EndpointMetadataResult\n oid4vciClientState: OpenID4VCIClientState\n}\n\nexport type PrepareAuthorizationResult = {\n authorizationCodeURL?: string\n oid4vciClientState: OpenID4VCIClientState\n}\n\nexport type SelectAppLocaleBrandingArgs = {\n locale?: string\n localeBranding?: Array<IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding>\n}\n\nexport type IssuanceOpts = CredentialConfigurationSupported & {\n credentialConfigurationId?: string // Explicit ID for a credential\n supportedBindingMethods: ManagedIdentifierMethod[]\n supportedPreferredDidMethod?: SupportedDidMethodEnum\n schemaValidation?: SchemaValidation\n // todo: rename, now we have generic identifiers\n identifier?: ManagedIdentifierOptsOrResult\n // todo: replace by signature alg, so we can determine applicable key types instead of determining up front. Use proof_types_supported\n keyType?: TKeyType\n codecName?: string\n kms?: string\n}\n\nexport type VerificationResult = {\n result: boolean\n source: WrappedVerifiableCredential | WrappedVerifiablePresentation\n subResults: Array<VerificationSubResult>\n error?: string | undefined\n errorDetails?: string\n}\n\nexport type VerificationSubResult = {\n result: boolean\n error?: string\n errorDetails?: string\n}\n\nexport type CredentialToAccept = {\n id?: string\n types: string[]\n issuanceOpt: IssuanceOpts\n credentialResponse: CredentialResponseV1_0_15 | CredentialResponse\n}\n\nexport type GetCredentialConfigsSupportedArgs = {\n client: OpenID4VCIClientV1_0_15\n vcFormatPreferences: Array<string>\n format?: Array<string>\n types?: Array<Array<string>>\n configurationIds?: Array<string>\n}\n\n/**\n * Please note that this method is restricting the results to one set of types or configurationId.\n * It can potentially return multiple results mainly because of different formats.\n */\nexport type GetCredentialConfigsSupportedBySingleTypeOrIdArgs = {\n client: OpenID4VCIClientV1_0_15\n vcFormatPreferences: Array<string>\n format?: string[]\n types?: string[]\n configurationId?: string\n}\n\nexport type GetCredentialBrandingArgs = {\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n context: RequiredContext\n}\n\nexport type GetBasicIssuerLocaleBrandingArgs = {\n display: MetadataDisplay[]\n dynamicRegistrationClientMetadata?: DynamicRegistrationClientMetadataDisplay\n context: RequiredContext\n}\n\nexport type GetPreferredCredentialFormatsArgs = {\n credentials: Record<string, CredentialConfigurationSupported>\n vcFormatPreferences: Array<string>\n}\n\nexport type MapCredentialToAcceptArgs = {\n credentialToAccept: CredentialToAccept\n hasher?: HasherSync\n}\n\nexport type GetDefaultIssuanceOptsArgs = {\n credentialSupported: CredentialConfigurationSupported\n opts: DefaultIssuanceOpts\n context: RequiredContext\n}\n\nexport type DefaultIssuanceOpts = {\n client: OpenID4VCIClientV1_0_15\n}\n\nexport type GetIdentifierArgs = {\n issuanceOpt: IssuanceOpts\n context: RequiredContext\n}\n\nexport type GetAuthenticationKeyArgs = {\n identifier: ManagedIdentifierOptsOrResult\n offlineWhenNoDIDRegistered?: boolean\n noVerificationMethodFallback?: boolean\n context: IAgentContext<IResolver & IDIDManager & IKeyManager>\n}\n\nexport type GetOrCreatePrimaryIdentifierArgs = {\n context: RequiredContext\n opts?: CreateOrGetIdentifierOpts\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 CreateIdentifierCreateOpts = {\n kms?: string\n alias?: string\n options?: IdentifierProviderOpts\n}\n\nexport type GetIssuanceOptsArgs = {\n client: OpenID4VCIClientV1_0_15\n credentialsSupported: Record<string, CredentialConfigurationSupported>\n serverMetadata: EndpointMetadataResult\n context: RequiredContext\n didMethodPreferences: Array<SupportedDidMethodEnum>\n jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n jsonldCryptographicSuitePreferences: Array<string>\n forceIssuanceOpt?: IssuanceOpts\n}\n\nexport type GetIssuanceDidMethodArgs = {\n credentialSupported: CredentialConfigurationSupported\n client: OpenID4VCIClientV1_0_15\n didMethodPreferences: Array<SupportedDidMethodEnum>\n}\n\nexport type GetIssuanceCryptoSuiteArgs = {\n credentialSupported: CredentialConfigurationSupported\n client: OpenID4VCIClientV1_0_15\n jwtCryptographicSuitePreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString>\n jsonldCryptographicSuitePreferences: Array<string>\n}\n\nexport type GetCredentialArgs = {\n pin?: string\n issuanceOpt: IssuanceOpts\n client: OpenID4VCIClientV1_0_15\n accessTokenOpts?: AccessTokenOpts\n}\n\nexport type AccessTokenOpts = {\n additionalRequestParams?: Record<string, any>\n clientOpts?: AuthorizationServerClientOpts\n}\n\nexport enum IdentifierAliasEnum {\n PRIMARY = 'primary',\n}\n\nexport type CredentialVerificationError = {\n error?: string\n errorDetails?: string\n}\n\nexport type VerifyMdocArgs = { credential: string }\n\nexport type VerifySDJWTCredentialArgs = { credential: string; hasher?: HasherSync }\n\nexport interface VerifyCredentialArgs {\n credential: OriginalVerifiableCredential\n fetchRemoteContexts?: boolean\n policies?: VerificationPolicies\n\n [x: string]: any\n}\n\nexport type IssuerType = 'RootTAO' | 'TAO' | 'TI' | 'Revoked or Undefined'\n\nexport type VerifyEBSICredentialIssuerArgs = {\n wrappedVc: WrappedVerifiableCredential\n issuerType?: IssuerType[]\n}\n\nexport type Attribute = {\n hash: string\n body: string\n issuerType: IssuerType\n tao: string\n rootTao: string\n}\n\nexport type VerifyEBSICredentialIssuerResult = {\n did: string\n attributes: Attribute[]\n}\n\nexport type Oid4vciCredentialLocaleBrandingFromArgs = {\n credentialDisplay: CredentialsSupportedDisplay\n}\n\nexport type SdJwtCredentialLocaleBrandingFromArgs = {\n credentialDisplay: SdJwtTypeDisplayMetadata\n}\n\nexport type SdJwtGetCredentialBrandingFromArgs = {\n credentialDisplay?: Array<SdJwtTypeDisplayMetadata>\n claimsMetadata?: Array<SdJwtClaimMetadata>\n}\n\nexport type SdJwtCredentialClaimLocalesFromArgs = {\n claimsMetadata: Array<SdJwtClaimMetadata>\n}\n\nexport type IssuerLocaleBrandingFromArgs = {\n issuerDisplay: MetadataDisplay\n dynamicRegistrationClientMetadata?: DynamicRegistrationClientMetadataDisplay\n}\n\nexport type Oid4vciGetCredentialBrandingFromArgs = {\n credentialDisplay?: Array<CredentialsSupportedDisplay>\n issuerCredentialSubject?: IssuerCredentialSubject\n}\n\nexport type Oid4vciCredentialDisplayLocalesFromArgs = {\n credentialDisplay: Array<CredentialsSupportedDisplay>\n}\n\nexport type SdJwtCredentialDisplayLocalesFromArgs = {\n credentialDisplay: Array<SdJwtTypeDisplayMetadata>\n}\n\nexport type Oid4vciIssuerCredentialSubjectLocalesFromArgs = {\n issuerCredentialSubject: IssuerCredentialSubject\n}\n\nexport type Oid4vciCombineDisplayLocalesFromArgs = {\n credentialDisplayLocales?: Map<string, CredentialsSupportedDisplay>\n issuerCredentialSubjectLocales?: Map<string, Array<IBasicCredentialClaim>>\n}\n\nexport type SdJwtCombineDisplayLocalesFromArgs = {\n credentialDisplayLocales?: Map<string, SdJwtTypeDisplayMetadata>\n claimsMetadata?: Map<string, Array<IBasicCredentialClaim>>\n}\n\nexport type DynamicRegistrationClientMetadataDisplay = Pick<\n DynamicRegistrationClientMetadata,\n 'client_name' | 'client_uri' | 'contacts' | 'tos_uri' | 'policy_uri' | 'logo_uri'\n>\n\nexport type WalletType = 'NATURAL_PERSON' | 'ORGANIZATIONAL'\n\nexport type DidAgents = TAgent<IResolver & IDIDManager>\n\nexport type RequiredContext = IAgentContext<\n IIssuanceBranding &\n IContactManager &\n ICredentialValidation &\n ICredentialVerifier &\n ICredentialIssuer &\n ICredentialStore &\n IIdentifierResolution &\n IJwtService &\n IDIDManager &\n IResolver &\n IKeyManager &\n ISDJwtPlugin &\n ImDLMdoc &\n IDidAuthSiopOpAuthenticator\n>\n","import { RPRegistrationMetadataPayload } from '@sphereon/did-auth-siop'\nimport { OpenID4VCIClientState } from '@sphereon/oid4vci-client'\nimport { AuthorizationChallengeCodeResponse } from '@sphereon/oid4vci-common'\nimport { UniqueDigitalCredential } from '@sphereon/ssi-sdk.credential-store'\nimport { DidAuthConfig, Party } from '@sphereon/ssi-sdk.data-store-types'\nimport { IIdentifier } from '@veramo/core'\nimport { DcqlQuery } from 'dcql'\nimport { BaseActionObject, Interpreter, ResolveTypegenMeta, ServiceMap, State, StateMachine, StatesConfig, TypegenDisabled } from 'xstate'\nimport { ErrorDetails, RequiredContext } from './IOID4VCIHolder'\n\nexport enum FirstPartyMachineStateTypes {\n sendAuthorizationChallengeRequest = 'sendAuthorizationChallengeRequest',\n sendAuthorizationResponse = 'sendAuthorizationResponse',\n selectCredentials = 'selectCredentials',\n createConfig = 'createConfig',\n getSiopRequest = 'getSiopRequest',\n error = 'error',\n done = 'done',\n aborted = 'aborted',\n declined = 'declined',\n}\n\nexport enum FirstPartyMachineServices {\n sendAuthorizationChallengeRequest = 'sendAuthorizationChallengeRequest',\n sendAuthorizationResponse = 'sendAuthorizationResponse',\n createConfig = 'createConfig',\n getSiopRequest = 'getSiopRequest',\n}\n\nexport type FirstPartyMachineStates = Record<FirstPartyMachineStateTypes, {}>\n\nexport type FirstPartyMachineContext = {\n openID4VCIClientState: OpenID4VCIClientState\n selectedCredentials: Array<UniqueDigitalCredential>\n contact: Party\n authSession?: string\n presentationUri?: string\n identifier?: IIdentifier\n didAuthConfig?: Omit<DidAuthConfig, 'identifier'>\n authorizationRequestData?: SiopV2AuthorizationRequestData\n presentationDuringIssuanceSession?: string\n authorizationCodeResponse?: AuthorizationChallengeCodeResponse\n error?: ErrorDetails\n}\n\nexport enum FirstPartyMachineEvents {\n NEXT = 'NEXT',\n PREVIOUS = 'PREVIOUS',\n DECLINE = 'DECLINE',\n SET_SELECTED_CREDENTIALS = 'SET_SELECTED_CREDENTIALS',\n}\n\nexport type FirstPartyNextEvent = { type: FirstPartyMachineEvents.NEXT }\nexport type FirstPartyPreviousEvent = { type: FirstPartyMachineEvents.PREVIOUS }\nexport type FirstPartyDeclineEvent = { type: FirstPartyMachineEvents.DECLINE }\nexport type FirstPartySelectCredentialsEvent = {\n type: FirstPartyMachineEvents.SET_SELECTED_CREDENTIALS\n data: Array<UniqueDigitalCredential>\n}\n\nexport type FirstPartyMachineEventTypes = FirstPartyNextEvent | FirstPartyPreviousEvent | FirstPartyDeclineEvent | FirstPartySelectCredentialsEvent\n\nexport type FirstPartyMachineStatesConfig = StatesConfig<\n FirstPartyMachineContext,\n {\n states: FirstPartyMachineStates\n },\n FirstPartyMachineEventTypes,\n any\n>\n\nexport type CreateFirstPartyMachineOpts = {\n openID4VCIClientState: OpenID4VCIClientState\n contact: Party\n agentContext: RequiredContext\n machineId?: string\n}\n\nexport type FirstPartyStateMachine = StateMachine<\n FirstPartyMachineContext,\n any,\n FirstPartyMachineEventTypes,\n {\n value: any\n context: FirstPartyMachineContext\n },\n BaseActionObject,\n ServiceMap,\n ResolveTypegenMeta<TypegenDisabled, FirstPartyMachineEventTypes, BaseActionObject, ServiceMap>\n>\n\nexport type FirstPartyMachineInterpreter = Interpreter<\n FirstPartyMachineContext,\n any,\n FirstPartyMachineEventTypes,\n {\n value: any\n context: FirstPartyMachineContext\n },\n any\n>\n\nexport type FirstPartyMachineStateNavigationListener = (\n firstPartyMachine: FirstPartyMachineInterpreter,\n state: FirstPartyMachineState,\n navigation?: any,\n) => Promise<void>\n\nexport type InstanceFirstPartyMachineOpts = {\n services?: any\n guards?: any\n subscription?: () => void\n requireCustomNavigationHook?: boolean\n stateNavigationListener?: FirstPartyMachineStateNavigationListener\n} & CreateFirstPartyMachineOpts\n\nexport type FirstPartyMachineState = State<\n FirstPartyMachineContext,\n FirstPartyMachineEventTypes,\n any,\n {\n value: any\n context: FirstPartyMachineContext\n },\n any\n>\n\nexport type FirstPartyMachineServiceDefinitions = Record<keyof typeof FirstPartyMachineServices, (...args: Array<any>) => any>\n\nexport type SendAuthorizationChallengeRequestArgs = Pick<\n FirstPartyMachineContext,\n 'openID4VCIClientState' | 'authSession' | 'presentationDuringIssuanceSession'\n>\n\nexport type SendAuthorizationResponseArgs = Pick<\n FirstPartyMachineContext,\n 'authSession' | 'presentationUri' | 'didAuthConfig' | 'authorizationRequestData' | 'selectedCredentials'\n>\n\nexport type CreateConfigArgs = Pick<FirstPartyMachineContext, 'presentationUri' | 'identifier'>\n\nexport type GetSiopRequestArgs = Pick<FirstPartyMachineContext, 'didAuthConfig' | 'presentationUri'>\n\nexport type SiopV2AuthorizationRequestData = {\n correlationId: string\n registrationMetadataPayload: RPRegistrationMetadataPayload\n issuer?: string\n name?: string\n uri?: URL\n clientIdScheme?: string\n clientId?: string\n entityId?: string\n dcqlQuery: DcqlQuery\n}\n\nexport type FirstPartyMachineNavigationArgs = {\n firstPartyMachine: FirstPartyMachineInterpreter\n state: FirstPartyMachineState\n navigation: any\n onNext?: () => void\n onBack?: () => void\n}\n","import { LOG } from '@sphereon/oid4vci-client'\nimport {\n AuthorizationChallengeCodeResponse,\n CredentialConfigurationSupported,\n CredentialConfigurationSupportedSdJwtVcV1_0_15,\n CredentialResponse,\n CredentialResponseV1_0_15,\n CredentialSupportedSdJwtVc,\n getSupportedCredentials,\n getTypesFromCredentialSupported,\n getTypesFromObject,\n MetadataDisplay,\n} from '@sphereon/oid4vci-common'\nimport { KeyUse } from '@sphereon/ssi-sdk-ext.did-resolver-jwk'\nimport { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from '@sphereon/ssi-sdk-ext.did-utils'\nimport {\n isIIdentifier,\n isManagedIdentifierDidResult,\n isManagedIdentifierResult,\n ManagedIdentifierMethod,\n ManagedIdentifierResult,\n managedIdentifierToJwk,\n} from '@sphereon/ssi-sdk-ext.identifier-resolution'\nimport { keyTypeFromCryptographicSuite } from '@sphereon/ssi-sdk-ext.key-utils'\nimport { defaultHasher } from '@sphereon/ssi-sdk.core'\nimport { IBasicCredentialLocaleBranding, IBasicIssuerLocaleBranding } from '@sphereon/ssi-sdk.data-store-types'\nimport {\n CredentialMapper,\n Hasher,\n IVerifiableCredential,\n JoseSignatureAlgorithm,\n JoseSignatureAlgorithmString,\n mdocDecodedCredentialToUniformCredential,\n OriginalVerifiableCredential,\n sdJwtDecodedCredentialToUniformCredential,\n SdJwtDecodedVerifiableCredential,\n SdJwtTypeMetadata,\n W3CVerifiableCredential,\n WrappedVerifiableCredential,\n} from '@sphereon/ssi-types'\nimport { asArray } from '@veramo/utils'\nimport { translate } from '../localization/Localization'\nimport { FirstPartyMachine } from '../machines/firstPartyMachine'\nimport { issuerLocaleBrandingFrom, oid4vciGetCredentialBrandingFrom, sdJwtGetCredentialBrandingFrom } from '../mappers/OIDC4VCIBrandingMapper'\nimport { FirstPartyMachineState, FirstPartyMachineStateTypes } from '../types/FirstPartyMachine'\nimport {\n DidAgents,\n GetBasicIssuerLocaleBrandingArgs,\n GetCredentialBrandingArgs,\n GetCredentialConfigsSupportedArgs,\n GetCredentialConfigsSupportedBySingleTypeOrIdArgs,\n GetIdentifierArgs,\n GetIssuanceCryptoSuiteArgs,\n GetIssuanceDidMethodArgs,\n GetIssuanceOptsArgs,\n GetPreferredCredentialFormatsArgs,\n IssuanceOpts,\n MapCredentialToAcceptArgs,\n MappedCredentialToAccept,\n OID4VCIHolderEvent,\n RequiredContext,\n SelectAppLocaleBrandingArgs,\n StartFirstPartApplicationMachine,\n VerificationResult,\n VerifyCredentialToAcceptArgs,\n} from '../types/IOID4VCIHolder'\n\nexport const getCredentialBranding = async (args: GetCredentialBrandingArgs): Promise<Record<string, Array<IBasicCredentialLocaleBranding>>> => {\n const { credentialsSupported, context } = args\n const credentialBranding: Record<string, Array<IBasicCredentialLocaleBranding>> = {}\n await Promise.all(\n Object.entries(credentialsSupported).map(async ([configId, credentialsConfigSupported]): Promise<void> => {\n let sdJwtTypeMetadata: SdJwtTypeMetadata | undefined\n if (credentialsConfigSupported.format === 'dc+sd-jwt') {\n const vct = (<CredentialSupportedSdJwtVc | CredentialConfigurationSupportedSdJwtVcV1_0_15>credentialsConfigSupported).vct\n if (vct.startsWith('http')) {\n try {\n sdJwtTypeMetadata = await context.agent.fetchSdJwtTypeMetadataFromVctUrl({ vct })\n } catch {\n // For now, we are just going to ignore and continue without any branding as we still have a fallback\n }\n }\n }\n let mappedLocaleBranding: Array<IBasicCredentialLocaleBranding> = []\n if (sdJwtTypeMetadata) {\n mappedLocaleBranding = await sdJwtGetCredentialBrandingFrom({\n credentialDisplay: sdJwtTypeMetadata.display,\n claimsMetadata: sdJwtTypeMetadata.claims,\n })\n } else {\n mappedLocaleBranding = await oid4vciGetCredentialBrandingFrom({\n credentialDisplay: credentialsConfigSupported.display,\n issuerCredentialSubject:\n // @ts-ignore // FIXME SPRIND-123 add proper support for type recognition as claim display can be located elsewhere for v13\n credentialsSupported.claims !== undefined ? credentialsConfigSupported.claims : credentialsConfigSupported.credentialSubject,\n })\n }\n // TODO we should make the mapper part of the plugin, so that the logic for getting the branding becomes more clear and easier to use\n const localeBranding = await Promise.all(\n mappedLocaleBranding.map(\n async (localeBranding): Promise<IBasicCredentialLocaleBranding> => await context.agent.ibCredentialLocaleBrandingFrom({ localeBranding }),\n ),\n )\n const defaultCredentialType = 'VerifiableCredential'\n const configSupportedTypes = getTypesFromCredentialSupported(credentialsConfigSupported)\n const credentialTypes: Array<string> = configSupportedTypes.length === 0 ? asArray(defaultCredentialType) : configSupportedTypes\n const filteredCredentialTypes = credentialTypes.filter((type: string): boolean => type !== defaultCredentialType)\n credentialBranding[filteredCredentialTypes[0]] = localeBranding // TODO for now taking the first type\n }),\n )\n\n return credentialBranding\n}\n\nexport const getBasicIssuerLocaleBranding = async (args: GetBasicIssuerLocaleBrandingArgs): Promise<Array<IBasicIssuerLocaleBranding>> => {\n const { display, dynamicRegistrationClientMetadata, context } = args\n return await Promise.all(\n display.map(async (issuerDisplay: MetadataDisplay): Promise<IBasicIssuerLocaleBranding> => {\n // FIXME for now we do not have locale support for dynamicRegistrationClientMetadata, so we add all the metadata to every locale\n const branding = await issuerLocaleBrandingFrom({ issuerDisplay, dynamicRegistrationClientMetadata })\n return context.agent.ibIssuerLocaleBrandingFrom({ localeBranding: branding })\n }),\n )\n}\n\nexport const getCredentialConfigsBasedOnFormatPref = async (\n args: GetPreferredCredentialFormatsArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n const { vcFormatPreferences, credentials } = args\n const prefConfigs = {} as Record<string, CredentialConfigurationSupported>\n Object.entries(credentials).forEach(([key, config]) => {\n const result = !config.format || vcFormatPreferences.map((pref) => pref.toLowerCase()).includes(config.format.toLowerCase())\n if (result) {\n prefConfigs[key] = config\n }\n })\n\n return prefConfigs\n}\n\nexport const selectCredentialLocaleBranding = async (\n args: SelectAppLocaleBrandingArgs,\n): Promise<IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding | undefined> => {\n const { locale, localeBranding } = args\n\n return localeBranding?.find(\n (branding: IBasicCredentialLocaleBranding | IBasicIssuerLocaleBranding) =>\n locale ? branding.locale?.startsWith(locale) || branding.locale === undefined : branding.locale === undefined, // TODO refactor as we have duplicate code\n )\n}\n\nexport const verifyCredentialToAccept = async (args: VerifyCredentialToAcceptArgs): Promise<VerificationResult> => {\n const { mappedCredential, hasher, onVerifyEBSICredentialIssuer, schemaValidation, context } = args\n\n const credential = extractCredentialFromResponse(mappedCredential.credentialToAccept.credentialResponse)\n\n const wrappedVC = CredentialMapper.toWrappedVerifiableCredential(credential, { hasher: hasher ?? defaultHasher })\n if (\n wrappedVC.decoded?.iss?.includes('did:ebsi:') ||\n (typeof wrappedVC.decoded?.vc?.issuer === 'string'\n ? wrappedVC.decoded?.vc?.issuer?.includes('did:ebsi:')\n : wrappedVC.decoded?.vc?.issuer?.existingInstanceId?.includes('did:ebsi:'))\n ) {\n // TODO: Skipping VC validation for EBSI conformance issued credential, as their Issuer is not present in the ledger (sigh)\n // just calling the verifySchema functionality for ebsi credentials\n await context.agent.cvVerifySchema({ credential, hasher, validationPolicy: schemaValidation })\n if (JSON.stringify(wrappedVC.decoded).includes('vc:ebsi:conformance')) {\n return { source: wrappedVC, error: undefined, result: true, subResults: [] } satisfies VerificationResult\n }\n\n if (onVerifyEBSICredentialIssuer) {\n try {\n await onVerifyEBSICredentialIssuer({\n wrappedVc: wrappedVC,\n })\n } catch (e) {\n return { source: wrappedVC, error: e.message, result: true, subResults: [] } satisfies VerificationResult\n }\n }\n }\n\n const verificationResult: VerificationResult = await context.agent.cvVerifyCredential({\n credential,\n hasher,\n // TODO WAL-675 we might want to allow these types of options as part of the context, now we have state machines. Allows us to pre-determine whether these policies apply and whether remote context should be fetched\n fetchRemoteContexts: true,\n policies: {\n schemaValidation: schemaValidation,\n credentialStatus: false,\n expirationDate: false,\n issuanceDate: false,\n },\n })\n\n if (!verificationResult.result || verificationResult.error) {\n return Promise.reject(Error(verificationResult.error ?? translate('oid4vci_machine_credential_verification_failed_message')))\n }\n return verificationResult\n}\n\nexport const mapCredentialToAccept = async (args: MapCredentialToAcceptArgs): Promise<MappedCredentialToAccept> => {\n const { credentialToAccept, hasher } = args\n\n const verifiableCredential = extractCredentialFromResponse(credentialToAccept.credentialResponse) as W3CVerifiableCredential\n\n const wrappedVerifiableCredential: WrappedVerifiableCredential = CredentialMapper.toWrappedVerifiableCredential(\n verifiableCredential as OriginalVerifiableCredential,\n { hasher },\n )\n let uniformVerifiableCredential: IVerifiableCredential\n if (CredentialMapper.isSdJwtDecodedCredential(wrappedVerifiableCredential.credential)) {\n uniformVerifiableCredential = sdJwtDecodedCredentialToUniformCredential(<SdJwtDecodedVerifiableCredential>wrappedVerifiableCredential.credential)\n } else if (CredentialMapper.isSdJwtEncoded(wrappedVerifiableCredential.credential)) {\n if (!hasher) {\n return Promise.reject('a hasher is required for encoded SD-JWT credentials')\n }\n const asyncHasher: Hasher = (data: string | ArrayBuffer | SharedArrayBuffer, algorithm: string) => Promise.resolve(hasher(data, algorithm))\n const decodedSdJwt = await CredentialMapper.decodeSdJwtVcAsync(wrappedVerifiableCredential.credential, asyncHasher)\n uniformVerifiableCredential = sdJwtDecodedCredentialToUniformCredential(<SdJwtDecodedVerifiableCredential>decodedSdJwt)\n } else if (CredentialMapper.isMsoMdocDecodedCredential(wrappedVerifiableCredential.credential)) {\n uniformVerifiableCredential = mdocDecodedCredentialToUniformCredential(wrappedVerifiableCredential.credential)\n } else {\n uniformVerifiableCredential = <IVerifiableCredential>wrappedVerifiableCredential.credential\n }\n\n const correlationId: string =\n typeof uniformVerifiableCredential.issuer === 'string'\n ? uniformVerifiableCredential.issuer\n : CredentialMapper.isSdJwtDecodedCredential(uniformVerifiableCredential)\n ? uniformVerifiableCredential.decodedPayload.iss\n : uniformVerifiableCredential.issuer.id\n\n const credentialResponse = credentialToAccept.credentialResponse as CredentialResponseV1_0_15\n return {\n correlationId,\n credentialToAccept,\n types: credentialToAccept.types,\n rawVerifiableCredential: verifiableCredential,\n uniformVerifiableCredential,\n ...(credentialResponse.credential_subject_issuance && { credential_subject_issuance: credentialResponse.credential_subject_issuance }),\n }\n}\n\nexport const extractCredentialFromResponse = (credentialResponse: CredentialResponse): OriginalVerifiableCredential => {\n let credential: OriginalVerifiableCredential | undefined\n\n if ('credential' in credentialResponse) {\n credential = credentialResponse.credential as OriginalVerifiableCredential\n } else if (\n 'credentials' in credentialResponse &&\n credentialResponse.credentials &&\n Array.isArray(credentialResponse.credentials) &&\n credentialResponse.credentials.length > 0\n ) {\n credential = credentialResponse.credentials[0].credential as OriginalVerifiableCredential // FIXME SSISDK-13 (no multi-credential support yet)\n }\n\n if (!credential) {\n throw new Error('No credential found in credential response')\n }\n\n return credential\n}\n\nexport const getIdentifierOpts = async (args: GetIdentifierArgs): Promise<ManagedIdentifierResult> => {\n const { issuanceOpt, context } = args\n const { identifier: identifierArg } = issuanceOpt\n if (identifierArg && isManagedIdentifierResult(identifierArg)) {\n return identifierArg\n }\n const {\n supportedPreferredDidMethod,\n supportedBindingMethods,\n keyType = 'Secp256r1',\n kms = await context.agent.keyManagerGetDefaultKeyManagementSystem(),\n } = issuanceOpt\n let identifier: ManagedIdentifierResult\n\n if (identifierArg) {\n if (isIIdentifier(identifierArg.identifier)) {\n identifier = await context.agent.identifierManagedGet(identifierArg)\n } else if (!identifierArg.method && issuanceOpt.supportedBindingMethods.includes('jwk')) {\n identifier = await managedIdentifierToJwk(identifierArg, context)\n } else if (identifierArg.method && !supportedBindingMethods.includes(identifierArg.method)) {\n throw Error(`Supplied identifier method ${identifierArg.method} not supported by the issuer: ${supportedBindingMethods.join(',')}`)\n } else {\n identifier = await context.agent.identifierManagedGet(identifierArg)\n }\n }\n const agentContext = { ...context, agent: context.agent as DidAgents }\n\n if (\n (!identifierArg || isIIdentifier(identifierArg.identifier)) &&\n supportedPreferredDidMethod &&\n (!supportedBindingMethods || supportedBindingMethods.length === 0 || supportedBindingMethods.filter((method) => method.startsWith('did')))\n ) {\n // previous code for managing DIDs only\n const { result, created } = await getOrCreatePrimaryIdentifier(agentContext, {\n method: supportedPreferredDidMethod,\n createOpts: {\n options: {\n type: issuanceOpt.keyType,\n use: KeyUse.Signature,\n codecName: issuanceOpt.codecName,\n kms: issuanceOpt.kms,\n },\n },\n })\n identifier = await context.agent.identifierManagedGetByDid({\n identifier: result,\n keyType,\n offlineWhenNoDIDRegistered: result.did.startsWith('did:ebsi:'),\n })\n if (created) {\n await agentContext.agent.emit(OID4VCIHolderEvent.IDENTIFIER_CREATED, { identifier })\n }\n } else if (supportedBindingMethods.includes('jwk')) {\n // todo: we probably should do something similar as with DIDs for re-use/new keys\n const key = await context.agent.keyManagerCreate({ type: keyType, kms, meta: { keyAlias: `key_${keyType}_${Date.now()}` } })\n // TODO. Create/move this to identifier service await agentContext.agent.emit(OID4VCIHolderEvent.IDENTIFIER_CREATED, { key })\n identifier = await managedIdentifierToJwk({ method: 'key', identifier: key, kmsKeyRef: key.kid }, context)\n // } else if (supportedBindingMethods.includes('cose_key')) {\n // // TODO COSE HERE\n // throw Error(`Holder currently does not support binding method: ${supportedBindingMethods.join(',')}`)\n } else {\n throw Error(`Holder currently does not support binding method: ${supportedBindingMethods.join(',')}`)\n }\n args.issuanceOpt.identifier = identifier\n return identifier\n}\n\nexport const getCredentialConfigsSupportedMerged = async (\n args: GetCredentialConfigsSupportedArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n let result = {} as Record<string, CredentialConfigurationSupported>\n ;(await getCredentialConfigsSupported(args)).forEach((supported: Record<string, CredentialConfigurationSupported>) => {\n result = { ...result, ...supported }\n })\n return result\n}\n\nexport const getCredentialConfigsSupported = async (\n args: GetCredentialConfigsSupportedArgs,\n): Promise<Array<Record<string, CredentialConfigurationSupported>>> => {\n const { types, configurationIds } = args\n if (Array.isArray(types) && types.length > 0) {\n return Promise.all(types.map((type) => getCredentialConfigsSupportedBySingleTypeOrId({ ...args, types: type })))\n } else if (Array.isArray(configurationIds) && configurationIds.length > 0) {\n return Promise.all(\n configurationIds.map((configurationId) =>\n getCredentialConfigsSupportedBySingleTypeOrId({\n ...args,\n configurationId,\n types: undefined,\n }),\n ),\n )\n }\n const configs = await getCredentialConfigsSupportedBySingleTypeOrId({\n ...args,\n types: undefined,\n configurationId: undefined,\n })\n return configs && Object.keys(configs).length > 0 ? [configs] : []\n}\n/**\n * Please note that this method only returns configs supported for a single set of credential types or a single config id.\n * If an offer contains multiple formats/types in an array or multiple config ids, you will have to call this method for all of them\n * @param args\n */\nexport const getCredentialConfigsSupportedBySingleTypeOrId = async (\n args: GetCredentialConfigsSupportedBySingleTypeOrIdArgs,\n): Promise<Record<string, CredentialConfigurationSupported>> => {\n const { client, vcFormatPreferences, configurationId } = args\n let { format = undefined, types = undefined } = args\n\n function createIdFromTypes(supported: CredentialConfigurationSupported) {\n const format = supported.format\n const type: string = getTypesFromObject(supported)?.join() ?? ''\n const id = `${type}:${format}`\n return id\n }\n\n if (configurationId) {\n const allSupported = client.getCredentialsSupported(undefined, format)\n return Object.fromEntries(\n Object.entries(allSupported).filter(\n ([id, supported]) => id === configurationId || supported.id === configurationId || createIdFromTypes(supported) === configurationId,\n ),\n )\n }\n\n if (!client.credentialOffer) {\n return Promise.reject(Error('openID4VCIClient has no credentialOffer'))\n }\n if (!types) {\n return Promise.reject(Error('openID4VCIClient has no types'))\n }\n\n const offerSupported = getSupportedCredentials({\n types: [types],\n format,\n version: client.version(),\n issuerMetadata: client.endpointMetadata.credentialIssuerMetadata,\n })\n let allSupported: Record<string, CredentialConfigurationSupported>\n\n if (!Array.isArray(offerSupported)) {\n allSupported = offerSupported\n } else {\n allSupported = {} satisfies Record<string, CredentialConfigurationSupported>\n offerSupported.forEach((supported) => {\n if (supported.id) {\n allSupported[supported.id as string] = supported\n return\n }\n const id = createIdFromTypes(supported)\n allSupported[id] = supported\n })\n }\n\n let credentialConfigsSupported = await getCredentialConfigsBasedOnFormatPref({\n credentials: allSupported,\n vcFormatPreferences,\n })\n if (!credentialConfigsSupported || Object.keys(credentialConfigsSupported).length === 0) {\n LOG.warning(`No matching supported credential found for ${client.getIssuer()}`)\n }\n\n if (client.credentialOffer === undefined) {\n return credentialConfigsSupported\n }\n // Filter configurations based on the credential offer IDs\n const credentialOffer = client.credentialOffer.credential_offer\n\n let credentialsToOffer: Record<string, CredentialConfigurationSupported>\n if ('credential_configuration_ids' in credentialOffer) {\n credentialsToOffer = Object.fromEntries(\n Object.entries(credentialConfigsSupported).filter(([configId, config]) => credentialOffer.credential_configuration_ids.includes(configId)),\n )\n if (Object.keys(credentialsToOffer).length === 0) {\n throw new Error(`No matching supported credential configs found for offer ${credentialOffer.credential_configuration_ids.join(', ')}`)\n }\n } else {\n credentialsToOffer = credentialConfigsSupported\n }\n if (Object.keys(credentialsToOffer).length === 0) {\n // Same check as above, but more generic error message, as it can also apply to below draft 13\n throw new Error(`No matching supported credential configs found for offer`)\n }\n\n return credentialsToOffer\n}\n\nexport const getIssuanceOpts = async (args: GetIssuanceOptsArgs): Promise<Array<IssuanceOpts>> => {\n const {\n client,\n credentialsSupported,\n // serverMetadata,\n context,\n didMethodPreferences,\n jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences,\n forceIssuanceOpt,\n } = args\n\n if (credentialsSupported === undefined || Object.keys(credentialsSupported).length === 0) {\n return Promise.reject(Error('No credentials supported'))\n }\n\n const getIssuanceOpts: Array<Promise<IssuanceOpts>> = Object.values(credentialsSupported).map(async (credentialSupported) => {\n /*if (!serverMetadata?.credentialIssuerMetadata) {\n return await getDefaultIssuanceOpts({ credentialSupported, opts: { client }, context })\n }*/\n\n const cryptographicSuite: string = await getIssuanceCryptoSuite({\n credentialSupported,\n client,\n jwtCryptographicSuitePreferences,\n jsonldCryptographicSuitePreferences,\n })\n const { didMethod, methods } = await getIssuanceMethod({\n credentialSupported,\n client,\n didMethodPreferences,\n })\n if (methods.length == 0) {\n console.log(`Could not determine supported cryptographic_binding_methods_supported, will use DIDs`)\n methods.push('did')\n }\n const issuanceOpt = forceIssuanceOpt\n ? { ...credentialSupported, ...forceIssuanceOpt }\n : ({\n ...credentialSupported,\n supportedPreferredDidMethod: didMethod,\n supportedBindingMethods: methods,\n format: credentialSupported.format,\n keyType: client.isEBSI() ? 'Secp256r1' : keyTypeFromCryptographicSuite({ crv: cryptographicSuite }),\n ...(client.isEBSI() && { codecName: 'EBSI' }),\n } satisfies IssuanceOpts)\n const identifier = await getIdentifierOpts({ issuanceOpt, context })\n if (!client.clientId && isManagedIdentifierDidResult(identifier)) {\n // FIXME: We really should fetch server metadata. Have user select required credentials. Take the first cred to determine a kid when no clientId is present and set that.\n // Needs a preference service for crypto, keys, dids, and clientId, with ecosystem support\n client.clientId = identifier.issuer ?? identifier.did\n }\n return { ...issuanceOpt, identifier }\n })\n\n return await Promise.all(getIssuanceOpts)\n}\n\nexport const getIssuanceMethod = async (\n opts: GetIssuanceDidMethodArgs,\n): Promise<{\n methods: ManagedIdentifierMethod[]\n didMethod?: SupportedDidMethodEnum\n}> => {\n const { client, credentialSupported, didMethodPreferences } = opts\n const { format, cryptographic_binding_methods_supported } = credentialSupported\n let methods: ManagedIdentifierMethod[] = [] // we use the external identifier method, as we should be supporting all values in the server metadata anyway\n if (cryptographic_binding_methods_supported && Array.isArray(cryptographic_binding_methods_supported)) {\n methods = cryptographic_binding_methods_supported as ManagedIdentifierMethod[]\n const didMethods: SupportedDidMethodEnum | undefined = didMethodPreferences.find((method: SupportedDidMethodEnum) =>\n cryptographic_binding_methods_supported.includes(`did:${method.toLowerCase() /*.replace('did:', '')*/}`),\n )\n if (didMethods) {\n return { methods, didMethod: didMethods }\n } else if (cryptographic_binding_methods_supported.includes('did')) {\n return { methods, didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0] }\n } else if (methods.length > 0) {\n return { methods }\n }\n console.warn(\n `We should have been able to determine cryptographic_binding_methods_supported, will fall back to legacy behaviour. This is likely a bug`,\n )\n }\n\n if (client.isEBSI()) {\n return { methods: ['did'], didMethod: SupportedDidMethodEnum.DID_KEY }\n }\n\n // legacy fallback\n methods = ['did']\n if (!format || (format.includes('jwt') && !format?.includes('jwt_vc_json_ld'))) {\n return { methods, didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0] }\n } else {\n // JsonLD\n return { methods, didMethod: didMethodPreferences[0] }\n }\n}\n\nexport const getIssuanceCryptoSuite = async (opts: GetIssuanceCryptoSuiteArgs): Promise<string> => {\n const { client, credentialSupported, jwtCryptographicSuitePreferences, jsonldCryptographicSuitePreferences } = opts\n\n let signing_algs_supported: Array<string>\n if ('proof_types_supported' in credentialSupported && credentialSupported.proof_types_supported) {\n if ('jwt' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.jwt) {\n signing_algs_supported = credentialSupported.proof_types_supported.jwt.proof_signing_alg_values_supported\n } else if ('ldp_vp' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.ldp_vp) {\n signing_algs_supported = credentialSupported.proof_types_supported.ldp_vp.proof_signing_alg_values_supported\n } else if ('cwt' in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.cwt) {\n signing_algs_supported = credentialSupported.proof_types_supported.cwt.proof_signing_alg_values_supported\n console.error('cwt proof type not supported. Likely that errors will occur after this point')\n } else {\n return Promise.reject(Error(`Unsupported proof_types_supported`))\n }\n } else {\n signing_algs_supported = asArray(\n // @ts-ignore // legacy\n credentialSupported.credential_signing_alg_values_supported ?? credentialSupported.proof_signing_alg_values_supported ?? [],\n )\n }\n\n // TODO: Return array, so the wallet/user could choose\n switch (credentialSupported.format) {\n // @ts-ignore legacy value\n case 'jwt':\n case 'jwt_vc_json':\n case 'jwt_vc':\n case 'vc+sd-jwt':\n case 'dc+sd-jwt':\n case 'mso_mdoc': {\n const supportedPreferences: Array<JoseSignatureAlgorithm | JoseSignatureAlgorithmString> = jwtCryptographicSuitePreferences.filter(\n (suite: JoseSignatureAlgorithm | JoseSignatureAlgorithmString) => signing_algs_supported.includes(suite),\n )\n\n if (supportedPreferences.length > 0) {\n return supportedPreferences[0]\n } else if (client.isEBSI()) {\n return JoseSignatureAlgorithm.ES256\n }\n\n // if we cannot find supported cryptographic suites, we just try with the first preference\n const fallback = jwtCryptographicSuitePreferences[0]\n console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`)\n return fallback\n }\n // @ts-ignore\n case 'ldp':\n // @ts-ignore\n case 'jwt_vc_json_ld':\n case 'ldp_vc': {\n const supportedPreferences: Array<string> = jsonldCryptographicSuitePreferences.filter((suite: string) =>\n signing_algs_supported.includes(suite),\n )\n if (supportedPreferences.length > 0) {\n return supportedPreferences[0]\n }\n\n // if we cannot find supported cryptographic suites, we just try with the first preference\n const fallback = jsonldCryptographicSuitePreferences[0]\n console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`)\n return fallback\n }\n default:\n return Promise.reject(Error(`Credential format '${credentialSupported.format}' not supported`))\n }\n}\n\nexport const startFirstPartApplicationMachine = async (\n args: StartFirstPartApplicationMachine,\n context: RequiredContext,\n): Promise<AuthorizationChallengeCodeResponse | string> => {\n const { openID4VCIClientState, stateNavigationListener, contact } = args\n\n if (!openID4VCIClientState) {\n return Promise.reject(Error('Missing openID4VCI client state in context'))\n }\n\n if (!contact) {\n return Promise.reject(Error('Missing contact in context'))\n }\n\n const firstPartyMachineInstance = FirstPartyMachine.newInstance({\n openID4VCIClientState,\n contact,\n agentContext: context,\n stateNavigationListener,\n })\n\n return new Promise((resolve, reject) => {\n try {\n firstPartyMachineInstance.onTransition((state: FirstPartyMachineState) => {\n if (state.matches(FirstPartyMachineStateTypes.done)) {\n const authorizationCodeResponse = state.context.authorizationCodeResponse\n if (!authorizationCodeResponse) {\n reject(Error('No authorizationCodeResponse acquired'))\n }\n resolve(authorizationCodeResponse!)\n } else if (state.matches(FirstPartyMachineStateTypes.aborted)) {\n resolve(FirstPartyMachineStateTypes.aborted)\n } else if (state.matches(FirstPartyMachineStateTypes.declined)) {\n resolve(FirstPartyMachineStateTypes.declined)\n } else if (state.matches(FirstPartyMachineStateTypes.error)) {\n reject(state.context.error)\n }\n })\n firstPartyMachineInstance.start()\n } catch (error) {\n reject(error)\n }\n })\n}\n","import { assign, createMachine, DoneInvokeEvent, interpret } from 'xstate'\nimport { AuthorizationChallengeCodeResponse, AuthorizationChallengeError, AuthorizationChallengeErrorResponse } from '@sphereon/oid4vci-common'\nimport { DidAuthConfig } from '@sphereon/ssi-sdk.data-store-types'\nimport { CreateConfigResult } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport { createConfig, getSiopRequest, sendAuthorizationChallengeRequest, sendAuthorizationResponse } from '../services/FirstPartyMachineServices'\nimport { translate } from '../localization/Localization'\nimport { ErrorDetails } from '../types/IOID4VCIHolder'\nimport {\n CreateConfigArgs,\n CreateFirstPartyMachineOpts,\n FirstPartyMachineContext,\n FirstPartyMachineEvents,\n FirstPartyMachineEventTypes,\n FirstPartyMachineInterpreter,\n FirstPartyMachineServices,\n FirstPartyMachineState,\n FirstPartyMachineStatesConfig,\n FirstPartyMachineStateTypes,\n FirstPartyMachineServiceDefinitions,\n FirstPartyStateMachine,\n GetSiopRequestArgs,\n InstanceFirstPartyMachineOpts,\n SiopV2AuthorizationRequestData,\n SendAuthorizationResponseArgs,\n FirstPartySelectCredentialsEvent,\n} from '../types/FirstPartyMachine'\n\nconst firstPartyMachineStates: FirstPartyMachineStatesConfig = {\n [FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest]: {\n id: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n invoke: {\n src: FirstPartyMachineServices.sendAuthorizationChallengeRequest,\n onDone: {\n target: FirstPartyMachineStateTypes.done,\n actions: assign({\n authorizationCodeResponse: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeCodeResponse>) => _event.data,\n }),\n },\n onError: [\n {\n target: FirstPartyMachineStateTypes.createConfig,\n cond: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>): boolean =>\n _event.data.error === AuthorizationChallengeError.insufficient_authorization,\n actions: assign({\n authSession: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>) => _event.data.auth_session,\n presentationUri: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<AuthorizationChallengeErrorResponse>) =>\n _event.data.presentation,\n }),\n },\n {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_send_authorization_challenge_request_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n ],\n },\n },\n [FirstPartyMachineStateTypes.createConfig]: {\n id: FirstPartyMachineStateTypes.createConfig,\n invoke: {\n src: FirstPartyMachineServices.createConfig,\n onDone: {\n target: FirstPartyMachineStateTypes.getSiopRequest,\n actions: assign({\n didAuthConfig: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<DidAuthConfig>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_create_config_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [FirstPartyMachineStateTypes.getSiopRequest]: {\n id: FirstPartyMachineStateTypes.getSiopRequest,\n invoke: {\n src: FirstPartyMachineServices.getSiopRequest,\n onDone: {\n target: FirstPartyMachineStateTypes.selectCredentials,\n actions: assign({\n authorizationRequestData: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<SiopV2AuthorizationRequestData>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _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 [FirstPartyMachineStateTypes.selectCredentials]: {\n id: FirstPartyMachineStateTypes.selectCredentials,\n on: {\n [FirstPartyMachineEvents.SET_SELECTED_CREDENTIALS]: {\n actions: assign({ selectedCredentials: (_ctx: FirstPartyMachineContext, _event: FirstPartySelectCredentialsEvent) => _event.data }),\n },\n [FirstPartyMachineEvents.NEXT]: {\n target: FirstPartyMachineStateTypes.sendAuthorizationResponse,\n },\n [FirstPartyMachineEvents.DECLINE]: {\n target: FirstPartyMachineStateTypes.declined,\n },\n [FirstPartyMachineEvents.PREVIOUS]: {\n target: FirstPartyMachineStateTypes.aborted,\n },\n },\n },\n [FirstPartyMachineStateTypes.sendAuthorizationResponse]: {\n id: FirstPartyMachineStateTypes.sendAuthorizationResponse,\n invoke: {\n src: FirstPartyMachineServices.sendAuthorizationResponse,\n onDone: {\n target: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n actions: assign({\n presentationDuringIssuanceSession: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<string>) => _event.data,\n }),\n },\n onError: {\n target: FirstPartyMachineStateTypes.error,\n actions: assign({\n error: (_ctx: FirstPartyMachineContext, _event: DoneInvokeEvent<Error>): ErrorDetails => ({\n title: translate('oid4vci_machine_get_request_error_title'),\n message: _event.data.message,\n stack: _event.data.stack,\n }),\n }),\n },\n },\n },\n [FirstPartyMachineStateTypes.aborted]: {\n id: FirstPartyMachineStateTypes.aborted,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.declined]: {\n id: FirstPartyMachineStateTypes.declined,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.error]: {\n id: FirstPartyMachineStateTypes.error,\n type: 'final',\n },\n [FirstPartyMachineStateTypes.done]: {\n id: FirstPartyMachineStateTypes.done,\n type: 'final',\n },\n}\n\nconst createFirstPartyActivationMachine = (opts: CreateFirstPartyMachineOpts): FirstPartyStateMachine => {\n const initialContext: FirstPartyMachineContext = {\n openID4VCIClientState: opts.openID4VCIClientState,\n contact: opts.contact,\n selectedCredentials: [],\n }\n\n return createMachine<FirstPartyMachineContext, FirstPartyMachineEventTypes>({\n id: opts?.machineId ?? 'FirstParty',\n predictableActionArguments: true,\n initial: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,\n context: initialContext,\n states: firstPartyMachineStates,\n schema: {\n events: {} as FirstPartyMachineEventTypes,\n services: {} as {\n [FirstPartyMachineServices.sendAuthorizationChallengeRequest]: {\n data: void\n }\n [FirstPartyMachineServices.createConfig]: {\n data: CreateConfigResult\n }\n [FirstPartyMachineServices.getSiopRequest]: {\n data: SiopV2AuthorizationRequestData\n }\n [FirstPartyMachineServices.sendAuthorizationResponse]: {\n data: string\n }\n },\n },\n })\n}\n\nexport class FirstPartyMachine {\n private static _instance: FirstPartyMachineInterpreter | undefined\n\n static hasInstance(): boolean {\n return FirstPartyMachine._instance !== undefined\n }\n\n static get instance(): FirstPartyMachineInterpreter {\n if (!FirstPartyMachine._instance) {\n throw Error('Please initialize ESIMActivation machine first')\n }\n return FirstPartyMachine._instance\n }\n\n static clearInstance(opts: { stop: boolean }) {\n const { stop } = opts\n if (FirstPartyMachine.hasInstance()) {\n if (stop) {\n FirstPartyMachine.stopInstance()\n }\n }\n FirstPartyMachine._instance = undefined\n }\n\n static stopInstance(): void {\n if (!FirstPartyMachine.hasInstance()) {\n return\n }\n FirstPartyMachine.instance.stop()\n FirstPartyMachine._instance = undefined\n }\n\n public static newInstance(opts: InstanceFirstPartyMachineOpts): FirstPartyMachineInterpreter {\n const { agentContext } = opts\n const services: FirstPartyMachineServiceDefinitions = {\n [FirstPartyMachineServices.sendAuthorizationChallengeRequest]: sendAuthorizationChallengeRequest,\n [FirstPartyMachineServices.createConfig]: (args: CreateConfigArgs) => createConfig(args, agentContext),\n [FirstPartyMachineServices.getSiopRequest]: (args: GetSiopRequestArgs) => getSiopRequest(args, agentContext),\n [FirstPartyMachineServices.sendAuthorizationResponse]: (args: SendAuthorizationResponseArgs) => sendAuthorizationResponse(args, agentContext),\n }\n\n const newInst: FirstPartyMachineInterpreter = interpret(\n createFirstPartyActivationMachine(opts).withConfig({\n services: {\n ...services,\n ...opts?.services,\n },\n guards: {\n ...opts?.guards,\n },\n }),\n )\n\n if (typeof opts?.subscription === 'function') {\n newInst.onTransition(opts.subscription)\n }\n\n if (opts?.requireCustomNavigationHook !== true) {\n newInst.onTransition((snapshot: FirstPartyMachineState): void => {\n if (opts?.stateNavigationListener) {\n void opts.stateNavigationListener(newInst, snapshot)\n }\n })\n }\n\n return newInst\n }\n\n static getInstance(\n opts: InstanceFirstPartyMachineOpts & {\n requireExisting?: boolean\n },\n ): FirstPartyMachineInterpreter {\n if (!FirstPartyMachine._instance) {\n if (opts?.requireExisting === true) {\n throw Error(`Existing FirstPartyMachine instance requested, but none was created at this point!`)\n }\n FirstPartyMachine._instance = FirstPartyMachine.newInstance(opts)\n }\n return FirstPartyMachine._instance\n }\n}\n","import { OpenID4VCIClient } from '@sphereon/oid4vci-client'\nimport { AuthorizationChallengeValidationResponse } from '@sphereon/ssi-sdk.siopv2-oid4vp-common'\nimport { AuthorizationChallengeCodeResponse } from '@sphereon/oid4vci-common'\nimport { CreateConfigResult } from '@sphereon/ssi-sdk.siopv2-oid4vp-op-auth'\nimport { v4 as uuidv4 } from 'uuid'\nimport { RequiredContext } from '../types/IOID4VCIHolder'\nimport {\n CreateConfigArgs,\n GetSiopRequestArgs,\n SendAuthorizationChallengeRequestArgs,\n SendAuthorizationResponseArgs,\n SiopV2AuthorizationRequestData,\n} from '../types/FirstPartyMachine'\n\nexport const sendAuthorizationChallengeRequest = async (args: SendAuthorizationChallengeRequestArgs): Promise<AuthorizationChallengeCodeResponse> => {\n const { openID4VCIClientState, authSession, presentationDuringIssuanceSession } = args\n\n const oid4vciClient = await OpenID4VCIClient.fromState({ state: openID4VCIClientState })\n return oid4vciClient.acquireAuthorizationChallengeCode({\n clientId: oid4vciClient.clientId ?? uuidv4(),\n ...(authSession && { authSession }),\n ...(!authSession &&\n openID4VCIClientState.credentialOffer?.preAuthorizedCode && { issuerState: openID4VCIClientState.credentialOffer?.preAuthorizedCode }),\n ...(!authSession && openID4VCIClientState.credentialOffer?.issuerState && { issuerState: openID4VCIClientState.credentialOffer?.issuerState }),\n ...(presentationDuringIssuanceSession && { presentationDuringIssuanceSession }),\n })\n}\n\nexport const createConfig = async (args: CreateConfigArgs, context: RequiredContext): Promise<CreateConfigResult> => {\n const { presentationUri } = args\n\n if (!presentationUri) {\n return Promise.reject(Error('Missing presentation uri in context'))\n }\n\n return context.agent.siopCreateConfig({ url: presentationUri })\n}\n\nexport const getSiopRequest = async (args: GetSiopRequestArgs, context: RequiredContext): Promise<SiopV2AuthorizationRequestData> => {\n const { didAuthConfig, presentationUri } = args\n\n if (presentationUri === undefined) {\n return Promise.reject(Error('Missing presentation uri in context'))\n }\n\n if (didAuthConfig === undefined) {\n return Promise.reject(Error('Missing did auth config in context'))\n }\n\n return context.agent.siopGetSiopRequest({ didAuthConfig, url: presentationUri })\n}\n\nexport const sendAuthorizationResponse = async (args: SendAuthorizationResponseArgs, context: RequiredContext): Promise<string> => {\n const { didAuthConfig, authorizationRequestData, selectedCredentials } = args\n\n const responseData = await context.agent.siopSendResponse({\n authorizationRequestData,\n selectedCredentials,\n didAuthConfig,\n isFirstParty: true,\n })\n\n return (<AuthorizationChallengeValidationResponse>responseData.body).presentation_during_issuance_session\n}\n","import { CredentialsSupportedDisplay, NameAndLocale } from '@sphereon/oid4vci-common'\nimport { IBasicCredentialClaim, IBasicCredentialLocaleBranding, IBasicIssuerLocaleBranding } from '@sphereon/ssi-sdk.data-store-types'\nimport { SdJwtClaimDisplayMetadata, SdJwtClaimMetadata, SdJwtClaimPath, SdJwtTypeDisplayMetadata } from '@sphereon/ssi-types'\nimport {\n IssuerLocaleBrandingFromArgs,\n Oid4vciCombineDisplayLocalesFromArgs,\n Oid4vciCredentialDisplayLocalesFromArgs,\n Oid4vciCredentialLocaleBrandingFromArgs,\n Oid4vciGetCredentialBrandingFromArgs,\n Oid4vciIssuerCredentialSubjectLocalesFromArgs,\n SdJwtCombineDisplayLocalesFromArgs,\n SdJwtCredentialClaimLocalesFromArgs,\n SdJwtCredentialDisplayLocalesFromArgs,\n SdJwtCredentialLocaleBrandingFromArgs,\n SdJwtGetCredentialBrandingFromArgs,\n} from '../types/IOID4VCIHolder'\n\n// FIXME should we not move this to the branding plugin?\n\nexport const oid4vciGetCredentialBrandingFrom = async (\n args: Oid4vciGetCredentialBrandingFromArgs,\n): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplay, issuerCredentialSubject } = args\n\n return oid4vciCombineDisplayLocalesFrom({\n ...(issuerCredentialSubject && { issuerCredentialSubjectLocales: await oid4vciIssuerCredentialSubjectLocalesFrom({ issuerCredentialSubject }) }),\n ...(credentialDisplay && { credentialDisplayLocales: await oid4vciCredentialDisplayLocalesFrom({ credentialDisplay }) }),\n })\n}\n\nexport const oid4vciCredentialDisplayLocalesFrom = async (\n args: Oid4vciCredentialDisplayLocalesFromArgs,\n): Promise<Map<string, CredentialsSupportedDisplay>> => {\n const { credentialDisplay } = args\n return credentialDisplay.reduce((localeDisplays, display) => {\n const localeKey = display.locale || ''\n localeDisplays.set(localeKey, display)\n return localeDisplays\n }, new Map<string, CredentialsSupportedDisplay>())\n}\n\nexport const oid4vciIssuerCredentialSubjectLocalesFrom = async (\n args: Oid4vciIssuerCredentialSubjectLocalesFromArgs,\n): Promise<Map<string, Array<IBasicCredentialClaim>>> => {\n const { issuerCredentialSubject } = args\n const localeClaims = new Map<string, Array<IBasicCredentialClaim>>()\n\n const processClaimObject = (claim: any, parentKey: string = ''): void => {\n Object.entries(claim).forEach(([key, value]): void => {\n if (key === 'mandatory' || key === 'value_type') {\n return\n }\n\n if (key === 'display' && Array.isArray(value)) {\n value.forEach(({ name, locale = '' }: NameAndLocale): void => {\n if (!name) {\n return\n }\n\n //const localeKey = locale || ''\n if (!localeClaims.has(locale)) {\n localeClaims.set(locale, [])\n }\n localeClaims.get(locale)!.push({ key: parentKey, name })\n })\n } else if (typeof value === 'object' && value !== null) {\n processClaimObject(value, parentKey ? `${parentKey}.${key}` : key)\n }\n })\n }\n\n processClaimObject(issuerCredentialSubject)\n return localeClaims\n}\n\nexport const oid4vciCredentialLocaleBrandingFrom = async (args: Oid4vciCredentialLocaleBrandingFromArgs): Promise<IBasicCredentialLocaleBranding> => {\n const { credentialDisplay } = args\n\n return {\n ...(credentialDisplay.name && {\n alias: credentialDisplay.name,\n }),\n ...(credentialDisplay.locale && {\n locale: credentialDisplay.locale,\n }),\n ...(credentialDisplay.logo && {\n logo: {\n ...((credentialDisplay.logo.url || <string>credentialDisplay.logo.uri) && {\n uri: credentialDisplay.logo?.url ?? <string>credentialDisplay.logo.uri,\n }),\n ...(credentialDisplay.logo.alt_text && {\n alt: credentialDisplay.logo?.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.description && {\n description: credentialDisplay.description,\n }),\n\n ...(credentialDisplay.text_color && {\n text: {\n color: credentialDisplay.text_color,\n },\n }),\n ...((credentialDisplay.background_image || credentialDisplay.background_color) && {\n background: {\n ...(credentialDisplay.background_image && {\n image: {\n ...((credentialDisplay.background_image.url || <string>credentialDisplay.background_image.uri) && {\n uri: credentialDisplay.background_image?.url ?? <string>credentialDisplay.background_image.uri,\n }),\n ...(credentialDisplay.background_image.alt_text && {\n alt: credentialDisplay.background_image?.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.background_color && {\n color: credentialDisplay.background_color,\n }),\n },\n }),\n }\n}\n\nexport const oid4vciCombineDisplayLocalesFrom = async (\n args: Oid4vciCombineDisplayLocalesFromArgs,\n): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const {\n credentialDisplayLocales = new Map<string, CredentialsSupportedDisplay>(),\n issuerCredentialSubjectLocales = new Map<string, Array<IBasicCredentialClaim>>(),\n } = args\n\n const locales: Array<string> = Array.from(new Set([...issuerCredentialSubjectLocales.keys(), ...credentialDisplayLocales.keys()]))\n\n return Promise.all(\n locales.map(async (locale: string): Promise<IBasicCredentialLocaleBranding> => {\n const display = credentialDisplayLocales.get(locale)\n const claims = issuerCredentialSubjectLocales.get(locale)\n\n return {\n ...(display && (await oid4vciCredentialLocaleBrandingFrom({ credentialDisplay: display }))),\n ...(locale.length > 0 && { locale }),\n claims,\n }\n }),\n )\n}\n\nexport const sdJwtGetCredentialBrandingFrom = async (args: SdJwtGetCredentialBrandingFromArgs): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplay, claimsMetadata } = args\n\n return sdJwtCombineDisplayLocalesFrom({\n ...(claimsMetadata && { claimsMetadata: await sdJwtCredentialClaimLocalesFrom({ claimsMetadata }) }),\n ...(credentialDisplay && { credentialDisplayLocales: await sdJwtCredentialDisplayLocalesFrom({ credentialDisplay }) }),\n })\n}\n\nexport const sdJwtCredentialDisplayLocalesFrom = async (\n args: SdJwtCredentialDisplayLocalesFromArgs,\n): Promise<Map<string, SdJwtTypeDisplayMetadata>> => {\n const { credentialDisplay } = args\n return credentialDisplay.reduce((localeDisplays, display) => {\n const localeKey = display.lang || ''\n localeDisplays.set(localeKey, display)\n return localeDisplays\n }, new Map<string, SdJwtTypeDisplayMetadata>())\n}\n\nexport const sdJwtCredentialClaimLocalesFrom = async (\n args: SdJwtCredentialClaimLocalesFromArgs,\n): Promise<Map<string, Array<IBasicCredentialClaim>>> => {\n const { claimsMetadata } = args\n const localeClaims = new Map<string, Array<IBasicCredentialClaim>>()\n\n claimsMetadata.forEach((claim: SdJwtClaimMetadata): void => {\n claim.display?.forEach((display: SdJwtClaimDisplayMetadata): void => {\n const { lang = '', label } = display\n const key = claim.path.map((value: SdJwtClaimPath) => String(value)).join('.')\n if (!localeClaims.has(lang)) {\n localeClaims.set(lang, [])\n }\n localeClaims.get(lang)!.push({ key, name: label })\n })\n })\n\n return localeClaims\n}\n\nexport const sdJwtCredentialLocaleBrandingFrom = async (args: SdJwtCredentialLocaleBrandingFromArgs): Promise<IBasicCredentialLocaleBranding> => {\n const { credentialDisplay } = args\n\n return {\n ...(credentialDisplay.name && {\n alias: credentialDisplay.name,\n }),\n ...(credentialDisplay.lang && {\n locale: credentialDisplay.lang,\n }),\n ...(credentialDisplay.rendering?.simple?.logo && {\n logo: {\n ...(credentialDisplay.rendering.simple.logo.uri && {\n uri: credentialDisplay.rendering.simple.logo.uri,\n }),\n ...(credentialDisplay.rendering.simple.logo.alt_text && {\n alt: credentialDisplay.rendering.simple.logo.alt_text,\n }),\n },\n }),\n ...(credentialDisplay.description && {\n description: credentialDisplay.description,\n }),\n ...(credentialDisplay.rendering?.simple?.text_color && {\n text: {\n color: credentialDisplay.rendering.simple.text_color,\n },\n }),\n ...(credentialDisplay.rendering?.simple?.background_color && {\n background: {\n color: credentialDisplay.rendering.simple.background_color,\n },\n }),\n }\n}\n\nexport const sdJwtCombineDisplayLocalesFrom = async (args: SdJwtCombineDisplayLocalesFromArgs): Promise<Array<IBasicCredentialLocaleBranding>> => {\n const { credentialDisplayLocales = new Map<string, SdJwtTypeDisplayMetadata>(), claimsMetadata = new Map<string, Array<IBasicCredentialClaim>>() } =\n args\n\n const locales: Array<string> = Array.from(new Set([...claimsMetadata.keys(), ...credentialDisplayLocales.keys()]))\n\n return Promise.all(\n locales.map(async (locale: string): Promise<IBasicCredentialLocaleBranding> => {\n const display = credentialDisplayLocales.get(locale)\n const claims = claimsMetadata.get(locale)\n\n return {\n ...(display && (await sdJwtCredentialLocaleBrandingFrom({ credentialDisplay: display }))),\n ...(locale.length > 0 && { locale }),\n claims,\n }\n }),\n )\n}\n\n// TODO since dynamicRegistrationClientMetadata can also be on a RP, we should start using this mapper in a more general way\nexport const issuerLocaleBrandingFrom = async (args: IssuerLocaleBrandingFromArgs): Promise<IBasicIssuerLocaleBranding> => {\n const { issuerDisplay, dynamicRegistrationClientMetadata } = args\n\n return {\n ...(dynamicRegistrationClientMetadata?.client_name && {\n alias: dynamicRegistrationClientMetadata.client_name,\n }),\n ...(issuerDisplay.name && {\n alias: issuerDisplay.name,\n }),\n ...(issuerDisplay.locale && {\n locale: issuerDisplay.locale,\n }),\n ...((issuerDisplay.logo || dynamicRegistrationClientMetadata?.logo_uri) && {\n logo: {\n ...(dynamicRegistrationClientMetadata?.logo_uri && {\n uri: dynamicRegistrationClientMetadata?.logo_uri,\n }),\n ...((issuerDisplay.logo?.url || <string>issuerDisplay.logo?.uri) && {\n uri: issuerDisplay.logo?.url ?? <string>issuerDisplay.logo?.uri,\n }),\n ...(issuerDisplay.logo?.alt_text && {\n alt: issuerDisplay.logo?.alt_text,\n }),\n },\n }),\n ...(issuerDisplay.description && {\n description: issuerDisplay.description,\n }),\n ...(issuerDisplay.text_color && {\n text: {\n color: issuerDisplay.text_color,\n },\n }),\n ...(dynamicRegistrationClientMetadata?.client_uri && {\n clientUri: dynamicRegistrationClientMetadata.client_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.tos_uri && {\n tosUri: dynamicRegistrationClientMetadata.tos_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.policy_uri && {\n policyUri: dynamicRegistrationClientMetadata.policy_uri,\n }),\n ...(dynamicRegistrationClientMetadata?.contacts && {\n contacts: dynamicRegistrationClientMetadata.contacts,\n }),\n }\n}\n","import { Loggers, LogLevel, LogMethod } from '@sphereon/ssi-types'\nimport { OID4VCIMachineInterpreter, OID4VCIMachineState, OID4VCIMachineStates } from '../types/IOID4VCIHolder'\n\nconst logger = Loggers.DEFAULT.options('sphereon:oid4vci:holder', { defaultLogLevel: LogLevel.DEBUG, methods: [LogMethod.CONSOLE] }).get(\n 'sphereon:oid4vci:holder',\n)\n\nexport const OID4VCICallbackStateListener = (\n callbacks?: Map<OID4VCIMachineStates, (machine: OID4VCIMachineInterpreter, state: OID4VCIMachineState, opts?: any) => Promise<void>>,\n) => {\n return async (oid4vciMachine: OID4VCIMachineInterpreter, state: OID4VCIMachineState): Promise<void> => {\n if (state._event.type === 'internal') {\n logger.debug('oid4vciCallbackStateListener: 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(`VCI state listener state: ${JSON.stringify(state.value)}`)\n\n if (!callbacks || callbacks.size === 0) {\n logger.info(`VCI 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(`VCI state callback for state: ${JSON.stringify(state.value)}, will execute...`)\n await callback(oid4vciMachine, state)\n .then(() => logger.log(`state callback executed for state: ${JSON.stringify(state.value)}`))\n .catch((error) => {\n logger.error(\n `VCI 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 { CredentialOfferClient } from '@sphereon/oid4vci-client'\nimport { AuthorizationRequestOpts, AuthorizationServerClientOpts, AuthzFlowType, convertURIToJsonObject } from '@sphereon/oid4vci-common'\nimport { DefaultLinkPriorities, LinkHandlerAdapter } from '@sphereon/ssi-sdk.core'\nimport { IMachineStatePersistence, interpreterStartOrResume, SerializableState } from '@sphereon/ssi-sdk.xstate-machine-persistence'\nimport { IAgentContext } from '@veramo/core'\nimport { GetMachineArgs, IOID4VCIHolder, OID4VCIMachineEvents, OID4VCIMachineStateNavigationListener, WalletType } from '../types/IOID4VCIHolder'\nimport { FirstPartyMachineStateNavigationListener } from '../types/FirstPartyMachine'\n\n/**\n * This handler only handles credential offer links (either by value or by reference)\n */\nexport class OID4VCIHolderLinkHandler extends LinkHandlerAdapter {\n private readonly context: IAgentContext<IOID4VCIHolder & IMachineStatePersistence>\n private readonly stateNavigationListener?: OID4VCIMachineStateNavigationListener\n private readonly firstPartyStateNavigationListener?: FirstPartyMachineStateNavigationListener\n private readonly noStateMachinePersistence: boolean\n private readonly walletType: WalletType\n private readonly authorizationRequestOpts?: AuthorizationRequestOpts\n private readonly clientOpts?: AuthorizationServerClientOpts\n private readonly trustAnchors?: Array<string>\n\n constructor(\n args: Pick<\n GetMachineArgs,\n 'stateNavigationListener' | 'authorizationRequestOpts' | 'clientOpts' | 'trustAnchors' | 'firstPartyStateNavigationListener' | 'walletType'\n > & {\n priority?: number | DefaultLinkPriorities\n protocols?: Array<string | RegExp>\n noStateMachinePersistence?: boolean\n context: IAgentContext<IOID4VCIHolder & IMachineStatePersistence>\n },\n ) {\n super({ ...args, id: 'OID4VCIHolder' })\n this.authorizationRequestOpts = args.authorizationRequestOpts\n this.clientOpts = args.clientOpts\n this.context = args.context\n this.walletType = args.walletType ?? 'NATURAL_PERSON'\n this.noStateMachinePersistence = args.noStateMachinePersistence === true\n this.stateNavigationListener = args.stateNavigationListener\n this.firstPartyStateNavigationListener = args.firstPartyStateNavigationListener\n this.trustAnchors = args.trustAnchors\n }\n\n async handle(\n url: string | URL,\n opts?: {\n machineState?: SerializableState\n authorizationRequestOpts?: AuthorizationRequestOpts\n createAuthorizationRequestURL?: boolean\n clientOpts?: AuthorizationServerClientOpts\n flowType?: AuthzFlowType\n },\n ): Promise<void> {\n const uri = new URL(url).toString()\n const offerData = convertURIToJsonObject(uri) as Record<string, unknown>\n const hasCode = 'code' in offerData && !!offerData.code && !('issuer' in offerData)\n const code = hasCode ? (offerData.code as string) : undefined\n const clientOpts = { ...this.clientOpts, ...opts?.clientOpts }\n const oid4vciMachine = await this.context.agent.oid4vciHolderGetMachineInterpreter({\n requestData: {\n // We know this can only be invoked with a credential offer, so we convert the URI to offer\n ...(!hasCode && { credentialOffer: await CredentialOfferClient.fromURI(uri) }),\n ...(hasCode && { code: code }),\n createAuthorizationRequestURL: opts?.createAuthorizationRequestURL,\n flowType: opts?.flowType,\n uri,\n },\n trustAnchors: this.trustAnchors,\n authorizationRequestOpts: { ...this.authorizationRequestOpts, ...opts?.authorizationRequestOpts },\n ...((clientOpts.clientId || clientOpts.clientAssertionType) && { clientOpts: clientOpts as AuthorizationServerClientOpts }),\n stateNavigationListener: this.stateNavigationListener,\n firstPartyStateNavigationListener: this.firstPartyStateNavigationListener,\n walletType: this.walletType,\n })\n\n const interpreter = oid4vciMachine.interpreter\n //FIXME we need a better way to check if the state persistence plugin is available in the agent\n if (!opts?.machineState && this.context.agent.availableMethods().includes('machineStatesFindActive')) {\n const stateType = hasCode ? 'existing' : 'new'\n await interpreterStartOrResume({\n stateType,\n interpreter,\n context: this.context,\n cleanupAllOtherInstances: true,\n cleanupOnFinalState: true,\n singletonCheck: true,\n noRegistration: this.noStateMachinePersistence,\n })\n } else {\n // @ts-ignore\n interpreter.start(opts?.machineState)\n }\n\n if (hasCode) {\n interpreter.send(OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE, { data: uri })\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,mDAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,gDAAkD;AAAA,MAClD,uDAAyD;AAAA,MACzD,8CAAgD;AAAA,MAChD,kDAAoD;AAAA,MACpD,kDAAoD;AAAA,MACpD,sDAAwD;AAAA,MACxD,mDAAqD;AAAA,MACrD,8CAAgD;AAAA,MAChD,kDAAoD;AAAA,MACpD,wCAA0C;AAAA,MAC1C,wDAA0D;AAAA,MAC1D,+DAAiE;AAAA,MACjE,uDAAyD;AAAA,MACzD,yCAA2C;AAAA,MAC3C,kEAAoE;AAAA,MACpE,2CAA6C;AAAA,MAC7C,yCAA2C;AAAA,IAC7C;AAAA;AAAA;;;AClBA;AAAA,mDAA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AACA,UAAUG,QAAQ,EAAE,YAAYH;AACzE,UAAMG,OAAOD,UAAWF,UAAUG,OAAkBC;AACpD,UAAMd,aAAa;MAAE,GAAG,KAAKA;MAAY,GAAGM,MAAMN;IAAW;AAC7D,UAAMe,iBAAiB,MAAM,KAAKrB,QAAQsB,MAAMC,mCAAmC;MACjFC,aAAa;;QAEX,GAAI,CAACN,WAAW;UAAEO,iBAAiB,MAAMC,6CAAsBC,QAAQd,GAAAA;QAAK;QAC5E,GAAIK,WAAW;UAAEC;QAAW;QAC5BS,+BAA+BhB,MAAMgB;QACrCC,UAAUjB,MAAMiB;QAChBhB;MACF;MACAN,cAAc,KAAKA;MACnBF,0BAA0B;QAAE,GAAG,KAAKA;QAA0B,GAAGO,MAAMP;MAAyB;MAChG,IAAKC,WAAWwB,YAAYxB,WAAWyB,wBAAwB;QAAEzB;MAAwD;MACzHL,yBAAyB,KAAKA;MAC9BC,mCAAmC,KAAKA;MACxCE,YAAY,KAAKA;IACnB,CAAA;AAEA,UAAM4B,cAAcX,eAAeW;AAEnC,QAAI,CAACpB,MAAMqB,gBAAgB,KAAKjC,QAAQsB,MAAMY,iBAAgB,EAAGC,SAAS,yBAAA,GAA4B;AACpG,YAAMC,YAAYlB,UAAU,aAAa;AACzC,gBAAMmB,0CAAyB;QAC7BD;QACAJ;QACAhC,SAAS,KAAKA;QACdsC,0BAA0B;QAC1BC,qBAAqB;QACrBC,gBAAgB;QAChBC,gBAAgB,KAAKtC;MACvB,CAAA;IACF,OAAO;AAEL6B,kBAAYU,MAAM9B,MAAMqB,YAAAA;IAC1B;AAEA,QAAIf,SAAS;AACXc,kBAAYW,KAAKC,qBAAqBC,qCAAqC;QAAEC,MAAMjC;MAAI,CAAA;IACzF;EACF;AACF;","names":["module","module","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk_ext","import_ssi_sdk","import_ssi_types","import_utils","import_uuid","OID4VCIHolderEvent","SupportedLanguage","OID4VCIMachineStates","OID4VCIMachineAddContactStates","OID4VCIMachineVerifyPinStates","OID4VCIMachineEvents","OID4VCIMachineGuards","OID4VCIMachineServices","RequestType","IdentifierAliasEnum","Localization","translationGetters","SupportedLanguage","ENGLISH","require","DUTCH","translate","memoize","key","config","Object","keys","i18n","translations","length","locale","findSupportedLanguage","t","JSON","stringify","language","values","undefined","getLocale","FirstPartyMachineStateTypes","FirstPartyMachineServices","FirstPartyMachineEvents","oid4vciHasNoContactGuard","_ctx","_event","contact","undefined","oid4vciHasContactGuard","oid4vciContactHasLowTrustGuard","trustedAnchors","length","oid4vciCredentialsToSelectRequiredGuard","credentialToSelectFrom","oid4vciRequirePinGuard","requestData","credentialOffer","userPinRequired","oid4vciHasNoContactIdentityGuard","credentialsToAccept","toAcceptId","correlationId","match","URL","hostname","identities","some","identity","identifier","oid4vciVerificationCodeGuard","verificationCode","oid4vciCreateContactGuard","contactAlias","hasContactConsent","oid4vciHasSelectedCredentialsGuard","selectedCredentials","oid4vciIsOIDFOriginGuard","trustAnchors","oid4vciNoAuthorizationGuard","ctx","oid4vciHasAuthorizationResponse","oid4vciRequireAuthorizationGuard","openID4VCIClientState","Error","authorizationURL","authorizationRequestOpts","authorizationCodeResponse","supportedFlows","includes","AuthzFlowType","AUTHORIZATION_CODE_FLOW","PRE_AUTHORIZED_CODE_FLOW","endpointMetadata","credentialIssuerMetadata","authorization_endpoint","oid4vciIsFirstPartyApplication","serverMetadata","authorization_challenge_endpoint","createOID4VCIMachine","opts","initialContext","accessTokenOpts","walletType","issuanceOpt","didMethodPreferences","locale","credentialsSupported","createMachine","id","machineName","predictableActionArguments","initial","OID4VCIMachineStates","start","schema","events","guards","services","context","states","invoke","src","OID4VCIMachineServices","onDone","target","createCredentialsToSelectFrom","actions","assign","credentialBranding","data","oid4vciClientState","onError","handleError","error","title","translate","message","stack","getContact","getIssuerBranding","getFederationTrust","cond","OID4VCIMachineGuards","isOIDFOriginGuard","issuerBranding","transitionFromSetup","always","addContact","hasNoContactGuard","reviewContact","contactHasLowTrustGuard","selectCredentials","credentialsToSelectRequiredGuard","startFirstPartApplicationFlow","isFirstPartyApplication","prepareAuthorizationRequest","requireAuthorizationGuard","verifyPin","requirePinGuard","getCredentials","on","OID4VCIMachineEvents","SET_AUTHORIZATION_CODE_URL","authorizationCodeURL","OID4VCIMachineAddContactStates","idle","SET_CONTACT_CONSENT","SET_CONTACT_ALIAS","CREATE_CONTACT","next","createContactGuard","DECLINE","declined","PREVIOUS","aborted","storeIssuerBranding","hasContactGuard","NEXT","transitionFromContactSetup","FirstPartyMachineStateTypes","toAuthorizationResponsePayload","SET_SELECTED_CREDENTIALS","transitionFromSelectingCredentials","hasSelectedCredentialsGuard","initiateAuthorizationRequest","INVOKED_AUTHORIZATION_CODE_REQUEST","waitForAuthorizationResponse","PROVIDE_AUTHORIZATION_CODE_RESPONSE","hasAuthorizationResponse","OID4VCIMachineVerifyPinStates","SET_VERIFICATION_CODE","verificationCodeGuard","verifyCredentials","exit","assertValidCredentials","transitionFromWalletInput","addContactIdentity","hasNoContactIdentityGuard","reviewCredentials","addIssuerBrandingAfterIdentity","push","storeCredentialBranding","storeCredentials","done","type","OID4VCIMachine","newInstance","interpreter","interpret","withConfig","subscription","onTransition","requireCustomNavigationHook","stateNavigationListener","snapshot","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk_ext","import_xstate","import_oid4vci_common","sendAuthorizationChallengeRequest","args","openID4VCIClientState","authSession","presentationDuringIssuanceSession","oid4vciClient","OpenID4VCIClient","fromState","state","acquireAuthorizationChallengeCode","clientId","uuidv4","credentialOffer","preAuthorizedCode","issuerState","createConfig","context","presentationUri","Promise","reject","Error","agent","siopCreateConfig","url","getSiopRequest","didAuthConfig","undefined","siopGetSiopRequest","sendAuthorizationResponse","authorizationRequestData","selectedCredentials","responseData","siopSendResponse","isFirstParty","body","presentation_during_issuance_session","firstPartyMachineStates","FirstPartyMachineStateTypes","sendAuthorizationChallengeRequest","id","invoke","src","FirstPartyMachineServices","onDone","target","done","actions","assign","authorizationCodeResponse","_ctx","_event","data","onError","createConfig","cond","error","AuthorizationChallengeError","insufficient_authorization","authSession","auth_session","presentationUri","presentation","title","translate","message","stack","getSiopRequest","didAuthConfig","selectCredentials","authorizationRequestData","on","FirstPartyMachineEvents","SET_SELECTED_CREDENTIALS","selectedCredentials","NEXT","sendAuthorizationResponse","DECLINE","declined","PREVIOUS","aborted","presentationDuringIssuanceSession","type","createFirstPartyActivationMachine","opts","initialContext","openID4VCIClientState","contact","createMachine","machineId","predictableActionArguments","initial","context","states","schema","events","services","FirstPartyMachine","_instance","hasInstance","undefined","instance","Error","clearInstance","stop","stopInstance","newInstance","agentContext","args","newInst","interpret","withConfig","guards","subscription","onTransition","requireCustomNavigationHook","snapshot","stateNavigationListener","getInstance","requireExisting","oid4vciGetCredentialBrandingFrom","args","credentialDisplay","issuerCredentialSubject","oid4vciCombineDisplayLocalesFrom","issuerCredentialSubjectLocales","oid4vciIssuerCredentialSubjectLocalesFrom","credentialDisplayLocales","oid4vciCredentialDisplayLocalesFrom","reduce","localeDisplays","display","localeKey","locale","set","Map","localeClaims","processClaimObject","claim","parentKey","Object","entries","forEach","key","value","Array","isArray","name","has","get","push","oid4vciCredentialLocaleBrandingFrom","alias","logo","url","uri","alt_text","alt","description","text_color","text","color","background_image","background_color","background","image","locales","from","Set","keys","Promise","all","map","claims","length","sdJwtGetCredentialBrandingFrom","claimsMetadata","sdJwtCombineDisplayLocalesFrom","sdJwtCredentialClaimLocalesFrom","sdJwtCredentialDisplayLocalesFrom","lang","label","path","String","join","sdJwtCredentialLocaleBrandingFrom","rendering","simple","issuerLocaleBrandingFrom","issuerDisplay","dynamicRegistrationClientMetadata","client_name","logo_uri","client_uri","clientUri","tos_uri","tosUri","policy_uri","policyUri","contacts","getCredentialBranding","args","credentialsSupported","context","credentialBranding","Promise","all","Object","entries","map","configId","credentialsConfigSupported","sdJwtTypeMetadata","format","vct","startsWith","agent","fetchSdJwtTypeMetadataFromVctUrl","mappedLocaleBranding","sdJwtGetCredentialBrandingFrom","credentialDisplay","display","claimsMetadata","claims","oid4vciGetCredentialBrandingFrom","issuerCredentialSubject","undefined","credentialSubject","localeBranding","ibCredentialLocaleBrandingFrom","defaultCredentialType","configSupportedTypes","getTypesFromCredentialSupported","credentialTypes","length","asArray","filteredCredentialTypes","filter","type","getBasicIssuerLocaleBranding","dynamicRegistrationClientMetadata","issuerDisplay","branding","issuerLocaleBrandingFrom","ibIssuerLocaleBrandingFrom","getCredentialConfigsBasedOnFormatPref","vcFormatPreferences","credentials","prefConfigs","forEach","key","config","result","pref","toLowerCase","includes","selectCredentialLocaleBranding","locale","find","verifyCredentialToAccept","mappedCredential","hasher","onVerifyEBSICredentialIssuer","schemaValidation","credential","extractCredentialFromResponse","credentialToAccept","credentialResponse","wrappedVC","CredentialMapper","toWrappedVerifiableCredential","defaultHasher","decoded","iss","vc","issuer","existingInstanceId","cvVerifySchema","validationPolicy","JSON","stringify","source","error","subResults","wrappedVc","e","message","verificationResult","cvVerifyCredential","fetchRemoteContexts","policies","credentialStatus","expirationDate","issuanceDate","reject","Error","translate","mapCredentialToAccept","verifiableCredential","wrappedVerifiableCredential","uniformVerifiableCredential","isSdJwtDecodedCredential","sdJwtDecodedCredentialToUniformCredential","isSdJwtEncoded","asyncHasher","data","algorithm","resolve","decodedSdJwt","decodeSdJwtVcAsync","isMsoMdocDecodedCredential","mdocDecodedCredentialToUniformCredential","correlationId","decodedPayload","id","types","rawVerifiableCredential","credential_subject_issuance","Array","isArray","getIdentifierOpts","issuanceOpt","identifier","identifierArg","isManagedIdentifierResult","supportedPreferredDidMethod","supportedBindingMethods","keyType","kms","keyManagerGetDefaultKeyManagementSystem","isIIdentifier","identifierManagedGet","method","managedIdentifierToJwk","join","agentContext","created","getOrCreatePrimaryIdentifier","createOpts","options","use","KeyUse","Signature","codecName","identifierManagedGetByDid","offlineWhenNoDIDRegistered","did","emit","OID4VCIHolderEvent","IDENTIFIER_CREATED","keyManagerCreate","meta","keyAlias","Date","now","kmsKeyRef","kid","getCredentialConfigsSupportedMerged","getCredentialConfigsSupported","supported","configurationIds","getCredentialConfigsSupportedBySingleTypeOrId","configurationId","configs","keys","client","createIdFromTypes","getTypesFromObject","allSupported","getCredentialsSupported","fromEntries","credentialOffer","offerSupported","getSupportedCredentials","version","issuerMetadata","endpointMetadata","credentialIssuerMetadata","credentialConfigsSupported","LOG","warning","getIssuer","credential_offer","credentialsToOffer","credential_configuration_ids","getIssuanceOpts","didMethodPreferences","jwtCryptographicSuitePreferences","jsonldCryptographicSuitePreferences","forceIssuanceOpt","values","credentialSupported","cryptographicSuite","getIssuanceCryptoSuite","didMethod","methods","getIssuanceMethod","console","log","push","isEBSI","keyTypeFromCryptographicSuite","crv","clientId","isManagedIdentifierDidResult","opts","cryptographic_binding_methods_supported","didMethods","warn","SupportedDidMethodEnum","DID_KEY","signing_algs_supported","proof_types_supported","jwt","proof_signing_alg_values_supported","ldp_vp","cwt","credential_signing_alg_values_supported","supportedPreferences","suite","JoseSignatureAlgorithm","ES256","fallback","startFirstPartApplicationMachine","openID4VCIClientState","stateNavigationListener","contact","firstPartyMachineInstance","FirstPartyMachine","newInstance","onTransition","state","matches","FirstPartyMachineStateTypes","done","authorizationCodeResponse","aborted","declined","start","oid4vciHolderContextMethods","logger","Loggers","DEFAULT","get","signCallback","identifier","context","nonce","jwt","kid","noIssPayloadUpdate","resolution","agent","identifierManagedGet","jwk","header","method","undefined","issuer","payload","iss","Promise","reject","Error","JSON","stringify","console","log","jwtCreateJwsCompactSignature","protectedHeader","OID4VCIHolder","hasher","eventTypes","OID4VCIHolderEvent","CONTACT_IDENTITY_CREATED","CREDENTIAL_STORED","IDENTIFIER_CREATED","methods","oid4vciHolderStart","bind","oid4vciHolderGetIssuerMetadata","oid4vciHolderGetMachineInterpreter","oid4vciHolderPrepareAuthorizationRequest","oid4vciHolderCreateCredentialsToSelectFrom","oid4vciHolderGetContact","oid4vciHolderGetCredentials","oid4vciHolderGetCredential","oid4vciHolderAddContactIdentity","oid4vciHolderAssertValidCredentials","oid4vciHolderStoreCredentialBranding","oid4vciHolderStoreCredentials","oid4vciHolderSendNotification","oid4vciHolderGetIssuerBranding","oid4vciHolderStoreIssuerBranding","vcFormatPreferences","jsonldCryptographicSuitePreferences","didMethodPreferences","SupportedDidMethodEnum","DID_JWK","DID_KEY","DID_OYD","DID_EBSI","DID_ION","jwtCryptographicSuitePreferences","JoseSignatureAlgorithm","ES256","ES256K","EdDSA","DEFAULT_MOBILE_REDIRECT_URI","DefaultURISchemes","CREDENTIAL_OFFER","defaultAuthorizationRequestOpts","redirectUri","onContactIdentityCreated","onCredentialStored","onIdentifierCreated","onVerifyEBSICredentialIssuer","options","defaultAuthorizationRequestOptions","defaultHasher","undefined","length","onEvent","event","context","type","data","Promise","reject","Error","opts","authorizationRequestOpts","services","OID4VCIMachineServices","start","args","startFirstPartApplicationFlow","startFirstPartApplicationMachine","stateNavigationListener","firstPartyStateNavigationListener","createCredentialsToSelectFrom","prepareAuthorizationRequest","getContact","getCredentials","accessTokenOpts","addContactIdentity","getIssuerBranding","storeIssuerBranding","assertValidCredentials","storeCredentialBranding","storeCredentials","sendNotification","getFederationTrust","oid4vciMachineInstanceArgs","interpreter","OID4VCIMachine","newInstance","requestData","uri","authorizationDetails","asArray","startsWith","clientId","formats","authFormats","map","detail","format","filter","Array","from","Set","oid4vciClient","offer","existingClientState","OpenID4VCIClientV1_0_15","fromState","state","credentialOffer","RequestType","OPENID_INITIATE_ISSUANCE","OPENID_CREDENTIAL_OFFER","match","CredentialOfferClient","fromURI","logger","warning","log","fromCredentialIssuer","credentialIssuer","authorizationRequest","createAuthorizationRequestURL","configurationIds","original_credential_offer","credential_configuration_ids","authReqOpts","credential_configuration_id","id","credentialsSupported","getCredentialConfigsSupportedMerged","client","serverMetadata","retrieveServerMetadata","credentialBranding","getCredentialBranding","oid4vciClientState","JSON","parse","exportState","openID4VCIClientState","contact","identities","identity","connectionConfig","connection","config","find","authorizationCodeURL","createAuthorizationRequestUrl","locale","selectedCredentials","info","Object","keys","join","credentialSelection","all","entries","credentialConfigSupported","credentialTypes","getTypesFromObject","localeBranding","_brandings","supported","credentialAlias","selectCredentialLocaleBranding","alias","uuidv4","credentialId","isSelected","sel","push","stringify","names","credentialIssuerMetadata","display","name","size","correlationId","URL","issuer","hostname","identifier","legalName","displayName","parties","agent","cmGetContacts","party","verificationCode","issuanceOpt","walletType","debug","issuanceOpts","getIssuanceOpts","selectDidMethodPreferences","forceIssuanceOpt","pin","allCredentials","supportedDidMethodEnums","isArray","DID_WEB","getIdentifierOpts","alg","signatureAlgorithmFromKey","key","jwk","isManagedIdentifierJwkResult","callbacks","signCallback","isManagedIdentifierDidResult","did","asOpts","kid","clientOpts","isEBSI","includes","split","signCallbacks","acquireAccessToken","authorizationResponse","authorizationCodeResponse","additionalRequestParams","types","credentialConfigurationId","credentialDefinition","getCredentialDefinition","credentialResponse","acquireCredentials","proofCallbacks","deferredCredentialAwait","jti","credential","mapCredentialToAccept","credentialToAccept","error","credentialsToAccept","identifierType","CorrelationIdentifierType","DID","toLowerCase","origin","IdentityOrigin","EXTERNAL","roles","CredentialRole","ISSUER","ConnectionType","OPENID_CONNECT","clientSecret","scopes","redirectUrl","dangerouslyAllowInsecureHttpRequests","clientAuthMethod","emit","contactId","cmAddIdentity","issuerCorrelationId","branding","ibGetIssuerBranding","getBasicIssuerLocaleBranding","dynamicRegistrationClientMetadata","issuerBranding","ibAddIssuerBranding","verifyCredentialToAccept","mappedCredential","schemaValidation","counter","configId","ac","credAccept","cred","ibAddCredentialBranding","vcHash","computeEntryHash","rawVerifiableCredential","b","trimmed","input","trim","mappedCredentialToAccept","kmsKeyRef","method","persist","verifiableCredential","uniformVerifiableCredential","notificationId","notification_id","subjectIssuance","credential_subject_issuance","notificationEndpoint","notification_endpoint","holderCredential","notification_events_supported","issuerVC","extractCredentialFromResponse","wrappedIssuerVC","CredentialMapper","toWrappedVerifiableCredential","console","isWrappedSdJwtVerifiableCredential","decoded","sub","isWrappedW3CVerifiableCredential","credentialSubject","idFromW3cCredentialSubject","isWrappedMdocCredential","parseDid","accessTokenResponse","decodedJwt","decodeJWT","access_token","payload","resolution","identifierManagedGet","holderCredentialToSign","proofFormat","iss","vc","proof","issuanceDate","iat","issuedVC","createVerifiableCredential","fetchRemoteContexts","save","storedCredentialToOriginalFormat","notificationRequest","stored","persistCredential","issuerCorrelationIdFromIssuerType","subjectCorrelationType","subjectCorrelationId","determineSubjectCorrelation","persistedCredential","crsAddCredential","rawDocument","ensureRawDocument","identifierMethod","credentialRole","HOLDER","issuerCorrelationType","CredentialCorrelationType","hash","OpenID4VCIClient","trustAnchors","url","params","URLSearchParams","search","openidFederation","get","entityIdentifier","warn","toString","result","identifierExternalResolveByOIDFEntityId","trustedAnchors","errorOnNotFound","MetadataClient","retrieveAllMetadata","isManagedIdentifierResult","isManagedIdentifierDidOpts","isManagedIdentifierKidResult","KID","isManagedIdentifierX5cResult","X509_SAN","x5c","isManagedIdentifierX5cOpts","credential_definition","import_ssi_types","logger","Loggers","DEFAULT","options","defaultLogLevel","LogLevel","DEBUG","methods","LogMethod","CONSOLE","get","OID4VCICallbackStateListener","callbacks","oid4vciMachine","state","_event","type","debug","info","JSON","stringify","value","size","stateKey","callback","matches","log","then","catch","error","message","event","stack","import_oid4vci_client","import_oid4vci_common","import_ssi_sdk","OID4VCIHolderLinkHandler","LinkHandlerAdapter","context","stateNavigationListener","firstPartyStateNavigationListener","noStateMachinePersistence","walletType","authorizationRequestOpts","clientOpts","trustAnchors","args","id","handle","url","opts","uri","URL","toString","offerData","convertURIToJsonObject","hasCode","code","undefined","oid4vciMachine","agent","oid4vciHolderGetMachineInterpreter","requestData","credentialOffer","CredentialOfferClient","fromURI","createAuthorizationRequestURL","flowType","clientId","clientAssertionType","interpreter","machineState","availableMethods","includes","stateType","interpreterStartOrResume","cleanupAllOtherInstances","cleanupOnFinalState","singletonCheck","noRegistration","start","send","OID4VCIMachineEvents","PROVIDE_AUTHORIZATION_CODE_RESPONSE","data"]}