@credebl/ssi-mobile-openid4vc 2.2.1 → 2.3.0-alpha-20261104134326

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,3 +1,4 @@
1
+ import { CredentialBindingPolicy } from "./credentialBindingResolver.mjs";
1
2
  import { FormattedSubmission, FormattedSubmissionEntry } from "./display/proof.mjs";
2
3
  import "./display/index.mjs";
3
4
  import { GetCredentialsForProofRequestOptions, extractCredentialPlaceholderFromQueryCredential } from "./resolverProof.mjs";
@@ -70,7 +71,9 @@ declare class OpenID4VCSDK implements MobileSDKModule {
70
71
  accessToken,
71
72
  clientId,
72
73
  pidSchemes,
73
- requestBatch
74
+ requestBatch,
75
+ holderDidUrl,
76
+ bindingPolicy
74
77
  }: {
75
78
  resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer;
76
79
  credentialConfigurationIdsToRequest?: string[];
@@ -80,6 +83,18 @@ declare class OpenID4VCSDK implements MobileSDKModule {
80
83
  msoMdocDoctypes: Array<string>;
81
84
  };
82
85
  requestBatch?: boolean | number;
86
+ /**
87
+ * Bind the credentials to this DID instead of a new key: a verification method id
88
+ * (e.g. `did:web:example.com#key-1`), or a bare DID to use its first authentication key.
89
+ * The DID must have been created or imported in this agent.
90
+ */
91
+ holderDidUrl?: string;
92
+ /**
93
+ * What to do when the issuer does not support `holderDidUrl` (DID method or key algorithm):
94
+ * `require` fails the request, `prefer` binds to a new key instead. Ignored without `holderDidUrl`.
95
+ * @default "require"
96
+ */
97
+ bindingPolicy?: CredentialBindingPolicy;
83
98
  accessToken: OpenId4VciRequestTokenResponse;
84
99
  }): Promise<{
85
100
  deferredCredentials: _credo_ts_openid4vc0.OpenId4VciDeferredCredentialResponse[];
@@ -154,6 +169,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
154
169
  token_type?: string | undefined;
155
170
  access_token?: string | undefined;
156
171
  expires_in?: number | undefined;
172
+ error?: undefined;
157
173
  } & {
158
174
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
159
175
  }) | {
@@ -169,6 +185,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
169
185
  token_type?: string | undefined;
170
186
  access_token?: string | undefined;
171
187
  expires_in?: number | undefined;
188
+ error?: undefined;
172
189
  } & {
173
190
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
174
191
  };
@@ -191,6 +208,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
191
208
  token_type?: string | undefined;
192
209
  access_token?: string | undefined;
193
210
  expires_in?: number | undefined;
211
+ error?: undefined;
194
212
  } & {
195
213
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
196
214
  }) | {
@@ -206,6 +224,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
206
224
  token_type?: string | undefined;
207
225
  access_token?: string | undefined;
208
226
  expires_in?: number | undefined;
227
+ error?: undefined;
209
228
  } & {
210
229
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
211
230
  };
@@ -227,6 +246,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
227
246
  token_type?: string | undefined;
228
247
  access_token?: string | undefined;
229
248
  expires_in?: number | undefined;
249
+ error?: undefined;
230
250
  } & {
231
251
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
232
252
  }) | {
@@ -242,6 +262,7 @@ declare class OpenID4VCSDK implements MobileSDKModule {
242
262
  token_type?: string | undefined;
243
263
  access_token?: string | undefined;
244
264
  expires_in?: number | undefined;
265
+ error?: undefined;
245
266
  } & {
246
267
  presentation_submission?: _credo_ts_core0.DifPresentationExchangeSubmission;
247
268
  };
@@ -1 +1 @@
1
- {"version":3,"file":"OpenIDSdk.d.mts","names":[],"sources":["../src/OpenIDSdk.tsx"],"mappings":";;;;;;;;;;;KAsEY,0BAAA,GAA6B,OAAA,CAAQ,UAAA,CAAW,YAAA;AAAA,KAEhD,sBAAA,QAA8B,uBAAA;AAAA,cAE7B,mBAAA,GAAuB,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BAAA,CAAA,oCAAA;;;;;;;;;;EAkCjE,oBAAA,CAAqB,IAAA;IAChC,eAAA,EAAiB,0BAAA;IACjB,SAAA,EAAW,yBAAA;IACX,QAAA;IACA,YAAA;EAAA,IACD,OAAA;EAyCY,2BAAA,CAA4B,OAAA,GAAS,4BAAA,GAAuC,OAAA;AAAA"}
@@ -1,3 +1,4 @@
1
+ import { assertOfferAcceptsHolderDid, assertW3cCredentialsBoundToHolderDid, getCredentialBindingResolver } from "./credentialBindingResolver.mjs";
1
2
  import { extractOpenId4VcCredentialMetadata, setOpenId4VcCredentialMetadata } from "./metadata/metadata.mjs";
2
3
  import "./metadata/index.mjs";
3
4
  import { applySelectedCredentialFilter, ensureSingleCredentialRequest, extractProviderRequest } from "./utils/dcapi.mjs";
@@ -6,7 +7,6 @@ import "./utils/index.mjs";
6
7
  import { getSelectedCredentialsForRequest } from "./display/proof.mjs";
7
8
  import { getAttributesAndMetadataForMdocPayload, getCredentialForDisplay } from "./display/display.mjs";
8
9
  import "./display/index.mjs";
9
- import { getCredentialBindingResolver } from "./credentialBindingResolver.mjs";
10
10
  import { loadCachedImageAsBase64DataUrl, mapMdocAttributes, mapMdocAttributesToClaimDisplay, mapSdJwtAttributesToClaimDisplay } from "./dcapi/mapAttributes.mjs";
11
11
  import { MdocRecordProvider } from "./providers/MdocProvider.mjs";
12
12
  import { SdJwtVcRecordProvider } from "./providers/SdJwtVcProvider.mjs";
@@ -16,7 +16,7 @@ import { BiometricAuthenticationError } from "./utils/error.mjs";
16
16
  import { Kms, MdocRecord, MdocRepository, SdJwtVcRecord, SdJwtVcRepository, W3cCredentialRecord, W3cCredentialRepository, X509Module } from "@credo-ts/core";
17
17
  import { OpenId4VcModule, getOfferedCredentials, getScopesFromCredentialConfigurationsSupported, preAuthorizedCodeGrantIdentifier } from "@credo-ts/openid4vc";
18
18
  import { registerCredentials, sendResponse } from "@animo-id/expo-digital-credentials-api";
19
- import { DeviceRequest, limitDisclosureToDeviceRequestNameSpaces } from "@owf/mdoc";
19
+ import { DeviceRequest } from "@owf/mdoc";
20
20
  import { Platform } from "react-native";
21
21
  import { jsx } from "react/jsx-runtime";
22
22
 
@@ -28,6 +28,26 @@ const getOpenid4VcModules = (configuration) => ({
28
28
  getTrustedCertificatesForVerification: configuration?.getTrustedCertificatesForVerification
29
29
  })
30
30
  });
31
+ /**
32
+ * Returns the issuer-signed items of a credential that answer a doc request. Throws when the
33
+ * credential cannot disclose a requested namespace or element, so it is not offered as a match.
34
+ */
35
+ function limitDisclosureToDeviceRequestNameSpaces(issuerSigned, docRequest) {
36
+ const issuerNamespaces = issuerSigned.issuerNamespaces?.issuerNamespaces;
37
+ const disclosedNamespaces = /* @__PURE__ */ new Map();
38
+ for (const [namespace, requestedElements] of docRequest.itemsRequest.namespaces) {
39
+ const namespaceItems = issuerNamespaces?.get(namespace);
40
+ if (!namespaceItems) throw new Error(`Credential does not contain the requested namespace '${namespace}'`);
41
+ const disclosedItems = [];
42
+ for (const elementIdentifier of requestedElements.keys()) {
43
+ const item = namespaceItems.find((issuerSignedItem) => issuerSignedItem.elementIdentifier === elementIdentifier);
44
+ if (!item) throw new Error(`Credential does not contain the requested element '${elementIdentifier}' in namespace '${namespace}'`);
45
+ disclosedItems.push(item);
46
+ }
47
+ disclosedNamespaces.set(namespace, disclosedItems);
48
+ }
49
+ return disclosedNamespaces;
50
+ }
31
51
  var OpenID4VCSDK = class {
32
52
  constructor(configuration) {
33
53
  this.configuration = configuration;
@@ -88,23 +108,31 @@ var OpenID4VCSDK = class {
88
108
  };
89
109
  });
90
110
  }
