@sphereon/ssi-sdk.oid4vci-holder 0.33.1-feature.vcdm2.tsup.31 → 0.33.1-next.2

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.
Files changed (55) hide show
  1. package/dist/agent/OID4VCIHolder.d.ts +59 -0
  2. package/dist/agent/OID4VCIHolder.d.ts.map +1 -0
  3. package/dist/agent/OID4VCIHolder.js +884 -0
  4. package/dist/agent/OID4VCIHolder.js.map +1 -0
  5. package/dist/index.d.ts +11 -785
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +31 -3111
  8. package/dist/index.js.map +1 -1
  9. package/dist/link-handler/index.d.ts +31 -0
  10. package/dist/link-handler/index.d.ts.map +1 -0
  11. package/dist/link-handler/index.js +65 -0
  12. package/dist/link-handler/index.js.map +1 -0
  13. package/dist/listeners/headlessStateNavListener.d.ts +3 -0
  14. package/dist/listeners/headlessStateNavListener.d.ts.map +1 -0
  15. package/dist/listeners/headlessStateNavListener.js +45 -0
  16. package/dist/listeners/headlessStateNavListener.js.map +1 -0
  17. package/dist/localization/Localization.d.ts +9 -0
  18. package/dist/localization/Localization.d.ts.map +1 -0
  19. package/dist/localization/Localization.js +46 -0
  20. package/dist/localization/Localization.js.map +1 -0
  21. package/dist/localization/translations/en.json +19 -0
  22. package/dist/localization/translations/nl.json +18 -0
  23. package/dist/machines/firstPartyMachine.d.ts +15 -0
  24. package/dist/machines/firstPartyMachine.d.ts.map +1 -0
  25. package/dist/machines/firstPartyMachine.js +222 -0
  26. package/dist/machines/firstPartyMachine.js.map +1 -0
  27. package/dist/machines/oid4vciMachine.d.ts +7 -0
  28. package/dist/machines/oid4vciMachine.d.ts.map +1 -0
  29. package/dist/machines/oid4vciMachine.js +727 -0
  30. package/dist/machines/oid4vciMachine.js.map +1 -0
  31. package/dist/mappers/OIDC4VCIBrandingMapper.d.ts +16 -0
  32. package/dist/mappers/OIDC4VCIBrandingMapper.d.ts.map +1 -0
  33. package/dist/mappers/OIDC4VCIBrandingMapper.js +201 -0
  34. package/dist/mappers/OIDC4VCIBrandingMapper.js.map +1 -0
  35. package/dist/services/FirstPartyMachineServices.d.ts +9 -0
  36. package/dist/services/FirstPartyMachineServices.d.ts.map +1 -0
  37. package/dist/services/FirstPartyMachineServices.js +53 -0
  38. package/dist/services/FirstPartyMachineServices.js.map +1 -0
  39. package/dist/services/OID4VCIHolderService.d.ts +28 -0
  40. package/dist/services/OID4VCIHolderService.d.ts.map +1 -0
  41. package/dist/services/OID4VCIHolderService.js +524 -0
  42. package/dist/services/OID4VCIHolderService.js.map +1 -0
  43. package/dist/types/FirstPartyMachine.d.ts +112 -0
  44. package/dist/types/FirstPartyMachine.d.ts.map +1 -0
  45. package/dist/types/FirstPartyMachine.js +30 -0
  46. package/dist/types/FirstPartyMachine.js.map +1 -0
  47. package/dist/types/IOID4VCIHolder.d.ts +558 -0
  48. package/dist/types/IOID4VCIHolder.d.ts.map +1 -0
  49. package/dist/types/IOID4VCIHolder.js +114 -0
  50. package/dist/types/IOID4VCIHolder.js.map +1 -0
  51. package/package.json +34 -44
  52. package/src/agent/OID4VCIHolder.ts +4 -3
  53. package/dist/index.cjs +0 -3142
  54. package/dist/index.cjs.map +0 -1
  55. package/dist/index.d.cts +0 -786