91
- async receiveCredentialFromOpenId4VciOffer({ resolvedCredentialOffer, credentialConfigurationIdsToRequest, accessToken, clientId, pidSchemes, requestBatch }) {
111
+ async receiveCredentialFromOpenId4VciOffer({ resolvedCredentialOffer, credentialConfigurationIdsToRequest, accessToken, clientId, pidSchemes, requestBatch, holderDidUrl, bindingPolicy }) {
92
112
  const agent = this.assertAndGetAgent();
93
113
  const offeredCredentialsToRequest = getOfferedCredentials(credentialConfigurationIdsToRequest ?? [resolvedCredentialOffer.credentialOfferPayload.credential_configuration_ids[0]], resolvedCredentialOffer.offeredCredentialConfigurations);
94
114
  if (Object.keys(offeredCredentialsToRequest).length === 0) throw new Error(`Parameter 'credentialConfigurationIdsToRequest' with values ${credentialConfigurationIdsToRequest} is not a credential_configuration_id in the credential offer.`);
115
+ const credentialConfigurationIds = Object.keys(offeredCredentialsToRequest);
116
+ if (holderDidUrl) await assertOfferAcceptsHolderDid(agent.context, resolvedCredentialOffer, credentialConfigurationIds, {
117
+ holderDidUrl,
118
+ bindingPolicy
119
+ });
95
120
  try {
96
121
  const { credentials, deferredCredentials } = await agent.openid4vc.holder.requestCredentials({
97
122
  resolvedCredentialOffer,
98
123
  ...accessToken,
99
124
  clientId,
100
- credentialConfigurationIds: Object.keys(offeredCredentialsToRequest),
125
+ credentialConfigurationIds,
101
126
  verifyCredentialStatus: false,
102
127
  allowedProofOfPossessionSignatureAlgorithms: [Kms.KnownJwaSignatureAlgorithms.ES256, Kms.KnownJwaSignatureAlgorithms.EdDSA],
103
128
  credentialBindingResolver: await getCredentialBindingResolver({
104
129
  pidSchemes,
105
- requestBatch
130
+ requestBatch,
131
+ holderDidUrl,
132
+ bindingPolicy
106
133
  })
107
134
  });
135
+ if (holderDidUrl && bindingPolicy !== "prefer") assertW3cCredentialsBoundToHolderDid(credentials.map((credential) => credential.record), holderDidUrl);
108
136
  return {
109
137
  deferredCredentials,
110
138
  credentials: await this.parseCredentialResponses(credentials, resolvedCredentialOffer.metadata)
@@ -228,8 +256,8 @@ var OpenID4VCSDK = class {
228
256
  inputDescriptorId: docRequest.itemsRequest.docType,
229
257
  isSatisfied: true,
230
258
  credentials: matchingMdocs.map((matchingMdoc) => {
231
- const disclosedAttributePaths = Array.from(matchingMdoc.disclosedNameSpaces.issuerNamespaces.entries()).flatMap(([namespace, value]) => value.map((issuerSignedItem) => [namespace, issuerSignedItem.elementIdentifier]));
232
- const { attributes, metadata } = getAttributesAndMetadataForMdocPayload(Object.fromEntries(Array.from(matchingMdoc.disclosedNameSpaces.issuerNamespaces.entries()).map(([namespace, value]) => [namespace, Object.fromEntries(value.map((issuerSignedItem) => [issuerSignedItem.elementIdentifier, issuerSignedItem.elementValue]))])), matchingMdoc.mdoc);
259
+ const disclosedAttributePaths = Array.from(matchingMdoc.disclosedNameSpaces.entries()).flatMap(([namespace, value]) => value.map((issuerSignedItem) => [namespace, issuerSignedItem.elementIdentifier]));
260
+ const { attributes, metadata } = getAttributesAndMetadataForMdocPayload(Object.fromEntries(Array.from(matchingMdoc.disclosedNameSpaces.entries()).map(([namespace, value]) => [namespace, Object.fromEntries(value.map((issuerSignedItem) => [issuerSignedItem.elementIdentifier, issuerSignedItem.elementValue]))])), matchingMdoc.mdoc);
233
261
  return {
234
262
  credential: matchingMdoc.credential,
235
263
  disclosed: {
@@ -1 +1 @@
1
- {"version":3,"file":"OpenIDSdk.mjs","names":[],"sources":["../src/OpenIDSdk.tsx"],"sourcesContent":["import {\n DigitalCredentialsApiMatcher,\n DigitalCredentialsRequest,\n registerCredentials,\n sendResponse,\n} from '@animo-id/expo-digital-credentials-api'\nimport type { MobileSDKModule } from '@credebl/ssi-mobile-core'\nimport {\n type Agent,\n type DifPresentationExchangeDefinitionV2,\n Kms,\n MdocRecord,\n MdocRepository,\n type SdJwtVcPayload,\n SdJwtVcRecord,\n SdJwtVcRepository,\n type SdJwtVcSignOptions,\n W3cCredentialRecord,\n W3cCredentialRepository,\n X509Module,\n type X509ModuleConfigOptions,\n} from '@credo-ts/core'\nimport {\n getOfferedCredentials,\n getScopesFromCredentialConfigurationsSupported,\n type OpenId4VciCredentialConfigurationSupportedWithFormats,\n OpenId4VciCredentialResponse,\n OpenId4VciMetadata,\n type OpenId4VciRequestTokenResponse,\n type OpenId4VciResolvedAuthorizationRequest,\n type OpenId4VciResolvedCredentialOffer,\n OpenId4VcModule,\n preAuthorizedCodeGrantIdentifier,\n} from '@credo-ts/openid4vc'\nimport { DeviceRequest, limitDisclosureToDeviceRequestNameSpaces } from '@owf/mdoc'\nimport type { PropsWithChildren } from 'react'\nimport { Platform } from 'react-native'\nimport { getCredentialBindingResolver } from './credentialBindingResolver'\nimport {\n CredentialItem,\n loadCachedImageAsBase64DataUrl,\n mapMdocAttributes,\n mapMdocAttributesToClaimDisplay,\n mapSdJwtAttributesToClaimDisplay,\n} from './dcapi/mapAttributes'\nimport {\n type FormattedSubmission,\n type FormattedSubmissionEntry,\n type FormattedSubmissionEntrySatisfiedCredential,\n getAttributesAndMetadataForMdocPayload,\n getCredentialForDisplay,\n getSelectedCredentialsForRequest,\n} from './display'\nimport { extractOpenId4VcCredentialMetadata, setOpenId4VcCredentialMetadata } from './metadata'\nimport { MdocRecordProvider, SdJwtVcRecordProvider } from './providers'\nimport {\n formatDcqlCredentialsForRequest,\n formatDifPexCredentialsForRequest,\n type GetCredentialsForProofRequestOptions,\n} from './resolverProof'\nimport {\n applySelectedCredentialFilter,\n ensureSingleCredentialRequest,\n extractProviderRequest,\n getHostNameFromUrl,\n} from './utils'\nimport { BiometricAuthenticationError } from './utils/error'\n\nexport { extractCredentialPlaceholderFromQueryCredential } from '../src/resolverProof'\n\nexport type CredentialsForProofRequest = Awaited<ReturnType<OpenID4VCSDK['getCredentialsForProofRequest']>>\n\nexport type OpenId4VcConfiguration = {} & X509ModuleConfigOptions\n\nexport const getOpenid4VcModules = (configuration: OpenId4VcConfiguration) =>\n ({\n openid4vc: new OpenId4VcModule({}),\n x509: new X509Module({\n trustedCertificates: configuration?.trustedCertificates,\n getTrustedCertificatesForVerification: configuration?.getTrustedCertificatesForVerification,\n }),\n }) as const\n\nexport type OpenId4VcAgent = Agent<ReturnType<typeof getOpenid4VcModules>>\n\nexport class OpenID4VCSDK implements MobileSDKModule {\n private agent?: OpenId4VcAgent\n private configuration: OpenId4VcConfiguration\n\n public constructor(configuration: OpenId4VcConfiguration) {\n this.configuration = configuration\n }\n\n private assertAndGetAgent(): OpenId4VcAgent {\n if (!this.agent) {\n throw new Error('Agent not initialized')\n }\n\n return this.agent\n }\n\n public initialize(agent: OpenId4VcAgent): void {\n this.agent = agent\n }\n\n public getAgentModules() {\n return getOpenid4VcModules(this.configuration)\n }\n\n public static OpenIDProvider({ agent, children }: PropsWithChildren<{ agent: Agent }>) {\n return (\n <SdJwtVcRecordProvider agent={agent}>\n <MdocRecordProvider agent={agent}>{children}</MdocRecordProvider>\n </SdJwtVcRecordProvider>\n )\n }\n\n public async resolveOpenId4VciOffer({\n offer,\n authorization,\n customHeaders,\n fetchAuthorization = true,\n }: {\n offer: { uri: string }\n authorization?: { clientId: string; redirectUri: string }\n customHeaders?: Record<string, unknown>\n fetchAuthorization?: boolean\n }) {\n const agent = this.assertAndGetAgent()\n\n agent.config.logger.info(`Receiving openid uri ${offer.uri}`, {\n uri: offer.uri,\n })\n\n const resolvedCredentialOffer = await agent.modules.openid4vc.holder.resolveCredentialOffer(offer.uri)\n let resolvedAuthorizationRequest: OpenId4VciResolvedAuthorizationRequest | undefined\n\n // NOTE: we always assume scopes are used at the moment\n if (fetchAuthorization && resolvedCredentialOffer.credentialOfferPayload.grants?.authorization_code) {\n // If only authorization_code grant is valid and user didn't provide authorization details we can't continue\n if (!resolvedCredentialOffer.credentialOfferPayload.grants[preAuthorizedCodeGrantIdentifier] && !authorization) {\n throw new Error(\n \"Missing 'authorization' parameter with 'clientId' and 'redirectUri' and authorization code flow is only allowed grant type on offer.\"\n )\n }\n\n // TODO: authorization should only be initiated after we know which credentials we're going to request\n if (authorization) {\n resolvedAuthorizationRequest = await agent.modules.openid4vc.holder.resolveOpenId4VciAuthorizationRequest(\n resolvedCredentialOffer,\n {\n redirectUri: authorization.redirectUri,\n clientId: authorization.clientId,\n scope: getScopesFromCredentialConfigurationsSupported(\n resolvedCredentialOffer.offeredCredentialConfigurations\n ),\n // Added in patch but not in types\n // @ts-expect-error\n customHeaders,\n }\n )\n }\n }\n\n return {\n resolvedCredentialOffer,\n resolvedAuthorizationRequest,\n }\n }\n\n public async acquirePreAuthorizedAccessToken({\n resolvedCredentialOffer,\n txCode,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n txCode?: string\n }) {\n const agent = this.assertAndGetAgent()\n return await agent.modules.openid4vc.holder.requestToken({\n resolvedCredentialOffer,\n txCode,\n })\n }\n\n async parseCredentialResponses(credentials: OpenId4VciCredentialResponse[], issuerMetadata: OpenId4VciMetadata) {\n return credentials.map(({ record, ...credentialResponse }) => {\n // OpenID4VC metadata\n const openId4VcMetadata = extractOpenId4VcCredentialMetadata(credentialResponse.credentialConfiguration, {\n id: issuerMetadata.credentialIssuer.credential_issuer,\n display: issuerMetadata.credentialIssuer.display,\n })\n setOpenId4VcCredentialMetadata(record, openId4VcMetadata)\n\n return {\n ...credentialResponse,\n credential: record,\n }\n })\n }\n\n public async receiveCredentialFromOpenId4VciOffer({\n resolvedCredentialOffer,\n credentialConfigurationIdsToRequest,\n accessToken,\n clientId,\n pidSchemes,\n requestBatch,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n credentialConfigurationIdsToRequest?: string[]\n clientId?: string\n pidSchemes?: { sdJwtVcVcts: Array<string>; msoMdocDoctypes: Array<string> }\n requestBatch?: boolean | number\n\n // TODO: cNonce should maybe be provided separately (multiple calls can have different c_nonce values)\n accessToken: OpenId4VciRequestTokenResponse\n }) {\n const agent = this.assertAndGetAgent()\n const offeredCredentialsToRequest = getOfferedCredentials(\n credentialConfigurationIdsToRequest ?? [\n resolvedCredentialOffer.credentialOfferPayload.credential_configuration_ids[0],\n ],\n resolvedCredentialOffer.offeredCredentialConfigurations\n ) as OpenId4VciCredentialConfigurationSupportedWithFormats\n\n if (Object.keys(offeredCredentialsToRequest).length === 0) {\n throw new Error(\n `Parameter 'credentialConfigurationIdsToRequest' with values ${credentialConfigurationIdsToRequest} is not a credential_configuration_id in the credential offer.`\n )\n }\n\n try {\n const { credentials, deferredCredentials } = await agent.openid4vc.holder.requestCredentials({\n resolvedCredentialOffer,\n ...accessToken,\n clientId,\n credentialConfigurationIds: Object.keys(offeredCredentialsToRequest),\n verifyCredentialStatus: false,\n allowedProofOfPossessionSignatureAlgorithms: [\n Kms.KnownJwaSignatureAlgorithms.ES256,\n Kms.KnownJwaSignatureAlgorithms.EdDSA,\n ],\n credentialBindingResolver: await getCredentialBindingResolver({\n pidSchemes,\n requestBatch,\n }),\n })\n\n return {\n deferredCredentials,\n credentials: await this.parseCredentialResponses(credentials, resolvedCredentialOffer.metadata),\n }\n } catch (error) {\n // TODO: if one biometric operation fails it will fail the whole credential receiving. We should have more control so we\n // can retry e.g. the second credential\n // Handle biometric authentication errors\n throw BiometricAuthenticationError.tryParseFromError(error) ?? error\n }\n }\n\n public async storeOpenIdCredential(\n cred: W3cCredentialRecord | SdJwtVcRecord | MdocRecord,\n matcher: DigitalCredentialsApiMatcher = 'ubique'\n ): Promise<void> {\n const agent = this.assertAndGetAgent()\n if (cred instanceof W3cCredentialRecord) {\n await agent.dependencyManager.resolve(W3cCredentialRepository).save(agent.context, cred)\n } else if (cred instanceof SdJwtVcRecord) {\n await agent.dependencyManager.resolve(SdJwtVcRepository).save(agent.context, cred)\n } else if (cred instanceof MdocRecord) {\n await agent.dependencyManager.resolve(MdocRepository).save(agent.context, cred)\n } else {\n throw new Error('Credential type is not supported')\n }\n this.registerCredentialsForDcApi(matcher)\n }\n\n public async acquireAuthorizationCodeAccessToken({\n resolvedCredentialOffer,\n codeVerifier,\n authorizationCode,\n clientId,\n redirectUri,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n codeVerifier?: string\n authorizationCode: string\n clientId: string\n redirectUri?: string\n }) {\n const agent = this.assertAndGetAgent()\n const response = await agent.modules.openid4vc.holder.requestToken({\n resolvedCredentialOffer,\n code: authorizationCode,\n codeVerifier,\n redirectUri,\n clientId,\n })\n return response\n }\n\n // Proofs\n public async getCredentialsForProofRequest({\n uri,\n requestPayload,\n allowUntrustedFederation = true,\n origin,\n trustedX509Entities,\n preferredLocale,\n selectedCredentialsId,\n }: GetCredentialsForProofRequestOptions) {\n const agent = this.assertAndGetAgent()\n\n let request: string | Record<string, unknown>\n if (uri) {\n request = uri\n } else if (requestPayload) {\n request = requestPayload\n } else {\n throw new Error('Either requestPayload or uri must be provided')\n }\n\n agent.config.logger.info('Receiving openid request', {\n request,\n })\n\n const resolved = await agent.modules.openid4vc.holder.resolveOpenId4VpAuthorizationRequest(request, {\n origin,\n })\n\n const { authorizationRequestPayload } = resolved\n const clientMetadata = authorizationRequestPayload.client_metadata\n const verifier = {\n entity_id: authorizationRequestPayload.client_id ?? `web-origin:${origin}`,\n uri:\n typeof authorizationRequestPayload.response_uri === 'string'\n ? new URL(authorizationRequestPayload.response_uri).origin\n : undefined,\n logo_uri: clientMetadata?.logo_uri,\n organization_name: clientMetadata?.client_name,\n }\n let formattedSubmission: FormattedSubmission\n if (resolved.presentationExchange) {\n formattedSubmission = formatDifPexCredentialsForRequest(\n resolved.presentationExchange.credentialsForRequest,\n resolved.presentationExchange.definition as DifPresentationExchangeDefinitionV2,\n preferredLocale\n )\n } else if (resolved.dcql) {\n formattedSubmission = formatDcqlCredentialsForRequest(resolved.dcql.queryResult)\n } else {\n throw new Error('No presentation exchange or dcql found in authorization request.')\n }\n\n return {\n ...resolved.presentationExchange,\n ...resolved.dcql,\n origin,\n verifier: {\n hostName: verifier.uri,\n entityId: verifier.entity_id,\n logo: verifier.logo_uri\n ? {\n url: verifier.logo_uri,\n }\n : undefined,\n name: verifier.organization_name,\n },\n authorizationRequest: resolved.authorizationRequestPayload,\n formattedSubmission,\n transactionData: resolved.transactionData,\n } as const\n }\n\n public async shareProof({\n resolvedRequest,\n selectedCredentials,\n acceptTransactionData,\n }: {\n resolvedRequest: CredentialsForProofRequest\n selectedCredentials: { [inputDescriptorId: string]: string }\n acceptTransactionData?: boolean\n }) {\n const agent = this.assertAndGetAgent()\n const { authorizationRequest } = resolvedRequest\n if (\n !resolvedRequest.credentialsForRequest?.areRequirementsSatisfied &&\n !resolvedRequest.queryResult?.can_be_satisfied\n ) {\n throw new Error('Requirements from proof request are not satisfied')\n }\n const presentationExchangeCredentials = resolvedRequest.credentialsForRequest\n ? Object.fromEntries(\n await Promise.all(\n resolvedRequest.credentialsForRequest.requirements.flatMap((requirement) =>\n requirement.submissionEntry.slice(0, requirement.needsCount).map(async (entry) => {\n const credentialId = selectedCredentials[entry.inputDescriptorId]\n const credential =\n entry.verifiableCredentials.find((vc) => vc.credentialRecord.id === credentialId) ??\n entry.verifiableCredentials[0]\n\n return [entry.inputDescriptorId, [credential]]\n })\n )\n )\n )\n : undefined\n\n const dcqlCredentials = resolvedRequest.queryResult\n ? Object.fromEntries(\n await Promise.all(\n Object.entries(\n Object.keys(selectedCredentials).length > 0\n ? getSelectedCredentialsForRequest(resolvedRequest.queryResult, selectedCredentials)\n : agent.modules.openid4vc.holder.selectCredentialsForDcqlRequest(resolvedRequest.queryResult)\n ).map(async ([queryCredentialId, credentials]) => {\n return [queryCredentialId, credentials]\n })\n )\n )\n : undefined\n\n const result = await agent.modules.openid4vc.holder.acceptOpenId4VpAuthorizationRequest({\n authorizationRequestPayload: authorizationRequest,\n presentationExchange: presentationExchangeCredentials\n ? {\n credentials: presentationExchangeCredentials,\n }\n : undefined,\n dcql: dcqlCredentials\n ? {\n credentials: dcqlCredentials,\n }\n : undefined,\n transactionData: undefined,\n origin: resolvedRequest.origin,\n })\n\n if (result.serverResponse && (result.serverResponse.status < 200 || result.serverResponse.status > 299)) {\n agent.config.logger.error('Error while accepting authorization request', {\n authorizationRequest,\n response: result.authorizationResponse,\n responsePayload: result.authorizationResponsePayload,\n })\n throw new Error(\n `Error while accepting authorization request. ${JSON.stringify(result.serverResponse.body, null, 2)}`\n )\n }\n\n return result\n }\n\n public async getSubmissionForMdocDocumentRequest(encodedDeviceRequest: Uint8Array) {\n const agent = this.assertAndGetAgent()\n\n const deviceRequest = DeviceRequest.decode(encodedDeviceRequest)\n\n const matchingDocTypeRecords = await agent.mdoc.findAllByQuery({\n $or: deviceRequest.docRequests.map((request) => ({\n docType: request.itemsRequest.docType,\n })),\n })\n\n const mdocs = matchingDocTypeRecords.map((record) => ({\n credential: getCredentialForDisplay(record),\n mdoc: record.firstCredential,\n issuerSignedDocument: record.firstCredential.issuerSigned,\n }))\n\n const entries: FormattedSubmissionEntry[] = deviceRequest.docRequests.map(\n (docRequest): FormattedSubmissionEntry => {\n const matchingMdocs = mdocs\n .map((mdoc) => {\n if (mdoc.mdoc.docType !== docRequest.itemsRequest.docType) return undefined\n\n try {\n const disclosedNamespaces = limitDisclosureToDeviceRequestNameSpaces(\n mdoc.issuerSignedDocument,\n docRequest\n )\n\n return {\n ...mdoc,\n disclosedNameSpaces: disclosedNamespaces,\n }\n } catch (_error) {\n return undefined\n }\n })\n .filter((m): m is NonNullable<typeof m> => m !== undefined)\n\n if (matchingMdocs.length === 0) {\n const requestedAttributePaths = Array.from(docRequest.itemsRequest.namespaces.values()).flatMap((value) =>\n Array.from(value.keys()).map((key) => [key])\n )\n\n return {\n inputDescriptorId: docRequest.itemsRequest.docType,\n isSatisfied: false,\n name: docRequest.itemsRequest.docType,\n requestedAttributePaths,\n }\n }\n\n return {\n // input descriptor id is doctype\n inputDescriptorId: docRequest.itemsRequest.docType,\n isSatisfied: true,\n credentials: matchingMdocs.map((matchingMdoc): FormattedSubmissionEntrySatisfiedCredential => {\n const disclosedAttributePaths = Array.from(\n matchingMdoc.disclosedNameSpaces.issuerNamespaces.entries()\n ).flatMap(([namespace, value]) =>\n value.map((issuerSignedItem) => [namespace, issuerSignedItem.elementIdentifier])\n )\n\n const disclosedNamespaces = Object.fromEntries(\n Array.from(matchingMdoc.disclosedNameSpaces.issuerNamespaces.entries()).map(([namespace, value]) => [\n namespace,\n Object.fromEntries(\n value.map((issuerSignedItem) => [\n issuerSignedItem.elementIdentifier,\n // TODO: what is element value here?\n issuerSignedItem.elementValue,\n ])\n ),\n ])\n )\n const { attributes, metadata } = getAttributesAndMetadataForMdocPayload(\n disclosedNamespaces,\n matchingMdoc.mdoc\n )\n\n return {\n credential: matchingMdoc.credential,\n disclosed: {\n attributes,\n metadata,\n paths: disclosedAttributePaths,\n },\n }\n }) as [FormattedSubmissionEntrySatisfiedCredential, ...FormattedSubmissionEntrySatisfiedCredential[]],\n }\n }\n )\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n entries,\n }\n }\n\n public async signAndStoreCredential({\n format,\n payload,\n }: {\n format: 'sd-jwt'\n payload: SdJwtVcSignOptions<SdJwtVcPayload>\n }) {\n const agent = this.assertAndGetAgent()\n\n if (format === 'sd-jwt') {\n const credential = await agent.sdJwtVc.sign(payload)\n const record = await agent.sdJwtVc.store({ record: SdJwtVcRecord.fromSdJwtVc(credential) })\n return record\n }\n\n throw new Error(`Unsupported format ${format}`)\n }\n\n // DCAPI\n\n public async resolveRequestForDcApi(args: { request: DigitalCredentialsRequest }) {\n const agent = this.assertAndGetAgent()\n const { request } = args\n\n // Determine the raw provider request payload\n const providerRequest = extractProviderRequest(request)\n\n // Parse into authorization payload\n const authorizationPayload = typeof providerRequest === 'string' ? JSON.parse(providerRequest) : providerRequest\n\n // Fetch credentials matching the authorization request\n const result = await this.getCredentialsForProofRequest({\n requestPayload: authorizationPayload,\n origin: request.origin,\n })\n\n ensureSingleCredentialRequest(result)\n\n agent.config.logger.debug('Resolved Digital Credentials API request', {\n result,\n })\n\n // Filter down to only the selected credential\n applySelectedCredentialFilter(result, request.selectedEntry.credentialId)\n\n return {\n ...result,\n verifier: {\n ...result.verifier,\n hostName: getHostNameFromUrl(request.origin),\n },\n }\n }\n\n public async sendResponseForDcApi(args: {\n resolvedRequest: CredentialsForProofRequest\n dcRequest: DigitalCredentialsRequest\n protocol: string\n credentialId: string\n }) {\n const agent = this.assertAndGetAgent()\n const { resolvedRequest, dcRequest, protocol, credentialId } = args\n\n const entry = resolvedRequest.formattedSubmission.entries[0]\n\n if (!entry?.isSatisfied) {\n agent.config.logger.debug('Invalid DC API response state', {\n resolvedRequest,\n dcRequest,\n })\n throw new Error('Expected the Digital Credentials API request to be satisfied')\n }\n\n if (!credentialId) {\n agent.config.logger.debug('No credential id found for DC API', {\n resolvedRequest,\n dcRequest,\n })\n throw new Error('No credential id found for DC API')\n }\n\n const result = await this.shareProof({\n resolvedRequest,\n selectedCredentials: {\n [entry.inputDescriptorId]: credentialId,\n },\n })\n\n agent.config.logger.debug('Sending Digital Credentials API response', {\n result,\n })\n\n sendResponse({\n response: JSON.stringify({\n protocol,\n data: result.authorizationResponse,\n }),\n })\n }\n\n public async registerCredentialsForDcApi(matcher: DigitalCredentialsApiMatcher = 'ubique') {\n const agent = this.assertAndGetAgent()\n\n if (Platform.OS === 'ios') return\n\n const mdocRecords = await agent.mdoc.getAll()\n const sdJwtVcRecords = await agent.sdJwtVc.getAll()\n\n const mdocCredentials = mdocRecords.map(async (record): Promise<CredentialItem> => {\n const mdoc = record.firstCredential\n const { display } = getCredentialForDisplay(record)\n\n const iconDataUrl = display.backgroundImage?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.backgroundImage?.url)\n : display.issuer.logo?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.issuer.logo.url)\n : undefined\n\n return {\n id: record.id,\n credential: {\n doctype: mdoc.docType,\n format: 'mso_mdoc',\n namespaces: mapMdocAttributes(mdoc.issuerSignedNamespaces),\n },\n display: {\n title: display.name,\n subtitle: `Issued by ${display.issuer.name}`,\n claims: mapMdocAttributesToClaimDisplay(mdoc.issuerSignedNamespaces),\n iconDataUrl,\n },\n } as const\n })\n\n const sdJwtCredentials = sdJwtVcRecords.map(async (record): Promise<CredentialItem> => {\n const sdJwtVc = record.firstCredential\n const { display } = getCredentialForDisplay(record)\n\n const iconDataUrl = display.backgroundImage?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.backgroundImage?.url)\n : display.issuer.logo?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.issuer.logo.url)\n : undefined\n\n return {\n id: record.id,\n credential: {\n vct: record.getTags().vct,\n format: 'dc+sd-jwt',\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n claims: sdJwtVc.prettyClaims as any,\n },\n display: {\n title: display.name,\n subtitle: `Issued by ${display.issuer.name}`,\n claims: mapSdJwtAttributesToClaimDisplay(sdJwtVc.prettyClaims),\n iconDataUrl,\n },\n } as const\n })\n\n const credentials = await Promise.all([...sdJwtCredentials, ...mdocCredentials])\n agent.config.logger.trace('Registering credentials for Digital Credentials API')\n\n await registerCredentials({\n credentials,\n matcher,\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAa,uBAAuB,mBACjC;CACC,WAAW,IAAI,gBAAgB,EAAE,CAAC;CAClC,MAAM,IAAI,WAAW;EACnB,qBAAqB,eAAe;EACpC,uCAAuC,eAAe;EACvD,CAAC;CACH;AAIH,IAAa,eAAb,MAAqD;CAInD,AAAO,YAAY,eAAuC;AACxD,OAAK,gBAAgB;;CAGvB,AAAQ,oBAAoC;AAC1C,MAAI,CAAC,KAAK,MACR,OAAM,IAAI,MAAM,wBAAwB;AAG1C,SAAO,KAAK;;CAGd,AAAO,WAAW,OAA6B;AAC7C,OAAK,QAAQ;;CAGf,AAAO,kBAAkB;AACvB,SAAO,oBAAoB,KAAK,cAAc;;CAGhD,OAAc,eAAe,EAAE,OAAO,YAAiD;AACrF,SACE,oBAAC;GAA6B;aAC5B,oBAAC;IAA0B;IAAQ;KAA8B;IAC3C;;CAI5B,MAAa,uBAAuB,EAClC,OACA,eACA,eACA,qBAAqB,QAMpB;EACD,MAAM,QAAQ,KAAK,mBAAmB;AAEtC,QAAM,OAAO,OAAO,KAAK,wBAAwB,MAAM,OAAO,EAC5D,KAAK,MAAM,KACZ,CAAC;EAEF,MAAM,0BAA0B,MAAM,MAAM,QAAQ,UAAU,OAAO,uBAAuB,MAAM,IAAI;EACtG,IAAI;AAGJ,MAAI,sBAAsB,wBAAwB,uBAAuB,QAAQ,oBAAoB;AAEnG,OAAI,C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entialsApiMatcher,\n DigitalCredentialsRequest,\n registerCredentials,\n sendResponse,\n} from '@animo-id/expo-digital-credentials-api'\nimport type { MobileSDKModule } from '@credebl/ssi-mobile-core'\nimport {\n type Agent,\n type DifPresentationExchangeDefinitionV2,\n Kms,\n MdocRecord,\n MdocRepository,\n type SdJwtVcPayload,\n SdJwtVcRecord,\n SdJwtVcRepository,\n type SdJwtVcSignOptions,\n W3cCredentialRecord,\n W3cCredentialRepository,\n X509Module,\n type X509ModuleConfigOptions,\n} from '@credo-ts/core'\nimport {\n getOfferedCredentials,\n getScopesFromCredentialConfigurationsSupported,\n type OpenId4VciCredentialConfigurationSupportedWithFormats,\n OpenId4VciCredentialResponse,\n OpenId4VciMetadata,\n type OpenId4VciRequestTokenResponse,\n type OpenId4VciResolvedAuthorizationRequest,\n type OpenId4VciResolvedCredentialOffer,\n OpenId4VcModule,\n preAuthorizedCodeGrantIdentifier,\n} from '@credo-ts/openid4vc'\nimport { DeviceRequest, type DocRequest, type IssuerSigned, type IssuerSignedItem } from '@owf/mdoc'\nimport type { PropsWithChildren } from 'react'\nimport { Platform } from 'react-native'\nimport {\n assertOfferAcceptsHolderDid,\n assertW3cCredentialsBoundToHolderDid,\n type CredentialBindingPolicy,\n getCredentialBindingResolver,\n} from './credentialBindingResolver'\nimport {\n CredentialItem,\n loadCachedImageAsBase64DataUrl,\n mapMdocAttributes,\n mapMdocAttributesToClaimDisplay,\n mapSdJwtAttributesToClaimDisplay,\n} from './dcapi/mapAttributes'\nimport {\n type FormattedSubmission,\n type FormattedSubmissionEntry,\n type FormattedSubmissionEntrySatisfiedCredential,\n getAttributesAndMetadataForMdocPayload,\n getCredentialForDisplay,\n getSelectedCredentialsForRequest,\n} from './display'\nimport { extractOpenId4VcCredentialMetadata, setOpenId4VcCredentialMetadata } from './metadata'\nimport { MdocRecordProvider, SdJwtVcRecordProvider } from './providers'\nimport {\n formatDcqlCredentialsForRequest,\n formatDifPexCredentialsForRequest,\n type GetCredentialsForProofRequestOptions,\n} from './resolverProof'\nimport {\n applySelectedCredentialFilter,\n ensureSingleCredentialRequest,\n extractProviderRequest,\n getHostNameFromUrl,\n} from './utils'\nimport { BiometricAuthenticationError } from './utils/error'\n\nexport { extractCredentialPlaceholderFromQueryCredential } from '../src/resolverProof'\n\nexport type CredentialsForProofRequest = Awaited<ReturnType<OpenID4VCSDK['getCredentialsForProofRequest']>>\n\nexport type OpenId4VcConfiguration = {} & X509ModuleConfigOptions\n\nexport const getOpenid4VcModules = (configuration: OpenId4VcConfiguration) =>\n ({\n openid4vc: new OpenId4VcModule({}),\n x509: new X509Module({\n trustedCertificates: configuration?.trustedCertificates,\n getTrustedCertificatesForVerification: configuration?.getTrustedCertificatesForVerification,\n }),\n }) as const\n\nexport type OpenId4VcAgent = Agent<ReturnType<typeof getOpenid4VcModules>>\n\n/**\n * Returns the issuer-signed items of a credential that answer a doc request. Throws when the\n * credential cannot disclose a requested namespace or element, so it is not offered as a match.\n */\nfunction limitDisclosureToDeviceRequestNameSpaces(issuerSigned: IssuerSigned, docRequest: DocRequest) {\n const issuerNamespaces = issuerSigned.issuerNamespaces?.issuerNamespaces\n const disclosedNamespaces = new Map<string, IssuerSignedItem[]>()\n\n for (const [namespace, requestedElements] of docRequest.itemsRequest.namespaces) {\n const namespaceItems = issuerNamespaces?.get(namespace)\n if (!namespaceItems) {\n throw new Error(`Credential does not contain the requested namespace '${namespace}'`)\n }\n\n const disclosedItems: IssuerSignedItem[] = []\n for (const elementIdentifier of requestedElements.keys()) {\n const item = namespaceItems.find((issuerSignedItem) => issuerSignedItem.elementIdentifier === elementIdentifier)\n if (!item) {\n throw new Error(\n `Credential does not contain the requested element '${elementIdentifier}' in namespace '${namespace}'`\n )\n }\n disclosedItems.push(item)\n }\n\n disclosedNamespaces.set(namespace, disclosedItems)\n }\n\n return disclosedNamespaces\n}\n\nexport class OpenID4VCSDK implements MobileSDKModule {\n private agent?: OpenId4VcAgent\n private configuration: OpenId4VcConfiguration\n\n public constructor(configuration: OpenId4VcConfiguration) {\n this.configuration = configuration\n }\n\n private assertAndGetAgent(): OpenId4VcAgent {\n if (!this.agent) {\n throw new Error('Agent not initialized')\n }\n\n return this.agent\n }\n\n public initialize(agent: OpenId4VcAgent): void {\n this.agent = agent\n }\n\n public getAgentModules() {\n return getOpenid4VcModules(this.configuration)\n }\n\n public static OpenIDProvider({ agent, children }: PropsWithChildren<{ agent: Agent }>) {\n return (\n <SdJwtVcRecordProvider agent={agent}>\n <MdocRecordProvider agent={agent}>{children}</MdocRecordProvider>\n </SdJwtVcRecordProvider>\n )\n }\n\n public async resolveOpenId4VciOffer({\n offer,\n authorization,\n customHeaders,\n fetchAuthorization = true,\n }: {\n offer: { uri: string }\n authorization?: { clientId: string; redirectUri: string }\n customHeaders?: Record<string, unknown>\n fetchAuthorization?: boolean\n }) {\n const agent = this.assertAndGetAgent()\n\n agent.config.logger.info(`Receiving openid uri ${offer.uri}`, {\n uri: offer.uri,\n })\n\n const resolvedCredentialOffer = await agent.modules.openid4vc.holder.resolveCredentialOffer(offer.uri)\n let resolvedAuthorizationRequest: OpenId4VciResolvedAuthorizationRequest | undefined\n\n // NOTE: we always assume scopes are used at the moment\n if (fetchAuthorization && resolvedCredentialOffer.credentialOfferPayload.grants?.authorization_code) {\n // If only authorization_code grant is valid and user didn't provide authorization details we can't continue\n if (!resolvedCredentialOffer.credentialOfferPayload.grants[preAuthorizedCodeGrantIdentifier] && !authorization) {\n throw new Error(\n \"Missing 'authorization' parameter with 'clientId' and 'redirectUri' and authorization code flow is only allowed grant type on offer.\"\n )\n }\n\n // TODO: authorization should only be initiated after we know which credentials we're going to request\n if (authorization) {\n resolvedAuthorizationRequest = await agent.modules.openid4vc.holder.resolveOpenId4VciAuthorizationRequest(\n resolvedCredentialOffer,\n {\n redirectUri: authorization.redirectUri,\n clientId: authorization.clientId,\n scope: getScopesFromCredentialConfigurationsSupported(\n resolvedCredentialOffer.offeredCredentialConfigurations\n ),\n // Added in patch but not in types\n // @ts-expect-error\n customHeaders,\n }\n )\n }\n }\n\n return {\n resolvedCredentialOffer,\n resolvedAuthorizationRequest,\n }\n }\n\n public async acquirePreAuthorizedAccessToken({\n resolvedCredentialOffer,\n txCode,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n txCode?: string\n }) {\n const agent = this.assertAndGetAgent()\n return await agent.modules.openid4vc.holder.requestToken({\n resolvedCredentialOffer,\n txCode,\n })\n }\n\n async parseCredentialResponses(credentials: OpenId4VciCredentialResponse[], issuerMetadata: OpenId4VciMetadata) {\n return credentials.map(({ record, ...credentialResponse }) => {\n // OpenID4VC metadata\n const openId4VcMetadata = extractOpenId4VcCredentialMetadata(credentialResponse.credentialConfiguration, {\n id: issuerMetadata.credentialIssuer.credential_issuer,\n display: issuerMetadata.credentialIssuer.display,\n })\n setOpenId4VcCredentialMetadata(record, openId4VcMetadata)\n\n return {\n ...credentialResponse,\n credential: record,\n }\n })\n }\n\n public async receiveCredentialFromOpenId4VciOffer({\n resolvedCredentialOffer,\n credentialConfigurationIdsToRequest,\n accessToken,\n clientId,\n pidSchemes,\n requestBatch,\n holderDidUrl,\n bindingPolicy,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n credentialConfigurationIdsToRequest?: string[]\n clientId?: string\n pidSchemes?: { sdJwtVcVcts: Array<string>; msoMdocDoctypes: Array<string> }\n requestBatch?: boolean | number\n /**\n * Bind the credentials to this DID instead of a new key: a verification method id\n * (e.g. `did:web:example.com#key-1`), or a bare DID to use its first authentication key.\n * The DID must have been created or imported in this agent.\n */\n holderDidUrl?: string\n /**\n * What to do when the issuer does not support `holderDidUrl` (DID method or key algorithm):\n * `require` fails the request, `prefer` binds to a new key instead. Ignored without `holderDidUrl`.\n * @default \"require\"\n */\n bindingPolicy?: CredentialBindingPolicy\n\n // TODO: cNonce should maybe be provided separately (multiple calls can have different c_nonce values)\n accessToken: OpenId4VciRequestTokenResponse\n }) {\n const agent = this.assertAndGetAgent()\n const offeredCredentialsToRequest = getOfferedCredentials(\n credentialConfigurationIdsToRequest ?? [\n resolvedCredentialOffer.credentialOfferPayload.credential_configuration_ids[0],\n ],\n resolvedCredentialOffer.offeredCredentialConfigurations\n ) as OpenId4VciCredentialConfigurationSupportedWithFormats\n\n if (Object.keys(offeredCredentialsToRequest).length === 0) {\n throw new Error(\n `Parameter 'credentialConfigurationIdsToRequest' with values ${credentialConfigurationIdsToRequest} is not a credential_configuration_id in the credential offer.`\n )\n }\n\n const credentialConfigurationIds = Object.keys(offeredCredentialsToRequest)\n\n if (holderDidUrl) {\n await assertOfferAcceptsHolderDid(agent.context, resolvedCredentialOffer, credentialConfigurationIds, {\n holderDidUrl,\n bindingPolicy,\n })\n }\n\n try {\n const { credentials, deferredCredentials } = await agent.openid4vc.holder.requestCredentials({\n resolvedCredentialOffer,\n ...accessToken,\n clientId,\n credentialConfigurationIds,\n verifyCredentialStatus: false,\n allowedProofOfPossessionSignatureAlgorithms: [\n Kms.KnownJwaSignatureAlgorithms.ES256,\n Kms.KnownJwaSignatureAlgorithms.EdDSA,\n ],\n credentialBindingResolver: await getCredentialBindingResolver({\n pidSchemes,\n requestBatch,\n holderDidUrl,\n bindingPolicy,\n }),\n })\n\n if (holderDidUrl && bindingPolicy !== 'prefer') {\n assertW3cCredentialsBoundToHolderDid(\n credentials.map((credential) => credential.record),\n holderDidUrl\n )\n }\n\n return {\n deferredCredentials,\n credentials: await this.parseCredentialResponses(credentials, resolvedCredentialOffer.metadata),\n }\n } catch (error) {\n // TODO: if one biometric operation fails it will fail the whole credential receiving. We should have more control so we\n // can retry e.g. the second credential\n // Handle biometric authentication errors\n throw BiometricAuthenticationError.tryParseFromError(error) ?? error\n }\n }\n\n public async storeOpenIdCredential(\n cred: W3cCredentialRecord | SdJwtVcRecord | MdocRecord,\n matcher: DigitalCredentialsApiMatcher = 'ubique'\n ): Promise<void> {\n const agent = this.assertAndGetAgent()\n if (cred instanceof W3cCredentialRecord) {\n await agent.dependencyManager.resolve(W3cCredentialRepository).save(agent.context, cred)\n } else if (cred instanceof SdJwtVcRecord) {\n await agent.dependencyManager.resolve(SdJwtVcRepository).save(agent.context, cred)\n } else if (cred instanceof MdocRecord) {\n await agent.dependencyManager.resolve(MdocRepository).save(agent.context, cred)\n } else {\n throw new Error('Credential type is not supported')\n }\n this.registerCredentialsForDcApi(matcher)\n }\n\n public async acquireAuthorizationCodeAccessToken({\n resolvedCredentialOffer,\n codeVerifier,\n authorizationCode,\n clientId,\n redirectUri,\n }: {\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer\n codeVerifier?: string\n authorizationCode: string\n clientId: string\n redirectUri?: string\n }) {\n const agent = this.assertAndGetAgent()\n const response = await agent.modules.openid4vc.holder.requestToken({\n resolvedCredentialOffer,\n code: authorizationCode,\n codeVerifier,\n redirectUri,\n clientId,\n })\n return response\n }\n\n // Proofs\n public async getCredentialsForProofRequest({\n uri,\n requestPayload,\n allowUntrustedFederation = true,\n origin,\n trustedX509Entities,\n preferredLocale,\n selectedCredentialsId,\n }: GetCredentialsForProofRequestOptions) {\n const agent = this.assertAndGetAgent()\n\n let request: string | Record<string, unknown>\n if (uri) {\n request = uri\n } else if (requestPayload) {\n request = requestPayload\n } else {\n throw new Error('Either requestPayload or uri must be provided')\n }\n\n agent.config.logger.info('Receiving openid request', {\n request,\n })\n\n const resolved = await agent.modules.openid4vc.holder.resolveOpenId4VpAuthorizationRequest(request, {\n origin,\n })\n\n const { authorizationRequestPayload } = resolved\n const clientMetadata = authorizationRequestPayload.client_metadata\n const verifier = {\n entity_id: authorizationRequestPayload.client_id ?? `web-origin:${origin}`,\n uri:\n typeof authorizationRequestPayload.response_uri === 'string'\n ? new URL(authorizationRequestPayload.response_uri).origin\n : undefined,\n logo_uri: clientMetadata?.logo_uri,\n organization_name: clientMetadata?.client_name,\n }\n let formattedSubmission: FormattedSubmission\n if (resolved.presentationExchange) {\n formattedSubmission = formatDifPexCredentialsForRequest(\n resolved.presentationExchange.credentialsForRequest,\n resolved.presentationExchange.definition as DifPresentationExchangeDefinitionV2,\n preferredLocale\n )\n } else if (resolved.dcql) {\n formattedSubmission = formatDcqlCredentialsForRequest(resolved.dcql.queryResult)\n } else {\n throw new Error('No presentation exchange or dcql found in authorization request.')\n }\n\n return {\n ...resolved.presentationExchange,\n ...resolved.dcql,\n origin,\n verifier: {\n hostName: verifier.uri,\n entityId: verifier.entity_id,\n logo: verifier.logo_uri\n ? {\n url: verifier.logo_uri,\n }\n : undefined,\n name: verifier.organization_name,\n },\n authorizationRequest: resolved.authorizationRequestPayload,\n formattedSubmission,\n transactionData: resolved.transactionData,\n } as const\n }\n\n public async shareProof({\n resolvedRequest,\n selectedCredentials,\n acceptTransactionData,\n }: {\n resolvedRequest: CredentialsForProofRequest\n selectedCredentials: { [inputDescriptorId: string]: string }\n acceptTransactionData?: boolean\n }) {\n const agent = this.assertAndGetAgent()\n const { authorizationRequest } = resolvedRequest\n if (\n !resolvedRequest.credentialsForRequest?.areRequirementsSatisfied &&\n !resolvedRequest.queryResult?.can_be_satisfied\n ) {\n throw new Error('Requirements from proof request are not satisfied')\n }\n const presentationExchangeCredentials = resolvedRequest.credentialsForRequest\n ? Object.fromEntries(\n await Promise.all(\n resolvedRequest.credentialsForRequest.requirements.flatMap((requirement) =>\n requirement.submissionEntry.slice(0, requirement.needsCount).map(async (entry) => {\n const credentialId = selectedCredentials[entry.inputDescriptorId]\n const credential =\n entry.verifiableCredentials.find((vc) => vc.credentialRecord.id === credentialId) ??\n entry.verifiableCredentials[0]\n\n return [entry.inputDescriptorId, [credential]]\n })\n )\n )\n )\n : undefined\n\n const dcqlCredentials = resolvedRequest.queryResult\n ? Object.fromEntries(\n await Promise.all(\n Object.entries(\n Object.keys(selectedCredentials).length > 0\n ? getSelectedCredentialsForRequest(resolvedRequest.queryResult, selectedCredentials)\n : agent.modules.openid4vc.holder.selectCredentialsForDcqlRequest(resolvedRequest.queryResult)\n ).map(async ([queryCredentialId, credentials]) => {\n return [queryCredentialId, credentials]\n })\n )\n )\n : undefined\n\n const result = await agent.modules.openid4vc.holder.acceptOpenId4VpAuthorizationRequest({\n authorizationRequestPayload: authorizationRequest,\n presentationExchange: presentationExchangeCredentials\n ? {\n credentials: presentationExchangeCredentials,\n }\n : undefined,\n dcql: dcqlCredentials\n ? {\n credentials: dcqlCredentials,\n }\n : undefined,\n transactionData: undefined,\n origin: resolvedRequest.origin,\n })\n\n if (result.serverResponse && (result.serverResponse.status < 200 || result.serverResponse.status > 299)) {\n agent.config.logger.error('Error while accepting authorization request', {\n authorizationRequest,\n response: result.authorizationResponse,\n responsePayload: result.authorizationResponsePayload,\n })\n throw new Error(\n `Error while accepting authorization request. ${JSON.stringify(result.serverResponse.body, null, 2)}`\n )\n }\n\n return result\n }\n\n public async getSubmissionForMdocDocumentRequest(encodedDeviceRequest: Uint8Array) {\n const agent = this.assertAndGetAgent()\n\n const deviceRequest = DeviceRequest.decode(encodedDeviceRequest)\n\n const matchingDocTypeRecords = await agent.mdoc.findAllByQuery({\n $or: deviceRequest.docRequests.map((request) => ({\n docType: request.itemsRequest.docType,\n })),\n })\n\n const mdocs = matchingDocTypeRecords.map((record) => ({\n credential: getCredentialForDisplay(record),\n mdoc: record.firstCredential,\n issuerSignedDocument: record.firstCredential.issuerSigned,\n }))\n\n const entries: FormattedSubmissionEntry[] = deviceRequest.docRequests.map(\n (docRequest): FormattedSubmissionEntry => {\n const matchingMdocs = mdocs\n .map((mdoc) => {\n if (mdoc.mdoc.docType !== docRequest.itemsRequest.docType) return undefined\n\n try {\n const disclosedNamespaces = limitDisclosureToDeviceRequestNameSpaces(\n mdoc.issuerSignedDocument,\n docRequest\n )\n\n return {\n ...mdoc,\n disclosedNameSpaces: disclosedNamespaces,\n }\n } catch (_error) {\n return undefined\n }\n })\n .filter((m): m is NonNullable<typeof m> => m !== undefined)\n\n if (matchingMdocs.length === 0) {\n const requestedAttributePaths = Array.from(docRequest.itemsRequest.namespaces.values()).flatMap((value) =>\n Array.from(value.keys()).map((key) => [key])\n )\n\n return {\n inputDescriptorId: docRequest.itemsRequest.docType,\n isSatisfied: false,\n name: docRequest.itemsRequest.docType,\n requestedAttributePaths,\n }\n }\n\n return {\n // input descriptor id is doctype\n inputDescriptorId: docRequest.itemsRequest.docType,\n isSatisfied: true,\n credentials: matchingMdocs.map((matchingMdoc): FormattedSubmissionEntrySatisfiedCredential => {\n const disclosedAttributePaths = Array.from(matchingMdoc.disclosedNameSpaces.entries()).flatMap(\n ([namespace, value]) => value.map((issuerSignedItem) => [namespace, issuerSignedItem.elementIdentifier])\n )\n\n const disclosedNamespaces = Object.fromEntries(\n Array.from(matchingMdoc.disclosedNameSpaces.entries()).map(([namespace, value]) => [\n namespace,\n Object.fromEntries(\n value.map((issuerSignedItem) => [\n issuerSignedItem.elementIdentifier,\n // TODO: what is element value here?\n issuerSignedItem.elementValue,\n ])\n ),\n ])\n )\n const { attributes, metadata } = getAttributesAndMetadataForMdocPayload(\n disclosedNamespaces,\n matchingMdoc.mdoc\n )\n\n return {\n credential: matchingMdoc.credential,\n disclosed: {\n attributes,\n metadata,\n paths: disclosedAttributePaths,\n },\n }\n }) as [FormattedSubmissionEntrySatisfiedCredential, ...FormattedSubmissionEntrySatisfiedCredential[]],\n }\n }\n )\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n entries,\n }\n }\n\n public async signAndStoreCredential({\n format,\n payload,\n }: {\n format: 'sd-jwt'\n payload: SdJwtVcSignOptions<SdJwtVcPayload>\n }) {\n const agent = this.assertAndGetAgent()\n\n if (format === 'sd-jwt') {\n const credential = await agent.sdJwtVc.sign(payload)\n const record = await agent.sdJwtVc.store({ record: SdJwtVcRecord.fromSdJwtVc(credential) })\n return record\n }\n\n throw new Error(`Unsupported format ${format}`)\n }\n\n // DCAPI\n\n public async resolveRequestForDcApi(args: { request: DigitalCredentialsRequest }) {\n const agent = this.assertAndGetAgent()\n const { request } = args\n\n // Determine the raw provider request payload\n const providerRequest = extractProviderRequest(request)\n\n // Parse into authorization payload\n const authorizationPayload = typeof providerRequest === 'string' ? JSON.parse(providerRequest) : providerRequest\n\n // Fetch credentials matching the authorization request\n const result = await this.getCredentialsForProofRequest({\n requestPayload: authorizationPayload,\n origin: request.origin,\n })\n\n ensureSingleCredentialRequest(result)\n\n agent.config.logger.debug('Resolved Digital Credentials API request', {\n result,\n })\n\n // Filter down to only the selected credential\n applySelectedCredentialFilter(result, request.selectedEntry.credentialId)\n\n return {\n ...result,\n verifier: {\n ...result.verifier,\n hostName: getHostNameFromUrl(request.origin),\n },\n }\n }\n\n public async sendResponseForDcApi(args: {\n resolvedRequest: CredentialsForProofRequest\n dcRequest: DigitalCredentialsRequest\n protocol: string\n credentialId: string\n }) {\n const agent = this.assertAndGetAgent()\n const { resolvedRequest, dcRequest, protocol, credentialId } = args\n\n const entry = resolvedRequest.formattedSubmission.entries[0]\n\n if (!entry?.isSatisfied) {\n agent.config.logger.debug('Invalid DC API response state', {\n resolvedRequest,\n dcRequest,\n })\n throw new Error('Expected the Digital Credentials API request to be satisfied')\n }\n\n if (!credentialId) {\n agent.config.logger.debug('No credential id found for DC API', {\n resolvedRequest,\n dcRequest,\n })\n throw new Error('No credential id found for DC API')\n }\n\n const result = await this.shareProof({\n resolvedRequest,\n selectedCredentials: {\n [entry.inputDescriptorId]: credentialId,\n },\n })\n\n agent.config.logger.debug('Sending Digital Credentials API response', {\n result,\n })\n\n sendResponse({\n response: JSON.stringify({\n protocol,\n data: result.authorizationResponse,\n }),\n })\n }\n\n public async registerCredentialsForDcApi(matcher: DigitalCredentialsApiMatcher = 'ubique') {\n const agent = this.assertAndGetAgent()\n\n if (Platform.OS === 'ios') return\n\n const mdocRecords = await agent.mdoc.getAll()\n const sdJwtVcRecords = await agent.sdJwtVc.getAll()\n\n const mdocCredentials = mdocRecords.map(async (record): Promise<CredentialItem> => {\n const mdoc = record.firstCredential\n const { display } = getCredentialForDisplay(record)\n\n const iconDataUrl = display.backgroundImage?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.backgroundImage?.url)\n : display.issuer.logo?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.issuer.logo.url)\n : undefined\n\n return {\n id: record.id,\n credential: {\n doctype: mdoc.docType,\n format: 'mso_mdoc',\n namespaces: mapMdocAttributes(mdoc.issuerSignedNamespaces),\n },\n display: {\n title: display.name,\n subtitle: `Issued by ${display.issuer.name}`,\n claims: mapMdocAttributesToClaimDisplay(mdoc.issuerSignedNamespaces),\n iconDataUrl,\n },\n } as const\n })\n\n const sdJwtCredentials = sdJwtVcRecords.map(async (record): Promise<CredentialItem> => {\n const sdJwtVc = record.firstCredential\n const { display } = getCredentialForDisplay(record)\n\n const iconDataUrl = display.backgroundImage?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.backgroundImage?.url)\n : display.issuer.logo?.url\n ? await loadCachedImageAsBase64DataUrl(agent.config.logger, display.issuer.logo.url)\n : undefined\n\n return {\n id: record.id,\n credential: {\n vct: record.getTags().vct,\n format: 'dc+sd-jwt',\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n claims: sdJwtVc.prettyClaims as any,\n },\n display: {\n title: display.name,\n subtitle: `Issued by ${display.issuer.name}`,\n claims: mapSdJwtAttributesToClaimDisplay(sdJwtVc.prettyClaims),\n iconDataUrl,\n },\n } as const\n })\n\n const credentials = await Promise.all([...sdJwtCredentials, ...mdocCredentials])\n agent.config.logger.trace('Registering credentials for Digital Credentials API')\n\n await registerCredentials({\n credentials,\n matcher,\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+EA,MAAa,uBAAuB,mBACjC;CACC,WAAW,IAAI,gBAAgB,EAAE,CAAC;CAClC,MAAM,IAAI,WAAW;EACnB,qBAAqB,eAAe;EACpC,uCAAuC,eAAe;EACvD,CAAC;CACH;;;;;AAQH,SAAS,yCAAyC,cAA4B,YAAwB;CACpG,MAAM,mBAAmB,aAAa,kBAAkB;CACxD,MAAM,sCAAsB,IAAI,KAAiC;AAEjE,MAAK,MAAM,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}
@@ -0,0 +1,20 @@
1
+ import "@credo-ts/core";
2
+ import { OpenId4VciResolvedCredentialOffer } from "@credo-ts/openid4vc";
3
+
4
+ //#region src/credentialBindingResolver.d.ts
5
+ /**
6
+ * What to do when the issuer does not support `holderDidUrl` (DID method or key algorithm):
7
+ * `require` fails the request, `prefer` binds to a new key instead.
8
+ */
9
+ type CredentialBindingPolicy = 'require' | 'prefer';
10
+ /** The issuer does not accept the requested holder DID. */
11
+ declare class HolderBindingNotSupportedError extends Error {
12
+ constructor(message: string);
13
+ }
14
+ /** The issuer returned a credential that is not bound to the requested holder DID. */
15
+ declare class HolderBindingMismatchError extends Error {
16
+ constructor(message: string);
17
+ }
18
+ //#endregion
19
+ export { CredentialBindingPolicy, HolderBindingMismatchError, HolderBindingNotSupportedError };
20
+ //# sourceMappingURL=credentialBindingResolver.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentialBindingResolver.d.mts","names":[],"sources":["../src/credentialBindingResolver.ts"],"mappings":";;;;;;AA0BA;;KAAY,uBAAA;;cAcC,8BAAA,SAAuC,KAAA;cAC/B,OAAA;AAAA;;cAOR,0BAAA,SAAmC,KAAA;cAC3B,OAAA;AAAA"}
@@ -1,52 +1,181 @@
1
- import { DidJwk, DidKey, DidsApi, Kms } from "@credo-ts/core";
1
+ import { DidJwk, DidKey, DidsApi, Kms, W3cCredentialRecord, getPublicJwkFromVerificationMethod, parseDid, tryParseDid } from "@credo-ts/core";
2
2
  import { OpenId4VciCredentialFormatProfile } from "@credo-ts/openid4vc";
3
3
 
4
4
  //#region src/credentialBindingResolver.ts
5
- function getCredentialBindingResolver({ pidSchemes, requestBatch }) {
6
- return async ({ supportedDidMethods, credentialConfiguration, issuerMaxBatchSize, proofTypes, supportsAllDidMethods, supportsJwk, credentialFormat, agentContext }) => {
7
- const kms = agentContext.resolve(Kms.KeyManagementApi);
8
- let didMethod = supportsAllDidMethods || supportedDidMethods?.includes("did:jwk") ? "jwk" : supportedDidMethods?.includes("did:key") ? "key" : void 0;
9
- if (!supportedDidMethods && !supportsJwk) didMethod = "key";
10
- const shouldKeyBeHardwareBackedForMsoMdoc = credentialConfiguration?.format === OpenId4VciCredentialFormatProfile.MsoMdoc && pidSchemes?.msoMdocDoctypes.includes(credentialConfiguration.doctype);
11
- const shouldKeyBeHardwareBacked = (credentialConfiguration?.format === "vc+sd-jwt" || credentialConfiguration.format === "dc+sd-jwt") && credentialConfiguration.vct && pidSchemes?.sdJwtVcVcts.includes(credentialConfiguration.vct) || shouldKeyBeHardwareBackedForMsoMdoc;
12
- const batchSize = requestBatch === true ? Math.min(issuerMaxBatchSize, 10) : typeof requestBatch === "number" ? Math.min(issuerMaxBatchSize, requestBatch) : 1;
13
- if (!proofTypes.jwt || proofTypes.jwt.keyAttestationsRequired) throw new Error("Unable to request credentials. Only jwt proof type without key attestations supported");
14
- const algs = proofTypes.jwt.supportedSignatureAlgorithms;
15
- if (!algs?.length) throw new Error("No supported JWT signature algorithms provided by issuer");
16
- const signatureAlgorithm = algs[0];
17
- const keys = await Promise.all(new Array(batchSize).fill(0).map(() => kms.createKeyForSignatureAlgorithm({
18
- algorithm: signatureAlgorithm,
19
- backend: shouldKeyBeHardwareBacked ? "secureEnvironment" : "askar"
20
- }).then((key) => Kms.PublicJwk.fromUnknown(key.publicJwk))));
21
- if (didMethod) {
22
- const dm = didMethod;
23
- const didsApi = agentContext.dependencyManager.resolve(DidsApi);
5
+ /** The issuer does not accept the requested holder DID. */
6
+ var HolderBindingNotSupportedError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "HolderBindingNotSupportedError";
10
+ }
11
+ };
12
+ /** The issuer returned a credential that is not bound to the requested holder DID. */
13
+ var HolderBindingMismatchError = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "HolderBindingMismatchError";
17
+ }
18
+ };
19
+ /**
20
+ * Checks that each W3C credential names the holder DID as a `credentialSubject`.
21
+ *
22
+ * Credo proves possession of the holder key to the issuer and verifies the issuer's signature, but not
23
+ * that the issuer used the proven DID as the subject. Call it before storing, with the `require` policy.
24
+ */
25
+ function assertW3cCredentialsBoundToHolderDid(records, holderDidUrl) {
26
+ const holderDid = parseDid(holderDidUrl).did;
27
+ for (const record of records) {
28
+ if (!(record instanceof W3cCredentialRecord)) continue;
29
+ const subjectIds = record.firstCredential.credentialSubjectIds;
30
+ if (!subjectIds.some((subjectId) => tryParseDid(subjectId)?.did === holderDid)) throw new HolderBindingMismatchError(`The issuer returned a credential whose subject (${subjectIds.join(", ") || "none"}) is not the holder DID '${holderDid}'`);
31
+ }
32
+ }
33
+ function getCredentialBindingResolver({ pidSchemes, requestBatch, holderDidUrl, bindingPolicy = "require" }) {
34
+ return async (options) => {
35
+ if (holderDidUrl) try {
24
36
  return {
25
37
  method: "did",
26
- didUrls: await Promise.all(keys.map(async (key) => {
27
- const didResult = await didsApi.create({
28
- method: dm,
29
- options: { keyId: key.keyId }
30
- });
31
- if (didResult.didState.state !== "finished") throw new Error("DID creation failed.");
32
- let verificationMethodId;
33
- if (didMethod === "jwk") verificationMethodId = DidJwk.fromDid(didResult.didState.did).verificationMethodId;
34
- else {
35
- const didKey = DidKey.fromDid(didResult.didState.did);
36
- verificationMethodId = `${didKey.did}#${didKey.publicJwk.fingerprint}`;
37
- }
38
- return verificationMethodId;
39
- }))
38
+ didUrls: [await resolveHolderDidBinding(options, holderDidUrl)]
40
39
  };
40
+ } catch (error) {
41
+ if (!(error instanceof HolderBindingNotSupportedError) || bindingPolicy === "require") throw error;
42
+ options.agentContext.config.logger.warn(`Issuer does not support binding to '${holderDidUrl}', falling back to a new key: ${error.message}`);
41
43
  }
42
- if (supportsJwk && (credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtVc || credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtDc || credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc || credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJsonLd)) return {
43
- method: "jwk",
44
- keys
44
+ return createNewKeyBinding(options, {
45
+ pidSchemes,
46
+ requestBatch
47
+ });
48
+ };
49
+ }
50
+ /**
51
+ * Checks the holder DID, and with the `require` policy the offered credential configurations,
52
+ * before the token request, so that a binding that will fail does so before the pre-authorized
53
+ * code and PIN are used. Covers the format and DID method; the resolver also checks the key algorithm.
54
+ */
55
+ async function assertOfferAcceptsHolderDid(agentContext, resolvedCredentialOffer, credentialConfigurationIds, { holderDidUrl, bindingPolicy = "require" }) {
56
+ const { verificationMethod, verificationMethodId } = await resolveHolderVerificationMethod(agentContext, holderDidUrl);
57
+ if (bindingPolicy === "prefer") return;
58
+ for (const configurationId of credentialConfigurationIds) {
59
+ const configuration = resolvedCredentialOffer.offeredCredentialConfigurations[configurationId];
60
+ if (!configuration) continue;
61
+ const bindingMethods = configuration.cryptographic_binding_methods_supported;
62
+ try {
63
+ assertDidBindingAllowed(verificationMethodId, configuration.format, bindingMethods?.filter((method) => method.startsWith("did:")), bindingMethods?.includes("did") ?? false);
64
+ const proofTypes = configuration.proof_types_supported;
65
+ if (proofTypes) {
66
+ const jwt = proofTypes.jwt;
67
+ assertJwtProofAllowed(verificationMethod, verificationMethodId, jwt ? {
68
+ keyAttestationsRequired: Boolean(jwt.key_attestations_required),
69
+ algorithms: jwt.proof_signing_alg_values_supported
70
+ } : void 0);
71
+ }
72
+ } catch (error) {
73
+ if (error instanceof HolderBindingNotSupportedError) throw new HolderBindingNotSupportedError(`${configurationId}: ${error.message}`);
74
+ throw error;
75
+ }
76
+ }
77
+ }
78
+ /**
79
+ * Checks that the issuer accepts a proof signed with the holder DID's key and returns the
80
+ * absolute verification method id to bind to. Credo picks the signing algorithm itself.
81
+ */
82
+ async function resolveHolderDidBinding({ agentContext, proofTypes, supportedDidMethods, supportsAllDidMethods, credentialFormat }, holderDidUrl) {
83
+ const { verificationMethod, verificationMethodId } = await resolveHolderVerificationMethod(agentContext, holderDidUrl);
84
+ assertDidBindingAllowed(verificationMethodId, credentialFormat, supportedDidMethods, supportsAllDidMethods);
85
+ assertJwtProofAllowed(verificationMethod, verificationMethodId, proofTypes.jwt ? {
86
+ keyAttestationsRequired: Boolean(proofTypes.jwt.keyAttestationsRequired),
87
+ algorithms: proofTypes.jwt.supportedSignatureAlgorithms
88
+ } : void 0);
89
+ return verificationMethodId;
90
+ }
91
+ function assertDidBindingAllowed(verificationMethodId, credentialFormat, supportedDidMethods, supportsAllDidMethods) {
92
+ if (credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc) throw new HolderBindingNotSupportedError(`DID binding is not supported for the '${credentialFormat}' format`);
93
+ const { did, method } = parseDid(verificationMethodId);
94
+ if (!(supportsAllDidMethods || supportedDidMethods === void 0 || supportedDidMethods.some((supportedDidMethod) => did.startsWith(supportedDidMethod)))) throw new HolderBindingNotSupportedError(`Issuer does not support did:${method} binding for '${credentialFormat}' credentials. Supported: ${supportedDidMethods.join(", ") || "none"}`);
95
+ }
96
+ /** Checks that the issuer accepts a jwt proof, without key attestations, signed with the holder's key. */
97
+ function assertJwtProofAllowed(verificationMethod, verificationMethodId, jwtProof) {
98
+ if (!jwtProof || jwtProof.keyAttestationsRequired) throw new HolderBindingNotSupportedError("Issuer does not accept a jwt proof without key attestations");
99
+ if (!jwtProof.algorithms) throw new HolderBindingNotSupportedError("Issuer metadata does not list proof_signing_alg_values_supported for the jwt proof type");
100
+ const keyAlgorithms = getPublicJwkFromVerificationMethod(verificationMethod).supportedSignatureAlgorithms;
101
+ if (!jwtProof.algorithms.some((algorithm) => keyAlgorithms.includes(algorithm))) throw new HolderBindingNotSupportedError(`Key '${verificationMethodId}' signs with ${keyAlgorithms.join(", ")}, but the issuer accepts ${jwtProof.algorithms.join(", ")}`);
102
+ }
103
+ async function resolveHolderVerificationMethod(agentContext, holderDidUrl) {
104
+ let parsedDid;
105
+ try {
106
+ parsedDid = parseDid(holderDidUrl);
107
+ } catch {
108
+ throw new Error(`Holder DID URL '${holderDidUrl}' is not a valid DID or DID URL`);
109
+ }
110
+ const { did, fragment } = parsedDid;
111
+ let didDocument;
112
+ try {
113
+ ({didDocument} = await agentContext.resolve(DidsApi).resolveCreatedDidDocumentWithKeys(did));
114
+ } catch {
115
+ throw new Error(`Holder DID '${did}' was not created in this wallet`);
116
+ }
117
+ let keyId = holderDidUrl;
118
+ if (!fragment) {
119
+ const [authentication] = didDocument.authentication ?? [];
120
+ const authenticationId = typeof authentication === "string" ? authentication : authentication?.id;
121
+ if (!authenticationId) throw new Error(`Holder DID '${did}' has no authentication key`);
122
+ keyId = authenticationId;
123
+ }
124
+ let verificationMethod;
125
+ try {
126
+ verificationMethod = didDocument.dereferenceKey(keyId);
127
+ } catch {
128
+ throw new Error(`Verification method '${keyId}' not found in the DID document of '${did}'`);
129
+ }
130
+ const verificationMethodId = verificationMethod.id.startsWith("#") ? `${did}${verificationMethod.id}` : verificationMethod.id;
131
+ return {
132
+ verificationMethod,
133
+ verificationMethodId
134
+ };
135
+ }
136
+ async function createNewKeyBinding({ supportedDidMethods, issuerMaxBatchSize, proofTypes, supportsAllDidMethods, supportsJwk, credentialFormat, credentialConfiguration, agentContext }, { pidSchemes, requestBatch }) {
137
+ const kms = agentContext.resolve(Kms.KeyManagementApi);
138
+ let didMethod = supportsAllDidMethods || supportedDidMethods?.includes("did:jwk") ? "jwk" : supportedDidMethods?.includes("did:key") ? "key" : void 0;
139
+ if (!supportedDidMethods && !supportsJwk) didMethod = "key";
140
+ const shouldKeyBeHardwareBackedForMsoMdoc = credentialConfiguration?.format === OpenId4VciCredentialFormatProfile.MsoMdoc && pidSchemes?.msoMdocDoctypes.includes(credentialConfiguration.doctype);
141
+ const shouldKeyBeHardwareBacked = (credentialConfiguration?.format === "vc+sd-jwt" || credentialConfiguration?.format === "dc+sd-jwt") && credentialConfiguration.vct && pidSchemes?.sdJwtVcVcts.includes(credentialConfiguration.vct) || shouldKeyBeHardwareBackedForMsoMdoc;
142
+ const batchSize = requestBatch === true ? Math.min(issuerMaxBatchSize, 10) : typeof requestBatch === "number" ? Math.min(issuerMaxBatchSize, requestBatch) : 1;
143
+ if (!proofTypes.jwt || proofTypes.jwt.keyAttestationsRequired) throw new Error("Unable to request credentials. Only jwt proof type without key attestations supported");
144
+ const algs = proofTypes.jwt.supportedSignatureAlgorithms;
145
+ if (!algs?.length) throw new Error("No supported JWT signature algorithms provided by issuer");
146
+ const signatureAlgorithm = algs[0];
147
+ const keys = await Promise.all(new Array(batchSize).fill(0).map(() => kms.createKeyForSignatureAlgorithm({
148
+ algorithm: signatureAlgorithm,
149
+ backend: shouldKeyBeHardwareBacked ? "secureEnvironment" : "askar"
150
+ }).then((key) => Kms.PublicJwk.fromUnknown(key.publicJwk))));
151
+ if (didMethod) {
152
+ const dm = didMethod;
153
+ const didsApi = agentContext.dependencyManager.resolve(DidsApi);
154
+ return {
155
+ method: "did",
156
+ didUrls: await Promise.all(keys.map(async (key) => {
157
+ const didResult = await didsApi.create({
158
+ method: dm,
159
+ options: { keyId: key.keyId }
160
+ });
161
+ if (didResult.didState.state !== "finished") throw new Error("DID creation failed.");
162
+ let verificationMethodId;
163
+ if (didMethod === "jwk") verificationMethodId = DidJwk.fromDid(didResult.didState.did).verificationMethodId;
164
+ else {
165
+ const didKey = DidKey.fromDid(didResult.didState.did);
166
+ verificationMethodId = `${didKey.did}#${didKey.publicJwk.fingerprint}`;
167
+ }
168
+ return verificationMethodId;
169
+ }))
45
170
  };
46
- throw new Error(`No supported binding method could be found. Supported methods are did:key and did:jwk, or plain jwk for sd-jwt/mdoc. Issuer supports ${supportsJwk ? "jwk, " : ""}${supportedDidMethods?.join(", ") ?? "Unknown"}`);
171
+ }
172
+ if (supportsJwk && (credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtVc || credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtDc || credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc || credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJsonLd || credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJson || credentialFormat === OpenId4VciCredentialFormatProfile.LdpVc)) return {
173
+ method: "jwk",
174
+ keys
47
175
  };
176
+ throw new Error(`No supported binding method could be found. Supported methods are did:key and did:jwk, or plain jwk for sd-jwt/mdoc. Issuer supports ${supportsJwk ? "jwk, " : ""}${supportedDidMethods?.join(", ") ?? "Unknown"}`);
48
177
  }
49
178
 
50
179
  //#endregion
51
- export { getCredentialBindingResolver };
180
+ export { HolderBindingMismatchError, HolderBindingNotSupportedError, assertOfferAcceptsHolderDid, assertW3cCredentialsBoundToHolderDid, getCredentialBindingResolver };
52
181
  //# sourceMappingURL=credentialBindingResolver.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"credentialBindingResolver.mjs","names":[],"sources":["../src/credentialBindingResolver.ts"],"sourcesContent":["import { DidJwk, DidKey, DidsApi, type JwkDidCreateOptions, type KeyDidCreateOptions, Kms } from '@credo-ts/core'\nimport { type OpenId4VciCredentialBindingResolver, OpenId4VciCredentialFormatProfile } from '@credo-ts/openid4vc'\n\nexport function getCredentialBindingResolver({\n pidSchemes,\n requestBatch,\n}: {\n pidSchemes?: { sdJwtVcVcts: Array<string>; msoMdocDoctypes: Array<string> }\n requestBatch?: boolean | number\n}): OpenId4VciCredentialBindingResolver {\n return async ({\n supportedDidMethods,\n credentialConfiguration,\n issuerMaxBatchSize,\n proofTypes,\n supportsAllDidMethods,\n supportsJwk,\n credentialFormat,\n agentContext,\n }) => {\n const kms = agentContext.resolve(Kms.KeyManagementApi)\n let didMethod: 'key' | 'jwk' | undefined =\n supportsAllDidMethods || supportedDidMethods?.includes('did:jwk')\n ? 'jwk'\n : supportedDidMethods?.includes('did:key')\n ? 'key'\n : undefined\n\n if (!supportedDidMethods && !supportsJwk) {\n didMethod = 'key'\n }\n\n const shouldKeyBeHardwareBackedForMsoMdoc =\n credentialConfiguration?.format === OpenId4VciCredentialFormatProfile.MsoMdoc &&\n pidSchemes?.msoMdocDoctypes.includes(credentialConfiguration.doctype)\n\n const shouldKeyBeHardwareBackedForSdJwtVc =\n (credentialConfiguration?.format === 'vc+sd-jwt' || credentialConfiguration.format === 'dc+sd-jwt') &&\n credentialConfiguration.vct &&\n pidSchemes?.sdJwtVcVcts.includes(credentialConfiguration.vct)\n\n const shouldKeyBeHardwareBacked = shouldKeyBeHardwareBackedForSdJwtVc || shouldKeyBeHardwareBackedForMsoMdoc\n\n // We don't want to request more than 10 credentials\n const batchSize =\n requestBatch === true\n ? Math.min(issuerMaxBatchSize, 10)\n : typeof requestBatch === 'number'\n ? Math.min(issuerMaxBatchSize, requestBatch)\n : 1\n\n // TODO: support key attestations\n if (!proofTypes.jwt || proofTypes.jwt.keyAttestationsRequired) {\n throw new Error('Unable to request credentials. Only jwt proof type without key attestations supported')\n }\n\n const algs = proofTypes.jwt.supportedSignatureAlgorithms\n if (!algs?.length) {\n throw new Error('No supported JWT signature algorithms provided by issuer')\n }\n const signatureAlgorithm = algs[0]\n const keys = await Promise.all(\n new Array(batchSize).fill(0).map(() =>\n kms\n .createKeyForSignatureAlgorithm({\n algorithm: signatureAlgorithm,\n // FIXME: what should happen with already existing keys created in the secure environment?\n backend: shouldKeyBeHardwareBacked ? 'secureEnvironment' : 'askar',\n })\n .then((key) => Kms.PublicJwk.fromUnknown(key.publicJwk))\n )\n )\n\n if (didMethod) {\n const dm = didMethod\n const didsApi = agentContext.dependencyManager.resolve(DidsApi)\n const didResults = await Promise.all(\n keys.map(async (key) => {\n const didResult = await didsApi.create<JwkDidCreateOptions | KeyDidCreateOptions>({\n method: dm,\n options: {\n keyId: key.keyId,\n },\n })\n\n if (didResult.didState.state !== 'finished') {\n throw new Error('DID creation failed.')\n }\n\n let verificationMethodId: string\n if (didMethod === 'jwk') {\n const didJwk = DidJwk.fromDid(didResult.didState.did)\n verificationMethodId = didJwk.verificationMethodId\n } else {\n const didKey = DidKey.fromDid(didResult.didState.did)\n verificationMethodId = `${didKey.did}#${didKey.publicJwk.fingerprint}`\n }\n\n return verificationMethodId\n })\n )\n\n return {\n method: 'did',\n didUrls: didResults,\n }\n }\n\n if (\n supportsJwk &&\n (credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtVc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtDc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJsonLd)\n ) {\n return {\n method: 'jwk',\n keys,\n }\n }\n\n throw new Error(\n `No supported binding method could be found. Supported methods are did:key and did:jwk, or plain jwk for sd-jwt/mdoc. Issuer supports ${\n supportsJwk ? 'jwk, ' : ''\n }${supportedDidMethods?.join(', ') ?? 'Unknown'}`\n )\n }\n}\n"],"mappings":";;;;AAGA,SAAgB,6BAA6B,EAC3C,YACA,gBAIsC;AACtC,QAAO,OAAO,EACZ,qBACA,yBACA,oBACA,YACA,uBACA,aACA,kBACA,mBACI;EACJ,MAAM,MAAM,aAAa,QAAQ,IAAI,iBAAiB;EACtD,IAAI,YACF,yBAAyB,qBAAqB,SAAS,UAAU,GAC7D,QACA,qBAAqB,SAAS,UAAU,GACtC,QACA;AAER,MAAI,CAAC,uBAAuB,CAAC,YAC3B,aAAY;EAGd,MAAM,sCACJ,yBAAyB,WAAW,kCAAkC,WACtE,YAAY,gBAAgB,SAAS,wBAAwB,QAAQ;EAOvE,MAAM,6BAJH,yBAAyB,WAAW,eAAe,wBAAwB,WAAW,gBACvF,wBAAwB,OACxB,YAAY,YAAY,SAAS,wBAAwB,IAAI,IAEU;EAGzE,MAAM,YACJ,iBAAiB,OACb,KAAK,IAAI,oBAAoB,GAAG,GAChC,OAAO,iBAAiB,WACtB,KAAK,IAAI,oBAAoB,aAAa,GAC1C;AAGR,MAAI,CAAC,WAAW,OAAO,WAAW,IAAI,wBACpC,OAAM,IAAI,MAAM,wFAAwF;EAG1G,MAAM,OAAO,WAAW,IAAI;AAC5B,MAAI,CAAC,MAAM,OACT,OAAM,IAAI,MAAM,2DAA2D;EAE7E,MAAM,qBAAqB,KAAK;EAChC,MAAM,OAAO,MAAM,QAAQ,IACzB,IAAI,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC,UAC3B,IACG,+BAA+B;GAC9B,WAAW;GAEX,SAAS,4BAA4B,sBAAsB;GAC5D,CAAC,CACD,MAAM,QAAQ,IAAI,UAAU,YAAY,IAAI,UAAU,CAAC,CAC3D,CACF;AAED,MAAI,WAAW;GACb,MAAM,KAAK;GACX,MAAM,UAAU,aAAa,kBAAkB,QAAQ,QAAQ;AA2B/D,UAAO;IACL,QAAQ;IACR,SA5BiB,MAAM,QAAQ,IAC/B,KAAK,IAAI,OAAO,QAAQ;KACtB,MAAM,YAAY,MAAM,QAAQ,OAAkD;MAChF,QAAQ;MACR,SAAS,EACP,OAAO,IAAI,OACZ;MACF,CAAC;AAEF,SAAI,UAAU,SAAS,UAAU,WAC/B,OAAM,IAAI,MAAM,uBAAuB;KAGzC,IAAI;AACJ,SAAI,cAAc,MAEhB,wBADe,OAAO,QAAQ,UAAU,SAAS,IAAI,CACvB;UACzB;MACL,MAAM,SAAS,OAAO,QAAQ,UAAU,SAAS,IAAI;AACrD,6BAAuB,GAAG,OAAO,IAAI,GAAG,OAAO,UAAU;;AAG3D,YAAO;MACP,CACH;IAKA;;AAGH,MACE,gBACC,qBAAqB,kCAAkC,WACtD,qBAAqB,kCAAkC,WACvD,qBAAqB,kCAAkC,WACvD,qBAAqB,kCAAkC,aAEzD,QAAO;GACL,QAAQ;GACR;GACD;AAGH,QAAM,IAAI,MACR,wIACE,cAAc,UAAU,KACvB,qBAAqB,KAAK,KAAK,IAAI,YACvC"}
1
+ {"version":3,"file":"credentialBindingResolver.mjs","names":[],"sources":["../src/credentialBindingResolver.ts"],"sourcesContent":["import {\n type AgentContext,\n type DidDocument,\n DidJwk,\n DidKey,\n DidsApi,\n getPublicJwkFromVerificationMethod,\n type JwkDidCreateOptions,\n type KeyDidCreateOptions,\n Kms,\n parseDid,\n tryParseDid,\n type VerificationMethod,\n W3cCredentialRecord,\n} from '@credo-ts/core'\nimport {\n type OpenId4VciCredentialBindingOptions,\n type OpenId4VciCredentialBindingResolver,\n OpenId4VciCredentialFormatProfile,\n type OpenId4VciResolvedCredentialOffer,\n} from '@credo-ts/openid4vc'\n\n/**\n * What to do when the issuer does not support `holderDidUrl` (DID method or key algorithm):\n * `require` fails the request, `prefer` binds to a new key instead.\n */\nexport type CredentialBindingPolicy = 'require' | 'prefer'\n\nexport interface CredentialBindingResolverOptions {\n pidSchemes?: { sdJwtVcVcts: Array<string>; msoMdocDoctypes: Array<string> }\n requestBatch?: boolean | number\n /**\n * DID URL of a verification method (e.g. `did:web:example.com#key-1`), or a bare DID to use its\n * first authentication key. The DID must have been created or imported in this agent.\n */\n holderDidUrl?: string\n bindingPolicy?: CredentialBindingPolicy\n}\n\n/** The issuer does not accept the requested holder DID. */\nexport class HolderBindingNotSupportedError extends Error {\n public constructor(message: string) {\n super(message)\n this.name = 'HolderBindingNotSupportedError'\n }\n}\n\n/** The issuer returned a credential that is not bound to the requested holder DID. */\nexport class HolderBindingMismatchError extends Error {\n public constructor(message: string) {\n super(message)\n this.name = 'HolderBindingMismatchError'\n }\n}\n\n/**\n * Checks that each W3C credential names the holder DID as a `credentialSubject`.\n *\n * Credo proves possession of the holder key to the issuer and verifies the issuer's signature, but not\n * that the issuer used the proven DID as the subject. Call it before storing, with the `require` policy.\n */\nexport function assertW3cCredentialsBoundToHolderDid(records: unknown[], holderDidUrl: string) {\n const holderDid = parseDid(holderDidUrl).did\n for (const record of records) {\n if (!(record instanceof W3cCredentialRecord)) continue\n\n const subjectIds = record.firstCredential.credentialSubjectIds\n if (!subjectIds.some((subjectId) => tryParseDid(subjectId)?.did === holderDid)) {\n throw new HolderBindingMismatchError(\n `The issuer returned a credential whose subject (${subjectIds.join(', ') || 'none'}) is not the holder DID '${holderDid}'`\n )\n }\n }\n}\n\nexport function getCredentialBindingResolver({\n pidSchemes,\n requestBatch,\n holderDidUrl,\n bindingPolicy = 'require',\n}: CredentialBindingResolverOptions): OpenId4VciCredentialBindingResolver {\n return async (options) => {\n if (holderDidUrl) {\n try {\n const didUrl = await resolveHolderDidBinding(options, holderDidUrl)\n return { method: 'did', didUrls: [didUrl] }\n } catch (error) {\n if (!(error instanceof HolderBindingNotSupportedError) || bindingPolicy === 'require') throw error\n options.agentContext.config.logger.warn(\n `Issuer does not support binding to '${holderDidUrl}', falling back to a new key: ${error.message}`\n )\n }\n }\n\n return createNewKeyBinding(options, { pidSchemes, requestBatch })\n }\n}\n\n/**\n * Checks the holder DID, and with the `require` policy the offered credential configurations,\n * before the token request, so that a binding that will fail does so before the pre-authorized\n * code and PIN are used. Covers the format and DID method; the resolver also checks the key algorithm.\n */\nexport async function assertOfferAcceptsHolderDid(\n agentContext: AgentContext,\n resolvedCredentialOffer: OpenId4VciResolvedCredentialOffer,\n credentialConfigurationIds: string[],\n { holderDidUrl, bindingPolicy = 'require' }: { holderDidUrl: string; bindingPolicy?: CredentialBindingPolicy }\n) {\n const { verificationMethod, verificationMethodId } = await resolveHolderVerificationMethod(agentContext, holderDidUrl)\n if (bindingPolicy === 'prefer') return\n\n for (const configurationId of credentialConfigurationIds) {\n const configuration = resolvedCredentialOffer.offeredCredentialConfigurations[configurationId]\n // Credo rejects configurations with unknown formats itself\n if (!configuration) continue\n\n const bindingMethods = configuration.cryptographic_binding_methods_supported\n try {\n assertDidBindingAllowed(\n verificationMethodId,\n configuration.format,\n bindingMethods?.filter((method) => method.startsWith('did:')),\n bindingMethods?.includes('did') ?? false\n )\n // Without proof_types_supported the issuer states no proof requirements to check\n const proofTypes = configuration.proof_types_supported\n if (proofTypes) {\n const jwt = proofTypes.jwt\n assertJwtProofAllowed(\n verificationMethod,\n verificationMethodId,\n jwt\n ? {\n keyAttestationsRequired: Boolean(jwt.key_attestations_required),\n algorithms: jwt.proof_signing_alg_values_supported,\n }\n : undefined\n )\n }\n } catch (error) {\n if (error instanceof HolderBindingNotSupportedError) {\n throw new HolderBindingNotSupportedError(`${configurationId}: ${error.message}`)\n }\n throw error\n }\n }\n}\n\n/**\n * Checks that the issuer accepts a proof signed with the holder DID's key and returns the\n * absolute verification method id to bind to. Credo picks the signing algorithm itself.\n */\nasync function resolveHolderDidBinding(\n {\n agentContext,\n proofTypes,\n supportedDidMethods,\n supportsAllDidMethods,\n credentialFormat,\n }: OpenId4VciCredentialBindingOptions,\n holderDidUrl: string\n): Promise<string> {\n const { verificationMethod, verificationMethodId } = await resolveHolderVerificationMethod(agentContext, holderDidUrl)\n\n assertDidBindingAllowed(verificationMethodId, credentialFormat, supportedDidMethods, supportsAllDidMethods)\n assertJwtProofAllowed(\n verificationMethod,\n verificationMethodId,\n proofTypes.jwt\n ? {\n keyAttestationsRequired: Boolean(proofTypes.jwt.keyAttestationsRequired),\n algorithms: proofTypes.jwt.supportedSignatureAlgorithms,\n }\n : undefined\n )\n\n return verificationMethodId\n}\n\nfunction assertDidBindingAllowed(\n verificationMethodId: string,\n credentialFormat: string,\n supportedDidMethods: string[] | undefined,\n supportsAllDidMethods: boolean\n) {\n if (credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc) {\n throw new HolderBindingNotSupportedError(`DID binding is not supported for the '${credentialFormat}' format`)\n }\n\n // supportedDidMethods is undefined when the issuer lists no binding methods at all\n // (same check as Credo's OpenId4VciHolderService)\n const { did, method } = parseDid(verificationMethodId)\n const didMethodAllowed =\n supportsAllDidMethods ||\n supportedDidMethods === undefined ||\n supportedDidMethods.some((supportedDidMethod) => did.startsWith(supportedDidMethod))\n if (!didMethodAllowed) {\n throw new HolderBindingNotSupportedError(\n `Issuer does not support did:${method} binding for '${credentialFormat}' credentials. Supported: ${supportedDidMethods.join(', ') || 'none'}`\n )\n }\n}\n\n/** Checks that the issuer accepts a jwt proof, without key attestations, signed with the holder's key. */\nfunction assertJwtProofAllowed(\n verificationMethod: VerificationMethod,\n verificationMethodId: string,\n jwtProof: { keyAttestationsRequired: boolean; algorithms: string[] | undefined } | undefined\n) {\n if (!jwtProof || jwtProof.keyAttestationsRequired) {\n throw new HolderBindingNotSupportedError('Issuer does not accept a jwt proof without key attestations')\n }\n if (!jwtProof.algorithms) {\n throw new HolderBindingNotSupportedError(\n 'Issuer metadata does not list proof_signing_alg_values_supported for the jwt proof type'\n )\n }\n\n const keyAlgorithms = getPublicJwkFromVerificationMethod(verificationMethod).supportedSignatureAlgorithms\n if (!jwtProof.algorithms.some((algorithm) => (keyAlgorithms as string[]).includes(algorithm))) {\n throw new HolderBindingNotSupportedError(\n `Key '${verificationMethodId}' signs with ${keyAlgorithms.join(', ')}, but the issuer accepts ${jwtProof.algorithms.join(', ')}`\n )\n }\n}\n\nasync function resolveHolderVerificationMethod(\n agentContext: AgentContext,\n holderDidUrl: string\n): Promise<{ verificationMethod: VerificationMethod; verificationMethodId: string }> {\n let parsedDid: ReturnType<typeof parseDid>\n try {\n parsedDid = parseDid(holderDidUrl)\n } catch {\n throw new Error(`Holder DID URL '${holderDidUrl}' is not a valid DID or DID URL`)\n }\n const { did, fragment } = parsedDid\n\n let didDocument: DidDocument\n try {\n ;({ didDocument } = await agentContext.resolve(DidsApi).resolveCreatedDidDocumentWithKeys(did))\n } catch {\n throw new Error(`Holder DID '${did}' was not created in this wallet`)\n }\n\n let keyId = holderDidUrl\n if (!fragment) {\n const [authentication] = didDocument.authentication ?? []\n const authenticationId = typeof authentication === 'string' ? authentication : authentication?.id\n if (!authenticationId) {\n throw new Error(`Holder DID '${did}' has no authentication key`)\n }\n keyId = authenticationId\n }\n\n let verificationMethod: VerificationMethod\n try {\n verificationMethod = didDocument.dereferenceKey(keyId)\n } catch {\n throw new Error(`Verification method '${keyId}' not found in the DID document of '${did}'`)\n }\n\n // DID documents may use relative ids such as '#key-1'\n const verificationMethodId = verificationMethod.id.startsWith('#')\n ? `${did}${verificationMethod.id}`\n : verificationMethod.id\n return { verificationMethod, verificationMethodId }\n}\n\nasync function createNewKeyBinding(\n {\n supportedDidMethods,\n issuerMaxBatchSize,\n proofTypes,\n supportsAllDidMethods,\n supportsJwk,\n credentialFormat,\n credentialConfiguration,\n agentContext,\n }: OpenId4VciCredentialBindingOptions,\n { pidSchemes, requestBatch }: Pick<CredentialBindingResolverOptions, 'pidSchemes' | 'requestBatch'>\n) {\n const kms = agentContext.resolve(Kms.KeyManagementApi)\n let didMethod: 'key' | 'jwk' | undefined =\n supportsAllDidMethods || supportedDidMethods?.includes('did:jwk')\n ? 'jwk'\n : supportedDidMethods?.includes('did:key')\n ? 'key'\n : undefined\n\n if (!supportedDidMethods && !supportsJwk) {\n didMethod = 'key'\n }\n\n const shouldKeyBeHardwareBackedForMsoMdoc =\n credentialConfiguration?.format === OpenId4VciCredentialFormatProfile.MsoMdoc &&\n pidSchemes?.msoMdocDoctypes.includes(credentialConfiguration.doctype)\n\n const shouldKeyBeHardwareBackedForSdJwtVc =\n (credentialConfiguration?.format === 'vc+sd-jwt' || credentialConfiguration?.format === 'dc+sd-jwt') &&\n credentialConfiguration.vct &&\n pidSchemes?.sdJwtVcVcts.includes(credentialConfiguration.vct)\n\n const shouldKeyBeHardwareBacked = shouldKeyBeHardwareBackedForSdJwtVc || shouldKeyBeHardwareBackedForMsoMdoc\n\n // We don't want to request more than 10 credentials\n const batchSize =\n requestBatch === true\n ? Math.min(issuerMaxBatchSize, 10)\n : typeof requestBatch === 'number'\n ? Math.min(issuerMaxBatchSize, requestBatch)\n : 1\n\n // TODO: support key attestations\n if (!proofTypes.jwt || proofTypes.jwt.keyAttestationsRequired) {\n throw new Error('Unable to request credentials. Only jwt proof type without key attestations supported')\n }\n\n const algs = proofTypes.jwt.supportedSignatureAlgorithms\n if (!algs?.length) {\n throw new Error('No supported JWT signature algorithms provided by issuer')\n }\n const signatureAlgorithm = algs[0]\n const keys = await Promise.all(\n new Array(batchSize).fill(0).map(() =>\n kms\n .createKeyForSignatureAlgorithm({\n algorithm: signatureAlgorithm,\n // FIXME: what should happen with already existing keys created in the secure environment?\n backend: shouldKeyBeHardwareBacked ? 'secureEnvironment' : 'askar',\n })\n .then((key) => Kms.PublicJwk.fromUnknown(key.publicJwk))\n )\n )\n\n if (didMethod) {\n const dm = didMethod\n const didsApi = agentContext.dependencyManager.resolve(DidsApi)\n const didResults = await Promise.all(\n keys.map(async (key) => {\n const didResult = await didsApi.create<JwkDidCreateOptions | KeyDidCreateOptions>({\n method: dm,\n options: {\n keyId: key.keyId,\n },\n })\n\n if (didResult.didState.state !== 'finished') {\n throw new Error('DID creation failed.')\n }\n\n let verificationMethodId: string\n if (didMethod === 'jwk') {\n const didJwk = DidJwk.fromDid(didResult.didState.did)\n verificationMethodId = didJwk.verificationMethodId\n } else {\n const didKey = DidKey.fromDid(didResult.didState.did)\n verificationMethodId = `${didKey.did}#${didKey.publicJwk.fingerprint}`\n }\n\n return verificationMethodId\n })\n )\n\n return {\n method: 'did' as const,\n didUrls: didResults,\n }\n }\n\n if (\n supportsJwk &&\n (credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtVc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.SdJwtDc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.MsoMdoc ||\n credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJsonLd ||\n credentialFormat === OpenId4VciCredentialFormatProfile.JwtVcJson ||\n credentialFormat === OpenId4VciCredentialFormatProfile.LdpVc)\n ) {\n return {\n method: 'jwk' as const,\n keys,\n }\n }\n\n throw new Error(\n `No supported binding method could be found. Supported methods are did:key and did:jwk, or plain jwk for sd-jwt/mdoc. Issuer supports ${\n supportsJwk ? 'jwk, ' : ''\n }${supportedDidMethods?.join(', ') ?? 'Unknown'}`\n )\n}\n"],"mappings":";;;;;AAwCA,IAAa,iCAAb,cAAoD,MAAM;CACxD,AAAO,YAAY,SAAiB;AAClC,QAAM,QAAQ;AACd,OAAK,OAAO;;;;AAKhB,IAAa,6BAAb,cAAgD,MAAM;CACpD,AAAO,YAAY,SAAiB;AAClC,QAAM,QAAQ;AACd,OAAK,OAAO;;;;;;;;;AAUhB,SAAgB,qCAAqC,SAAoB,cAAsB;CAC7F,MAAM,YAAY,SAAS,aAAa,CAAC;AACzC,MAAK,MAAM,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 +84,7 @@ function getSelectedCredentialsForRequest(dcqlQueryResult, selectedCredentials)
84
84
  useMode: CredentialMultiInstanceUseMode.NewOrFirst
85
85
  }];
86
86
  else if (matchWithRecord.record.type === "W3cCredentialRecord") credentials[credentialQueryId] = [{
87
- claimFormat: ClaimFormat.JwtVc,
87
+ claimFormat: matchWithRecord.record.firstCredential.claimFormat,
88
88
  credentialRecord: matchWithRecord.record,
89
89
  disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output,
90
90
  useMode: CredentialMultiInstanceUseMode.NewOrFirst
@@ -1 +1 @@
1
- {"version":3,"file":"proof.mjs","names":[],"sources":["../../src/display/proof.ts"],"sourcesContent":["import type {\n DcqlCredentialsForRequest,\n DcqlQueryResult,\n DifPexCredentialsForRequest,\n JsonObject,\n Kms,\n MdocNameSpaces,\n MdocRecord,\n SdJwtVcRecord,\n W3cCredentialRecord,\n W3cV2CredentialRecord,\n} from '@credo-ts/core'\nimport { ClaimFormat, CredentialMultiInstanceUseMode, DateOnly, Hasher, TypedArrayEncoder } from '@credo-ts/core'\nimport type { OpenId4VpResolvedAuthorizationRequest } from '@credo-ts/openid4vc'\nimport { formatDate, isDateString } from '../utils'\nimport { detectImageMimeType } from '../utils/attributes'\nimport type { CredentialMetadata, FormattedSubmissionEntrySatisfiedCredential } from './display'\n\ntype MappedAttributesReturnType =\n | string\n | number\n | boolean\n | { [key: string]: MappedAttributesReturnType }\n | null\n | undefined\n | Array<MappedAttributesReturnType>\n\nexport interface FormattedSubmission {\n name?: string\n purpose?: string\n areAllSatisfied: boolean\n entries: FormattedSubmissionEntry[]\n}\n\nexport interface OpenId4VPRequestRecord extends OpenId4VpResolvedAuthorizationRequest {\n verifierHostName: string | undefined\n createdAt: string | Date\n credentialsForRequest: DifPexCredentialsForRequest | undefined\n type: string\n}\n\nexport interface FormattedSubmissionEntrySatisfied {\n /**\n * can be either:\n * - AnonCreds groupName\n * - PEX inputDescriptorId\n * - DCQL credential query id\n */\n inputDescriptorId: string\n\n name?: string\n description?: string\n\n /**\n * Whether the entry is satisfied\n */\n isSatisfied: true\n\n /**\n * Credentials that match the request entry. Wallet always needs to pick one.\n */\n credentials: [FormattedSubmissionEntrySatisfiedCredential, ...FormattedSubmissionEntrySatisfiedCredential[]]\n}\n\nexport interface FormattedSubmissionEntryNotSatisfied {\n /**\n * can be either:\n * - AnonCreds groupName\n * - PEX inputDescriptorId\n * - DCQL credential query id\n */\n inputDescriptorId: string\n\n name?: string\n description?: string\n\n /**\n * Whether the entry is satisfied\n */\n isSatisfied: false\n\n requestedAttributePaths: Array<Array<string | number | null>>\n}\n\nexport type FormattedSubmissionEntry = FormattedSubmissionEntryNotSatisfied | FormattedSubmissionEntrySatisfied\n\nexport function getDisclosedAttributePathArrays(\n payload: object,\n maxDepth: number | undefined = undefined,\n prefix: string[] = []\n): string[][] {\n let attributePaths: string[][] = []\n\n for (const [key, value] of Object.entries(payload)) {\n if (!value) continue\n\n // TODO: handle arrays\n const newPath = [...prefix, key]\n if (value && typeof value === 'object' && maxDepth !== 0) {\n // If the value is a nested object, recurse\n attributePaths = [\n ...attributePaths,\n ...getDisclosedAttributePathArrays(value, maxDepth !== undefined ? maxDepth - 1 : undefined, newPath),\n ]\n } else {\n // If the value is a primitive or maxDepth is reached, add the key to the list\n attributePaths.push(newPath)\n }\n }\n\n return attributePaths\n}\n\nexport function getAttributesAndMetadataForSdJwtPayload(sdJwtVcPayload: Record<string, unknown>) {\n type SdJwtVcPayload = {\n iss: string\n cnf: Record<string, unknown>\n vct: string\n iat?: number\n nbf?: number\n exp?: number\n [key: string]: unknown\n }\n const { _sd_alg, _sd_hash, iss, vct, cnf, iat, exp, nbf, ...visibleProperties } = sdJwtVcPayload as SdJwtVcPayload\n\n const holder = (cnf.kid ?? cnf.jwk) ? safeCalculateJwkThumbprint(cnf.jwk as Kms.Jwk) : undefined\n const credentialMetadata: CredentialMetadata = {\n type: vct,\n issuer: iss,\n holder,\n }\n\n if (iat) {\n credentialMetadata.issuedAt = formatDate(new Date(iat * 1000))\n }\n if (exp) {\n credentialMetadata.validUntil = formatDate(new Date(exp * 1000))\n }\n if (nbf) {\n credentialMetadata.validFrom = formatDate(new Date(nbf * 1000))\n }\n\n return {\n attributes: Object.fromEntries(\n Object.entries(visibleProperties).map(([key, value]) => [key, recursivelyMapAttributes(value)])\n ),\n metadata: credentialMetadata,\n raw: {\n issuedAt: iat ? new Date(iat * 1000) : undefined,\n validUntil: exp ? new Date(exp * 1000) : undefined,\n validFrom: nbf ? new Date(nbf * 1000) : undefined,\n },\n }\n}\n\nexport function safeCalculateJwkThumbprint(jwk: Kms.Jwk): string | undefined {\n try {\n const thumbprint = TypedArrayEncoder.toBase64Url(\n Hasher.hash(\n JSON.stringify({\n k: jwk.k,\n e: jwk.e,\n crv: jwk.crv,\n kty: jwk.kty,\n n: jwk.n,\n x: jwk.x,\n y: jwk.y,\n }),\n 'sha-256'\n )\n )\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-256:${thumbprint}`\n } catch (_e) {\n return undefined\n }\n}\n\nexport function recursivelyMapAttributes(value: unknown): MappedAttributesReturnType {\n if (value instanceof Uint8Array) {\n const imageMimeType = detectImageMimeType(value)\n if (imageMimeType) {\n return `data:${imageMimeType};base64,${TypedArrayEncoder.toBase64(value)}`\n }\n\n return TypedArrayEncoder.toUtf8String(value)\n }\n if (value === null || value === undefined || typeof value === 'number' || typeof value === 'boolean') return value\n\n if (value instanceof Date || value instanceof DateOnly || (typeof value === 'string' && isDateString(value))) {\n return formatDate(value instanceof DateOnly ? value.toISOString() : value)\n }\n if (typeof value === 'string') return value\n if (value instanceof Map) {\n return Object.fromEntries(Array.from(value.entries()).map(([key, value]) => [key, recursivelyMapAttributes(value)]))\n }\n if (Array.isArray(value)) return value.map(recursivelyMapAttributes)\n\n return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, recursivelyMapAttributes(value)]))\n}\n\nexport function getSelectedCredentialsForRequest(\n dcqlQueryResult: DcqlQueryResult,\n selectedCredentials: { [credentialQueryId: string]: string }\n): DcqlCredentialsForRequest {\n if (!dcqlQueryResult.can_be_satisfied) {\n throw new Error('Cannot select the credentials for the dcql query presentation if the request cannot be satisfied')\n }\n\n const credentials: DcqlCredentialsForRequest = {}\n\n type WithRecord<T> = T & {\n record: MdocRecord | SdJwtVcRecord | W3cCredentialRecord | W3cV2CredentialRecord\n }\n\n for (const [credentialQueryId, credentialRecordId] of Object.entries(selectedCredentials)) {\n const matchesForCredentialQuery = dcqlQueryResult.credential_matches[credentialQueryId]\n if (matchesForCredentialQuery.success) {\n const validCredentialMatch = matchesForCredentialQuery.valid_credentials.find(\n (credential) => (credential as WithRecord<typeof credential>).record.id === credentialRecordId\n )\n\n if (!validCredentialMatch) {\n throw new Error(\n `Could not find credential record ${credentialRecordId} in valid credential matches for credentialQueryId ${credentialQueryId}`\n )\n }\n\n // TODO: fix the typing, make selection in Credo easier\n const matchWithRecord = validCredentialMatch as typeof validCredentialMatch & {\n record: MdocRecord | SdJwtVcRecord | W3cCredentialRecord | W3cV2CredentialRecord\n }\n\n if (matchWithRecord.record.type === 'MdocRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: ClaimFormat.MsoMdoc,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as MdocNameSpaces,\n // FIXME: we currently allow re-sharing if we don't have new instances anymore\n // we should make this configurable maybe? Or dependant on credential type?\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n } else if (matchWithRecord.record.type === 'SdJwtVcRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as JsonObject,\n // FIXME: we currently allow re-sharing if we don't have new instances anymore\n // we should make this configurable maybe? Or dependant on credential type?\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n } else if (matchWithRecord.record.type === 'W3cCredentialRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: ClaimFormat.JwtVc,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as JsonObject,\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n }\n }\n }\n\n return credentials\n}\n"],"mappings":";;;;;;AAsFA,SAAgB,gCACd,SACA,WAA+B,QAC/B,SAAmB,EAAE,EACT;CACZ,IAAI,iBAA6B,EAAE;AAEnC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,MAAI,CAAC,MAAO;EAGZ,MAAM,UAAU,CAAC,GAAG,QAAQ,IAAI;AAChC,MAAI,SAAS,OAAO,UAAU,YAAY,aAAa,EAErD,kBAAiB,CACf,GAAG,gBACH,GAAG,gCAAgC,OAAO,aAAa,SAAY,WAAW,IAAI,QAAW,QAAQ,CACtG;MAGD,gBAAe,KAAK,QAAQ;;AAIhC,QAAO;;AAGT,SAAgB,wCAAwC,gBAAyC;CAU/F,MAAM,EAAE,SAAS,UAAU,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,sBAAsB;CAGlF,MAAM,qBAAyC;EAC7C,MAAM;EACN,QAAQ;EACR,QAJc,IAAI,OAAO,IAAI,MAAO,2BAA2B,IAAI,IAAe,GAAG;EAKtF;AAED,KAAI,IACF,oBAAmB,WAAW,2BAAW,IAAI,KAAK,MAAM,IAAK,CAAC;AAEhE,KAAI,IACF,oBAAmB,aAAa,2BAAW,IAAI,KAAK,MAAM,IAAK,CAAC;AAElE,KAAI,IACF,oBAAmB,YAAY,2BAAW,IAAI,KAAK,MAAM,IAAK,CAAC;AAGjE,QAAO;EACL,YAAY,OAAO,YACjB,OAAO,QAAQ,kBAAkB,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,yBAAyB,MAAM,CAAC,CAAC,CAChG;EACD,UAAU;EACV,KAAK;GACH,UAAU,sBAAM,IAAI,KAAK,MAAM,IAAK,GAAG;GACvC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mG;CAGrH,MAAM,cAAyC,EAAE;AAMjD,MAAK,MAAM,CAAC,mBAAmB,uBAAuB,OAAO,QAAQ,oBAAoB,EAAE;EACzF,MAAM,4BAA4B,gBAAgB,mBAAmB;AACrE,MAAI,0BAA0B,SAAS;GACrC,MAAM,uBAAuB,0BAA0B,kBAAkB,MACtE,eAAgB,WAA6C,OAAO,OAAO,mBAC7E;AAED,OAAI,CAAC,qBACH,OAAM,IAAI,MACR,oCAAoC,mBAAmB,qDAAqD,oBAC7G;GAIH,MAAM,kBAAkB;AAIxB,OAAI,gBAAgB,OAAO,SAAS,aAClC,aAAY,qBAAqB,CAC/B;IACE,aAAa,YAAY;IACzB,kBAAkB,gBAAgB;IAClC,kBAAkB,gBAAgB,OAAO,iBAAiB,GAAG;IAG7D,SAAS,+BAA+B;IACzC,CACF;YACQ,gBAAgB,OAAO,SAAS,gBACzC,aAAY,qBAAqB,CAC/B;IACE,aAAa,YAAY;IACzB,kBAAkB,gBAAgB;IAClC,kBAAkB,gBAAgB,OAAO,iBAAiB,GAAG;IAG7D,SAAS,+BAA+B;IACzC,CACF;YACQ,gBAAgB,OAAO,SAAS,sBACzC,aAAY,qBAAqB,CAC/B;IACE,aAAa,YAAY;IACzB,kBAAkB,gBAAgB;IAClC,kBAAkB,gBAAgB,OAAO,iBAAiB,GAAG;IAC7D,SAAS,+BAA+B;IACzC,CACF;;;AAKP,QAAO"}
1
+ {"version":3,"file":"proof.mjs","names":[],"sources":["../../src/display/proof.ts"],"sourcesContent":["import type {\n DcqlCredentialsForRequest,\n DcqlQueryResult,\n DifPexCredentialsForRequest,\n JsonObject,\n Kms,\n MdocNameSpaces,\n MdocRecord,\n SdJwtVcRecord,\n W3cCredentialRecord,\n W3cV2CredentialRecord,\n} from '@credo-ts/core'\nimport { ClaimFormat, CredentialMultiInstanceUseMode, DateOnly, Hasher, TypedArrayEncoder } from '@credo-ts/core'\nimport type { OpenId4VpResolvedAuthorizationRequest } from '@credo-ts/openid4vc'\nimport { formatDate, isDateString } from '../utils'\nimport { detectImageMimeType } from '../utils/attributes'\nimport type { CredentialMetadata, FormattedSubmissionEntrySatisfiedCredential } from './display'\n\ntype MappedAttributesReturnType =\n | string\n | number\n | boolean\n | { [key: string]: MappedAttributesReturnType }\n | null\n | undefined\n | Array<MappedAttributesReturnType>\n\nexport interface FormattedSubmission {\n name?: string\n purpose?: string\n areAllSatisfied: boolean\n entries: FormattedSubmissionEntry[]\n}\n\nexport interface OpenId4VPRequestRecord extends OpenId4VpResolvedAuthorizationRequest {\n verifierHostName: string | undefined\n createdAt: string | Date\n credentialsForRequest: DifPexCredentialsForRequest | undefined\n type: string\n}\n\nexport interface FormattedSubmissionEntrySatisfied {\n /**\n * can be either:\n * - AnonCreds groupName\n * - PEX inputDescriptorId\n * - DCQL credential query id\n */\n inputDescriptorId: string\n\n name?: string\n description?: string\n\n /**\n * Whether the entry is satisfied\n */\n isSatisfied: true\n\n /**\n * Credentials that match the request entry. Wallet always needs to pick one.\n */\n credentials: [FormattedSubmissionEntrySatisfiedCredential, ...FormattedSubmissionEntrySatisfiedCredential[]]\n}\n\nexport interface FormattedSubmissionEntryNotSatisfied {\n /**\n * can be either:\n * - AnonCreds groupName\n * - PEX inputDescriptorId\n * - DCQL credential query id\n */\n inputDescriptorId: string\n\n name?: string\n description?: string\n\n /**\n * Whether the entry is satisfied\n */\n isSatisfied: false\n\n requestedAttributePaths: Array<Array<string | number | null>>\n}\n\nexport type FormattedSubmissionEntry = FormattedSubmissionEntryNotSatisfied | FormattedSubmissionEntrySatisfied\n\nexport function getDisclosedAttributePathArrays(\n payload: object,\n maxDepth: number | undefined = undefined,\n prefix: string[] = []\n): string[][] {\n let attributePaths: string[][] = []\n\n for (const [key, value] of Object.entries(payload)) {\n if (!value) continue\n\n // TODO: handle arrays\n const newPath = [...prefix, key]\n if (value && typeof value === 'object' && maxDepth !== 0) {\n // If the value is a nested object, recurse\n attributePaths = [\n ...attributePaths,\n ...getDisclosedAttributePathArrays(value, maxDepth !== undefined ? maxDepth - 1 : undefined, newPath),\n ]\n } else {\n // If the value is a primitive or maxDepth is reached, add the key to the list\n attributePaths.push(newPath)\n }\n }\n\n return attributePaths\n}\n\nexport function getAttributesAndMetadataForSdJwtPayload(sdJwtVcPayload: Record<string, unknown>) {\n type SdJwtVcPayload = {\n iss: string\n cnf: Record<string, unknown>\n vct: string\n iat?: number\n nbf?: number\n exp?: number\n [key: string]: unknown\n }\n const { _sd_alg, _sd_hash, iss, vct, cnf, iat, exp, nbf, ...visibleProperties } = sdJwtVcPayload as SdJwtVcPayload\n\n const holder = (cnf.kid ?? cnf.jwk) ? safeCalculateJwkThumbprint(cnf.jwk as Kms.Jwk) : undefined\n const credentialMetadata: CredentialMetadata = {\n type: vct,\n issuer: iss,\n holder,\n }\n\n if (iat) {\n credentialMetadata.issuedAt = formatDate(new Date(iat * 1000))\n }\n if (exp) {\n credentialMetadata.validUntil = formatDate(new Date(exp * 1000))\n }\n if (nbf) {\n credentialMetadata.validFrom = formatDate(new Date(nbf * 1000))\n }\n\n return {\n attributes: Object.fromEntries(\n Object.entries(visibleProperties).map(([key, value]) => [key, recursivelyMapAttributes(value)])\n ),\n metadata: credentialMetadata,\n raw: {\n issuedAt: iat ? new Date(iat * 1000) : undefined,\n validUntil: exp ? new Date(exp * 1000) : undefined,\n validFrom: nbf ? new Date(nbf * 1000) : undefined,\n },\n }\n}\n\nexport function safeCalculateJwkThumbprint(jwk: Kms.Jwk): string | undefined {\n try {\n const thumbprint = TypedArrayEncoder.toBase64Url(\n Hasher.hash(\n JSON.stringify({\n k: jwk.k,\n e: jwk.e,\n crv: jwk.crv,\n kty: jwk.kty,\n n: jwk.n,\n x: jwk.x,\n y: jwk.y,\n }),\n 'sha-256'\n )\n )\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-256:${thumbprint}`\n } catch (_e) {\n return undefined\n }\n}\n\nexport function recursivelyMapAttributes(value: unknown): MappedAttributesReturnType {\n if (value instanceof Uint8Array) {\n const imageMimeType = detectImageMimeType(value)\n if (imageMimeType) {\n return `data:${imageMimeType};base64,${TypedArrayEncoder.toBase64(value)}`\n }\n\n return TypedArrayEncoder.toUtf8String(value)\n }\n if (value === null || value === undefined || typeof value === 'number' || typeof value === 'boolean') return value\n\n if (value instanceof Date || value instanceof DateOnly || (typeof value === 'string' && isDateString(value))) {\n return formatDate(value instanceof DateOnly ? value.toISOString() : value)\n }\n if (typeof value === 'string') return value\n if (value instanceof Map) {\n return Object.fromEntries(Array.from(value.entries()).map(([key, value]) => [key, recursivelyMapAttributes(value)]))\n }\n if (Array.isArray(value)) return value.map(recursivelyMapAttributes)\n\n return Object.fromEntries(Object.entries(value).map(([key, value]) => [key, recursivelyMapAttributes(value)]))\n}\n\nexport function getSelectedCredentialsForRequest(\n dcqlQueryResult: DcqlQueryResult,\n selectedCredentials: { [credentialQueryId: string]: string }\n): DcqlCredentialsForRequest {\n if (!dcqlQueryResult.can_be_satisfied) {\n throw new Error('Cannot select the credentials for the dcql query presentation if the request cannot be satisfied')\n }\n\n const credentials: DcqlCredentialsForRequest = {}\n\n type WithRecord<T> = T & {\n record: MdocRecord | SdJwtVcRecord | W3cCredentialRecord | W3cV2CredentialRecord\n }\n\n for (const [credentialQueryId, credentialRecordId] of Object.entries(selectedCredentials)) {\n const matchesForCredentialQuery = dcqlQueryResult.credential_matches[credentialQueryId]\n if (matchesForCredentialQuery.success) {\n const validCredentialMatch = matchesForCredentialQuery.valid_credentials.find(\n (credential) => (credential as WithRecord<typeof credential>).record.id === credentialRecordId\n )\n\n if (!validCredentialMatch) {\n throw new Error(\n `Could not find credential record ${credentialRecordId} in valid credential matches for credentialQueryId ${credentialQueryId}`\n )\n }\n\n // TODO: fix the typing, make selection in Credo easier\n const matchWithRecord = validCredentialMatch as typeof validCredentialMatch & {\n record: MdocRecord | SdJwtVcRecord | W3cCredentialRecord | W3cV2CredentialRecord\n }\n\n if (matchWithRecord.record.type === 'MdocRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: ClaimFormat.MsoMdoc,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as MdocNameSpaces,\n // FIXME: we currently allow re-sharing if we don't have new instances anymore\n // we should make this configurable maybe? Or dependant on credential type?\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n } else if (matchWithRecord.record.type === 'SdJwtVcRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as JsonObject,\n // FIXME: we currently allow re-sharing if we don't have new instances anymore\n // we should make this configurable maybe? Or dependant on credential type?\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n } else if (matchWithRecord.record.type === 'W3cCredentialRecord') {\n credentials[credentialQueryId] = [\n {\n claimFormat: matchWithRecord.record.firstCredential.claimFormat,\n credentialRecord: matchWithRecord.record,\n disclosedPayload: matchWithRecord.claims.valid_claim_sets[0].output as JsonObject,\n useMode: CredentialMultiInstanceUseMode.NewOrFirst,\n },\n ]\n }\n }\n }\n\n return credentials\n}\n"],"mappings":";;;;;;AAsFA,SAAgB,gCACd,SACA,WAA+B,QAC/B,SAAmB,EAAE,EACT;CACZ,IAAI,iBAA6B,EAAE;AAEnC,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,EAAE;AAClD,MAAI,CAAC,MAAO;EAGZ,MAAM,UAAU,CAAC,GAAG,QAAQ,IAAI;AAChC,MAAI,SAAS,OAAO,UAAU,YAAY,aAAa,EAErD,kBAAiB,CACf,GAAG,gBACH,GAAG,gCAAgC,OAAO,aAAa,SAAY,WAAW,IAAI,QAAW,QAAQ,CACtG;MAGD,gBAAe,KAAK,QAAQ;;AAIhC,QAAO;;AAGT,SAAgB,wCAAwC,gBAAyC;CAU/F,MAAM,EAAE,SAAS,UAAU,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,sBAAsB;CA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AS,sBACzC,aAAY,qBAAqB,CAC/B;IACE,aAAa,gBAAgB,OAAO,gBAAgB;IACpD,kBAAkB,gBAAgB;IAClC,kBAAkB,gBAAgB,OAAO,iBAAiB,GAAG;IAC7D,SAAS,+BAA+B;IACzC,CACF;;;AAKP,QAAO"}
package/build/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { CredentialBindingPolicy, HolderBindingMismatchError, HolderBindingNotSupportedError } from "./credentialBindingResolver.mjs";
1
2
  import { sendErrorResponseForDcApi } from "./dcapi/dcapiHelper.mjs";
2
3
  import { CredentialCategoryMetadata, CredentialDisplay, CredentialForDisplay, CredentialForDisplayId, CredentialIssuerDisplay, CredentialMetadata, DisplayImage, FormattedSubmissionEntrySatisfiedCredential, JffW3cCredentialJson, W3cCredentialJson, W3cCredentialSubjectJson, W3cIssuerJson, filterAndMapSdJwtKeys, getAttributesAndMetadataForMdocPayload, getCredentialCategoryMetadata, getCredentialDisplay, getCredentialDisplayWithDefaults, getCredentialForDisplay, getCredentialForDisplayId, getDisclosedAttributeNamesForDisplay, getIssuerDisplay, getOpenId4VcCredentialDisplay, getOpenId4VcIssuerDisplay, getSdJwtCredentialDisplay, getSdJwtIssuerDisplay, getSdJwtTypeMetadataCredentialDisplay, getW3cCredentialDisplay, processIssuerDisplay } from "./display/display.mjs";
3
4
  import { FormattedSubmission, FormattedSubmissionEntry, FormattedSubmissionEntryNotSatisfied, FormattedSubmissionEntrySatisfied, OpenId4VPRequestRecord, getAttributesAndMetadataForSdJwtPayload, getDisclosedAttributePathArrays, getSelectedCredentialsForRequest, recursivelyMapAttributes, safeCalculateJwkThumbprint } from "./display/proof.mjs";
@@ -16,4 +17,4 @@ import { getHostNameFromUrl } from "./utils/url.mjs";
16
17
  import "./utils/index.mjs";
17
18
  import { GenericRecord, MdocRecord, SdJwtVcRecord, W3cCredentialRecord } from "@credo-ts/core";
18
19
  import { OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode } from "@credo-ts/openid4vc";
19
- export { CredentialCategoryMetadata, CredentialDisplay, CredentialForDisplay, CredentialForDisplayId, CredentialIssuerDisplay, CredentialMetadata, CredentialsForProofRequest, DisplayImage, FormattedSubmission, FormattedSubmissionEntry, FormattedSubmissionEntryNotSatisfied, FormattedSubmissionEntrySatisfied, FormattedSubmissionEntrySatisfiedCredential, GenericRecord, InvitationQrTypesSupported, JffW3cCredentialJson, Mdoc, MdocRecord, MdocRecordProvider, OpenID4VCSDK, OpenId4VPRequestRecord, OpenId4VcAgent, OpenId4VcConfiguration, OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode, ParseInvitationResult, ParsedInvitation, SdJwtVc, SdJwtVcRecord, SdJwtVcRecordProvider, W3cCredentialJson, W3cCredentialRecord, W3cCredentialSubjectJson, W3cIssuerJson, applySelectedCredentialFilter, credentialRecordFromCredential, encodeCredential, ensureSingleCredentialRequest, extractCredentialPlaceholderFromQueryCredential, extractProviderRequest, filterAndMapSdJwtKeys, formatDate, getAttributesAndMetadataForMdocPayload, getAttributesAndMetadataForSdJwtPayload, getCredentialCategoryMetadata, getCredentialDisplay, getCredentialDisplayWithDefaults, getCredentialForDisplay, getCredentialForDisplayId, getDisclosedAttributeNamesForDisplay, getDisclosedAttributePathArrays, getHostNameFromUrl, getIssuerDisplay, getOpenId4VcCredentialDisplay, getOpenId4VcIssuerDisplay, getOpenid4VcModules, getSdJwtCredentialDisplay, getSdJwtIssuerDisplay, getSdJwtTypeMetadataCredentialDisplay, getSelectedCredentialsForRequest, getW3cCredentialDisplay, isDateString, isOpenIdCredentialOffer, isOpenIdPresentationRequest, parseInvitationUrl, processIssuerDisplay, recursivelyMapAttributes, safeCalculateJwkThumbprint, sanitizeString, sendErrorResponseForDcApi, useMdocRecordById, useMdocRecords, useSdJwtVcRecordById, useSdJwtVcRecords };
20
+ export { type CredentialBindingPolicy, CredentialCategoryMetadata, CredentialDisplay, CredentialForDisplay, CredentialForDisplayId, CredentialIssuerDisplay, CredentialMetadata, CredentialsForProofRequest, DisplayImage, FormattedSubmission, FormattedSubmissionEntry, FormattedSubmissionEntryNotSatisfied, FormattedSubmissionEntrySatisfied, FormattedSubmissionEntrySatisfiedCredential, GenericRecord, HolderBindingMismatchError, HolderBindingNotSupportedError, InvitationQrTypesSupported, JffW3cCredentialJson, Mdoc, MdocRecord, MdocRecordProvider, OpenID4VCSDK, OpenId4VPRequestRecord, OpenId4VcAgent, OpenId4VcConfiguration, OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode, ParseInvitationResult, ParsedInvitation, SdJwtVc, SdJwtVcRecord, SdJwtVcRecordProvider, W3cCredentialJson, W3cCredentialRecord, W3cCredentialSubjectJson, W3cIssuerJson, applySelectedCredentialFilter, credentialRecordFromCredential, encodeCredential, ensureSingleCredentialRequest, extractCredentialPlaceholderFromQueryCredential, extractProviderRequest, filterAndMapSdJwtKeys, formatDate, getAttributesAndMetadataForMdocPayload, getAttributesAndMetadataForSdJwtPayload, getCredentialCategoryMetadata, getCredentialDisplay, getCredentialDisplayWithDefaults, getCredentialForDisplay, getCredentialForDisplayId, getDisclosedAttributeNamesForDisplay, getDisclosedAttributePathArrays, getHostNameFromUrl, getIssuerDisplay, getOpenId4VcCredentialDisplay, getOpenId4VcIssuerDisplay, getOpenid4VcModules, getSdJwtCredentialDisplay, getSdJwtIssuerDisplay, getSdJwtTypeMetadataCredentialDisplay, getSelectedCredentialsForRequest, getW3cCredentialDisplay, isDateString, isOpenIdCredentialOffer, isOpenIdPresentationRequest, parseInvitationUrl, processIssuerDisplay, recursivelyMapAttributes, safeCalculateJwkThumbprint, sanitizeString, sendErrorResponseForDcApi, useMdocRecordById, useMdocRecords, useSdJwtVcRecordById, useSdJwtVcRecords };
package/build/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { HolderBindingMismatchError, HolderBindingNotSupportedError } from "./credentialBindingResolver.mjs";
1
2
  import { sendErrorResponseForDcApi } from "./dcapi/dcapiHelper.mjs";
2
3
  import "./dcapi/index.mjs";
3
4
  import { formatDate, isDateString } from "./utils/date.mjs";
@@ -18,4 +19,4 @@ import { OpenID4VCSDK, getOpenid4VcModules } from "./OpenIDSdk.mjs";
18
19
  import { GenericRecord, MdocRecord, SdJwtVcRecord, W3cCredentialRecord } from "@credo-ts/core";
19
20
  import { OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode } from "@credo-ts/openid4vc";
20
21
 
21
- export { GenericRecord, InvitationQrTypesSupported, Mdoc, MdocRecord, MdocRecordProvider, OpenID4VCSDK, OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode, SdJwtVc, SdJwtVcRecord, SdJwtVcRecordProvider, W3cCredentialRecord, applySelectedCredentialFilter, credentialRecordFromCredential, encodeCredential, ensureSingleCredentialRequest, extractCredentialPlaceholderFromQueryCredential, extractProviderRequest, filterAndMapSdJwtKeys, formatDate, getAttributesAndMetadataForMdocPayload, getAttributesAndMetadataForSdJwtPayload, getCredentialCategoryMetadata, getCredentialDisplay, getCredentialDisplayWithDefaults, getCredentialForDisplay, getCredentialForDisplayId, getDisclosedAttributeNamesForDisplay, getDisclosedAttributePathArrays, getHostNameFromUrl, getIssuerDisplay, getOpenId4VcCredentialDisplay, getOpenId4VcIssuerDisplay, getOpenid4VcModules, getSdJwtCredentialDisplay, getSdJwtIssuerDisplay, getSdJwtTypeMetadataCredentialDisplay, getSelectedCredentialsForRequest, getW3cCredentialDisplay, isDateString, isOpenIdCredentialOffer, isOpenIdPresentationRequest, parseInvitationUrl, processIssuerDisplay, recursivelyMapAttributes, safeCalculateJwkThumbprint, sanitizeString, sendErrorResponseForDcApi, useMdocRecordById, useMdocRecords, useSdJwtVcRecordById, useSdJwtVcRecords };
22
+ export { GenericRecord, HolderBindingMismatchError, HolderBindingNotSupportedError, InvitationQrTypesSupported, Mdoc, MdocRecord, MdocRecordProvider, OpenID4VCSDK, OpenId4VciAuthorizationFlow, OpenId4VciRequestTokenResponse, OpenId4VciResolvedAuthorizationRequest, OpenId4VciResolvedCredentialOffer, OpenId4VciTxCode, SdJwtVc, SdJwtVcRecord, SdJwtVcRecordProvider, W3cCredentialRecord, applySelectedCredentialFilter, credentialRecordFromCredential, encodeCredential, ensureSingleCredentialRequest, extractCredentialPlaceholderFromQueryCredential, extractProviderRequest, filterAndMapSdJwtKeys, formatDate, getAttributesAndMetadataForMdocPayload, getAttributesAndMetadataForSdJwtPayload, getCredentialCategoryMetadata, getCredentialDisplay, getCredentialDisplayWithDefaults, getCredentialForDisplay, getCredentialForDisplayId, getDisclosedAttributeNamesForDisplay, getDisclosedAttributePathArrays, getHostNameFromUrl, getIssuerDisplay, getOpenId4VcCredentialDisplay, getOpenId4VcIssuerDisplay, getOpenid4VcModules, getSdJwtCredentialDisplay, getSdJwtIssuerDisplay, getSdJwtTypeMetadataCredentialDisplay, getSelectedCredentialsForRequest, getW3cCredentialDisplay, isDateString, isOpenIdCredentialOffer, isOpenIdPresentationRequest, parseInvitationUrl, processIssuerDisplay, recursivelyMapAttributes, safeCalculateJwkThumbprint, sanitizeString, sendErrorResponseForDcApi, useMdocRecordById, useMdocRecords, useSdJwtVcRecordById, useSdJwtVcRecords };
@@ -17,19 +17,12 @@ type GetCredentialsForProofRequestOptions = {
17
17
  preferredLocale?: string;
18
18
  selectedCredentialsId?: string[];
19
19
  };
20
- declare function extractCredentialPlaceholderFromQueryCredential(credential: DcqlQueryResult['credentials'][number]): {
20
+ interface CredentialPlaceholder {
21
21
  claimFormat: ClaimFormat;
22
- credentialName: string;
23
- requestedAttributePaths: string[][] | undefined;
24
- } | {
25
- claimFormat: ClaimFormat;
26
- requestedAttributePaths: [string | number | null, ...(string | number | null)[]][] | undefined;
27
- credentialName?: undefined;
28
- } | {
29
- claimFormat: ClaimFormat;
30
- credentialName: string | undefined;
31
- requestedAttributePaths: [string | number | null, ...(string | number | null)[]][] | undefined;
32
- };
22
+ credentialName?: string;
23
+ requestedAttributePaths?: Array<Array<string | number | null>>;
24
+ }
25
+ declare function extractCredentialPlaceholderFromQueryCredential(credential: DcqlQueryResult['credentials'][number]): CredentialPlaceholder;
33
26
  //#endregion
34
27
  export { GetCredentialsForProofRequestOptions, extractCredentialPlaceholderFromQueryCredential };
35
28
  //# sourceMappingURL=resolverProof.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolverProof.d.mts","names":[],"sources":["../src/resolverProof.ts"],"mappings":";;;;KAoBY,iBAAA;EAAsB,WAAA;EAAqB,IAAA;EAAc,OAAA;EAAiB,GAAA;AAAA;AAAA,KAE1E,oCAAA;EACV,cAAA,GAAiB,MAAA;EACjB,GAAA;EACA,wBAAA;EACA,MAAA;EACA,mBAAA,GAAsB,iBAAA;EACtB,eAAA;EACA,qBAAA;AAAA;AAAA,iBA8Kc,+CAAA,CAAgD,UAAA,EAAY,eAAA"}
1
+ {"version":3,"file":"resolverProof.d.mts","names":[],"sources":["../src/resolverProof.ts"],"mappings":";;;;KAoBY,iBAAA;EAAsB,WAAA;EAAqB,IAAA;EAAc,OAAA;EAAiB,GAAA;AAAA;AAAA,KAE1E,oCAAA;EACV,cAAA,GAAiB,MAAA;EACjB,GAAA;EACA,wBAAA;EACA,MAAA;EACA,mBAAA,GAAsB,iBAAA;EACtB,eAAA;EACA,qBAAA;AAAA;AAAA,UA8Ke,qBAAA;EACf,WAAA,EAAa,WAAA;EACb,cAAA;EACA,uBAAA,GAA0B,KAAA,CAAM,KAAA;AAAA;AAAA,iBAGlB,+CAAA,CACd,UAAA,EAAY,eAAA,0BACX,qBAAA"}
@@ -138,6 +138,11 @@ function extractCredentialPlaceholderFromQueryCredential(credential) {
138
138
  credentialName: credential.meta?.vct_values?.[0].replace("https://", ""),
139
139
  requestedAttributePaths: credential.claims?.map((c) => c.path)
140
140
  };
141
+ if (credential.format === "ldp_vc") return {
142
+ claimFormat: ClaimFormat.LdpVc,
143
+ credentialName: credential.meta?.type_values?.[0]?.at(-1)?.replace("https://", ""),
144
+ requestedAttributePaths: credential.claims?.map((c) => c.path)
145
+ };
141
146
  return {
142
147
  claimFormat: ClaimFormat.JwtVc,
143
148
  requestedAttributePaths: credential.claims?.map((c) => c.path)
@@ -1 +1 @@
1
- {"version":3,"file":"resolverProof.mjs","names":[],"sources":["../src/resolverProof.ts"],"sourcesContent":["import { JSONPath } from '@astronautlabs/jsonpath'\nimport {\n ClaimFormat,\n type DcqlQueryResult,\n type DifPexCredentialsForRequest,\n type DifPresentationExchangeDefinitionV2,\n MdocNameSpaces,\n} from '@credo-ts/core'\nimport {\n type FormattedSubmission,\n type FormattedSubmissionEntry,\n type FormattedSubmissionEntrySatisfiedCredential,\n getAttributesAndMetadataForMdocPayload,\n getAttributesAndMetadataForSdJwtPayload,\n getCredentialForDisplay,\n getDisclosedAttributePathArrays,\n} from './display'\n\nexport type NonEmptyArray<T> = [T, ...T[]]\n\nexport type TrustedX509Entity = { certificate: string; name: string; logoUri: string; url: string }\n\nexport type GetCredentialsForProofRequestOptions = {\n requestPayload?: Record<string, unknown>\n uri?: string\n allowUntrustedFederation?: boolean\n origin?: string\n trustedX509Entities?: TrustedX509Entity[]\n preferredLocale?: string\n selectedCredentialsId?: string[]\n}\n\nexport function formatDifPexCredentialsForRequest(\n credentialsForRequest: DifPexCredentialsForRequest,\n definition: DifPresentationExchangeDefinitionV2,\n preferredLocale?: string\n): FormattedSubmission {\n const entries = credentialsForRequest.requirements.flatMap((requirement) => {\n // We take the first needsCount entries. Even if not satisfied we will just show these first entries as missing (otherwise it becomes too complex)\n // If selection is possible they can choose alternatives within that (otherwise it becomes too complex)\n const submissionEntries = requirement.submissionEntry.slice(0, requirement.needsCount)\n\n return submissionEntries.map((submission): FormattedSubmissionEntry => {\n if (submission.verifiableCredentials.length >= 1) {\n return {\n inputDescriptorId: submission.inputDescriptorId,\n name: submission.name,\n description: submission.purpose,\n isSatisfied: true,\n credentials: submission.verifiableCredentials.map(\n (verifiableCredential): FormattedSubmissionEntrySatisfiedCredential => {\n const credentialForDisplay = getCredentialForDisplay(\n verifiableCredential.credentialRecord,\n preferredLocale\n )\n\n // By default the whole credential is disclosed\n let disclosed: FormattedSubmissionEntrySatisfiedCredential['disclosed']\n if (verifiableCredential.claimFormat === ClaimFormat.SdJwtDc) {\n const { attributes, metadata } = getAttributesAndMetadataForSdJwtPayload(\n verifiableCredential.disclosedPayload\n )\n disclosed = {\n attributes,\n metadata,\n paths: getDisclosedAttributePathArrays(attributes, 2),\n }\n } else {\n disclosed = {\n attributes: credentialForDisplay.attributes,\n metadata: credentialForDisplay.metadata,\n paths: getDisclosedAttributePathArrays(credentialForDisplay.attributes, 2),\n }\n }\n\n return {\n credential: credentialForDisplay,\n disclosed,\n }\n }\n ) as NonEmptyArray<FormattedSubmissionEntrySatisfiedCredential>,\n }\n }\n\n // Try to determine requested attributes for credential\n const inputDescriptor = definition.input_descriptors.find(({ id }) => id === submission.inputDescriptorId)\n const requestedAttributePaths =\n inputDescriptor?.constraints?.fields\n ?.map((a) =>\n simplifyJsonPath(a.path[0], inputDescriptor.format?.mso_mdoc ? ClaimFormat.MsoMdoc : undefined)?.filter(\n (entry): entry is string => entry !== null\n )\n )\n .filter((path): path is string[] => path !== undefined) ?? []\n\n const docType = inputDescriptor?.format?.mso_mdoc ? inputDescriptor.id : undefined\n const vctField = inputDescriptor?.format?.['vc+sd-jwt']\n ? inputDescriptor.constraints.fields?.find((field) => field.path.includes('$.vct'))\n : undefined\n const vct = (vctField?.filter?.const ?? vctField?.filter?.enum?.[0]) as string | undefined\n\n return {\n inputDescriptorId: submission.inputDescriptorId,\n name: requirement.name ?? docType ?? vct?.replace('https://', ''),\n description: requirement.purpose,\n isSatisfied: false,\n requestedAttributePaths: requestedAttributePaths,\n }\n })\n })\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n name: credentialsForRequest.name ?? 'unknown',\n purpose: credentialsForRequest.purpose,\n entries,\n }\n}\n\nexport function formatDcqlCredentialsForRequest(dcqlQueryResult: DcqlQueryResult): FormattedSubmission {\n const credentialSets: NonNullable<DcqlQueryResult['credential_sets']> = dcqlQueryResult.credential_sets ?? [\n // If no credential sets are defined we create a default one with just all the credential options\n {\n required: true,\n options: [dcqlQueryResult.credentials.map((c) => c.id)],\n matching_options: dcqlQueryResult.can_be_satisfied ? [dcqlQueryResult.credentials.map((c) => c.id)] : undefined,\n },\n ]\n\n const entries: FormattedSubmissionEntry[] = []\n for (const credentialSet of credentialSets) {\n // Take first matching option, otherwise take first option\n for (const credentialId of credentialSet.matching_options?.[0] ?? credentialSet.options[0]) {\n const match = dcqlQueryResult.credential_matches[credentialId]\n const queryCredential = dcqlQueryResult.credentials.find((c) => c.id === credentialId)\n if (!queryCredential) {\n throw new Error(`Credential '${credentialId}' not found in dcql query`)\n }\n\n if (!match?.success) {\n const placeholderCredential = extractCredentialPlaceholderFromQueryCredential(queryCredential)\n entries.push({\n isSatisfied: false,\n inputDescriptorId: credentialId,\n name: placeholderCredential.credentialName,\n requestedAttributePaths: placeholderCredential.requestedAttributePaths ?? [],\n })\n continue\n }\n\n const credentials: FormattedSubmissionEntrySatisfiedCredential[] = []\n\n for (const validMatch of match.valid_credentials) {\n const credentialForDisplay = getCredentialForDisplay(validMatch.record)\n let disclosed: FormattedSubmissionEntrySatisfiedCredential['disclosed']\n\n if (validMatch.record.type === 'SdJwtVcRecord') {\n // Credo already applied selective disclosure on payload\n const { attributes, metadata } = getAttributesAndMetadataForSdJwtPayload(\n validMatch.claims.valid_claim_sets[0].output\n )\n disclosed = {\n attributes,\n metadata,\n paths: getDisclosedAttributePathArrays(attributes, 2),\n }\n } else if (validMatch.record.type === 'MdocRecord') {\n const namespaces = validMatch.claims.valid_claim_sets[0].output as MdocNameSpaces\n disclosed = {\n ...getAttributesAndMetadataForMdocPayload(namespaces, validMatch.record.firstCredential),\n paths: getDisclosedAttributePathArrays(namespaces, 2),\n }\n } else {\n // All paths disclosed for W3C\n disclosed = {\n attributes: credentialForDisplay.attributes,\n metadata: credentialForDisplay.metadata,\n paths: getDisclosedAttributePathArrays(credentialForDisplay.attributes, 2),\n }\n }\n\n credentials.push({\n credential: credentialForDisplay,\n disclosed,\n })\n }\n\n entries.push({\n inputDescriptorId: credentialId,\n credentials: credentials as NonEmptyArray<FormattedSubmissionEntrySatisfiedCredential>,\n isSatisfied: true,\n name: credentials[0].credential.display.name,\n })\n }\n }\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n purpose: credentialSets.map((s) => s.purpose).find((purpose): purpose is string => typeof purpose === 'string'),\n entries,\n }\n}\n\nexport function extractCredentialPlaceholderFromQueryCredential(credential: DcqlQueryResult['credentials'][number]) {\n if (credential.format === 'mso_mdoc') {\n return {\n claimFormat: ClaimFormat.MsoMdoc,\n credentialName: credential.meta?.doctype_value ?? 'Unknown MDoc',\n requestedAttributePaths: credential.claims?.map((c) => ('path' in c ? [c.path[1]] : [c.claim_name])),\n }\n }\n\n if (credential.format === 'vc+sd-jwt') {\n if (credential.meta && 'type_values' in credential.meta) {\n return {\n claimFormat: ClaimFormat.SdJwtW3cVc,\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n return {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialName: credential.meta?.vct_values?.[0].replace('https://', ''),\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n if (credential.format === 'dc+sd-jwt') {\n return {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialName: credential.meta?.vct_values?.[0].replace('https://', ''),\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n return {\n claimFormat: ClaimFormat.JwtVc,\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n}\n\nfunction simplifyJsonPath(path: string, format?: ClaimFormat, filterKeys: string[] = []) {\n try {\n const parsedPath: Array<{\n scope: string\n operation: string\n expression: { type: string; value: string; [key: string]: unknown }\n }> = JSONPath.parse(path)\n\n if (!Array.isArray(parsedPath)) {\n return null\n }\n\n const simplified: Array<string | null> = []\n\n if (format === ClaimFormat.MsoMdoc) {\n if (parsedPath.length === 3) {\n simplified.push(parsedPath[2].expression.value)\n }\n } else {\n for (const entry of parsedPath) {\n // Skip entries we want to remove\n const value = entry.expression.value\n if (['vc', 'vp', 'credentialSubject'].includes(value)) {\n continue\n }\n\n // Remove root\n if (entry.expression.type === 'root') {\n continue\n }\n\n if (\n entry.expression.type === 'wildcard' ||\n (entry.expression.type === 'numeric_literal' && !Number.isNaN(value))\n ) {\n // Replace wildcards and numeric indices with null\n simplified.push(null)\n }\n\n if (entry.expression.type === 'identifier' || entry.expression.type === 'string_literal') {\n // Return the identifier value for normal entries\n simplified.push(value)\n }\n }\n }\n\n if (filterKeys.some((key) => simplified.includes(key))) {\n return null\n }\n\n return simplified\n } catch (_error) {\n return null\n }\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,kCACd,uBACA,YACA,iBACqB;CACrB,MAAM,UAAU,sBAAsB,aAAa,SAAS,gBAAgB;AAK1E,SAF0B,YAAY,gBAAgB,MAAM,GAAG,YAAY,WAAW,CAE7D,KAAK,eAAyC;AACrE,OAAI,WAAW,sBAAsB,UAAU,EAC7C,QAAO;IACL,mBAAmB,WAAW;IAC9B,MAAM,WAAW;IACjB,aAAa,WAAW;IACxB,aAAa;IACb,aAAa,WAAW,sBAAsB,KAC3C,yBAAsE;KACrE,MAAM,uBAAuB,wBAC3B,qBAAqB,kBACrB,gBACD;KAGD,IAAI;AACJ,SAAI,qBAAqB,gBAAgB,YAAY,SAAS;MAC5D,MAAM,EAAE,YAAY,aAAa,wCAC/B,qBAAqB,iBACtB;AACD,kBAAY;OACV;OACA;OACA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D;AAIF,OAAI,MAAM,WAAW,SAAS,OAC5B;AAGF,OACE,MAAM,WAAW,SAAS,cACzB,MAAM,WAAW,SAAS,qBAAqB,CAAC,OAAO,MAAM,MAAM,CAGpE,YAAW,KAAK,KAAK;AAGvB,OAAI,MAAM,WAAW,SAAS,gBAAgB,MAAM,WAAW,SAAS,iBAEtE,YAAW,KAAK,MAAM;;AAK5B,MAAI,WAAW,MAAM,QAAQ,WAAW,SAAS,IAAI,CAAC,CACpD,QAAO;AAGT,SAAO;UACA,QAAQ;AACf,SAAO"}
1
+ {"version":3,"file":"resolverProof.mjs","names":[],"sources":["../src/resolverProof.ts"],"sourcesContent":["import { JSONPath } from '@astronautlabs/jsonpath'\nimport {\n ClaimFormat,\n type DcqlQueryResult,\n type DifPexCredentialsForRequest,\n type DifPresentationExchangeDefinitionV2,\n MdocNameSpaces,\n} from '@credo-ts/core'\nimport {\n type FormattedSubmission,\n type FormattedSubmissionEntry,\n type FormattedSubmissionEntrySatisfiedCredential,\n getAttributesAndMetadataForMdocPayload,\n getAttributesAndMetadataForSdJwtPayload,\n getCredentialForDisplay,\n getDisclosedAttributePathArrays,\n} from './display'\n\nexport type NonEmptyArray<T> = [T, ...T[]]\n\nexport type TrustedX509Entity = { certificate: string; name: string; logoUri: string; url: string }\n\nexport type GetCredentialsForProofRequestOptions = {\n requestPayload?: Record<string, unknown>\n uri?: string\n allowUntrustedFederation?: boolean\n origin?: string\n trustedX509Entities?: TrustedX509Entity[]\n preferredLocale?: string\n selectedCredentialsId?: string[]\n}\n\nexport function formatDifPexCredentialsForRequest(\n credentialsForRequest: DifPexCredentialsForRequest,\n definition: DifPresentationExchangeDefinitionV2,\n preferredLocale?: string\n): FormattedSubmission {\n const entries = credentialsForRequest.requirements.flatMap((requirement) => {\n // We take the first needsCount entries. Even if not satisfied we will just show these first entries as missing (otherwise it becomes too complex)\n // If selection is possible they can choose alternatives within that (otherwise it becomes too complex)\n const submissionEntries = requirement.submissionEntry.slice(0, requirement.needsCount)\n\n return submissionEntries.map((submission): FormattedSubmissionEntry => {\n if (submission.verifiableCredentials.length >= 1) {\n return {\n inputDescriptorId: submission.inputDescriptorId,\n name: submission.name,\n description: submission.purpose,\n isSatisfied: true,\n credentials: submission.verifiableCredentials.map(\n (verifiableCredential): FormattedSubmissionEntrySatisfiedCredential => {\n const credentialForDisplay = getCredentialForDisplay(\n verifiableCredential.credentialRecord,\n preferredLocale\n )\n\n // By default the whole credential is disclosed\n let disclosed: FormattedSubmissionEntrySatisfiedCredential['disclosed']\n if (verifiableCredential.claimFormat === ClaimFormat.SdJwtDc) {\n const { attributes, metadata } = getAttributesAndMetadataForSdJwtPayload(\n verifiableCredential.disclosedPayload\n )\n disclosed = {\n attributes,\n metadata,\n paths: getDisclosedAttributePathArrays(attributes, 2),\n }\n } else {\n disclosed = {\n attributes: credentialForDisplay.attributes,\n metadata: credentialForDisplay.metadata,\n paths: getDisclosedAttributePathArrays(credentialForDisplay.attributes, 2),\n }\n }\n\n return {\n credential: credentialForDisplay,\n disclosed,\n }\n }\n ) as NonEmptyArray<FormattedSubmissionEntrySatisfiedCredential>,\n }\n }\n\n // Try to determine requested attributes for credential\n const inputDescriptor = definition.input_descriptors.find(({ id }) => id === submission.inputDescriptorId)\n const requestedAttributePaths =\n inputDescriptor?.constraints?.fields\n ?.map((a) =>\n simplifyJsonPath(a.path[0], inputDescriptor.format?.mso_mdoc ? ClaimFormat.MsoMdoc : undefined)?.filter(\n (entry): entry is string => entry !== null\n )\n )\n .filter((path): path is string[] => path !== undefined) ?? []\n\n const docType = inputDescriptor?.format?.mso_mdoc ? inputDescriptor.id : undefined\n const vctField = inputDescriptor?.format?.['vc+sd-jwt']\n ? inputDescriptor.constraints.fields?.find((field) => field.path.includes('$.vct'))\n : undefined\n const vct = (vctField?.filter?.const ?? vctField?.filter?.enum?.[0]) as string | undefined\n\n return {\n inputDescriptorId: submission.inputDescriptorId,\n name: requirement.name ?? docType ?? vct?.replace('https://', ''),\n description: requirement.purpose,\n isSatisfied: false,\n requestedAttributePaths: requestedAttributePaths,\n }\n })\n })\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n name: credentialsForRequest.name ?? 'unknown',\n purpose: credentialsForRequest.purpose,\n entries,\n }\n}\n\nexport function formatDcqlCredentialsForRequest(dcqlQueryResult: DcqlQueryResult): FormattedSubmission {\n const credentialSets: NonNullable<DcqlQueryResult['credential_sets']> = dcqlQueryResult.credential_sets ?? [\n // If no credential sets are defined we create a default one with just all the credential options\n {\n required: true,\n options: [dcqlQueryResult.credentials.map((c) => c.id)],\n matching_options: dcqlQueryResult.can_be_satisfied ? [dcqlQueryResult.credentials.map((c) => c.id)] : undefined,\n },\n ]\n\n const entries: FormattedSubmissionEntry[] = []\n for (const credentialSet of credentialSets) {\n // Take first matching option, otherwise take first option\n for (const credentialId of credentialSet.matching_options?.[0] ?? credentialSet.options[0]) {\n const match = dcqlQueryResult.credential_matches[credentialId]\n const queryCredential = dcqlQueryResult.credentials.find((c) => c.id === credentialId)\n if (!queryCredential) {\n throw new Error(`Credential '${credentialId}' not found in dcql query`)\n }\n\n if (!match?.success) {\n const placeholderCredential = extractCredentialPlaceholderFromQueryCredential(queryCredential)\n entries.push({\n isSatisfied: false,\n inputDescriptorId: credentialId,\n name: placeholderCredential.credentialName,\n requestedAttributePaths: placeholderCredential.requestedAttributePaths ?? [],\n })\n continue\n }\n\n const credentials: FormattedSubmissionEntrySatisfiedCredential[] = []\n\n for (const validMatch of match.valid_credentials) {\n const credentialForDisplay = getCredentialForDisplay(validMatch.record)\n let disclosed: FormattedSubmissionEntrySatisfiedCredential['disclosed']\n\n if (validMatch.record.type === 'SdJwtVcRecord') {\n // Credo already applied selective disclosure on payload\n const { attributes, metadata } = getAttributesAndMetadataForSdJwtPayload(\n validMatch.claims.valid_claim_sets[0].output\n )\n disclosed = {\n attributes,\n metadata,\n paths: getDisclosedAttributePathArrays(attributes, 2),\n }\n } else if (validMatch.record.type === 'MdocRecord') {\n const namespaces = validMatch.claims.valid_claim_sets[0].output as MdocNameSpaces\n disclosed = {\n ...getAttributesAndMetadataForMdocPayload(namespaces, validMatch.record.firstCredential),\n paths: getDisclosedAttributePathArrays(namespaces, 2),\n }\n } else {\n // All paths disclosed for W3C\n disclosed = {\n attributes: credentialForDisplay.attributes,\n metadata: credentialForDisplay.metadata,\n paths: getDisclosedAttributePathArrays(credentialForDisplay.attributes, 2),\n }\n }\n\n credentials.push({\n credential: credentialForDisplay,\n disclosed,\n })\n }\n\n entries.push({\n inputDescriptorId: credentialId,\n credentials: credentials as NonEmptyArray<FormattedSubmissionEntrySatisfiedCredential>,\n isSatisfied: true,\n name: credentials[0].credential.display.name,\n })\n }\n }\n\n return {\n areAllSatisfied: entries.every((entry) => entry.isSatisfied),\n purpose: credentialSets.map((s) => s.purpose).find((purpose): purpose is string => typeof purpose === 'string'),\n entries,\n }\n}\n\nexport interface CredentialPlaceholder {\n claimFormat: ClaimFormat\n credentialName?: string\n requestedAttributePaths?: Array<Array<string | number | null>>\n}\n\nexport function extractCredentialPlaceholderFromQueryCredential(\n credential: DcqlQueryResult['credentials'][number]\n): CredentialPlaceholder {\n if (credential.format === 'mso_mdoc') {\n return {\n claimFormat: ClaimFormat.MsoMdoc,\n credentialName: credential.meta?.doctype_value ?? 'Unknown MDoc',\n requestedAttributePaths: credential.claims?.map((c) => ('path' in c ? [c.path[1]] : [c.claim_name])),\n }\n }\n\n if (credential.format === 'vc+sd-jwt') {\n if (credential.meta && 'type_values' in credential.meta) {\n return {\n claimFormat: ClaimFormat.SdJwtW3cVc,\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n return {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialName: credential.meta?.vct_values?.[0].replace('https://', ''),\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n if (credential.format === 'dc+sd-jwt') {\n return {\n claimFormat: ClaimFormat.SdJwtDc,\n credentialName: credential.meta?.vct_values?.[0].replace('https://', ''),\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n if (credential.format === 'ldp_vc') {\n return {\n claimFormat: ClaimFormat.LdpVc,\n credentialName: credential.meta?.type_values?.[0]?.at(-1)?.replace('https://', ''),\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n }\n\n return {\n claimFormat: ClaimFormat.JwtVc,\n requestedAttributePaths: credential.claims?.map((c) => c.path),\n }\n}\n\nfunction simplifyJsonPath(path: string, format?: ClaimFormat, filterKeys: string[] = []) {\n try {\n const parsedPath: Array<{\n scope: string\n operation: string\n expression: { type: string; value: string; [key: string]: unknown }\n }> = JSONPath.parse(path)\n\n if (!Array.isArray(parsedPath)) {\n return null\n }\n\n const simplified: Array<string | null> = []\n\n if (format === ClaimFormat.MsoMdoc) {\n if (parsedPath.length === 3) {\n simplified.push(parsedPath[2].expression.value)\n }\n } else {\n for (const entry of parsedPath) {\n // Skip entries we want to remove\n const value = entry.expression.value\n if (['vc', 'vp', 'credentialSubject'].includes(value)) {\n continue\n }\n\n // Remove root\n if (entry.expression.type === 'root') {\n continue\n }\n\n if (\n entry.expression.type === 'wildcard' ||\n (entry.expression.type === 'numeric_literal' && !Number.isNaN(value))\n ) {\n // Replace wildcards and numeric indices with null\n simplified.push(null)\n }\n\n if (entry.expression.type === 'identifier' || entry.expression.type === 'string_literal') {\n // Return the identifier value for normal entries\n simplified.push(value)\n }\n }\n }\n\n if (filterKeys.some((key) => simplified.includes(key))) {\n return null\n }\n\n return simplified\n } catch (_error) {\n return null\n }\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,kCACd,uBACA,YACA,iBACqB;CACrB,MAAM,UAAU,sBAAsB,aAAa,SAAS,gBAAgB;AAK1E,SAF0B,YAAY,gBAAgB,MAAM,GAAG,YAAY,WAAW,CAE7D,KAAK,eAAyC;AACrE,OAAI,WAAW,sBAAsB,UAAU,EAC7C,QAAO;IACL,mBAAmB,WAAW;IAC9B,MAAM,WAAW;IACjB,aAAa,WAAW;IACxB,aAAa;IACb,aA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;EAC/D;;AAGH,SAAS,iBAAiB,MAAc,QAAsB,aAAuB,EAAE,EAAE;AACvF,KAAI;EACF,MAAM,aAID,SAAS,MAAM,KAAK;AAEzB,MAAI,CAAC,MAAM,QAAQ,WAAW,CAC5B,QAAO;EAGT,MAAM,aAAmC,EAAE;AAE3C,MAAI,WAAW,YAAY,SACzB;OAAI,WAAW,WAAW,EACxB,YAAW,KAAK,WAAW,GAAG,WAAW,MAAM;QAGjD,MAAK,MAAM,SAAS,YAAY;GAE9B,MAAM,QAAQ,MAAM,WAAW;AAC/B,OAAI;IAAC;IAAM;IAAM;IAAoB,CAAC,SAAS,MAAM,CACnD;AAIF,OAAI,MAAM,WAAW,SAAS,OAC5B;AAGF,OACE,MAAM,WAAW,SAAS,cACzB,MAAM,WAAW,SAAS,qBAAqB,CAAC,OAAO,MAAM,MAAM,CAGpE,YAAW,KAAK,KAAK;AAGvB,OAAI,MAAM,WAAW,SAAS,gBAAgB,MAAM,WAAW,SAAS,iBAEtE,YAAW,KAAK,MAAM;;AAK5B,MAAI,WAAW,MAAM,QAAQ,WAAW,SAAS,IAAI,CAAC,CACpD,QAAO;AAGT,SAAO;UACA,QAAQ;AACf,SAAO"}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  ".": "./build/index.mjs",
5
5
  "./package.json": "./package.json"
6
6
  },
7
- "version": "2.2.1",
7
+ "version": "2.3.0-alpha-20261104134326",
8
8
  "files": [
9
9
  "build"
10
10
  ],
@@ -20,15 +20,15 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "@animo-id/expo-digital-credentials-api": "^0.4.0",
23
- "@owf/mdoc": "^0.6.0",
23
+ "@owf/mdoc": "^0.8.1",
24
24
  "@astronautlabs/jsonpath": "^1.1.2",
25
- "@credo-ts/core": "0.7.0",
26
- "@credo-ts/openid4vc": "0.7.0",
25
+ "@credo-ts/core": "0.7.4",
26
+ "@credo-ts/openid4vc": "0.7.4",
27
27
  "expo-asset": "^12.0.10",
28
28
  "expo-image": "^56.0.9",
29
29
  "expo-image-manipulator": "^57.0.9",
30
30
  "rxjs": "^7.8.2",
31
- "@credebl/ssi-mobile-core": "2.2.1"
31
+ "@credebl/ssi-mobile-core": "2.3.0-alpha-20261104134326"
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/react": "^19.2.18",