package/dist/index.js CHANGED
@@ -1,3112 +1,32 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
- var __commonJS = (cb, mod) => function __require() {
5
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
6
- };
7
-
8
- // src/localization/translations/en.json
9
- var require_en = __commonJS({
10
- "src/localization/translations/en.json"(exports, module) {
11
- module.exports = {
12
- oid4vci_machine_verify_credentials_error_title: "Verify credentials",
13
- oid4vci_machine_store_credential_branding_error_title: "Store credential branding",
14
- oid4vci_machine_store_credential_error_title: "Store credential",
15
- oid4vci_machine_add_contact_identity_error_title: "Add contact identity",
16
- oid4vci_machine_retrieve_credentials_error_title: "Retrieve credentials",
17
- oid4vci_machine_retrieve_issuer_branding_error_title: "Retrieve issuer branding",
18
- oid4vci_machine_store_issuer_branding_error_title: "Store issuer branding",
19
- oid4vci_machine_retrieve_contact_error_title: "Retrieve contact",
20
- oid4vci_machine_credential_selection_error_title: "Credential selection",
21
- oid4vci_machine_initiation_error_title: "Initiate OID4VCI provider",
22
- oid4vci_machine_credential_verification_failed_message: "The credential verification resulted in an error.",
23
- oid4vci_machine_credential_verification_schema_failed_message: "The credential schema verification resulted in an error.",
24
- oid4vci_machine_retrieve_federation_trust_error_title: "Retrieve federation trust",
25
- oid4vci_machine_first_party_error_title: "First party flow",
26
- oid4vci_machine_send_authorization_challenge_request_error_title: "Sending authorization challenge request",
27
- oid4vci_machine_create_config_error_title: "Creating siopV2 config",
28
- oid4vci_machine_get_request_error_title: "Getting siopV2 request"
29
- };
30
- }
31
- });
32
-
33
- // src/localization/translations/nl.json
34
- var require_nl = __commonJS({
35
- "src/localization/translations/nl.json"(exports, module) {
36
- module.exports = {
37
- oid4vci_machine_verify_credentials_error_title: "Verifi\xEBren credential",
38
- oid4vci_machine_store_credential_branding_error_title: "Opslaan credential branding",
39
- oid4vci_machine_store_credential_error_title: "Opslaan credential",
40
- oid4vci_machine_add_contact_identity_error_title: "Toevoegen identiteit contact",
41
- oid4vci_machine_retrieve_credentials_error_title: "Ophalen credential",
42
- oid4vci_machine_retrieve_issuer_branding_error_title: "Ophalen issuer branding",
43
- oid4vci_machine_store_issuer_branding_error_title: "Opslaan issuer branding",
44
- oid4vci_machine_retrieve_contact_error_title: "Ophalen contact",
45
- oid4vci_machine_credential_selection_error_title: "Credential selectie",
46
- oid4vci_machine_initiation_error_title: "Initi\xEBren OID4VCI provider",
47
- oid4vci_machine_credential_verification_failed_message: "Verificatie van de credential leidde tot een fout.",
48
- oid4vci_machine_retrieve_federation_trust_error_title: "Ophalen federatievertrouwen",
49
- oid4vci_machine_first_party_error_title: "Eerste partijstroom",
50
- oid4vci_machine_send_authorization_challenge_request_error_title: "Versturen autorisatie-uitdaging aanvraag",
51
- oid4vci_machine_create_config_error_title: "SiopV2-configuratie aanmaken",
52
- oid4vci_machine_get_request_error_title: "SiopV2-verzoek ophalen"
53
- };
54
- }
55
- });
56
-
57
- // src/agent/OID4VCIHolder.ts
58
- import { CredentialOfferClient, MetadataClient, OpenID4VCIClient as OpenID4VCIClient2 } from "@sphereon/oid4vci-client";
59
- import { DefaultURISchemes, getTypesFromAuthorizationDetails, getTypesFromCredentialOffer, getTypesFromObject as getTypesFromObject2 } from "@sphereon/oid4vci-common";
60
- import { SupportedDidMethodEnum as SupportedDidMethodEnum2 } from "@sphereon/ssi-sdk-ext.did-utils";
61
- import { isManagedIdentifierDidOpts, isManagedIdentifierDidResult as isManagedIdentifierDidResult2, isManagedIdentifierJwkResult, isManagedIdentifierKidResult, isManagedIdentifierResult as isManagedIdentifierResult2, isManagedIdentifierX5cOpts, isManagedIdentifierX5cResult } from "@sphereon/ssi-sdk-ext.identifier-resolution";
62
- import { signatureAlgorithmFromKey } from "@sphereon/ssi-sdk-ext.key-utils";
63
- import { ConnectionType, CorrelationIdentifierType, CredentialCorrelationType, CredentialRole, ensureRawDocument, IdentityOrigin } from "@sphereon/ssi-sdk.data-store";
64
- import { CredentialMapper as CredentialMapper2, JoseSignatureAlgorithm as JoseSignatureAlgorithm2, Loggers, parseDid } from "@sphereon/ssi-types";
65
- import { asArray as asArray2, computeEntryHash } from "@veramo/utils";
66
- import { decodeJWT } from "did-jwt";
67
- import { v4 as uuidv42 } from "uuid";
68
-
69
- // src/machines/oid4vciMachine.ts
70
- import { AuthzFlowType, toAuthorizationResponsePayload } from "@sphereon/oid4vci-common";
71
- import { assign, createMachine, interpret } from "xstate";
72
-
73
- // src/localization/Localization.ts
74
- import i18n from "i18n-js";
75
- import memoize from "lodash.memoize";
76
-
77
- // src/types/IOID4VCIHolder.ts
78
- var OID4VCIHolderEvent = /* @__PURE__ */ function(OID4VCIHolderEvent2) {
79
- OID4VCIHolderEvent2["CONTACT_IDENTITY_CREATED"] = "contact_identity_created";
80
- OID4VCIHolderEvent2["CREDENTIAL_STORED"] = "credential_stored";
81
- OID4VCIHolderEvent2["IDENTIFIER_CREATED"] = "identifier_created";
82
- return OID4VCIHolderEvent2;
83
- }({});
84
- var SupportedLanguage = /* @__PURE__ */ function(SupportedLanguage2) {
85
- SupportedLanguage2["ENGLISH"] = "en";
86
- SupportedLanguage2["DUTCH"] = "nl";
87
- return SupportedLanguage2;
88
- }({});
89
- var OID4VCIMachineStates = /* @__PURE__ */ function(OID4VCIMachineStates2) {
90
- OID4VCIMachineStates2["start"] = "start";
91
- OID4VCIMachineStates2["createCredentialsToSelectFrom"] = "createCredentialsToSelectFrom";
92
- OID4VCIMachineStates2["getContact"] = "getContact";
93
- OID4VCIMachineStates2["transitionFromSetup"] = "transitionFromSetup";
94
- OID4VCIMachineStates2["getFederationTrust"] = "getFederationTrust";
95
- OID4VCIMachineStates2["reviewContact"] = "reviewContact";
96
- OID4VCIMachineStates2["addContact"] = "addContact";
97
- OID4VCIMachineStates2["getIssuerBranding"] = "getIssuerBranding";
98
- OID4VCIMachineStates2["storeIssuerBranding"] = "storeIssuerBranding";
99
- OID4VCIMachineStates2["addIssuerBrandingAfterIdentity"] = "addIssuerBrandingAfterIdentity";
100
- OID4VCIMachineStates2["transitionFromContactSetup"] = "transitionFromContactSetup";
101
- OID4VCIMachineStates2["startFirstPartApplicationFlow"] = "startFirstPartApplicationFlow";
102
- OID4VCIMachineStates2["selectCredentials"] = "selectCredentials";
103
- OID4VCIMachineStates2["transitionFromSelectingCredentials"] = "transitionFromSelectingCredentials";
104
- OID4VCIMachineStates2["verifyPin"] = "verifyPin";
105
- OID4VCIMachineStates2["initiateAuthorizationRequest"] = "initiateAuthorizationRequest";
106
- OID4VCIMachineStates2["waitForAuthorizationResponse"] = "waitForAuthorizationResponse";
107
- OID4VCIMachineStates2["getCredentials"] = "getCredentials";
108
- OID4VCIMachineStates2["transitionFromWalletInput"] = "transitionFromWalletInput";
109
- OID4VCIMachineStates2["addContactIdentity"] = "addContactIdentity";
110
- OID4VCIMachineStates2["reviewCredentials"] = "reviewCredentials";
111
- OID4VCIMachineStates2["verifyCredentials"] = "verifyCredentials";
112
- OID4VCIMachineStates2["storeCredentialBranding"] = "storeCredentialBranding";
113
- OID4VCIMachineStates2["storeCredentials"] = "storeCredentials";
114
- OID4VCIMachineStates2["handleError"] = "handleError";
115
- OID4VCIMachineStates2["aborted"] = "aborted";
116
- OID4VCIMachineStates2["declined"] = "declined";
117
- OID4VCIMachineStates2["error"] = "error";
118
- OID4VCIMachineStates2["done"] = "done";
119
- return OID4VCIMachineStates2;
120
- }({});
121
- var OID4VCIMachineAddContactStates = /* @__PURE__ */ function(OID4VCIMachineAddContactStates2) {
122
- OID4VCIMachineAddContactStates2["idle"] = "idle";
123
- OID4VCIMachineAddContactStates2["next"] = "next";
124
- return OID4VCIMachineAddContactStates2;
125
- }({});
126
- var OID4VCIMachineVerifyPinStates = /* @__PURE__ */ function(OID4VCIMachineVerifyPinStates2) {
127
- OID4VCIMachineVerifyPinStates2["idle"] = "idle";
128
- OID4VCIMachineVerifyPinStates2["next"] = "next";
129
- return OID4VCIMachineVerifyPinStates2;
130
- }({});
131
- var OID4VCIMachineEvents = /* @__PURE__ */ function(OID4VCIMachineEvents2) {
132
- OID4VCIMachineEvents2["NEXT"] = "NEXT";
133
- OID4VCIMachineEvents2["PREVIOUS"] = "PREVIOUS";
134
- OID4VCIMachineEvents2["DECLINE"] = "DECLINE";
135
- OID4VCIMachineEvents2["CREATE_CONTACT"] = "CREATE_CONTACT";
136
- OID4VCIMachineEvents2["SET_VERIFICATION_CODE"] = "SET_VERIFICATION_CODE";
137
- OID4VCIMachineEvents2["SET_CONTACT_ALIAS"] = "SET_CONTACT_ALIAS";
138
- OID4VCIMachineEvents2["SET_CONTACT_CONSENT"] = "SET_CONTACT_CONSENT";
139
- OID4VCIMachineEvents2["SET_SELECTED_CREDENTIALS"] = "SET_SELECTED_CREDENTIALS";
140
- OID4VCIMachineEvents2["SET_AUTHORIZATION_CODE_URL"] = "SET_AUTHORIZATION_CODE_URL";
141
- OID4VCIMachineEvents2["INVOKED_AUTHORIZATION_CODE_REQUEST"] = "INVOKED_AUTHORIZATION_CODE_REQUEST";
142
- OID4VCIMachineEvents2["PROVIDE_AUTHORIZATION_CODE_RESPONSE"] = "PROVIDE_AUTHORIZATION_CODE_RESPONSE";
143
- return OID4VCIMachineEvents2;
144
- }({});
145
- var OID4VCIMachineGuards = /* @__PURE__ */ function(OID4VCIMachineGuards2) {
146
- OID4VCIMachineGuards2["hasContactGuard"] = "oid4vciHasContactGuard";
147
- OID4VCIMachineGuards2["hasNoContactGuard"] = "oid4vciHasNoContactGuard";
148
- OID4VCIMachineGuards2["credentialsToSelectRequiredGuard"] = "oid4vciCredentialsToSelectRequiredGuard";
149
- OID4VCIMachineGuards2["requirePinGuard"] = "oid4vciRequirePinGuard";
150
- OID4VCIMachineGuards2["requireAuthorizationGuard"] = "oid4vciRequireAuthorizationGuard";
151
- OID4VCIMachineGuards2["noAuthorizationGuard"] = "oid4vciNoAuthorizationGuard";
152
- OID4VCIMachineGuards2["hasAuthorizationResponse"] = "oid4vciHasAuthorizationResponse";
153
- OID4VCIMachineGuards2["hasNoContactIdentityGuard"] = "oid4vciHasNoContactIdentityGuard";
154
- OID4VCIMachineGuards2["verificationCodeGuard"] = "oid4vciVerificationCodeGuard";
155
- OID4VCIMachineGuards2["createContactGuard"] = "oid4vciCreateContactGuard";
156
- OID4VCIMachineGuards2["hasSelectedCredentialsGuard"] = "oid4vciHasSelectedCredentialsGuard";
157
- OID4VCIMachineGuards2["isOIDFOriginGuard"] = "oid4vciIsOIDFOriginGuard";
158
- OID4VCIMachineGuards2["contactHasLowTrustGuard"] = "oid4vciContactHasLowTrustGuard";
159
- OID4VCIMachineGuards2["isFirstPartyApplication"] = "oid4vciIsFirstPartyApplication";
160
- return OID4VCIMachineGuards2;
161
- }({});
162
- var OID4VCIMachineServices = /* @__PURE__ */ function(OID4VCIMachineServices2) {
163
- OID4VCIMachineServices2["start"] = "start";
164
- OID4VCIMachineServices2["getContact"] = "getContact";
165
- OID4VCIMachineServices2["getFederationTrust"] = "getFederationTrust";
166
- OID4VCIMachineServices2["addContactIdentity"] = "addContactIdentity";
167
- OID4VCIMachineServices2["createCredentialsToSelectFrom"] = "createCredentialsToSelectFrom";
168
- OID4VCIMachineServices2["getIssuerBranding"] = "getIssuerBranding";
169
- OID4VCIMachineServices2["storeIssuerBranding"] = "storeIssuerBranding";
170
- OID4VCIMachineServices2["getCredentials"] = "getCredentials";
171
- OID4VCIMachineServices2["assertValidCredentials"] = "assertValidCredentials";
172
- OID4VCIMachineServices2["storeCredentialBranding"] = "storeCredentialBranding";
173
- OID4VCIMachineServices2["sendNotification"] = "sendNotification";
174
- OID4VCIMachineServices2["storeCredentials"] = "storeCredentials";
175
- OID4VCIMachineServices2["startFirstPartApplicationFlow"] = "startFirstPartApplicationFlow";
176
- return OID4VCIMachineServices2;
177
- }({});
178
- var RequestType = /* @__PURE__ */ function(RequestType2) {
179
- RequestType2["OPENID_INITIATE_ISSUANCE"] = "openid-initiate-issuance";
180
- RequestType2["OPENID_CREDENTIAL_OFFER"] = "openid-credential-offer";
181
- RequestType2["URL"] = "URL";
182
- return RequestType2;
183
- }({});
184
- var IdentifierAliasEnum = /* @__PURE__ */ function(IdentifierAliasEnum2) {
185
- IdentifierAliasEnum2["PRIMARY"] = "primary";
186
- return IdentifierAliasEnum2;
187
- }({});
188
-
189
- // src/localization/Localization.ts
190
- var Localization = class Localization2 {
191
- static {
192
- __name(this, "Localization");
193
- }
194
- static translationGetters = {
195
- [SupportedLanguage.ENGLISH]: () => require_en(),
196
- [SupportedLanguage.DUTCH]: () => require_nl()
197
- };
198
- static translate = memoize((key, config) => {
199
- if (Object.keys(i18n.translations).length === 0) {
200
- i18n.translations = {
201
- [SupportedLanguage.ENGLISH]: Localization2.translationGetters[SupportedLanguage.ENGLISH]()
202
- };
203
- i18n.locale = SupportedLanguage.ENGLISH;
204
- } else {
205
- i18n.translations = {
206
- [i18n.locale]: {
207
- ...i18n.translations[i18n.locale],
208
- ...Localization2.translationGetters[this.findSupportedLanguage(i18n.locale) || SupportedLanguage.ENGLISH]()
209
- }
210
- };
211
- }
212
- return i18n.t(key, config);
213
- }, (key, config) => config ? key + JSON.stringify(config) : key);
214
- static findSupportedLanguage = /* @__PURE__ */ __name((locale) => {
215
- for (const language of Object.values(SupportedLanguage)) {
216
- if (language === locale) {
217
- return language;
218
- }
219
- }
220
- return void 0;
221
- }, "findSupportedLanguage");
222
- static getLocale = /* @__PURE__ */ __name(() => {
223
- return i18n.locale || SupportedLanguage.ENGLISH;
224
- }, "getLocale");
225
- };
226
- var translate = Localization.translate;
227
-
228
- // src/types/FirstPartyMachine.ts
229
- var FirstPartyMachineStateTypes = /* @__PURE__ */ function(FirstPartyMachineStateTypes2) {
230
- FirstPartyMachineStateTypes2["sendAuthorizationChallengeRequest"] = "sendAuthorizationChallengeRequest";
231
- FirstPartyMachineStateTypes2["sendAuthorizationResponse"] = "sendAuthorizationResponse";
232
- FirstPartyMachineStateTypes2["selectCredentials"] = "selectCredentials";
233
- FirstPartyMachineStateTypes2["createConfig"] = "createConfig";
234
- FirstPartyMachineStateTypes2["getSiopRequest"] = "getSiopRequest";
235
- FirstPartyMachineStateTypes2["error"] = "error";
236
- FirstPartyMachineStateTypes2["done"] = "done";
237
- FirstPartyMachineStateTypes2["aborted"] = "aborted";
238
- FirstPartyMachineStateTypes2["declined"] = "declined";
239
- return FirstPartyMachineStateTypes2;
240
- }({});
241
- var FirstPartyMachineServices = /* @__PURE__ */ function(FirstPartyMachineServices2) {
242
- FirstPartyMachineServices2["sendAuthorizationChallengeRequest"] = "sendAuthorizationChallengeRequest";
243
- FirstPartyMachineServices2["sendAuthorizationResponse"] = "sendAuthorizationResponse";
244
- FirstPartyMachineServices2["createConfig"] = "createConfig";
245
- FirstPartyMachineServices2["getSiopRequest"] = "getSiopRequest";
246
- return FirstPartyMachineServices2;
247
- }({});
248
- var FirstPartyMachineEvents = /* @__PURE__ */ function(FirstPartyMachineEvents2) {
249
- FirstPartyMachineEvents2["NEXT"] = "NEXT";
250
- FirstPartyMachineEvents2["PREVIOUS"] = "PREVIOUS";
251
- FirstPartyMachineEvents2["DECLINE"] = "DECLINE";
252
- FirstPartyMachineEvents2["SET_SELECTED_CREDENTIALS"] = "SET_SELECTED_CREDENTIALS";
253
- return FirstPartyMachineEvents2;
254
- }({});
255
-
256
- // src/machines/oid4vciMachine.ts
257
- var oid4vciHasNoContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
258
- const { contact } = _ctx;
259
- return contact === void 0;
260
- }, "oid4vciHasNoContactGuard");
261
- var oid4vciHasContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
262
- const { contact } = _ctx;
263
- return contact !== void 0;
264
- }, "oid4vciHasContactGuard");
265
- var oid4vciContactHasLowTrustGuard = /* @__PURE__ */ __name((_ctx, _event) => {
266
- const { contact, trustedAnchors } = _ctx;
267
- return contact !== void 0 && trustedAnchors !== void 0 && trustedAnchors.length === 0;
268
- }, "oid4vciContactHasLowTrustGuard");
269
- var oid4vciCredentialsToSelectRequiredGuard = /* @__PURE__ */ __name((_ctx, _event) => {
270
- const { credentialToSelectFrom } = _ctx;
271
- return credentialToSelectFrom && credentialToSelectFrom.length > 1;
272
- }, "oid4vciCredentialsToSelectRequiredGuard");
273
- var oid4vciRequirePinGuard = /* @__PURE__ */ __name((_ctx, _event) => {
274
- const { requestData } = _ctx;
275
- return requestData?.credentialOffer?.userPinRequired === true;
276
- }, "oid4vciRequirePinGuard");
277
- var oid4vciHasNoContactIdentityGuard = /* @__PURE__ */ __name((_ctx, _event) => {
278
- const { contact, credentialsToAccept } = _ctx;
279
- let toAcceptId = credentialsToAccept[0].correlationId;
280
- if (toAcceptId.match(/^https?:\/\/.*/)) {
281
- toAcceptId = new URL(toAcceptId).hostname;
282
- }
283
- return !contact?.identities.some((identity) => identity.identifier.correlationId === toAcceptId);
284
- }, "oid4vciHasNoContactIdentityGuard");
285
- var oid4vciVerificationCodeGuard = /* @__PURE__ */ __name((_ctx, _event) => {
286
- const { verificationCode } = _ctx;
287
- return verificationCode !== void 0 && verificationCode.length > 0;
288
- }, "oid4vciVerificationCodeGuard");
289
- var oid4vciCreateContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
290
- const { contactAlias, hasContactConsent } = _ctx;
291
- return hasContactConsent && !!contactAlias && contactAlias.length > 0;
292
- }, "oid4vciCreateContactGuard");
293
- var oid4vciHasSelectedCredentialsGuard = /* @__PURE__ */ __name((_ctx, _event) => {
294
- const { selectedCredentials } = _ctx;
295
- return selectedCredentials !== void 0 && selectedCredentials.length > 0;
296
- }, "oid4vciHasSelectedCredentialsGuard");
297
- var oid4vciIsOIDFOriginGuard = /* @__PURE__ */ __name((_ctx, _event) => {
298
- const { trustAnchors } = _ctx;
299
- return trustAnchors.length > 0;
300
- }, "oid4vciIsOIDFOriginGuard");
301
- var oid4vciNoAuthorizationGuard = /* @__PURE__ */ __name((ctx, _event) => {
302
- return !oid4vciHasAuthorizationResponse(ctx, _event);
303
- }, "oid4vciNoAuthorizationGuard");
304
- var oid4vciRequireAuthorizationGuard = /* @__PURE__ */ __name((ctx, _event) => {
305
- const { openID4VCIClientState } = ctx;
306
- if (!openID4VCIClientState) {
307
- throw Error("Missing openID4VCI client state in context");
308
- }
309
- if (!openID4VCIClientState.authorizationURL) {
310
- return false;
311
- } else if (openID4VCIClientState.authorizationRequestOpts) {
312
- return !ctx.openID4VCIClientState?.authorizationCodeResponse;
313
- } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.AUTHORIZATION_CODE_FLOW)) {
314
- return !ctx.openID4VCIClientState?.authorizationCodeResponse;
315
- } else if (openID4VCIClientState.credentialOffer?.supportedFlows?.includes(AuthzFlowType.PRE_AUTHORIZED_CODE_FLOW)) {
316
- return false;
317
- } else if (openID4VCIClientState.endpointMetadata?.credentialIssuerMetadata?.authorization_endpoint) {
318
- return !ctx.openID4VCIClientState?.authorizationCodeResponse;
319
- }
320
- return false;
321
- }, "oid4vciRequireAuthorizationGuard");
322
- var oid4vciHasAuthorizationResponse = /* @__PURE__ */ __name((ctx, _event) => {
323
- return !!ctx.openID4VCIClientState?.authorizationCodeResponse;
324
- }, "oid4vciHasAuthorizationResponse");
325
- var oid4vciIsFirstPartyApplication = /* @__PURE__ */ __name((ctx, _event) => {
326
- return !!ctx.serverMetadata?.authorization_challenge_endpoint;
327
- }, "oid4vciIsFirstPartyApplication");
328
- var createOID4VCIMachine = /* @__PURE__ */ __name((opts) => {
329
- const initialContext = {
330
- // TODO WAL-671 we need to store the data from OpenIdProvider here in the context and make sure we can restart the machine with it and init the OpenIdProvider
331
- accessTokenOpts: opts?.accessTokenOpts,
332
- requestData: opts?.requestData,
333
- trustAnchors: opts?.trustAnchors ?? [],
334
- issuanceOpt: opts?.issuanceOpt,
335
- didMethodPreferences: opts?.didMethodPreferences,
336
- locale: opts?.locale,
337
- credentialsSupported: {},
338
- credentialToSelectFrom: [],
339
- selectedCredentials: [],
340
- credentialsToAccept: [],
341
- hasContactConsent: true,
342
- contactAlias: ""
343
- };
344
- return createMachine({
345
- id: opts?.machineName ?? "OID4VCIHolder",
346
- predictableActionArguments: true,
347
- initial: OID4VCIMachineStates.start,
348
- schema: {
349
- events: {},
350
- guards: {},
351
- services: {}
352
- },
353
- context: initialContext,
354
- states: {
355
- [OID4VCIMachineStates.start]: {
356
- id: OID4VCIMachineStates.start,
357
- invoke: {
358
- src: OID4VCIMachineServices.start,
359
- onDone: {
360
- target: OID4VCIMachineStates.createCredentialsToSelectFrom,
361
- actions: assign({
362
- authorizationCodeURL: /* @__PURE__ */ __name((_ctx, _event) => _event.data.authorizationCodeURL, "authorizationCodeURL"),
363
- credentialBranding: /* @__PURE__ */ __name((_ctx, _event) => _event.data.credentialBranding ?? {}, "credentialBranding"),
364
- credentialsSupported: /* @__PURE__ */ __name((_ctx, _event) => _event.data.credentialsSupported, "credentialsSupported"),
365
- serverMetadata: /* @__PURE__ */ __name((_ctx, _event) => _event.data.serverMetadata, "serverMetadata"),
366
- openID4VCIClientState: /* @__PURE__ */ __name((_ctx, _event) => _event.data.oid4vciClientState, "openID4VCIClientState")
367
- })
368
- },
369
- onError: {
370
- target: OID4VCIMachineStates.handleError,
371
- actions: assign({
372
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
373
- title: translate("oid4vci_machine_initiation_error_title"),
374
- message: _event.data.message,
375
- stack: _event.data.stack
376
- }), "error")
377
- })
378
- }
379
- }
380
- },
381
- [OID4VCIMachineStates.createCredentialsToSelectFrom]: {
382
- id: OID4VCIMachineStates.createCredentialsToSelectFrom,
383
- invoke: {
384
- src: OID4VCIMachineServices.createCredentialsToSelectFrom,
385
- onDone: {
386
- target: OID4VCIMachineStates.getContact,
387
- actions: assign({
388
- credentialToSelectFrom: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "credentialToSelectFrom")
389
- })
390
- },
391
- onError: {
392
- target: OID4VCIMachineStates.handleError,
393
- actions: assign({
394
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
395
- title: translate("oid4vci_machine_credential_selection_error_title"),
396
- message: _event.data.message,
397
- stack: _event.data.stack
398
- }), "error")
399
- })
400
- }
401
- }
402
- },
403
- [OID4VCIMachineStates.getContact]: {
404
- id: OID4VCIMachineStates.getContact,
405
- invoke: {
406
- src: OID4VCIMachineServices.getContact,
407
- onDone: {
408
- target: OID4VCIMachineStates.getIssuerBranding,
409
- actions: assign({
410
- contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
411
- })
412
- },
413
- onError: {
414
- target: OID4VCIMachineStates.handleError,
415
- actions: assign({
416
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
417
- title: translate("oid4vci_machine_retrieve_contact_error_title"),
418
- message: _event.data.message,
419
- stack: _event.data.stack
420
- }), "error")
421
- })
422
- }
423
- }
424
- },
425
- [OID4VCIMachineStates.getIssuerBranding]: {
426
- id: OID4VCIMachineStates.getIssuerBranding,
427
- invoke: {
428
- src: OID4VCIMachineServices.getIssuerBranding,
429
- onDone: [
430
- {
431
- target: OID4VCIMachineStates.getFederationTrust,
432
- cond: OID4VCIMachineGuards.isOIDFOriginGuard,
433
- actions: assign({
434
- issuerBranding: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "issuerBranding")
435
- })
436
- },
437
- {
438
- target: OID4VCIMachineStates.transitionFromSetup,
439
- actions: assign({
440
- issuerBranding: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "issuerBranding")
441
- })
442
- }
443
- ],
444
- onError: {
445
- target: OID4VCIMachineStates.handleError,
446
- actions: assign({
447
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
448
- title: translate("oid4vci_machine_retrieve_issuer_branding_error_title"),
449
- message: _event.data.message,
450
- stack: _event.data.stack
451
- }), "error")
452
- })
453
- }
454
- }
455
- },
456
- [OID4VCIMachineStates.getFederationTrust]: {
457
- id: OID4VCIMachineStates.getFederationTrust,
458
- invoke: {
459
- src: OID4VCIMachineServices.getFederationTrust,
460
- onDone: {
461
- target: OID4VCIMachineStates.transitionFromSetup,
462
- actions: assign({
463
- trustedAnchors: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "trustedAnchors")
464
- })
465
- },
466
- onError: {
467
- target: OID4VCIMachineStates.handleError,
468
- actions: assign({
469
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
470
- title: translate("oid4vci_machine_retrieve_federation_trust_error_title"),
471
- message: _event.data.message,
472
- stack: _event.data.stack
473
- }), "error")
474
- })
475
- }
476
- }
477
- },
478
- [OID4VCIMachineStates.transitionFromSetup]: {
479
- id: OID4VCIMachineStates.transitionFromSetup,
480
- always: [
481
- {
482
- target: OID4VCIMachineStates.addContact,
483
- cond: OID4VCIMachineGuards.hasNoContactGuard
484
- },
485
- {
486
- target: OID4VCIMachineStates.reviewContact,
487
- cond: OID4VCIMachineGuards.contactHasLowTrustGuard
488
- },
489
- {
490
- target: OID4VCIMachineStates.selectCredentials,
491
- cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard
492
- },
493
- {
494
- target: OID4VCIMachineStates.startFirstPartApplicationFlow,
495
- cond: OID4VCIMachineGuards.isFirstPartyApplication
496
- },
497
- {
498
- target: OID4VCIMachineStates.initiateAuthorizationRequest,
499
- cond: OID4VCIMachineGuards.requireAuthorizationGuard
500
- },
501
- {
502
- target: OID4VCIMachineStates.verifyPin,
503
- cond: OID4VCIMachineGuards.requirePinGuard
504
- },
505
- {
506
- target: OID4VCIMachineStates.getCredentials
507
- }
508
- ],
509
- on: {
510
- [OID4VCIMachineEvents.SET_AUTHORIZATION_CODE_URL]: {
511
- actions: assign({
512
- authorizationCodeURL: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationCodeURL")
513
- })
514
- }
515
- }
516
- },
517
- [OID4VCIMachineStates.addContact]: {
518
- id: OID4VCIMachineStates.addContact,
519
- initial: OID4VCIMachineAddContactStates.idle,
520
- on: {
521
- [OID4VCIMachineEvents.SET_CONTACT_CONSENT]: {
522
- actions: assign({
523
- hasContactConsent: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "hasContactConsent")
524
- })
525
- },
526
- [OID4VCIMachineEvents.SET_CONTACT_ALIAS]: {
527
- actions: assign({
528
- contactAlias: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contactAlias")
529
- })
530
- },
531
- [OID4VCIMachineEvents.CREATE_CONTACT]: {
532
- target: `.${OID4VCIMachineAddContactStates.next}`,
533
- actions: assign({
534
- contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
535
- }),
536
- cond: OID4VCIMachineGuards.createContactGuard
537
- },
538
- [OID4VCIMachineEvents.DECLINE]: {
539
- target: OID4VCIMachineStates.declined
540
- },
541
- [OID4VCIMachineEvents.PREVIOUS]: {
542
- target: OID4VCIMachineStates.aborted
543
- }
544
- },
545
- states: {
546
- [OID4VCIMachineAddContactStates.idle]: {},
547
- [OID4VCIMachineAddContactStates.next]: {
548
- always: {
549
- target: `#${OID4VCIMachineStates.storeIssuerBranding}`,
550
- cond: OID4VCIMachineGuards.hasContactGuard
551
- }
552
- }
553
- }
554
- },
555
- [OID4VCIMachineStates.reviewContact]: {
556
- id: OID4VCIMachineStates.reviewContact,
557
- on: {
558
- [OID4VCIMachineEvents.NEXT]: {
559
- target: OID4VCIMachineStates.transitionFromContactSetup
560
- },
561
- [OID4VCIMachineEvents.DECLINE]: {
562
- target: OID4VCIMachineStates.declined
563
- },
564
- [OID4VCIMachineEvents.PREVIOUS]: {
565
- target: OID4VCIMachineStates.aborted
566
- }
567
- }
568
- },
569
- [OID4VCIMachineStates.storeIssuerBranding]: {
570
- id: OID4VCIMachineStates.storeIssuerBranding,
571
- invoke: {
572
- src: OID4VCIMachineServices.storeIssuerBranding,
573
- onDone: {
574
- target: OID4VCIMachineStates.transitionFromContactSetup
575
- },
576
- onError: {
577
- target: OID4VCIMachineStates.handleError,
578
- actions: assign({
579
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
580
- title: translate("oid4vci_machine_store_issuer_branding_error_title"),
581
- message: _event.data.message,
582
- stack: _event.data.stack
583
- }), "error")
584
- })
585
- }
586
- }
587
- },
588
- [OID4VCIMachineStates.transitionFromContactSetup]: {
589
- id: OID4VCIMachineStates.transitionFromContactSetup,
590
- always: [
591
- {
592
- target: OID4VCIMachineStates.selectCredentials,
593
- cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard
594
- },
595
- {
596
- target: OID4VCIMachineStates.startFirstPartApplicationFlow,
597
- cond: OID4VCIMachineGuards.isFirstPartyApplication
598
- },
599
- {
600
- target: OID4VCIMachineStates.initiateAuthorizationRequest,
601
- cond: OID4VCIMachineGuards.requireAuthorizationGuard
602
- },
603
- {
604
- target: OID4VCIMachineStates.verifyPin,
605
- cond: OID4VCIMachineGuards.requirePinGuard
606
- },
607
- {
608
- target: OID4VCIMachineStates.getCredentials
609
- }
610
- ]
611
- },
612
- [OID4VCIMachineStates.startFirstPartApplicationFlow]: {
613
- id: OID4VCIMachineStates.startFirstPartApplicationFlow,
614
- invoke: {
615
- src: OID4VCIMachineServices.startFirstPartApplicationFlow,
616
- onDone: [
617
- {
618
- target: OID4VCIMachineStates.aborted,
619
- cond: /* @__PURE__ */ __name((_ctx, _event) => _event.data === FirstPartyMachineStateTypes.aborted, "cond")
620
- },
621
- {
622
- target: OID4VCIMachineStates.declined,
623
- cond: /* @__PURE__ */ __name((_ctx, _event) => _event.data === FirstPartyMachineStateTypes.declined, "cond")
624
- },
625
- {
626
- target: OID4VCIMachineStates.getCredentials,
627
- actions: assign({
628
- openID4VCIClientState: /* @__PURE__ */ __name((_ctx, _event) => {
629
- const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data);
630
- return {
631
- ..._ctx.openID4VCIClientState,
632
- authorizationCodeResponse
633
- };
634
- }, "openID4VCIClientState")
635
- })
636
- }
637
- ],
638
- onError: {
639
- target: OID4VCIMachineStates.handleError,
640
- actions: assign({
641
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
642
- title: _event.data.title ?? translate("oid4vci_machine_first_party_error_title"),
643
- message: _event.data.message,
644
- stack: _event.data.stack
645
- }), "error")
646
- })
647
- }
648
- }
649
- },
650
- [OID4VCIMachineStates.selectCredentials]: {
651
- id: OID4VCIMachineStates.selectCredentials,
652
- on: {
653
- [OID4VCIMachineEvents.SET_SELECTED_CREDENTIALS]: {
654
- actions: assign({
655
- selectedCredentials: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectedCredentials")
656
- })
657
- },
658
- [OID4VCIMachineEvents.NEXT]: {
659
- target: OID4VCIMachineStates.transitionFromSelectingCredentials,
660
- cond: OID4VCIMachineGuards.hasSelectedCredentialsGuard
661
- },
662
- [OID4VCIMachineEvents.PREVIOUS]: {
663
- target: OID4VCIMachineStates.aborted
664
- }
665
- }
666
- },
667
- [OID4VCIMachineStates.transitionFromSelectingCredentials]: {
668
- id: OID4VCIMachineStates.transitionFromSelectingCredentials,
669
- always: [
670
- {
671
- target: OID4VCIMachineStates.startFirstPartApplicationFlow,
672
- cond: OID4VCIMachineGuards.isFirstPartyApplication
673
- },
674
- {
675
- target: OID4VCIMachineStates.verifyPin,
676
- cond: OID4VCIMachineGuards.requirePinGuard
677
- },
678
- {
679
- target: OID4VCIMachineStates.initiateAuthorizationRequest,
680
- cond: OID4VCIMachineGuards.requireAuthorizationGuard
681
- },
682
- {
683
- target: OID4VCIMachineStates.getCredentials
684
- }
685
- ]
686
- },
687
- [OID4VCIMachineStates.initiateAuthorizationRequest]: {
688
- id: OID4VCIMachineStates.initiateAuthorizationRequest,
689
- on: {
690
- [OID4VCIMachineEvents.PREVIOUS]: {
691
- target: OID4VCIMachineStates.selectCredentials
692
- },
693
- [OID4VCIMachineEvents.INVOKED_AUTHORIZATION_CODE_REQUEST]: {
694
- target: OID4VCIMachineStates.waitForAuthorizationResponse
695
- }
696
- }
697
- },
698
- [OID4VCIMachineStates.waitForAuthorizationResponse]: {
699
- id: OID4VCIMachineStates.waitForAuthorizationResponse,
700
- on: {
701
- [OID4VCIMachineEvents.PREVIOUS]: {
702
- target: OID4VCIMachineStates.initiateAuthorizationRequest
703
- },
704
- [OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE]: {
705
- actions: assign({
706
- openID4VCIClientState: /* @__PURE__ */ __name((_ctx, _event) => {
707
- const authorizationCodeResponse = toAuthorizationResponsePayload(_event.data);
708
- return {
709
- ..._ctx.openID4VCIClientState,
710
- authorizationCodeResponse
711
- };
712
- }, "openID4VCIClientState")
713
- })
714
- }
715
- },
716
- always: [
717
- {
718
- cond: OID4VCIMachineGuards.hasAuthorizationResponse,
719
- target: OID4VCIMachineStates.getCredentials
720
- }
721
- ]
722
- },
723
- [OID4VCIMachineStates.verifyPin]: {
724
- id: OID4VCIMachineStates.verifyPin,
725
- initial: OID4VCIMachineVerifyPinStates.idle,
726
- on: {
727
- [OID4VCIMachineEvents.SET_VERIFICATION_CODE]: {
728
- target: `.${OID4VCIMachineVerifyPinStates.next}`,
729
- actions: assign({
730
- verificationCode: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "verificationCode")
731
- })
732
- },
733
- [OID4VCIMachineEvents.PREVIOUS]: [
734
- {
735
- target: OID4VCIMachineStates.selectCredentials,
736
- cond: OID4VCIMachineGuards.credentialsToSelectRequiredGuard
737
- },
738
- {
739
- target: OID4VCIMachineStates.aborted
740
- }
741
- ]
742
- },
743
- states: {
744
- [OID4VCIMachineVerifyPinStates.idle]: {},
745
- [OID4VCIMachineVerifyPinStates.next]: {
746
- always: {
747
- target: `#${OID4VCIMachineStates.getCredentials}`,
748
- cond: OID4VCIMachineGuards.verificationCodeGuard
749
- }
750
- }
751
- }
752
- },
753
- [OID4VCIMachineStates.getCredentials]: {
754
- id: OID4VCIMachineStates.getCredentials,
755
- invoke: {
756
- src: OID4VCIMachineServices.getCredentials,
757
- onDone: {
758
- target: OID4VCIMachineStates.verifyCredentials,
759
- actions: assign({
760
- credentialsToAccept: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "credentialsToAccept")
761
- })
762
- },
763
- onError: {
764
- target: OID4VCIMachineStates.handleError,
765
- actions: assign({
766
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
767
- title: translate("oid4vci_machine_retrieve_credentials_error_title"),
768
- message: _event.data.message,
769
- stack: _event.data.stack
770
- }), "error")
771
- })
772
- }
773
- },
774
- exit: assign({
775
- verificationCode: void 0
776
- })
777
- },
778
- [OID4VCIMachineStates.verifyCredentials]: {
779
- id: OID4VCIMachineStates.verifyCredentials,
780
- invoke: {
781
- src: OID4VCIMachineServices.assertValidCredentials,
782
- onDone: {
783
- target: OID4VCIMachineStates.transitionFromWalletInput
784
- },
785
- onError: {
786
- target: OID4VCIMachineStates.handleError,
787
- actions: assign({
788
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
789
- title: translate("oid4vci_machine_verify_credentials_error_title"),
790
- message: _event.data.message,
791
- stack: _event.data.stack
792
- }), "error")
793
- })
794
- }
795
- }
796
- },
797
- [OID4VCIMachineStates.transitionFromWalletInput]: {
798
- id: OID4VCIMachineStates.transitionFromWalletInput,
799
- always: [
800
- {
801
- target: OID4VCIMachineStates.addContactIdentity,
802
- cond: OID4VCIMachineGuards.hasNoContactIdentityGuard
803
- },
804
- {
805
- target: OID4VCIMachineStates.reviewCredentials
806
- }
807
- ]
808
- },
809
- [OID4VCIMachineStates.addContactIdentity]: {
810
- id: OID4VCIMachineStates.addContactIdentity,
811
- invoke: {
812
- src: OID4VCIMachineServices.addContactIdentity,
813
- onDone: {
814
- target: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,
815
- actions: /* @__PURE__ */ __name((_ctx, _event) => {
816
- _ctx.contact?.identities.push(_event.data);
817
- }, "actions")
818
- },
819
- onError: {
820
- target: OID4VCIMachineStates.handleError,
821
- actions: assign({
822
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
823
- title: translate("oid4vci_machine_add_contact_identity_error_title"),
824
- message: _event.data.message,
825
- stack: _event.data.stack
826
- }), "error")
827
- })
828
- }
829
- }
830
- },
831
- [OID4VCIMachineStates.addIssuerBrandingAfterIdentity]: {
832
- id: OID4VCIMachineStates.addIssuerBrandingAfterIdentity,
833
- invoke: {
834
- src: OID4VCIMachineServices.storeIssuerBranding,
835
- onDone: {
836
- target: OID4VCIMachineStates.reviewCredentials
837
- },
838
- onError: {
839
- target: OID4VCIMachineStates.handleError,
840
- actions: assign({
841
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
842
- title: translate("oid4vci_machine_store_issuer_branding_error_title"),
843
- message: _event.data.message,
844
- stack: _event.data.stack
845
- }), "error")
846
- })
847
- }
848
- }
849
- },
850
- [OID4VCIMachineStates.reviewCredentials]: {
851
- id: OID4VCIMachineStates.reviewCredentials,
852
- on: {
853
- [OID4VCIMachineEvents.NEXT]: {
854
- target: OID4VCIMachineStates.storeCredentialBranding
855
- },
856
- [OID4VCIMachineEvents.DECLINE]: {
857
- target: OID4VCIMachineStates.declined
858
- },
859
- [OID4VCIMachineEvents.PREVIOUS]: {
860
- target: OID4VCIMachineStates.aborted
861
- }
862
- }
863
- },
864
- [OID4VCIMachineStates.storeCredentialBranding]: {
865
- id: OID4VCIMachineStates.storeCredentialBranding,
866
- invoke: {
867
- src: OID4VCIMachineServices.storeCredentialBranding,
868
- onDone: {
869
- target: OID4VCIMachineStates.storeCredentials
870
- },
871
- onError: {
872
- target: OID4VCIMachineStates.handleError,
873
- actions: assign({
874
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
875
- title: translate("oid4vci_machine_store_credential_branding_error_title"),
876
- message: _event.data.message,
877
- stack: _event.data.stack
878
- }), "error")
879
- })
880
- }
881
- }
882
- },
883
- [OID4VCIMachineStates.storeCredentials]: {
884
- id: OID4VCIMachineStates.storeCredentials,
885
- invoke: {
886
- src: OID4VCIMachineServices.storeCredentials,
887
- onDone: {
888
- target: OID4VCIMachineStates.done
889
- },
890
- onError: {
891
- target: OID4VCIMachineStates.handleError,
892
- actions: assign({
893
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
894
- title: translate("oid4vci_machine_store_credential_error_title"),
895
- message: _event.data.message,
896
- stack: _event.data.stack
897
- }), "error")
898
- })
899
- }
900
- }
901
- },
902
- [OID4VCIMachineStates.handleError]: {
903
- id: OID4VCIMachineStates.handleError,
904
- on: {
905
- [OID4VCIMachineEvents.NEXT]: {
906
- target: OID4VCIMachineStates.error
907
- },
908
- [OID4VCIMachineEvents.PREVIOUS]: {
909
- target: OID4VCIMachineStates.error
910
- }
911
- }
912
- },
913
- [OID4VCIMachineStates.aborted]: {
914
- id: OID4VCIMachineStates.aborted,
915
- type: "final"
916
- },
917
- [OID4VCIMachineStates.declined]: {
918
- id: OID4VCIMachineStates.declined,
919
- type: "final"
920
- },
921
- [OID4VCIMachineStates.error]: {
922
- id: OID4VCIMachineStates.error,
923
- type: "final"
924
- },
925
- [OID4VCIMachineStates.done]: {
926
- id: OID4VCIMachineStates.done,
927
- type: "final"
928
- }
929
- }
930
- });
931
- }, "createOID4VCIMachine");
932
- var OID4VCIMachine = class {
933
- static {
934
- __name(this, "OID4VCIMachine");
935
- }
936
- static async newInstance(opts, context) {
937
- const interpreter = interpret(createOID4VCIMachine(opts).withConfig({
938
- services: {
939
- ...opts?.services
940
- },
941
- guards: {
942
- oid4vciHasNoContactGuard,
943
- oid4vciCredentialsToSelectRequiredGuard,
944
- oid4vciRequirePinGuard,
945
- oid4vciHasNoContactIdentityGuard,
946
- oid4vciVerificationCodeGuard,
947
- oid4vciHasContactGuard,
948
- oid4vciCreateContactGuard,
949
- oid4vciHasSelectedCredentialsGuard,
950
- oid4vciRequireAuthorizationGuard,
951
- oid4vciNoAuthorizationGuard,
952
- oid4vciHasAuthorizationResponse,
953
- oid4vciIsOIDFOriginGuard,
954
- oid4vciContactHasLowTrustGuard,
955
- oid4vciIsFirstPartyApplication,
956
- ...opts?.guards
957
- }
958
- }));
959
- if (typeof opts?.subscription === "function") {
960
- interpreter.onTransition(opts.subscription);
961
- }
962
- if (opts?.requireCustomNavigationHook !== true) {
963
- if (typeof opts?.stateNavigationListener === "function") {
964
- interpreter.onTransition((snapshot) => {
965
- if (opts?.stateNavigationListener) {
966
- opts.stateNavigationListener(interpreter, snapshot);
967
- }
968
- });
969
- }
970
- }
971
- return {
972
- interpreter
973
- };
974
- }
975
- };
976
-
977
- // src/services/OID4VCIHolderService.ts
978
- import { LOG } from "@sphereon/oid4vci-client";
979
- import { getSupportedCredentials, getTypesFromCredentialSupported, getTypesFromObject, OpenId4VCIVersion } from "@sphereon/oid4vci-common";
980
- import { KeyUse } from "@sphereon/ssi-sdk-ext.did-resolver-jwk";
981
- import { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from "@sphereon/ssi-sdk-ext.did-utils";
982
- import { isIIdentifier, isManagedIdentifierDidResult, isManagedIdentifierResult, managedIdentifierToJwk } from "@sphereon/ssi-sdk-ext.identifier-resolution";
983
- import { keyTypeFromCryptographicSuite } from "@sphereon/ssi-sdk-ext.key-utils";
984
- import { CredentialMapper, JoseSignatureAlgorithm, mdocDecodedCredentialToUniformCredential, sdJwtDecodedCredentialToUniformCredential } from "@sphereon/ssi-types";
985
- import { asArray } from "@veramo/utils";
986
-
987
- // src/mappers/OIDC4VCIBrandingMapper.ts
988
- var oid4vciGetCredentialBrandingFrom = /* @__PURE__ */ __name(async (args) => {
989
- const { credentialDisplay, issuerCredentialSubject } = args;
990
- return oid4vciCombineDisplayLocalesFrom({
991
- ...issuerCredentialSubject && {
992
- issuerCredentialSubjectLocales: await oid4vciIssuerCredentialSubjectLocalesFrom({
993
- issuerCredentialSubject
994
- })
995
- },
996
- ...credentialDisplay && {
997
- credentialDisplayLocales: await oid4vciCredentialDisplayLocalesFrom({
998
- credentialDisplay
999
- })
1000
- }
1001
- });
1002
- }, "oid4vciGetCredentialBrandingFrom");
1003
- var oid4vciCredentialDisplayLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1004
- const { credentialDisplay } = args;
1005
- return credentialDisplay.reduce((localeDisplays, display) => {
1006
- const localeKey = display.locale || "";
1007
- localeDisplays.set(localeKey, display);
1008
- return localeDisplays;
1009
- }, /* @__PURE__ */ new Map());
1010
- }, "oid4vciCredentialDisplayLocalesFrom");
1011
- var oid4vciIssuerCredentialSubjectLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1012
- const { issuerCredentialSubject } = args;
1013
- const localeClaims = /* @__PURE__ */ new Map();
1014
- const processClaimObject = /* @__PURE__ */ __name((claim, parentKey = "") => {
1015
- Object.entries(claim).forEach(([key, value]) => {
1016
- if (key === "mandatory" || key === "value_type") {
1017
- return;
1018
- }
1019
- if (key === "display" && Array.isArray(value)) {
1020
- value.forEach(({ name, locale = "" }) => {
1021
- if (!name) {
1022
- return;
1023
- }
1024
- if (!localeClaims.has(locale)) {
1025
- localeClaims.set(locale, []);
1026
- }
1027
- localeClaims.get(locale).push({
1028
- key: parentKey,
1029
- name
1030
- });
1031
- });
1032
- } else if (typeof value === "object" && value !== null) {
1033
- processClaimObject(value, parentKey ? `${parentKey}.${key}` : key);
1034
- }
1035
- });
1036
- }, "processClaimObject");
1037
- processClaimObject(issuerCredentialSubject);
1038
- return localeClaims;
1039
- }, "oid4vciIssuerCredentialSubjectLocalesFrom");
1040
- var oid4vciCredentialLocaleBrandingFrom = /* @__PURE__ */ __name(async (args) => {
1041
- const { credentialDisplay } = args;
1042
- return {
1043
- ...credentialDisplay.name && {
1044
- alias: credentialDisplay.name
1045
- },
1046
- ...credentialDisplay.locale && {
1047
- locale: credentialDisplay.locale
1048
- },
1049
- ...credentialDisplay.logo && {
1050
- logo: {
1051
- ...(credentialDisplay.logo.url || credentialDisplay.logo.uri) && {
1052
- uri: credentialDisplay.logo?.url ?? credentialDisplay.logo.uri
1053
- },
1054
- ...credentialDisplay.logo.alt_text && {
1055
- alt: credentialDisplay.logo?.alt_text
1056
- }
1057
- }
1058
- },
1059
- ...credentialDisplay.description && {
1060
- description: credentialDisplay.description
1061
- },
1062
- ...credentialDisplay.text_color && {
1063
- text: {
1064
- color: credentialDisplay.text_color
1065
- }
1066
- },
1067
- ...(credentialDisplay.background_image || credentialDisplay.background_color) && {
1068
- background: {
1069
- ...credentialDisplay.background_image && {
1070
- image: {
1071
- ...(credentialDisplay.background_image.url || credentialDisplay.background_image.uri) && {
1072
- uri: credentialDisplay.background_image?.url ?? credentialDisplay.background_image.uri
1073
- },
1074
- ...credentialDisplay.background_image.alt_text && {
1075
- alt: credentialDisplay.background_image?.alt_text
1076
- }
1077
- }
1078
- },
1079
- ...credentialDisplay.background_color && {
1080
- color: credentialDisplay.background_color
1081
- }
1082
- }
1083
- }
1084
- };
1085
- }, "oid4vciCredentialLocaleBrandingFrom");
1086
- var oid4vciCombineDisplayLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1087
- const { credentialDisplayLocales = /* @__PURE__ */ new Map(), issuerCredentialSubjectLocales = /* @__PURE__ */ new Map() } = args;
1088
- const locales = Array.from(/* @__PURE__ */ new Set([
1089
- ...issuerCredentialSubjectLocales.keys(),
1090
- ...credentialDisplayLocales.keys()
1091
- ]));
1092
- return Promise.all(locales.map(async (locale) => {
1093
- const display = credentialDisplayLocales.get(locale);
1094
- const claims = issuerCredentialSubjectLocales.get(locale);
1095
- return {
1096
- ...display && await oid4vciCredentialLocaleBrandingFrom({
1097
- credentialDisplay: display
1098
- }),
1099
- ...locale.length > 0 && {
1100
- locale
1101
- },
1102
- claims
1103
- };
1104
- }));
1105
- }, "oid4vciCombineDisplayLocalesFrom");
1106
- var sdJwtGetCredentialBrandingFrom = /* @__PURE__ */ __name(async (args) => {
1107
- const { credentialDisplay, claimsMetadata } = args;
1108
- return sdJwtCombineDisplayLocalesFrom({
1109
- ...claimsMetadata && {
1110
- claimsMetadata: await sdJwtCredentialClaimLocalesFrom({
1111
- claimsMetadata
1112
- })
1113
- },
1114
- ...credentialDisplay && {
1115
- credentialDisplayLocales: await sdJwtCredentialDisplayLocalesFrom({
1116
- credentialDisplay
1117
- })
1118
- }
1119
- });
1120
- }, "sdJwtGetCredentialBrandingFrom");
1121
- var sdJwtCredentialDisplayLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1122
- const { credentialDisplay } = args;
1123
- return credentialDisplay.reduce((localeDisplays, display) => {
1124
- const localeKey = display.lang || "";
1125
- localeDisplays.set(localeKey, display);
1126
- return localeDisplays;
1127
- }, /* @__PURE__ */ new Map());
1128
- }, "sdJwtCredentialDisplayLocalesFrom");
1129
- var sdJwtCredentialClaimLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1130
- const { claimsMetadata } = args;
1131
- const localeClaims = /* @__PURE__ */ new Map();
1132
- claimsMetadata.forEach((claim) => {
1133
- claim.display?.forEach((display) => {
1134
- const { lang = "", label } = display;
1135
- const key = claim.path.map((value) => String(value)).join(".");
1136
- if (!localeClaims.has(lang)) {
1137
- localeClaims.set(lang, []);
1138
- }
1139
- localeClaims.get(lang).push({
1140
- key,
1141
- name: label
1142
- });
1143
- });
1144
- });
1145
- return localeClaims;
1146
- }, "sdJwtCredentialClaimLocalesFrom");
1147
- var sdJwtCredentialLocaleBrandingFrom = /* @__PURE__ */ __name(async (args) => {
1148
- const { credentialDisplay } = args;
1149
- return {
1150
- ...credentialDisplay.name && {
1151
- alias: credentialDisplay.name
1152
- },
1153
- ...credentialDisplay.lang && {
1154
- locale: credentialDisplay.lang
1155
- },
1156
- ...credentialDisplay.rendering?.simple?.logo && {
1157
- logo: {
1158
- ...credentialDisplay.rendering.simple.logo.uri && {
1159
- uri: credentialDisplay.rendering.simple.logo.uri
1160
- },
1161
- ...credentialDisplay.rendering.simple.logo.alt_text && {
1162
- alt: credentialDisplay.rendering.simple.logo.alt_text
1163
- }
1164
- }
1165
- },
1166
- ...credentialDisplay.description && {
1167
- description: credentialDisplay.description
1168
- },
1169
- ...credentialDisplay.rendering?.simple?.text_color && {
1170
- text: {
1171
- color: credentialDisplay.rendering.simple.text_color
1172
- }
1173
- },
1174
- ...credentialDisplay.rendering?.simple?.background_color && {
1175
- background: {
1176
- color: credentialDisplay.rendering.simple.background_color
1177
- }
1178
- }
1179
- };
1180
- }, "sdJwtCredentialLocaleBrandingFrom");
1181
- var sdJwtCombineDisplayLocalesFrom = /* @__PURE__ */ __name(async (args) => {
1182
- const { credentialDisplayLocales = /* @__PURE__ */ new Map(), claimsMetadata = /* @__PURE__ */ new Map() } = args;
1183
- const locales = Array.from(/* @__PURE__ */ new Set([
1184
- ...claimsMetadata.keys(),
1185
- ...credentialDisplayLocales.keys()
1186
- ]));
1187
- return Promise.all(locales.map(async (locale) => {
1188
- const display = credentialDisplayLocales.get(locale);
1189
- const claims = claimsMetadata.get(locale);
1190
- return {
1191
- ...display && await sdJwtCredentialLocaleBrandingFrom({
1192
- credentialDisplay: display
1193
- }),
1194
- ...locale.length > 0 && {
1195
- locale
1196
- },
1197
- claims
1198
- };
1199
- }));
1200
- }, "sdJwtCombineDisplayLocalesFrom");
1201
- var issuerLocaleBrandingFrom = /* @__PURE__ */ __name(async (args) => {
1202
- const { issuerDisplay, dynamicRegistrationClientMetadata } = args;
1203
- return {
1204
- ...dynamicRegistrationClientMetadata?.client_name && {
1205
- alias: dynamicRegistrationClientMetadata.client_name
1206
- },
1207
- ...issuerDisplay.name && {
1208
- alias: issuerDisplay.name
1209
- },
1210
- ...issuerDisplay.locale && {
1211
- locale: issuerDisplay.locale
1212
- },
1213
- ...(issuerDisplay.logo || dynamicRegistrationClientMetadata?.logo_uri) && {
1214
- logo: {
1215
- ...dynamicRegistrationClientMetadata?.logo_uri && {
1216
- uri: dynamicRegistrationClientMetadata?.logo_uri
1217
- },
1218
- ...(issuerDisplay.logo?.url || issuerDisplay.logo?.uri) && {
1219
- uri: issuerDisplay.logo?.url ?? issuerDisplay.logo?.uri
1220
- },
1221
- ...issuerDisplay.logo?.alt_text && {
1222
- alt: issuerDisplay.logo?.alt_text
1223
- }
1224
- }
1225
- },
1226
- ...issuerDisplay.description && {
1227
- description: issuerDisplay.description
1228
- },
1229
- ...issuerDisplay.text_color && {
1230
- text: {
1231
- color: issuerDisplay.text_color
1232
- }
1233
- },
1234
- ...dynamicRegistrationClientMetadata?.client_uri && {
1235
- clientUri: dynamicRegistrationClientMetadata.client_uri
1236
- },
1237
- ...dynamicRegistrationClientMetadata?.tos_uri && {
1238
- tosUri: dynamicRegistrationClientMetadata.tos_uri
1239
- },
1240
- ...dynamicRegistrationClientMetadata?.policy_uri && {
1241
- policyUri: dynamicRegistrationClientMetadata.policy_uri
1242
- },
1243
- ...dynamicRegistrationClientMetadata?.contacts && {
1244
- contacts: dynamicRegistrationClientMetadata.contacts
1245
- }
1246
- };
1247
- }, "issuerLocaleBrandingFrom");
1248
-
1249
- // src/machines/firstPartyMachine.ts
1250
- import { assign as assign2, createMachine as createMachine2, interpret as interpret2 } from "xstate";
1251
- import { AuthorizationChallengeError } from "@sphereon/oid4vci-common";
1252
-
1253
- // src/services/FirstPartyMachineServices.ts
1254
- import { OpenID4VCIClient } from "@sphereon/oid4vci-client";
1255
- import { v4 as uuidv4 } from "uuid";
1256
- var sendAuthorizationChallengeRequest = /* @__PURE__ */ __name(async (args) => {
1257
- const { openID4VCIClientState, authSession, presentationDuringIssuanceSession } = args;
1258
- const oid4vciClient = await OpenID4VCIClient.fromState({
1259
- state: openID4VCIClientState
1260
- });
1261
- return oid4vciClient.acquireAuthorizationChallengeCode({
1262
- clientId: oid4vciClient.clientId ?? uuidv4(),
1263
- ...authSession && {
1264
- authSession
1265
- },
1266
- ...!authSession && openID4VCIClientState.credentialOffer?.preAuthorizedCode && {
1267
- issuerState: openID4VCIClientState.credentialOffer?.preAuthorizedCode
1268
- },
1269
- ...!authSession && openID4VCIClientState.credentialOffer?.issuerState && {
1270
- issuerState: openID4VCIClientState.credentialOffer?.issuerState
1271
- },
1272
- ...presentationDuringIssuanceSession && {
1273
- presentationDuringIssuanceSession
1274
- }
1275
- });
1276
- }, "sendAuthorizationChallengeRequest");
1277
- var createConfig = /* @__PURE__ */ __name(async (args, context) => {
1278
- const { presentationUri } = args;
1279
- if (!presentationUri) {
1280
- return Promise.reject(Error("Missing presentation uri in context"));
1281
- }
1282
- return context.agent.siopCreateConfig({
1283
- url: presentationUri
1284
- });
1285
- }, "createConfig");
1286
- var getSiopRequest = /* @__PURE__ */ __name(async (args, context) => {
1287
- const { didAuthConfig, presentationUri } = args;
1288
- if (presentationUri === void 0) {
1289
- return Promise.reject(Error("Missing presentation uri in context"));
1290
- }
1291
- if (didAuthConfig === void 0) {
1292
- return Promise.reject(Error("Missing did auth config in context"));
1293
- }
1294
- return context.agent.siopGetSiopRequest({
1295
- didAuthConfig,
1296
- url: presentationUri
1297
- });
1298
- }, "getSiopRequest");
1299
- var sendAuthorizationResponse = /* @__PURE__ */ __name(async (args, context) => {
1300
- const { didAuthConfig, authorizationRequestData, selectedCredentials } = args;
1301
- const responseData = await context.agent.siopSendResponse({
1302
- authorizationRequestData,
1303
- selectedCredentials,
1304
- didAuthConfig,
1305
- isFirstParty: true
1306
- });
1307
- return responseData.body.presentation_during_issuance_session;
1308
- }, "sendAuthorizationResponse");
1309
-
1310
- // src/machines/firstPartyMachine.ts
1311
- var firstPartyMachineStates = {
1312
- [FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest]: {
1313
- id: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,
1314
- invoke: {
1315
- src: FirstPartyMachineServices.sendAuthorizationChallengeRequest,
1316
- onDone: {
1317
- target: FirstPartyMachineStateTypes.done,
1318
- actions: assign2({
1319
- authorizationCodeResponse: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationCodeResponse")
1320
- })
1321
- },
1322
- onError: [
1323
- {
1324
- target: FirstPartyMachineStateTypes.createConfig,
1325
- cond: /* @__PURE__ */ __name((_ctx, _event) => _event.data.error === AuthorizationChallengeError.insufficient_authorization, "cond"),
1326
- actions: assign2({
1327
- authSession: /* @__PURE__ */ __name((_ctx, _event) => _event.data.auth_session, "authSession"),
1328
- presentationUri: /* @__PURE__ */ __name((_ctx, _event) => _event.data.presentation, "presentationUri")
1329
- })
1330
- },
1331
- {
1332
- target: FirstPartyMachineStateTypes.error,
1333
- actions: assign2({
1334
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1335
- title: translate("oid4vci_machine_send_authorization_challenge_request_error_title"),
1336
- message: _event.data.message,
1337
- stack: _event.data.stack
1338
- }), "error")
1339
- })
1340
- }
1341
- ]
1342
- }
1343
- },
1344
- [FirstPartyMachineStateTypes.createConfig]: {
1345
- id: FirstPartyMachineStateTypes.createConfig,
1346
- invoke: {
1347
- src: FirstPartyMachineServices.createConfig,
1348
- onDone: {
1349
- target: FirstPartyMachineStateTypes.getSiopRequest,
1350
- actions: assign2({
1351
- didAuthConfig: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "didAuthConfig")
1352
- })
1353
- },
1354
- onError: {
1355
- target: FirstPartyMachineStateTypes.error,
1356
- actions: assign2({
1357
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1358
- title: translate("oid4vci_machine_create_config_error_title"),
1359
- message: _event.data.message,
1360
- stack: _event.data.stack
1361
- }), "error")
1362
- })
1363
- }
1364
- }
1365
- },
1366
- [FirstPartyMachineStateTypes.getSiopRequest]: {
1367
- id: FirstPartyMachineStateTypes.getSiopRequest,
1368
- invoke: {
1369
- src: FirstPartyMachineServices.getSiopRequest,
1370
- onDone: {
1371
- target: FirstPartyMachineStateTypes.selectCredentials,
1372
- actions: assign2({
1373
- authorizationRequestData: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationRequestData")
1374
- })
1375
- },
1376
- onError: {
1377
- target: FirstPartyMachineStateTypes.error,
1378
- actions: assign2({
1379
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1380
- title: translate("siopV2_machine_get_request_error_title"),
1381
- message: _event.data.message,
1382
- stack: _event.data.stack
1383
- }), "error")
1384
- })
1385
- }
1386
- }
1387
- },
1388
- [FirstPartyMachineStateTypes.selectCredentials]: {
1389
- id: FirstPartyMachineStateTypes.selectCredentials,
1390
- on: {
1391
- [FirstPartyMachineEvents.SET_SELECTED_CREDENTIALS]: {
1392
- actions: assign2({
1393
- selectedCredentials: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectedCredentials")
1394
- })
1395
- },
1396
- [FirstPartyMachineEvents.NEXT]: {
1397
- target: FirstPartyMachineStateTypes.sendAuthorizationResponse
1398
- },
1399
- [FirstPartyMachineEvents.DECLINE]: {
1400
- target: FirstPartyMachineStateTypes.declined
1401
- },
1402
- [FirstPartyMachineEvents.PREVIOUS]: {
1403
- target: FirstPartyMachineStateTypes.aborted
1404
- }
1405
- }
1406
- },
1407
- [FirstPartyMachineStateTypes.sendAuthorizationResponse]: {
1408
- id: FirstPartyMachineStateTypes.sendAuthorizationResponse,
1409
- invoke: {
1410
- src: FirstPartyMachineServices.sendAuthorizationResponse,
1411
- onDone: {
1412
- target: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,
1413
- actions: assign2({
1414
- presentationDuringIssuanceSession: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "presentationDuringIssuanceSession")
1415
- })
1416
- },
1417
- onError: {
1418
- target: FirstPartyMachineStateTypes.error,
1419
- actions: assign2({
1420
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1421
- title: translate("oid4vci_machine_get_request_error_title"),
1422
- message: _event.data.message,
1423
- stack: _event.data.stack
1424
- }), "error")
1425
- })
1426
- }
1427
- }
1428
- },
1429
- [FirstPartyMachineStateTypes.aborted]: {
1430
- id: FirstPartyMachineStateTypes.aborted,
1431
- type: "final"
1432
- },
1433
- [FirstPartyMachineStateTypes.declined]: {
1434
- id: FirstPartyMachineStateTypes.declined,
1435
- type: "final"
1436
- },
1437
- [FirstPartyMachineStateTypes.error]: {
1438
- id: FirstPartyMachineStateTypes.error,
1439
- type: "final"
1440
- },
1441
- [FirstPartyMachineStateTypes.done]: {
1442
- id: FirstPartyMachineStateTypes.done,
1443
- type: "final"
1444
- }
1445
- };
1446
- var createFirstPartyActivationMachine = /* @__PURE__ */ __name((opts) => {
1447
- const initialContext = {
1448
- openID4VCIClientState: opts.openID4VCIClientState,
1449
- contact: opts.contact,
1450
- selectedCredentials: []
1451
- };
1452
- return createMachine2({
1453
- id: opts?.machineId ?? "FirstParty",
1454
- predictableActionArguments: true,
1455
- initial: FirstPartyMachineStateTypes.sendAuthorizationChallengeRequest,
1456
- context: initialContext,
1457
- states: firstPartyMachineStates,
1458
- schema: {
1459
- events: {},
1460
- services: {}
1461
- }
1462
- });
1463
- }, "createFirstPartyActivationMachine");
1464
- var FirstPartyMachine = class _FirstPartyMachine {
1465
- static {
1466
- __name(this, "FirstPartyMachine");
1467
- }
1468
- static _instance;
1469
- static hasInstance() {
1470
- return _FirstPartyMachine._instance !== void 0;
1471
- }
1472
- static get instance() {
1473
- if (!_FirstPartyMachine._instance) {
1474
- throw Error("Please initialize ESIMActivation machine first");
1475
- }
1476
- return _FirstPartyMachine._instance;
1477
- }
1478
- static clearInstance(opts) {
1479
- const { stop } = opts;
1480
- if (_FirstPartyMachine.hasInstance()) {
1481
- if (stop) {
1482
- _FirstPartyMachine.stopInstance();
1483
- }
1484
- }
1485
- _FirstPartyMachine._instance = void 0;
1486
- }
1487
- static stopInstance() {
1488
- if (!_FirstPartyMachine.hasInstance()) {
1489
- return;
1490
- }
1491
- _FirstPartyMachine.instance.stop();
1492
- _FirstPartyMachine._instance = void 0;
1493
- }
1494
- static newInstance(opts) {
1495
- const { agentContext } = opts;
1496
- const services = {
1497
- [FirstPartyMachineServices.sendAuthorizationChallengeRequest]: sendAuthorizationChallengeRequest,
1498
- [FirstPartyMachineServices.createConfig]: (args) => createConfig(args, agentContext),
1499
- [FirstPartyMachineServices.getSiopRequest]: (args) => getSiopRequest(args, agentContext),
1500
- [FirstPartyMachineServices.sendAuthorizationResponse]: (args) => sendAuthorizationResponse(args, agentContext)
1501
- };
1502
- const newInst = interpret2(createFirstPartyActivationMachine(opts).withConfig({
1503
- services: {
1504
- ...services,
1505
- ...opts?.services
1506
- },
1507
- guards: {
1508
- ...opts?.guards
1509
- }
1510
- }));
1511
- if (typeof opts?.subscription === "function") {
1512
- newInst.onTransition(opts.subscription);
1513
- }
1514
- if (opts?.requireCustomNavigationHook !== true) {
1515
- newInst.onTransition((snapshot) => {
1516
- if (opts?.stateNavigationListener) {
1517
- void opts.stateNavigationListener(newInst, snapshot);
1518
- }
1519
- });
1520
- }
1521
- return newInst;
1522
- }
1523
- static getInstance(opts) {
1524
- if (!_FirstPartyMachine._instance) {
1525
- if (opts?.requireExisting === true) {
1526
- throw Error(`Existing FirstPartyMachine instance requested, but none was created at this point!`);
1527
- }
1528
- _FirstPartyMachine._instance = _FirstPartyMachine.newInstance(opts);
1529
- }
1530
- return _FirstPartyMachine._instance;
1531
- }
1532
- };
1533
-
1534
- // src/services/OID4VCIHolderService.ts
1535
- import { defaultHasher } from "@sphereon/ssi-sdk.core";
1536
- var getCredentialBranding = /* @__PURE__ */ __name(async (args) => {
1537
- const { credentialsSupported, context } = args;
1538
- const credentialBranding = {};
1539
- await Promise.all(Object.entries(credentialsSupported).map(async ([configId, credentialsConfigSupported]) => {
1540
- let sdJwtTypeMetadata;
1541
- if (credentialsConfigSupported.format === "vc+sd-jwt") {
1542
- const vct = credentialsConfigSupported.vct;
1543
- if (vct.startsWith("http")) {
1544
- try {
1545
- sdJwtTypeMetadata = await context.agent.fetchSdJwtTypeMetadataFromVctUrl({
1546
- vct
1547
- });
1548
- } catch {
1549
- }
1550
- }
1551
- }
1552
- let mappedLocaleBranding = [];
1553
- if (sdJwtTypeMetadata) {
1554
- mappedLocaleBranding = await sdJwtGetCredentialBrandingFrom({
1555
- credentialDisplay: sdJwtTypeMetadata.display,
1556
- claimsMetadata: sdJwtTypeMetadata.claims
1557
- });
1558
- } else {
1559
- mappedLocaleBranding = await oid4vciGetCredentialBrandingFrom({
1560
- credentialDisplay: credentialsConfigSupported.display,
1561
- issuerCredentialSubject: (
1562
- // @ts-ignore // FIXME SPRIND-123 add proper support for type recognition as claim display can be located elsewhere for v13
1563
- credentialsSupported.claims !== void 0 ? credentialsConfigSupported.claims : credentialsConfigSupported.credentialSubject
1564
- )
1565
- });
1566
- }
1567
- const localeBranding = await Promise.all(mappedLocaleBranding.map(async (localeBranding2) => await context.agent.ibCredentialLocaleBrandingFrom({
1568
- localeBranding: localeBranding2
1569
- })));
1570
- const defaultCredentialType = "VerifiableCredential";
1571
- const configSupportedTypes = getTypesFromCredentialSupported(credentialsConfigSupported);
1572
- const credentialTypes = configSupportedTypes.length === 0 ? asArray(defaultCredentialType) : configSupportedTypes;
1573
- const filteredCredentialTypes = credentialTypes.filter((type) => type !== defaultCredentialType);
1574
- credentialBranding[filteredCredentialTypes[0]] = localeBranding;
1575
- }));
1576
- return credentialBranding;
1577
- }, "getCredentialBranding");
1578
- var getBasicIssuerLocaleBranding = /* @__PURE__ */ __name(async (args) => {
1579
- const { display, dynamicRegistrationClientMetadata, context } = args;
1580
- return await Promise.all(display.map(async (issuerDisplay) => {
1581
- const branding = await issuerLocaleBrandingFrom({
1582
- issuerDisplay,
1583
- dynamicRegistrationClientMetadata
1584
- });
1585
- return context.agent.ibIssuerLocaleBrandingFrom({
1586
- localeBranding: branding
1587
- });
1588
- }));
1589
- }, "getBasicIssuerLocaleBranding");
1590
- var getCredentialConfigsBasedOnFormatPref = /* @__PURE__ */ __name(async (args) => {
1591
- const { vcFormatPreferences, credentials } = args;
1592
- const prefConfigs = {};
1593
- Object.entries(credentials).forEach(([key, config]) => {
1594
- const result = !config.format || vcFormatPreferences.map((pref) => pref.toLowerCase()).includes(config.format.toLowerCase());
1595
- if (result) {
1596
- prefConfigs[key] = config;
1597
- }
1598
- });
1599
- return prefConfigs;
1600
- }, "getCredentialConfigsBasedOnFormatPref");
1601
- var selectCredentialLocaleBranding = /* @__PURE__ */ __name(async (args) => {
1602
- const { locale, localeBranding } = args;
1603
- return localeBranding?.find((branding) => locale ? branding.locale?.startsWith(locale) || branding.locale === void 0 : branding.locale === void 0);
1604
- }, "selectCredentialLocaleBranding");
1605
- var verifyCredentialToAccept = /* @__PURE__ */ __name(async (args) => {
1606
- const { mappedCredential, hasher, onVerifyEBSICredentialIssuer, schemaValidation, context } = args;
1607
- const credential = mappedCredential.credentialToAccept.credentialResponse.credential;
1608
- if (!credential) {
1609
- return Promise.reject(Error("No credential found in credential response"));
1610
- }
1611
- const wrappedVC = CredentialMapper.toWrappedVerifiableCredential(credential, {
1612
- hasher: hasher ?? defaultHasher
1613
- });
1614
- if (wrappedVC.decoded?.iss?.includes("did:ebsi:") || (typeof wrappedVC.decoded?.vc?.issuer === "string" ? wrappedVC.decoded?.vc?.issuer?.includes("did:ebsi:") : wrappedVC.decoded?.vc?.issuer?.existingInstanceId?.includes("did:ebsi:"))) {
1615
- await context.agent.cvVerifySchema({
1616
- credential,
1617
- hasher,
1618
- validationPolicy: schemaValidation
1619
- });
1620
- if (JSON.stringify(wrappedVC.decoded).includes("vc:ebsi:conformance")) {
1621
- return {
1622
- source: wrappedVC,
1623
- error: void 0,
1624
- result: true,
1625
- subResults: []
1626
- };
1627
- }
1628
- if (onVerifyEBSICredentialIssuer) {
1629
- try {
1630
- await onVerifyEBSICredentialIssuer({
1631
- wrappedVc: wrappedVC
1632
- });
1633
- } catch (e) {
1634
- return {
1635
- source: wrappedVC,
1636
- error: e.message,
1637
- result: true,
1638
- subResults: []
1639
- };
1640
- }
1641
- }
1642
- }
1643
- const verificationResult = await context.agent.cvVerifyCredential({
1644
- credential,
1645
- hasher,
1646
- // TODO WAL-675 we might want to allow these types of options as part of the context, now we have state machines. Allows us to pre-determine whether these policies apply and whether remote context should be fetched
1647
- fetchRemoteContexts: true,
1648
- policies: {
1649
- schemaValidation,
1650
- credentialStatus: false,
1651
- expirationDate: false,
1652
- issuanceDate: false
1653
- }
1654
- });
1655
- if (!verificationResult.result || verificationResult.error) {
1656
- return Promise.reject(Error(verificationResult.error ?? translate("oid4vci_machine_credential_verification_failed_message")));
1657
- }
1658
- return verificationResult;
1659
- }, "verifyCredentialToAccept");
1660
- var mapCredentialToAccept = /* @__PURE__ */ __name(async (args) => {
1661
- const { credentialToAccept, hasher } = args;
1662
- const credentialResponse = credentialToAccept.credentialResponse;
1663
- const verifiableCredential = credentialResponse.credential;
1664
- if (!verifiableCredential) {
1665
- return Promise.reject(Error("No credential found in credential response"));
1666
- }
1667
- const wrappedVerifiableCredential = CredentialMapper.toWrappedVerifiableCredential(verifiableCredential, {
1668
- hasher
1669
- });
1670
- let uniformVerifiableCredential;
1671
- if (CredentialMapper.isSdJwtDecodedCredential(wrappedVerifiableCredential.credential)) {
1672
- uniformVerifiableCredential = await sdJwtDecodedCredentialToUniformCredential(wrappedVerifiableCredential.credential);
1673
- } else if (CredentialMapper.isSdJwtEncoded(wrappedVerifiableCredential.credential)) {
1674
- if (!hasher) {
1675
- return Promise.reject("a hasher is required for encoded SD-JWT credentials");
1676
- }
1677
- const asyncHasher = /* @__PURE__ */ __name((data, algorithm) => Promise.resolve(hasher(data, algorithm)), "asyncHasher");
1678
- const decodedSdJwt = await CredentialMapper.decodeSdJwtVcAsync(wrappedVerifiableCredential.credential, asyncHasher);
1679
- uniformVerifiableCredential = sdJwtDecodedCredentialToUniformCredential(decodedSdJwt);
1680
- } else if (CredentialMapper.isMsoMdocDecodedCredential(wrappedVerifiableCredential.credential)) {
1681
- uniformVerifiableCredential = mdocDecodedCredentialToUniformCredential(wrappedVerifiableCredential.credential);
1682
- } else {
1683
- uniformVerifiableCredential = wrappedVerifiableCredential.credential;
1684
- }
1685
- const correlationId = typeof uniformVerifiableCredential.issuer === "string" ? uniformVerifiableCredential.issuer : CredentialMapper.isSdJwtDecodedCredential(uniformVerifiableCredential) ? uniformVerifiableCredential.decodedPayload.iss : uniformVerifiableCredential.issuer.id;
1686
- return {
1687
- correlationId,
1688
- credentialToAccept,
1689
- types: credentialToAccept.types,
1690
- rawVerifiableCredential: verifiableCredential,
1691
- uniformVerifiableCredential,
1692
- ...credentialResponse.credential_subject_issuance && {
1693
- credential_subject_issuance: credentialResponse.credential_subject_issuance
1694
- }
1695
- };
1696
- }, "mapCredentialToAccept");
1697
- var getIdentifierOpts = /* @__PURE__ */ __name(async (args) => {
1698
- const { issuanceOpt, context } = args;
1699
- const { identifier: identifierArg } = issuanceOpt;
1700
- if (identifierArg && isManagedIdentifierResult(identifierArg)) {
1701
- return identifierArg;
1702
- }
1703
- const { supportedPreferredDidMethod, supportedBindingMethods, keyType = "Secp256r1", kms = await context.agent.keyManagerGetDefaultKeyManagementSystem() } = issuanceOpt;
1704
- let identifier;
1705
- if (identifierArg) {
1706
- if (isIIdentifier(identifierArg.identifier)) {
1707
- identifier = await context.agent.identifierManagedGet(identifierArg);
1708
- } else if (!identifierArg.method && issuanceOpt.supportedBindingMethods.includes("jwk")) {
1709
- identifier = await managedIdentifierToJwk(identifierArg, context);
1710
- } else if (identifierArg.method && !supportedBindingMethods.includes(identifierArg.method)) {
1711
- throw Error(`Supplied identifier method ${identifierArg.method} not supported by the issuer: ${supportedBindingMethods.join(",")}`);
1712
- } else {
1713
- identifier = await context.agent.identifierManagedGet(identifierArg);
1714
- }
1715
- }
1716
- const agentContext = {
1717
- ...context,
1718
- agent: context.agent
1719
- };
1720
- if ((!identifierArg || isIIdentifier(identifierArg.identifier)) && supportedPreferredDidMethod && (!supportedBindingMethods || supportedBindingMethods.length === 0 || supportedBindingMethods.filter((method) => method.startsWith("did")))) {
1721
- const { result, created } = await getOrCreatePrimaryIdentifier(agentContext, {
1722
- method: supportedPreferredDidMethod,
1723
- createOpts: {
1724
- options: {
1725
- type: issuanceOpt.keyType,
1726
- use: KeyUse.Signature,
1727
- codecName: issuanceOpt.codecName,
1728
- kms: issuanceOpt.kms
1729
- }
1730
- }
1731
- });
1732
- identifier = await context.agent.identifierManagedGetByDid({
1733
- identifier: result,
1734
- keyType,
1735
- offlineWhenNoDIDRegistered: result.did.startsWith("did:ebsi:")
1736
- });
1737
- if (created) {
1738
- await agentContext.agent.emit(OID4VCIHolderEvent.IDENTIFIER_CREATED, {
1739
- identifier
1740
- });
1741
- }
1742
- } else if (supportedBindingMethods.includes("jwk")) {
1743
- const key = await context.agent.keyManagerCreate({
1744
- type: keyType,
1745
- kms,
1746
- meta: {
1747
- keyAlias: `key_${keyType}_${Date.now()}`
1748
- }
1749
- });
1750
- identifier = await managedIdentifierToJwk({
1751
- method: "key",
1752
- identifier: key,
1753
- kmsKeyRef: key.kid
1754
- }, context);
1755
- } else {
1756
- throw Error(`Holder currently does not support binding method: ${supportedBindingMethods.join(",")}`);
1757
- }
1758
- args.issuanceOpt.identifier = identifier;
1759
- return identifier;
1760
- }, "getIdentifierOpts");
1761
- var getCredentialConfigsSupportedMerged = /* @__PURE__ */ __name(async (args) => {
1762
- let result = {};
1763
- (await getCredentialConfigsSupported(args)).forEach((supported) => {
1764
- result = {
1765
- ...result,
1766
- ...supported
1767
- };
1768
- });
1769
- return result;
1770
- }, "getCredentialConfigsSupportedMerged");
1771
- var getCredentialConfigsSupported = /* @__PURE__ */ __name(async (args) => {
1772
- const { types, configurationIds } = args;
1773
- if (Array.isArray(types) && types.length > 0) {
1774
- return Promise.all(types.map((type) => getCredentialConfigsSupportedBySingleTypeOrId({
1775
- ...args,
1776
- types: type
1777
- })));
1778
- } else if (Array.isArray(configurationIds) && configurationIds.length > 0) {
1779
- return Promise.all(configurationIds.map((configurationId) => getCredentialConfigsSupportedBySingleTypeOrId({
1780
- ...args,
1781
- configurationId,
1782
- types: void 0
1783
- })));
1784
- }
1785
- const configs = await getCredentialConfigsSupportedBySingleTypeOrId({
1786
- ...args,
1787
- types: void 0,
1788
- configurationId: void 0
1789
- });
1790
- return configs && Object.keys(configs).length > 0 ? [
1791
- configs
1792
- ] : [];
1793
- }, "getCredentialConfigsSupported");
1794
- var getCredentialConfigsSupportedBySingleTypeOrId = /* @__PURE__ */ __name(async (args) => {
1795
- const { client, vcFormatPreferences, configurationId } = args;
1796
- let { format = void 0, types = void 0 } = args;
1797
- function createIdFromTypes(supported) {
1798
- const format2 = supported.format;
1799
- const type = getTypesFromObject(supported)?.join() ?? "";
1800
- const id = `${type}:${format2}`;
1801
- return id;
1802
- }
1803
- __name(createIdFromTypes, "createIdFromTypes");
1804
- if (configurationId) {
1805
- const allSupported2 = client.getCredentialsSupported(false);
1806
- return Object.fromEntries(Object.entries(allSupported2).filter(([id, supported]) => id === configurationId || supported.id === configurationId || createIdFromTypes(supported) === configurationId));
1807
- }
1808
- if (!types && !client.credentialOffer) {
1809
- return Promise.reject(Error("openID4VCIClient has no credentialOffer and no types where provided"));
1810
- }
1811
- if (!Array.isArray(format) && client.credentialOffer) {
1812
- if (client.version() > OpenId4VCIVersion.VER_1_0_09 && typeof client.credentialOffer.credential_offer === "object" && "credentials" in client.credentialOffer.credential_offer) {
1813
- format = client.credentialOffer.credential_offer.credentials.filter((cred) => typeof cred !== "string").map((cred) => cred.format);
1814
- if (format?.length === 0) {
1815
- format = void 0;
1816
- }
1817
- }
1818
- }
1819
- const offerSupported = getSupportedCredentials({
1820
- types: types ? [
1821
- types
1822
- ] : client.getCredentialOfferTypes(),
1823
- format,
1824
- version: client.version(),
1825
- issuerMetadata: client.endpointMetadata.credentialIssuerMetadata
1826
- });
1827
- let allSupported;
1828
- if (!Array.isArray(offerSupported)) {
1829
- allSupported = offerSupported;
1830
- } else {
1831
- allSupported = {};
1832
- offerSupported.forEach((supported) => {
1833
- if (supported.id) {
1834
- allSupported[supported.id] = supported;
1835
- return;
1836
- }
1837
- const id = createIdFromTypes(supported);
1838
- allSupported[id] = supported;
1839
- });
1840
- }
1841
- let credentialConfigsSupported = await getCredentialConfigsBasedOnFormatPref({
1842
- credentials: allSupported,
1843
- vcFormatPreferences
1844
- });
1845
- if (!credentialConfigsSupported || Object.keys(credentialConfigsSupported).length === 0) {
1846
- LOG.warning(`No matching supported credential found for ${client.getIssuer()}`);
1847
- }
1848
- if (client.credentialOffer === void 0) {
1849
- return credentialConfigsSupported;
1850
- }
1851
- const credentialOffer = client.credentialOffer.credential_offer;
1852
- let credentialsToOffer;
1853
- if ("credential_configuration_ids" in credentialOffer) {
1854
- credentialsToOffer = Object.fromEntries(Object.entries(credentialConfigsSupported).filter(([configId, config]) => credentialOffer.credential_configuration_ids.includes(configId)));
1855
- if (Object.keys(credentialsToOffer).length === 0) {
1856
- throw new Error(`No matching supported credential configs found for offer ${credentialOffer.credential_configuration_ids.join(", ")}`);
1857
- }
1858
- } else {
1859
- credentialsToOffer = credentialConfigsSupported;
1860
- }
1861
- if (Object.keys(credentialsToOffer).length === 0) {
1862
- throw new Error(`No matching supported credential configs found for offer`);
1863
- }
1864
- return credentialsToOffer;
1865
- }, "getCredentialConfigsSupportedBySingleTypeOrId");
1866
- var getIssuanceOpts = /* @__PURE__ */ __name(async (args) => {
1867
- const {
1868
- client,
1869
- credentialsSupported,
1870
- // serverMetadata,
1871
- context,
1872
- didMethodPreferences,
1873
- jwtCryptographicSuitePreferences,
1874
- jsonldCryptographicSuitePreferences,
1875
- forceIssuanceOpt
1876
- } = args;
1877
- if (credentialsSupported === void 0 || Object.keys(credentialsSupported).length === 0) {
1878
- return Promise.reject(Error("No credentials supported"));
1879
- }
1880
- const getIssuanceOpts2 = Object.values(credentialsSupported).map(async (credentialSupported) => {
1881
- const cryptographicSuite = await getIssuanceCryptoSuite({
1882
- credentialSupported,
1883
- client,
1884
- jwtCryptographicSuitePreferences,
1885
- jsonldCryptographicSuitePreferences
1886
- });
1887
- const { didMethod, methods } = await getIssuanceMethod({
1888
- credentialSupported,
1889
- client,
1890
- didMethodPreferences
1891
- });
1892
- if (methods.length == 0) {
1893
- console.log(`Could not determine supported cryptographic_binding_methods_supported, will use DIDs`);
1894
- methods.push("did");
1895
- }
1896
- const issuanceOpt = forceIssuanceOpt ? {
1897
- ...credentialSupported,
1898
- ...forceIssuanceOpt
1899
- } : {
1900
- ...credentialSupported,
1901
- supportedPreferredDidMethod: didMethod,
1902
- supportedBindingMethods: methods,
1903
- format: credentialSupported.format,
1904
- keyType: client.isEBSI() ? "Secp256r1" : keyTypeFromCryptographicSuite({
1905
- crv: cryptographicSuite
1906
- }),
1907
- ...client.isEBSI() && {
1908
- codecName: "EBSI"
1909
- }
1910
- };
1911
- const identifier = await getIdentifierOpts({
1912
- issuanceOpt,
1913
- context
1914
- });
1915
- if (!client.clientId && isManagedIdentifierDidResult(identifier)) {
1916
- client.clientId = identifier.issuer ?? identifier.did;
1917
- }
1918
- return {
1919
- ...issuanceOpt,
1920
- identifier
1921
- };
1922
- });
1923
- return await Promise.all(getIssuanceOpts2);
1924
- }, "getIssuanceOpts");
1925
- var getIssuanceMethod = /* @__PURE__ */ __name(async (opts) => {
1926
- const { client, credentialSupported, didMethodPreferences } = opts;
1927
- const { format, cryptographic_binding_methods_supported } = credentialSupported;
1928
- let methods = [];
1929
- if (cryptographic_binding_methods_supported && Array.isArray(cryptographic_binding_methods_supported)) {
1930
- methods = cryptographic_binding_methods_supported;
1931
- const didMethods = didMethodPreferences.find((method) => cryptographic_binding_methods_supported.includes(`did:${method.toLowerCase()}`));
1932
- if (didMethods) {
1933
- return {
1934
- methods,
1935
- didMethod: didMethods
1936
- };
1937
- } else if (cryptographic_binding_methods_supported.includes("did")) {
1938
- return {
1939
- methods,
1940
- didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0]
1941
- };
1942
- } else if (methods.length > 0) {
1943
- return {
1944
- methods
1945
- };
1946
- }
1947
- console.warn(`We should have been able to determine cryptographic_binding_methods_supported, will fall back to legacy behaviour. This is likely a bug`);
1948
- }
1949
- if (client.isEBSI()) {
1950
- return {
1951
- methods: [
1952
- "did"
1953
- ],
1954
- didMethod: SupportedDidMethodEnum.DID_KEY
1955
- };
1956
- }
1957
- methods = [
1958
- "did"
1959
- ];
1960
- if (!format || format.includes("jwt") && !format?.includes("jwt_vc_json_ld")) {
1961
- return {
1962
- methods,
1963
- didMethod: format ? didMethodPreferences[1] : didMethodPreferences[0]
1964
- };
1965
- } else {
1966
- return {
1967
- methods,
1968
- didMethod: didMethodPreferences[0]
1969
- };
1970
- }
1971
- }, "getIssuanceMethod");
1972
- var getIssuanceCryptoSuite = /* @__PURE__ */ __name(async (opts) => {
1973
- const { client, credentialSupported, jwtCryptographicSuitePreferences, jsonldCryptographicSuitePreferences } = opts;
1974
- let signing_algs_supported;
1975
- if ("proof_types_supported" in credentialSupported && credentialSupported.proof_types_supported) {
1976
- if ("jwt" in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.jwt) {
1977
- signing_algs_supported = credentialSupported.proof_types_supported.jwt.proof_signing_alg_values_supported;
1978
- } else if ("ldp_vp" in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.ldp_vp) {
1979
- signing_algs_supported = credentialSupported.proof_types_supported.ldp_vp.proof_signing_alg_values_supported;
1980
- } else if ("cwt" in credentialSupported.proof_types_supported && credentialSupported.proof_types_supported.cwt) {
1981
- signing_algs_supported = credentialSupported.proof_types_supported.cwt.proof_signing_alg_values_supported;
1982
- console.error("cwt proof type not supported. Likely that errors will occur after this point");
1983
- } else {
1984
- return Promise.reject(Error(`Unsupported proof_types_supported`));
1985
- }
1986
- } else {
1987
- signing_algs_supported = asArray(
1988
- // @ts-ignore // legacy
1989
- credentialSupported.credential_signing_alg_values_supported ?? credentialSupported.proof_signing_alg_values_supported ?? []
1990
- );
1991
- }
1992
- switch (credentialSupported.format) {
1993
- // @ts-ignore legacy value
1994
- case "jwt":
1995
- case "jwt_vc_json":
1996
- case "jwt_vc":
1997
- case "vc+sd-jwt":
1998
- case "mso_mdoc": {
1999
- const supportedPreferences = jwtCryptographicSuitePreferences.filter((suite) => signing_algs_supported.includes(suite));
2000
- if (supportedPreferences.length > 0) {
2001
- return supportedPreferences[0];
2002
- } else if (client.isEBSI()) {
2003
- return JoseSignatureAlgorithm.ES256;
2004
- }
2005
- const fallback = jwtCryptographicSuitePreferences[0];
2006
- console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`);
2007
- return fallback;
2008
- }
2009
- // @ts-ignore
2010
- case "ldp":
2011
- // @ts-ignore
2012
- case "jwt_vc_json_ld":
2013
- case "ldp_vc": {
2014
- const supportedPreferences = jsonldCryptographicSuitePreferences.filter((suite) => signing_algs_supported.includes(suite));
2015
- if (supportedPreferences.length > 0) {
2016
- return supportedPreferences[0];
2017
- }
2018
- const fallback = jsonldCryptographicSuitePreferences[0];
2019
- console.log(`Warn: We could not determine the crypto suites from the server metadata, and will fallback to a default: ${fallback}`);
2020
- return fallback;
2021
- }
2022
- default:
2023
- return Promise.reject(Error(`Credential format '${credentialSupported.format}' not supported`));
2024
- }
2025
- }, "getIssuanceCryptoSuite");
2026
- var startFirstPartApplicationMachine = /* @__PURE__ */ __name(async (args, context) => {
2027
- const { openID4VCIClientState, stateNavigationListener, contact } = args;
2028
- if (!openID4VCIClientState) {
2029
- return Promise.reject(Error("Missing openID4VCI client state in context"));
2030
- }
2031
- if (!contact) {
2032
- return Promise.reject(Error("Missing contact in context"));
2033
- }
2034
- const firstPartyMachineInstance = FirstPartyMachine.newInstance({
2035
- openID4VCIClientState,
2036
- contact,
2037
- agentContext: context,
2038
- stateNavigationListener
2039
- });
2040
- return new Promise((resolve, reject) => {
2041
- try {
2042
- firstPartyMachineInstance.onTransition((state) => {
2043
- if (state.matches(FirstPartyMachineStateTypes.done)) {
2044
- const authorizationCodeResponse = state.context.authorizationCodeResponse;
2045
- if (!authorizationCodeResponse) {
2046
- reject(Error("No authorizationCodeResponse acquired"));
2047
- }
2048
- resolve(authorizationCodeResponse);
2049
- } else if (state.matches(FirstPartyMachineStateTypes.aborted)) {
2050
- resolve(FirstPartyMachineStateTypes.aborted);
2051
- } else if (state.matches(FirstPartyMachineStateTypes.declined)) {
2052
- resolve(FirstPartyMachineStateTypes.declined);
2053
- } else if (state.matches(FirstPartyMachineStateTypes.error)) {
2054
- reject(state.context.error);
2055
- }
2056
- });
2057
- firstPartyMachineInstance.start();
2058
- } catch (error) {
2059
- reject(error);
2060
- }
2061
- });
2062
- }, "startFirstPartApplicationMachine");
2063
-
2064
- // src/agent/OID4VCIHolder.ts
2065
- import "cross-fetch/polyfill";
2066
- import { defaultHasher as defaultHasher2 } from "@sphereon/ssi-sdk.core";
2067
- var oid4vciHolderContextMethods = [
2068
- "cmGetContacts",
2069
- "cmGetContact",
2070
- "cmAddContact",
2071
- "cmAddIdentity",
2072
- "ibCredentialLocaleBrandingFrom",
2073
- "ibAddCredentialBranding",
2074
- "dataStoreSaveVerifiableCredential",
2075
- "didManagerFind",
2076
- "didManagerGet",
2077
- "keyManagerSign",
2078
- "verifyCredential"
2079
- ];
2080
- var logger = Loggers.DEFAULT.get("sphereon:oid4vci:holder");
2081
- function signCallback(identifier, context, nonce) {
2082
- return async (jwt, kid) => {
2083
- let resolution = await context.agent.identifierManagedGet(identifier);
2084
- const jwk = jwt.header.jwk ?? (resolution.method === "jwk" ? resolution.jwk : void 0);
2085
- if (!resolution.issuer && !jwt.payload.iss) {
2086
- return Promise.reject(Error(`No issuer could be determined from the JWT ${JSON.stringify(jwt)} or identifier resolution`));
2087
- }
2088
- const header = jwt.header;
2089
- const payload = jwt.payload;
2090
- if (nonce) {
2091
- payload.nonce = nonce;
2092
- }
2093
- if (jwk && header.kid) {
2094
- console.log(`Deleting kid, as we are using a jwk and the oid4vci spec does not allow both to be present (which is not the case in the JOSE spec)`);
2095
- delete header.kid;
2096
- }
2097
- return (await context.agent.jwtCreateJwsCompactSignature({
2098
- issuer: {
2099
- ...resolution,
2100
- noIssPayloadUpdate: false
2101
- },
2102
- protectedHeader: header,
2103
- payload
2104
- })).jwt;
2105
- };
2106
- }
2107
- __name(signCallback, "signCallback");
2108
- var OID4VCIHolder = class _OID4VCIHolder {
2109
- static {
2110
- __name(this, "OID4VCIHolder");
2111
- }
2112
- hasher;
2113
- eventTypes = [
2114
- OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED,
2115
- OID4VCIHolderEvent.CREDENTIAL_STORED,
2116
- OID4VCIHolderEvent.IDENTIFIER_CREATED
2117
- ];
2118
- methods = {
2119
- oid4vciHolderStart: this.oid4vciHolderStart.bind(this),
2120
- oid4vciHolderGetIssuerMetadata: this.oid4vciHolderGetIssuerMetadata.bind(this),
2121
- oid4vciHolderGetMachineInterpreter: this.oid4vciHolderGetMachineInterpreter.bind(this),
2122
- oid4vciHolderCreateCredentialsToSelectFrom: this.oid4vciHolderCreateCredentialsToSelectFrom.bind(this),
2123
- oid4vciHolderGetContact: this.oid4vciHolderGetContact.bind(this),
2124
- oid4vciHolderGetCredentials: this.oid4vciHolderGetCredentials.bind(this),
2125
- oid4vciHolderGetCredential: this.oid4vciHolderGetCredential.bind(this),
2126
- oid4vciHolderAddContactIdentity: this.oid4vciHolderAddContactIdentity.bind(this),
2127
- oid4vciHolderAssertValidCredentials: this.oid4vciHolderAssertValidCredentials.bind(this),
2128
- oid4vciHolderStoreCredentialBranding: this.oid4vciHolderStoreCredentialBranding.bind(this),
2129
- oid4vciHolderStoreCredentials: this.oid4vciHolderStoreCredentials.bind(this),
2130
- oid4vciHolderSendNotification: this.oid4vciHolderSendNotification.bind(this),
2131
- oid4vciHolderGetIssuerBranding: this.oid4vciHolderGetIssuerBranding.bind(this),
2132
- oid4vciHolderStoreIssuerBranding: this.oid4vciHolderStoreIssuerBranding.bind(this)
2133
- };
2134
- vcFormatPreferences = [
2135
- "vc+sd-jwt",
2136
- "mso_mdoc",
2137
- "jwt_vc_json",
2138
- "jwt_vc",
2139
- "ldp_vc"
2140
- ];
2141
- jsonldCryptographicSuitePreferences = [
2142
- "Ed25519Signature2018",
2143
- "EcdsaSecp256k1Signature2019",
2144
- "Ed25519Signature2020",
2145
- "JsonWebSignature2020"
2146
- ];
2147
- didMethodPreferences = [
2148
- SupportedDidMethodEnum2.DID_JWK,
2149
- SupportedDidMethodEnum2.DID_KEY,
2150
- SupportedDidMethodEnum2.DID_OYD,
2151
- SupportedDidMethodEnum2.DID_EBSI,
2152
- SupportedDidMethodEnum2.DID_ION
2153
- ];
2154
- jwtCryptographicSuitePreferences = [
2155
- JoseSignatureAlgorithm2.ES256,
2156
- JoseSignatureAlgorithm2.ES256K,
2157
- JoseSignatureAlgorithm2.EdDSA
2158
- ];
2159
- static DEFAULT_MOBILE_REDIRECT_URI = `${DefaultURISchemes.CREDENTIAL_OFFER}://`;
2160
- defaultAuthorizationRequestOpts = {
2161
- redirectUri: _OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI
2162
- };
2163
- onContactIdentityCreated;
2164
- onCredentialStored;
2165
- onIdentifierCreated;
2166
- onVerifyEBSICredentialIssuer;
2167
- constructor(options) {
2168
- const { onContactIdentityCreated, onCredentialStored, onIdentifierCreated, onVerifyEBSICredentialIssuer, vcFormatPreferences, jsonldCryptographicSuitePreferences, didMethodPreferences, jwtCryptographicSuitePreferences, defaultAuthorizationRequestOptions, hasher = defaultHasher2 } = {
2169
- ...options
2170
- };
2171
- this.hasher = hasher;
2172
- if (vcFormatPreferences !== void 0 && vcFormatPreferences.length > 0) {
2173
- this.vcFormatPreferences = vcFormatPreferences;
2174
- }
2175
- if (jsonldCryptographicSuitePreferences !== void 0 && jsonldCryptographicSuitePreferences.length > 0) {
2176
- this.jsonldCryptographicSuitePreferences = jsonldCryptographicSuitePreferences;
2177
- }
2178
- if (didMethodPreferences !== void 0 && didMethodPreferences.length > 0) {
2179
- this.didMethodPreferences = didMethodPreferences;
2180
- }
2181
- if (jwtCryptographicSuitePreferences !== void 0 && jwtCryptographicSuitePreferences.length > 0) {
2182
- this.jwtCryptographicSuitePreferences = jwtCryptographicSuitePreferences;
2183
- }
2184
- if (defaultAuthorizationRequestOptions) {
2185
- this.defaultAuthorizationRequestOpts = defaultAuthorizationRequestOptions;
2186
- }
2187
- this.onContactIdentityCreated = onContactIdentityCreated;
2188
- this.onCredentialStored = onCredentialStored;
2189
- this.onIdentifierCreated = onIdentifierCreated;
2190
- this.onVerifyEBSICredentialIssuer = onVerifyEBSICredentialIssuer;
2191
- }
2192
- async onEvent(event, context) {
2193
- switch (event.type) {
2194
- case OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED:
2195
- this.onContactIdentityCreated?.(event.data);
2196
- break;
2197
- case OID4VCIHolderEvent.CREDENTIAL_STORED:
2198
- this.onCredentialStored?.(event.data);
2199
- break;
2200
- case OID4VCIHolderEvent.IDENTIFIER_CREATED:
2201
- this.onIdentifierCreated?.(event.data);
2202
- break;
2203
- default:
2204
- return Promise.reject(Error(`Event type ${event.type} not supported`));
2205
- }
2206
- }
2207
- /**
2208
- * FIXME: This method can only be used locally. Creating the interpreter should be local to where the agent is running
2209
- */
2210
- async oid4vciHolderGetMachineInterpreter(opts, context) {
2211
- const authorizationRequestOpts = {
2212
- ...this.defaultAuthorizationRequestOpts,
2213
- ...opts.authorizationRequestOpts
2214
- };
2215
- const services = {
2216
- [OID4VCIMachineServices.start]: (args) => this.oid4vciHolderStart({
2217
- ...args,
2218
- authorizationRequestOpts
2219
- }, context),
2220
- [OID4VCIMachineServices.startFirstPartApplicationFlow]: (args) => startFirstPartApplicationMachine({
2221
- ...args,
2222
- stateNavigationListener: opts.firstPartyStateNavigationListener
2223
- }, context),
2224
- [OID4VCIMachineServices.createCredentialsToSelectFrom]: (args) => this.oid4vciHolderCreateCredentialsToSelectFrom(args, context),
2225
- [OID4VCIMachineServices.getContact]: (args) => this.oid4vciHolderGetContact(args, context),
2226
- [OID4VCIMachineServices.getCredentials]: (args) => this.oid4vciHolderGetCredentials({
2227
- accessTokenOpts: args.accessTokenOpts ?? opts.accessTokenOpts,
2228
- ...args
2229
- }, context),
2230
- [OID4VCIMachineServices.addContactIdentity]: (args) => this.oid4vciHolderAddContactIdentity(args, context),
2231
- [OID4VCIMachineServices.getIssuerBranding]: (args) => this.oid4vciHolderGetIssuerBranding(args, context),
2232
- [OID4VCIMachineServices.storeIssuerBranding]: (args) => this.oid4vciHolderStoreIssuerBranding(args, context),
2233
- [OID4VCIMachineServices.assertValidCredentials]: (args) => this.oid4vciHolderAssertValidCredentials(args, context),
2234
- [OID4VCIMachineServices.storeCredentialBranding]: (args) => this.oid4vciHolderStoreCredentialBranding(args, context),
2235
- [OID4VCIMachineServices.storeCredentials]: (args) => this.oid4vciHolderStoreCredentials(args, context),
2236
- [OID4VCIMachineServices.sendNotification]: (args) => this.oid4vciHolderSendNotification(args, context),
2237
- [OID4VCIMachineServices.getFederationTrust]: (args) => this.getFederationTrust(args, context)
2238
- };
2239
- const oid4vciMachineInstanceArgs = {
2240
- ...opts,
2241
- authorizationRequestOpts,
2242
- services: {
2243
- ...services,
2244
- ...opts.services
2245
- }
2246
- };
2247
- const { interpreter } = await OID4VCIMachine.newInstance(oid4vciMachineInstanceArgs, context);
2248
- return {
2249
- interpreter
2250
- };
2251
- }
2252
- /**
2253
- * This method is run before the machine starts! So there is no concept of the state machine context or states yet
2254
- *
2255
- * The result of this method can be directly passed into the start method of the state machine
2256
- * @param args
2257
- * @param context
2258
- * @private
2259
- */
2260
- async oid4vciHolderStart(args, context) {
2261
- const { requestData } = args;
2262
- if (!requestData) {
2263
- throw Error(`Cannot start the OID4VCI holder flow without request data being provided`);
2264
- }
2265
- const { uri = void 0 } = requestData;
2266
- if (!uri) {
2267
- return Promise.reject(Error("Missing request URI in context"));
2268
- }
2269
- const authorizationRequestOpts = {
2270
- ...this.defaultAuthorizationRequestOpts,
2271
- ...args.authorizationRequestOpts
2272
- };
2273
- authorizationRequestOpts.authorizationDetails = authorizationRequestOpts?.authorizationDetails ? asArray2(authorizationRequestOpts.authorizationDetails).filter((detail) => typeof detail === "string" || this.vcFormatPreferences.includes(detail.format)) : void 0;
2274
- if (!authorizationRequestOpts.redirectUri) {
2275
- authorizationRequestOpts.redirectUri = _OID4VCIHolder.DEFAULT_MOBILE_REDIRECT_URI;
2276
- }
2277
- if (authorizationRequestOpts.redirectUri.startsWith("http") && !authorizationRequestOpts.clientId) {
2278
- authorizationRequestOpts.clientId = authorizationRequestOpts.redirectUri;
2279
- }
2280
- let formats = this.vcFormatPreferences;
2281
- const authFormats = authorizationRequestOpts?.authorizationDetails?.map((detail) => typeof detail === "object" && "format" in detail && detail.format ? detail.format : void 0).filter((format) => !!format).map((format) => format);
2282
- if (authFormats && authFormats.length > 0) {
2283
- formats = Array.from(new Set(authFormats));
2284
- }
2285
- let oid4vciClient;
2286
- let types = void 0;
2287
- let offer;
2288
- if (requestData.existingClientState) {
2289
- oid4vciClient = await OpenID4VCIClient2.fromState({
2290
- state: requestData.existingClientState
2291
- });
2292
- offer = oid4vciClient.credentialOffer;
2293
- } else {
2294
- offer = requestData.credentialOffer;
2295
- if (uri.startsWith(RequestType.OPENID_INITIATE_ISSUANCE) || uri.startsWith(RequestType.OPENID_CREDENTIAL_OFFER) || uri.match(/https?:\/\/.*credential_offer(_uri)=?.*/)) {
2296
- if (!offer) {
2297
- offer = await CredentialOfferClient.fromURI(uri);
2298
- }
2299
- } else {
2300
- if (!!offer) {
2301
- logger.warning(`Non default URI used for credential offer: ${uri}`);
2302
- }
2303
- }
2304
- if (!offer) {
2305
- logger.log(`Issuer url received (no credential offer): ${uri}`);
2306
- oid4vciClient = await OpenID4VCIClient2.fromCredentialIssuer({
2307
- credentialIssuer: uri,
2308
- authorizationRequest: authorizationRequestOpts,
2309
- clientId: authorizationRequestOpts.clientId,
2310
- createAuthorizationRequestURL: requestData.createAuthorizationRequestURL ?? true
2311
- });
2312
- } else {
2313
- logger.log(`Credential offer received: ${uri}`);
2314
- oid4vciClient = await OpenID4VCIClient2.fromURI({
2315
- uri,
2316
- authorizationRequest: authorizationRequestOpts,
2317
- clientId: authorizationRequestOpts.clientId,
2318
- createAuthorizationRequestURL: requestData.createAuthorizationRequestURL ?? true
2319
- });
2320
- }
2321
- }
2322
- if (offer) {
2323
- types = getTypesFromCredentialOffer(offer.original_credential_offer);
2324
- } else {
2325
- types = asArray2(authorizationRequestOpts.authorizationDetails).map((authReqOpts) => getTypesFromAuthorizationDetails(authReqOpts) ?? []).filter((inner) => inner.length > 0);
2326
- }
2327
- const serverMetadata = await oid4vciClient.retrieveServerMetadata();
2328
- const credentialsSupported = await getCredentialConfigsSupportedMerged({
2329
- client: oid4vciClient,
2330
- vcFormatPreferences: formats,
2331
- types
2332
- });
2333
- const credentialBranding = await getCredentialBranding({
2334
- credentialsSupported,
2335
- context
2336
- });
2337
- const authorizationCodeURL = oid4vciClient.authorizationURL;
2338
- if (authorizationCodeURL) {
2339
- logger.log(`authorization code URL ${authorizationCodeURL}`);
2340
- }
2341
- const oid4vciClientState = JSON.parse(await oid4vciClient.exportState());
2342
- return {
2343
- authorizationCodeURL,
2344
- credentialBranding,
2345
- credentialsSupported,
2346
- serverMetadata,
2347
- oid4vciClientState
2348
- };
2349
- }
2350
- async oid4vciHolderCreateCredentialsToSelectFrom(args, context) {
2351
- const { credentialBranding, locale, selectedCredentials, credentialsSupported } = args;
2352
- logger.info(`Credentials supported ${Object.keys(credentialsSupported).join(", ")}`);
2353
- const credentialSelection = await Promise.all(Object.entries(credentialsSupported).map(async ([id, credentialConfigSupported]) => {
2354
- const credentialTypes = getTypesFromObject2(credentialConfigSupported);
2355
- const localeBranding = !credentialBranding ? void 0 : credentialBranding?.[id] ?? Object.entries(credentialBranding).find(([type, _brandings]) => {
2356
- credentialTypes && type in credentialTypes;
2357
- })?.map(([type, supported]) => supported);
2358
- const credentialAlias = (await selectCredentialLocaleBranding({
2359
- locale,
2360
- localeBranding
2361
- }))?.alias;
2362
- return {
2363
- id: uuidv42(),
2364
- credentialId: id,
2365
- credentialTypes: credentialTypes ?? asArray2(id),
2366
- credentialAlias: credentialAlias ?? id,
2367
- isSelected: false
2368
- };
2369
- }));
2370
- if (credentialSelection.length >= 1) {
2371
- credentialSelection.map((sel) => selectedCredentials.push(sel.credentialId));
2372
- }
2373
- logger.log(`Credential selection ${JSON.stringify(credentialSelection)}`);
2374
- return credentialSelection;
2375
- }
2376
- async oid4vciHolderGetContact(args, context) {
2377
- const { serverMetadata } = args;
2378
- if (serverMetadata === void 0) {
2379
- return Promise.reject(Error("Missing serverMetadata in context"));
2380
- }
2381
- const names = new Set(serverMetadata.credentialIssuerMetadata?.display?.map((display) => display.name).filter((name2) => name2 != void 0).map((name2) => name2) ?? []);
2382
- const name = names.size > 0 ? Array.from(names)[0] : void 0;
2383
- const correlationId = new URL(serverMetadata.issuer).hostname;
2384
- const filter = [
2385
- {
2386
- identities: {
2387
- identifier: {
2388
- correlationId
2389
- }
2390
- }
2391
- }
2392
- ];
2393
- if (name) {
2394
- filter.push({
2395
- contact: {
2396
- legalName: name
2397
- }
2398
- });
2399
- filter.push({
2400
- contact: {
2401
- displayName: name
2402
- }
2403
- });
2404
- }
2405
- const parties = await context.agent.cmGetContacts({
2406
- filter
2407
- });
2408
- if (parties.length > 1) {
2409
- logger.warning(`Get contacts returned more than one result: ${parties.length}, ${parties.map((party2) => party2.contact.displayName).join(",")}`);
2410
- }
2411
- const party = parties.length >= 1 ? parties[0] : void 0;
2412
- logger.log(`Party involved: `, party);
2413
- return party;
2414
- }
2415
- async oid4vciHolderGetCredentials(args, context) {
2416
- const { verificationCode, openID4VCIClientState, didMethodPreferences = this.didMethodPreferences, issuanceOpt, accessTokenOpts } = args;
2417
- logger.debug(`Getting credentials`, issuanceOpt, accessTokenOpts);
2418
- if (!openID4VCIClientState) {
2419
- return Promise.reject(Error("Missing openID4VCI client state in context"));
2420
- }
2421
- const client = await OpenID4VCIClient2.fromState({
2422
- state: openID4VCIClientState
2423
- });
2424
- const credentialsSupported = await getCredentialConfigsSupportedMerged({
2425
- client,
2426
- vcFormatPreferences: this.vcFormatPreferences,
2427
- configurationIds: args.selectedCredentials
2428
- });
2429
- const serverMetadata = await client.retrieveServerMetadata();
2430
- const issuanceOpts = await getIssuanceOpts({
2431
- client,
2432
- credentialsSupported,
2433
- serverMetadata,
2434
- context,
2435
- didMethodPreferences: Array.isArray(didMethodPreferences) && didMethodPreferences.length > 0 ? didMethodPreferences : this.didMethodPreferences,
2436
- jwtCryptographicSuitePreferences: this.jwtCryptographicSuitePreferences,
2437
- jsonldCryptographicSuitePreferences: this.jsonldCryptographicSuitePreferences,
2438
- ...issuanceOpt && {
2439
- forceIssuanceOpt: issuanceOpt
2440
- }
2441
- });
2442
- const getCredentials = issuanceOpts.map(async (issuanceOpt2) => await this.oid4vciHolderGetCredential({
2443
- issuanceOpt: issuanceOpt2,
2444
- pin: verificationCode,
2445
- client,
2446
- accessTokenOpts
2447
- }, context));
2448
- const allCredentials = await Promise.all(getCredentials);
2449
- logger.log(`Credentials received`, allCredentials);
2450
- return allCredentials;
2451
- }
2452
- async oid4vciHolderGetCredential(args, context) {
2453
- const { issuanceOpt, pin, client, accessTokenOpts } = args;
2454
- logger.info(`Getting credential`, issuanceOpt);
2455
- if (!issuanceOpt) {
2456
- return Promise.reject(Error(`Cannot get credential issuance options`));
2457
- }
2458
- const identifier = await getIdentifierOpts({
2459
- issuanceOpt,
2460
- context
2461
- });
2462
- issuanceOpt.identifier = identifier;
2463
- logger.info(`ID opts`, identifier);
2464
- const alg = await signatureAlgorithmFromKey({
2465
- key: identifier.key
2466
- });
2467
- const jwk = isManagedIdentifierJwkResult(identifier) ? identifier.jwk : void 0;
2468
- const callbacks = {
2469
- signCallback: signCallback(identifier, context)
2470
- };
2471
- try {
2472
- if (!client.clientId) {
2473
- client.clientId = isManagedIdentifierDidResult2(identifier) ? identifier.did : identifier.issuer;
2474
- }
2475
- let asOpts = void 0;
2476
- let kid = accessTokenOpts?.clientOpts?.kid ?? identifier.kid;
2477
- if (accessTokenOpts?.clientOpts) {
2478
- const clientId = accessTokenOpts.clientOpts.clientId ?? client.clientId ?? identifier.issuer;
2479
- if (client.isEBSI() && clientId?.startsWith("http") && kid?.includes("#")) {
2480
- kid = kid.split("#")[1];
2481
- }
2482
- const clientOpts = {
2483
- ...accessTokenOpts.clientOpts,
2484
- clientId,
2485
- kid,
2486
- // @ts-ignore
2487
- alg: accessTokenOpts.clientOpts.alg ?? alg,
2488
- signCallbacks: accessTokenOpts.clientOpts.signCallbacks ?? callbacks
2489
- };
2490
- asOpts = {
2491
- clientOpts
2492
- };
2493
- }
2494
- await client.acquireAccessToken({
2495
- clientId: client.clientId,
2496
- pin,
2497
- authorizationResponse: JSON.parse(await client.exportState()).authorizationCodeResponse,
2498
- additionalRequestParams: accessTokenOpts?.additionalRequestParams,
2499
- ...asOpts && {
2500
- asOpts
2501
- }
2502
- });
2503
- const types = getTypesFromObject2(issuanceOpt);
2504
- const id = "id" in issuanceOpt && issuanceOpt.id ? issuanceOpt.id : void 0;
2505
- const credentialTypes = asArray2(issuanceOpt.credentialConfigurationId ?? types ?? id);
2506
- if (!credentialTypes || credentialTypes.length === 0) {
2507
- return Promise.reject(Error("cannot determine credential id to request"));
2508
- }
2509
- const credentialDefinition = this.getCredentialDefinition(issuanceOpt);
2510
- const credentialResponse = await client.acquireCredentials({
2511
- ...credentialDefinition && {
2512
- context: credentialDefinition["@context"]
2513
- },
2514
- credentialTypes,
2515
- proofCallbacks: callbacks,
2516
- format: issuanceOpt.format,
2517
- // TODO: We need to update the machine and add notifications support for actual deferred credentials instead of just waiting/retrying
2518
- deferredCredentialAwait: true,
2519
- ...!jwk && {
2520
- kid
2521
- },
2522
- jwk,
2523
- alg,
2524
- jti: uuidv42()
2525
- });
2526
- const credential = {
2527
- id: issuanceOpt.credentialConfigurationId ?? id,
2528
- types: types ?? asArray2(credentialTypes),
2529
- issuanceOpt,
2530
- credentialResponse
2531
- };
2532
- return mapCredentialToAccept({
2533
- credentialToAccept: credential,
2534
- hasher: this.hasher
2535
- });
2536
- } catch (error) {
2537
- return Promise.reject(error);
2538
- }
2539
- }
2540
- async oid4vciHolderAddContactIdentity(args, context) {
2541
- const { credentialsToAccept, contact } = args;
2542
- if (!contact) {
2543
- return Promise.reject(Error("Missing contact in context"));
2544
- }
2545
- if (credentialsToAccept === void 0 || credentialsToAccept.length === 0) {
2546
- return Promise.reject(Error("Missing credential offers in context"));
2547
- }
2548
- let correlationId = credentialsToAccept[0].correlationId;
2549
- let identifierType = CorrelationIdentifierType.DID;
2550
- if (!correlationId.toLowerCase().startsWith("did:")) {
2551
- identifierType = CorrelationIdentifierType.URL;
2552
- if (correlationId.startsWith("http")) {
2553
- correlationId = new URL(correlationId).hostname;
2554
- }
2555
- }
2556
- const identity = {
2557
- alias: credentialsToAccept[0].correlationId,
2558
- origin: IdentityOrigin.EXTERNAL,
2559
- roles: [
2560
- CredentialRole.ISSUER
2561
- ],
2562
- identifier: {
2563
- type: identifierType,
2564
- correlationId
2565
- },
2566
- ...identifierType === CorrelationIdentifierType.URL && {
2567
- connection: {
2568
- type: ConnectionType.OPENID_CONNECT,
2569
- config: {
2570
- clientId: "138d7bf8-c930-4c6e-b928-97d3a4928b01",
2571
- clientSecret: "03b3955f-d020-4f2a-8a27-4e452d4e27a0",
2572
- scopes: [
2573
- "auth"
2574
- ],
2575
- issuer: "https://example.com/app-test",
2576
- redirectUrl: "app:/callback",
2577
- dangerouslyAllowInsecureHttpRequests: true,
2578
- clientAuthMethod: "post"
2579
- }
2580
- }
2581
- }
2582
- };
2583
- await context.agent.emit(OID4VCIHolderEvent.CONTACT_IDENTITY_CREATED, {
2584
- contactId: contact.id,
2585
- identity
2586
- });
2587
- logger.log(`Contact added: ${correlationId}`);
2588
- return context.agent.cmAddIdentity({
2589
- contactId: contact.id,
2590
- identity
2591
- });
2592
- }
2593
- async oid4vciHolderGetIssuerBranding(args, context) {
2594
- const { serverMetadata, contact } = args;
2595
- const issuerCorrelationId = contact?.identities.filter((identity) => identity.roles.includes(CredentialRole.ISSUER)).map((identity) => identity.identifier.correlationId)[0];
2596
- if (issuerCorrelationId) {
2597
- const branding = await context.agent.ibGetIssuerBranding({
2598
- filter: [
2599
- {
2600
- issuerCorrelationId
2601
- }
2602
- ]
2603
- });
2604
- if (branding.length > 0) {
2605
- return branding[0].localeBranding;
2606
- }
2607
- }
2608
- if (!serverMetadata) {
2609
- return Promise.reject(Error("Missing serverMetadata in context"));
2610
- }
2611
- return getBasicIssuerLocaleBranding({
2612
- display: serverMetadata.credentialIssuerMetadata?.display ?? [],
2613
- dynamicRegistrationClientMetadata: serverMetadata.credentialIssuerMetadata,
2614
- context
2615
- });
2616
- }
2617
- async oid4vciHolderStoreIssuerBranding(args, context) {
2618
- const { issuerBranding, contact } = args;
2619
- if (!issuerBranding || issuerBranding.length === 0 || issuerBranding[0].id) {
2620
- return;
2621
- }
2622
- if (!contact) {
2623
- return Promise.reject(Error("Missing contact in context"));
2624
- }
2625
- const issuerCorrelationId = contact?.identities.filter((identity) => identity.roles.includes(CredentialRole.ISSUER)).map((identity) => identity.identifier.correlationId)[0];
2626
- const branding = await context.agent.ibGetIssuerBranding({
2627
- filter: [
2628
- {
2629
- issuerCorrelationId
2630
- }
2631
- ]
2632
- });
2633
- if (branding.length > 0) {
2634
- return;
2635
- }
2636
- await context.agent.ibAddIssuerBranding({
2637
- localeBranding: issuerBranding,
2638
- issuerCorrelationId
2639
- });
2640
- }
2641
- async oid4vciHolderAssertValidCredentials(args, context) {
2642
- const { credentialsToAccept, issuanceOpt } = args;
2643
- return await Promise.all(credentialsToAccept.map((credentialToAccept) => verifyCredentialToAccept({
2644
- mappedCredential: credentialToAccept,
2645
- onVerifyEBSICredentialIssuer: this.onVerifyEBSICredentialIssuer,
2646
- hasher: this.hasher,
2647
- schemaValidation: issuanceOpt?.schemaValidation,
2648
- context
2649
- })));
2650
- }
2651
- async oid4vciHolderStoreCredentialBranding(args, context) {
2652
- const { credentialBranding, serverMetadata, selectedCredentials, credentialsToAccept } = args;
2653
- if (serverMetadata === void 0) {
2654
- return Promise.reject(Error("Missing serverMetadata in context"));
2655
- } else if (selectedCredentials.length === 0) {
2656
- logger.warning(`No credentials selected for issuer: ${serverMetadata.issuer}`);
2657
- return;
2658
- }
2659
- let counter = 0;
2660
- for (const credentialId of selectedCredentials) {
2661
- const localeBranding = credentialBranding?.[credentialId];
2662
- if (localeBranding && localeBranding.length > 0) {
2663
- const credential = credentialsToAccept.find((credAccept) => credAccept.credentialToAccept.id === credentialId || JSON.stringify(credAccept.types) === credentialId || credentialsToAccept[counter]);
2664
- counter++;
2665
- await context.agent.ibAddCredentialBranding({
2666
- vcHash: computeEntryHash(credential.rawVerifiableCredential),
2667
- issuerCorrelationId: new URL(serverMetadata.issuer).hostname,
2668
- localeBranding
2669
- });
2670
- logger.log(`Credential branding for issuer ${serverMetadata.issuer} and type ${credentialId} stored with locales ${localeBranding.map((b) => b.locale).join(",")}`);
2671
- } else {
2672
- logger.warning(`No credential branding found for issuer: ${serverMetadata.issuer} and type ${credentialId}`);
2673
- }
2674
- }
2675
- }
2676
- async oid4vciHolderStoreCredentials(args, context) {
2677
- function trimmed(input) {
2678
- const trim = input?.trim();
2679
- if (trim === "") {
2680
- return void 0;
2681
- }
2682
- return trim;
2683
- }
2684
- __name(trimmed, "trimmed");
2685
- const { credentialsToAccept, openID4VCIClientState, credentialsSupported, serverMetadata, selectedCredentials } = args;
2686
- const mappedCredentialToAccept = credentialsToAccept[0];
2687
- if (selectedCredentials && selectedCredentials.length > 1) {
2688
- logger.error(`More than 1 credential selected ${selectedCredentials.join(", ")}, but current service only stores 1 credential!`);
2689
- }
2690
- const issuanceOpt = args.issuanceOpt ?? mappedCredentialToAccept.credentialToAccept.issuanceOpt;
2691
- if (!issuanceOpt || !issuanceOpt.identifier) {
2692
- return Promise.reject(Error("issuanceOpt.identifier must me set in order to store a credential"));
2693
- }
2694
- const { kmsKeyRef, method } = issuanceOpt.identifier;
2695
- let persist = true;
2696
- const verifiableCredential = mappedCredentialToAccept.uniformVerifiableCredential;
2697
- const notificationId = mappedCredentialToAccept.credentialToAccept.credentialResponse.notification_id;
2698
- const subjectIssuance = mappedCredentialToAccept.credential_subject_issuance;
2699
- const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint;
2700
- let holderCredential = void 0;
2701
- if (!notificationEndpoint) {
2702
- logger.log(`Notifications not supported by issuer ${serverMetadata?.issuer}. Will not provide a notification`);
2703
- } else if (notificationEndpoint && !notificationId) {
2704
- logger.warning(`Notification endpoint available in issuer metadata with value ${notificationEndpoint}, but no ${notificationId} provided. Will not send a notification to issuer ${serverMetadata?.issuer}`);
2705
- } else if (notificationEndpoint && notificationId) {
2706
- logger.log(`Notification id ${notificationId} found, will send back a notification to ${notificationEndpoint}`);
2707
- let event = "credential_accepted";
2708
- if (Array.isArray(subjectIssuance?.notification_events_supported)) {
2709
- event = subjectIssuance.notification_events_supported.includes("credential_accepted_holder_signed") ? "credential_accepted_holder_signed" : "credential_deleted_holder_signed";
2710
- logger.log(`Subject issuance/signing will be used, with event`, event);
2711
- const issuerVC = mappedCredentialToAccept.credentialToAccept.credentialResponse.credential;
2712
- const wrappedIssuerVC = CredentialMapper2.toWrappedVerifiableCredential(issuerVC, {
2713
- hasher: this.hasher ?? defaultHasher2
2714
- });
2715
- console.log(`Wrapped VC: ${wrappedIssuerVC.type}, ${wrappedIssuerVC.format}`);
2716
- let issuer;
2717
- if (CredentialMapper2.isWrappedSdJwtVerifiableCredential(wrappedIssuerVC)) {
2718
- issuer = trimmed(wrappedIssuerVC.decoded?.sub);
2719
- } else if (CredentialMapper2.isWrappedW3CVerifiableCredential(wrappedIssuerVC)) {
2720
- issuer = trimmed(wrappedIssuerVC.credential?.sub) ?? trimmed(this.idFromW3cCredentialSubject(wrappedIssuerVC));
2721
- } else if (CredentialMapper2.isWrappedMdocCredential(wrappedIssuerVC)) {
2722
- return Promise.reject(Error("mdoc not yet supported"));
2723
- }
2724
- if (!issuer) {
2725
- issuer = trimmed(verifiableCredential.credentialSubject?.id);
2726
- }
2727
- if (!issuer && openID4VCIClientState?.kid?.startsWith("did:")) {
2728
- issuer = parseDid(openID4VCIClientState?.kid).did;
2729
- }
2730
- if (!issuer && openID4VCIClientState?.jwk?.kid?.startsWith("did:")) {
2731
- issuer = parseDid(openID4VCIClientState.jwk.kid).did;
2732
- }
2733
- if (!issuer && openID4VCIClientState?.clientId) {
2734
- issuer = trimmed(openID4VCIClientState.clientId);
2735
- }
2736
- if (!issuer && openID4VCIClientState?.accessTokenResponse) {
2737
- const decodedJwt = decodeJWT(openID4VCIClientState.accessTokenResponse.access_token);
2738
- issuer = decodedJwt.payload.sub;
2739
- }
2740
- if (!issuer && mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier) {
2741
- const resolution = await context.agent.identifierManagedGet(mappedCredentialToAccept.credentialToAccept.issuanceOpt.identifier);
2742
- issuer = resolution.issuer;
2743
- }
2744
- if (!issuer) {
2745
- throw Error(`We could not determine the issuer, which means we cannot sign the credential`);
2746
- }
2747
- logger.log(`Issuer for self-issued credential will be: ${issuer}`);
2748
- const holderCredentialToSign = wrappedIssuerVC.decoded;
2749
- let proofFormat = "lds";
2750
- if (wrappedIssuerVC.format.includes("jwt") && !wrappedIssuerVC.format.includes("mso_mdoc")) {
2751
- holderCredentialToSign.iss = issuer;
2752
- proofFormat = "jwt";
2753
- }
2754
- if ("issuer" in holderCredentialToSign && !("iss" in holderCredentialToSign)) {
2755
- holderCredentialToSign.issuer = issuer;
2756
- }
2757
- if ("sub" in holderCredentialToSign) {
2758
- holderCredentialToSign.sub = issuer;
2759
- }
2760
- if ("credentialSubject" in holderCredentialToSign && !Array.isArray(holderCredentialToSign.credentialSubject)) {
2761
- holderCredentialToSign.credentialSubject.id = issuer;
2762
- }
2763
- if ("vc" in holderCredentialToSign) {
2764
- if (holderCredentialToSign.vc.credentialSubject) {
2765
- holderCredentialToSign.vc.credentialSubject.id = issuer;
2766
- }
2767
- holderCredentialToSign.vc.issuer = issuer;
2768
- delete holderCredentialToSign.vc.proof;
2769
- delete holderCredentialToSign.vc.issuanceDate;
2770
- }
2771
- delete holderCredentialToSign.proof;
2772
- delete holderCredentialToSign.issuanceDate;
2773
- delete holderCredentialToSign.iat;
2774
- logger.log(`Subject issuance/signing will sign credential of type ${proofFormat}:`, holderCredentialToSign);
2775
- const issuedVC = await context.agent.createVerifiableCredential({
2776
- credential: holderCredentialToSign,
2777
- fetchRemoteContexts: true,
2778
- save: false,
2779
- proofFormat
2780
- });
2781
- if (!issuedVC) {
2782
- throw Error(`Could not issue holder credential from the wallet`);
2783
- }
2784
- logger.log(`Holder ${issuedVC.issuer} issued new credential with id ${issuedVC.id}`, issuedVC);
2785
- holderCredential = CredentialMapper2.storedCredentialToOriginalFormat(issuedVC);
2786
- persist = event === "credential_accepted_holder_signed";
2787
- }
2788
- const notificationRequest = {
2789
- notification_id: notificationId,
2790
- ...holderCredential && {
2791
- credential: holderCredential
2792
- },
2793
- event
2794
- };
2795
- await this.oid4vciHolderSendNotification({
2796
- openID4VCIClientState,
2797
- stored: persist,
2798
- credentialsToAccept,
2799
- credentialsSupported,
2800
- notificationRequest,
2801
- serverMetadata
2802
- }, context);
2803
- }
2804
- const persistCredential = holderCredential ? CredentialMapper2.storedCredentialToOriginalFormat(holderCredential) : mappedCredentialToAccept.rawVerifiableCredential;
2805
- if (!persist && holderCredential) {
2806
- logger.log(`Will not persist credential, since we are signing as a holder and the issuer asked not to persist`);
2807
- } else {
2808
- logger.log(`Persisting credential`, persistCredential);
2809
- const issuer = CredentialMapper2.issuerCorrelationIdFromIssuerType(verifiableCredential.issuer);
2810
- const [subjectCorrelationType, subjectCorrelationId] = this.determineSubjectCorrelation(issuanceOpt.identifier, issuer);
2811
- const persistedCredential = await context.agent.crsAddCredential({
2812
- credential: {
2813
- rawDocument: ensureRawDocument(persistCredential),
2814
- kmsKeyRef,
2815
- identifierMethod: method,
2816
- credentialRole: CredentialRole.HOLDER,
2817
- issuerCorrelationType: issuer?.startsWith("did:") ? CredentialCorrelationType.DID : CredentialCorrelationType.URL,
2818
- issuerCorrelationId: issuer,
2819
- subjectCorrelationType,
2820
- subjectCorrelationId
2821
- }
2822
- });
2823
- await context.agent.emit(OID4VCIHolderEvent.CREDENTIAL_STORED, {
2824
- credential: persistedCredential,
2825
- vcHash: persistedCredential.hash
2826
- });
2827
- }
2828
- }
2829
- async oid4vciHolderSendNotification(args, context) {
2830
- const { serverMetadata, notificationRequest, openID4VCIClientState } = args;
2831
- const notificationEndpoint = serverMetadata?.credentialIssuerMetadata?.notification_endpoint;
2832
- if (!notificationEndpoint) {
2833
- return;
2834
- } else if (!openID4VCIClientState) {
2835
- return Promise.reject(Error("Missing openID4VCI client state in context"));
2836
- } else if (!notificationRequest) {
2837
- return Promise.reject(Error("Missing notification request"));
2838
- }
2839
- logger.log(`Will send notification to ${notificationEndpoint}`, notificationRequest);
2840
- const client = await OpenID4VCIClient2.fromState({
2841
- state: openID4VCIClientState
2842
- });
2843
- await client.sendNotification({
2844
- notificationEndpoint
2845
- }, notificationRequest, openID4VCIClientState?.accessTokenResponse?.access_token);
2846
- logger.log(`Notification to ${notificationEndpoint} has been dispatched`);
2847
- }
2848
- async getFederationTrust(args, context) {
2849
- const { requestData, serverMetadata, trustAnchors } = args;
2850
- if (trustAnchors.length === 0) {
2851
- return Promise.reject(Error("No trust anchors found"));
2852
- }
2853
- if (!requestData?.uri) {
2854
- return Promise.reject(Error("Missing request URI in context"));
2855
- }
2856
- if (!serverMetadata) {
2857
- return Promise.reject(Error("Missing serverMetadata in context"));
2858
- }
2859
- const url = new URL(requestData?.uri);
2860
- const params = new URLSearchParams(url.search);
2861
- const openidFederation = params.get("openid_federation");
2862
- const entityIdentifier = openidFederation ?? serverMetadata.issuer;
2863
- if (entityIdentifier.startsWith("http://")) {
2864
- console.warn(`OpenID federation does not support http://, only https:// allowed; got: (${url.toString()})`);
2865
- return [];
2866
- }
2867
- const result = await context.agent.identifierExternalResolveByOIDFEntityId({
2868
- method: "entity_id",
2869
- trustAnchors,
2870
- identifier: entityIdentifier
2871
- });
2872
- return result.trustedAnchors;
2873
- }
2874
- async oid4vciHolderGetIssuerMetadata(args, context) {
2875
- const { issuer, errorOnNotFound = true } = args;
2876
- return MetadataClient.retrieveAllMetadata(issuer, {
2877
- errorOnNotFound
2878
- });
2879
- }
2880
- determineSubjectCorrelation(identifier, issuer) {
2881
- switch (identifier.method) {
2882
- case "did":
2883
- if (isManagedIdentifierResult2(identifier) && isManagedIdentifierDidResult2(identifier)) {
2884
- return [
2885
- CredentialCorrelationType.DID,
2886
- identifier.did
2887
- ];
2888
- } else if (isManagedIdentifierDidOpts(identifier)) {
2889
- return [
2890
- CredentialCorrelationType.DID,
2891
- typeof identifier.identifier === "string" ? identifier.identifier : identifier.identifier.did
2892
- ];
2893
- }
2894
- break;
2895
- case "kid":
2896
- if (isManagedIdentifierResult2(identifier) && isManagedIdentifierKidResult(identifier)) {
2897
- return [
2898
- CredentialCorrelationType.KID,
2899
- identifier.kid
2900
- ];
2901
- } else if (isManagedIdentifierDidOpts(identifier)) {
2902
- return [
2903
- CredentialCorrelationType.KID,
2904
- identifier.identifier
2905
- ];
2906
- }
2907
- break;
2908
- case "x5c":
2909
- if (isManagedIdentifierResult2(identifier) && isManagedIdentifierX5cResult(identifier)) {
2910
- return [
2911
- CredentialCorrelationType.X509_SAN,
2912
- identifier.x5c.join("\r\n")
2913
- ];
2914
- } else if (isManagedIdentifierX5cOpts(identifier)) {
2915
- return [
2916
- CredentialCorrelationType.X509_SAN,
2917
- identifier.identifier.join("\r\n")
2918
- ];
2919
- }
2920
- break;
2921
- }
2922
- return [
2923
- CredentialCorrelationType.URL,
2924
- issuer
2925
- ];
2926
- }
2927
- idFromW3cCredentialSubject(wrappedIssuerVC) {
2928
- if (Array.isArray(wrappedIssuerVC.credential?.credentialSubject)) {
2929
- if (wrappedIssuerVC.credential?.credentialSubject.length > 0) {
2930
- return wrappedIssuerVC.credential?.credentialSubject[0].id;
2931
- }
2932
- } else {
2933
- return wrappedIssuerVC.credential?.credentialSubject?.id;
2934
- }
2935
- return void 0;
2936
- }
2937
- getCredentialDefinition(issuanceOpt) {
2938
- if (issuanceOpt.format == "ldp_vc" || issuanceOpt.format == "jwt_vc_json-ld") {
2939
- return issuanceOpt.credential_definition;
2940
- }
2941
- return void 0;
2942
- }
2943
- };
2944
-
2945
- // src/listeners/headlessStateNavListener.ts
2946
- import { Loggers as Loggers2, LogLevel, LogMethod } from "@sphereon/ssi-types";
2947
- var logger2 = Loggers2.DEFAULT.options("sphereon:oid4vci:holder", {
2948
- defaultLogLevel: LogLevel.DEBUG,
2949
- methods: [
2950
- LogMethod.CONSOLE
2951
- ]
2952
- }).get("sphereon:oid4vci:holder");
2953
- var OID4VCICallbackStateListener = /* @__PURE__ */ __name((callbacks) => {
2954
- return async (oid4vciMachine, state) => {
2955
- if (state._event.type === "internal") {
2956
- logger2.debug("oid4vciCallbackStateListener: internal event");
2957
- return;
2958
- }
2959
- logger2.info(`VCI state listener state: ${JSON.stringify(state.value)}`);
2960
- if (!callbacks || callbacks.size === 0) {
2961
- logger2.info(`VCI no callbacks registered for state: ${JSON.stringify(state.value)}`);
2962
- return;
2963
- }
2964
- for (const [stateKey, callback] of callbacks) {
2965
- if (state.matches(stateKey)) {
2966
- logger2.log(`VCI state callback for state: ${JSON.stringify(state.value)}, will execute...`);
2967
- await callback(oid4vciMachine, state).then(() => logger2.log(`state callback executed for state: ${JSON.stringify(state.value)}`)).catch((error) => {
2968
- logger2.error(`VCI state callback failed for state: ${JSON.stringify(state.value)}, error: ${JSON.stringify(error?.message)}, ${JSON.stringify(state.event)}`);
2969
- if (error.stack) {
2970
- logger2.error(error.stack);
2971
- }
2972
- });
2973
- break;
2974
- }
2975
- }
2976
- };
2977
- }, "OID4VCICallbackStateListener");
2978
-
2979
- // src/link-handler/index.ts
2980
- import { CredentialOfferClient as CredentialOfferClient2 } from "@sphereon/oid4vci-client";
2981
- import { convertURIToJsonObject } from "@sphereon/oid4vci-common";
2982
- import { LinkHandlerAdapter } from "@sphereon/ssi-sdk.core";
2983
- import { interpreterStartOrResume } from "@sphereon/ssi-sdk.xstate-machine-persistence";
2984
- var OID4VCIHolderLinkHandler = class extends LinkHandlerAdapter {
2985
- static {
2986
- __name(this, "OID4VCIHolderLinkHandler");
2987
- }
2988
- context;
2989
- stateNavigationListener;
2990
- firstPartyStateNavigationListener;
2991
- noStateMachinePersistence;
2992
- authorizationRequestOpts;
2993
- clientOpts;
2994
- trustAnchors;
2995
- constructor(args) {
2996
- super({
2997
- ...args,
2998
- id: "OID4VCIHolder"
2999
- });
3000
- this.authorizationRequestOpts = args.authorizationRequestOpts;
3001
- this.clientOpts = args.clientOpts;
3002
- this.context = args.context;
3003
- this.noStateMachinePersistence = args.noStateMachinePersistence === true;
3004
- this.stateNavigationListener = args.stateNavigationListener;
3005
- this.firstPartyStateNavigationListener = args.firstPartyStateNavigationListener;
3006
- this.trustAnchors = args.trustAnchors;
3007
- }
3008
- async handle(url, opts) {
3009
- const uri = new URL(url).toString();
3010
- const offerData = convertURIToJsonObject(uri);
3011
- const hasCode = "code" in offerData && !!offerData.code && !("issuer" in offerData);
3012
- const code = hasCode ? offerData.code : void 0;
3013
- const clientOpts = {
3014
- ...this.clientOpts,
3015
- ...opts?.clientOpts
3016
- };
3017
- const oid4vciMachine = await this.context.agent.oid4vciHolderGetMachineInterpreter({
3018
- requestData: {
3019
- // We know this can only be invoked with a credential offer, so we convert the URI to offer
3020
- ...!hasCode && {
3021
- credentialOffer: await CredentialOfferClient2.fromURI(uri)
3022
- },
3023
- ...hasCode && {
3024
- code
3025
- },
3026
- createAuthorizationRequestURL: opts?.createAuthorizationRequestURL,
3027
- flowType: opts?.flowType,
3028
- uri
3029
- },
3030
- trustAnchors: this.trustAnchors,
3031
- authorizationRequestOpts: {
3032
- ...this.authorizationRequestOpts,
3033
- ...opts?.authorizationRequestOpts
3034
- },
3035
- ...(clientOpts.clientId || clientOpts.clientAssertionType) && {
3036
- clientOpts
3037
- },
3038
- stateNavigationListener: this.stateNavigationListener,
3039
- firstPartyStateNavigationListener: this.firstPartyStateNavigationListener
3040
- });
3041
- const interpreter = oid4vciMachine.interpreter;
3042
- if (!opts?.machineState && this.context.agent.availableMethods().includes("machineStatesFindActive")) {
3043
- const stateType = hasCode ? "existing" : "new";
3044
- await interpreterStartOrResume({
3045
- stateType,
3046
- interpreter,
3047
- context: this.context,
3048
- cleanupAllOtherInstances: true,
3049
- cleanupOnFinalState: true,
3050
- singletonCheck: true,
3051
- noRegistration: this.noStateMachinePersistence
3052
- });
3053
- } else {
3054
- interpreter.start(opts?.machineState);
3055
- }
3056
- if (hasCode) {
3057
- interpreter.send(OID4VCIMachineEvents.PROVIDE_AUTHORIZATION_CODE_RESPONSE, {
3058
- data: uri
3059
- });
3060
- }
3061
- }
3062
- };
3063
- export {
3064
- FirstPartyMachineEvents,
3065
- FirstPartyMachineServices,
3066
- FirstPartyMachineStateTypes,
3067
- IdentifierAliasEnum,
3068
- OID4VCICallbackStateListener,
3069
- OID4VCIHolder,
3070
- OID4VCIHolderEvent,
3071
- OID4VCIHolderLinkHandler,
3072
- OID4VCIMachineAddContactStates,
3073
- OID4VCIMachineEvents,
3074
- OID4VCIMachineGuards,
3075
- OID4VCIMachineServices,
3076
- OID4VCIMachineStates,
3077
- OID4VCIMachineVerifyPinStates,
3078
- RequestType,
3079
- SupportedLanguage,
3080
- createConfig,
3081
- getBasicIssuerLocaleBranding,
3082
- getCredentialBranding,
3083
- getCredentialConfigsBasedOnFormatPref,
3084
- getCredentialConfigsSupported,
3085
- getCredentialConfigsSupportedBySingleTypeOrId,
3086
- getCredentialConfigsSupportedMerged,
3087
- getIdentifierOpts,
3088
- getIssuanceCryptoSuite,
3089
- getIssuanceMethod,
3090
- getIssuanceOpts,
3091
- getSiopRequest,
3092
- issuerLocaleBrandingFrom,
3093
- mapCredentialToAccept,
3094
- oid4vciCombineDisplayLocalesFrom,
3095
- oid4vciCredentialDisplayLocalesFrom,
3096
- oid4vciCredentialLocaleBrandingFrom,
3097
- oid4vciGetCredentialBrandingFrom,
3098
- oid4vciHolderContextMethods,
3099
- oid4vciIssuerCredentialSubjectLocalesFrom,
3100
- sdJwtCombineDisplayLocalesFrom,
3101
- sdJwtCredentialClaimLocalesFrom,
3102
- sdJwtCredentialDisplayLocalesFrom,
3103
- sdJwtCredentialLocaleBrandingFrom,
3104
- sdJwtGetCredentialBrandingFrom,
3105
- selectCredentialLocaleBranding,
3106
- sendAuthorizationChallengeRequest,
3107
- sendAuthorizationResponse,
3108
- signCallback,
3109
- startFirstPartApplicationMachine,
3110
- verifyCredentialToAccept
3111
- };
1
+ "use strict";
2
+ /**
3
+ * @public
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.signCallback = exports.oid4vciHolderContextMethods = exports.OID4VCIHolder = void 0;
21
+ var OID4VCIHolder_1 = require("./agent/OID4VCIHolder");
22
+ Object.defineProperty(exports, "OID4VCIHolder", { enumerable: true, get: function () { return OID4VCIHolder_1.OID4VCIHolder; } });
23
+ Object.defineProperty(exports, "oid4vciHolderContextMethods", { enumerable: true, get: function () { return OID4VCIHolder_1.oid4vciHolderContextMethods; } });
24
+ Object.defineProperty(exports, "signCallback", { enumerable: true, get: function () { return OID4VCIHolder_1.signCallback; } });
25
+ __exportStar(require("./mappers/OIDC4VCIBrandingMapper"), exports);
26
+ __exportStar(require("./services/OID4VCIHolderService"), exports);
27
+ __exportStar(require("./services/FirstPartyMachineServices"), exports);
28
+ __exportStar(require("./types/IOID4VCIHolder"), exports);
29
+ __exportStar(require("./types/FirstPartyMachine"), exports);
30
+ __exportStar(require("./listeners/headlessStateNavListener"), exports);
31
+ __exportStar(require("./link-handler"), exports);
3112
32
  //# sourceMappingURL=index.js.map