@sphereon/ssi-sdk.siopv2-oid4vp-op-auth 0.33.1-feature.vcdm2.tsup.32 → 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 (88) hide show
  1. package/dist/agent/DidAuthSiopOpAuthenticator.d.ts +36 -0
  2. package/dist/agent/DidAuthSiopOpAuthenticator.d.ts.map +1 -0
  3. package/dist/agent/DidAuthSiopOpAuthenticator.js +392 -0
  4. package/dist/agent/DidAuthSiopOpAuthenticator.js.map +1 -0
  5. package/dist/index.d.ts +8 -555
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +31 -2420
  8. package/dist/index.js.map +1 -1
  9. package/dist/link-handler/index.d.ts +22 -0
  10. package/dist/link-handler/index.d.ts.map +1 -0
  11. package/dist/link-handler/index.js +57 -0
  12. package/dist/link-handler/index.js.map +1 -0
  13. package/dist/localization/Localization.d.ts +9 -0
  14. package/dist/localization/Localization.d.ts.map +1 -0
  15. package/dist/localization/Localization.js +46 -0
  16. package/dist/localization/Localization.js.map +1 -0
  17. package/dist/localization/translations/en.json +9 -0
  18. package/dist/localization/translations/nl.json +8 -0
  19. package/dist/machine/CallbackStateListener.d.ts +3 -0
  20. package/dist/machine/CallbackStateListener.d.ts.map +1 -0
  21. package/dist/machine/CallbackStateListener.js +48 -0
  22. package/dist/machine/CallbackStateListener.js.map +1 -0
  23. package/dist/machine/Siopv2Machine.d.ts +8 -0
  24. package/dist/machine/Siopv2Machine.d.ts.map +1 -0
  25. package/dist/machine/Siopv2Machine.js +364 -0
  26. package/dist/machine/Siopv2Machine.js.map +1 -0
  27. package/dist/services/IdentifierService.d.ts +3 -0
  28. package/dist/services/IdentifierService.d.ts.map +1 -0
  29. package/dist/services/IdentifierService.js +28 -0
  30. package/dist/services/IdentifierService.js.map +1 -0
  31. package/dist/services/Siopv2MachineService.d.ts +18 -0
  32. package/dist/services/Siopv2MachineService.d.ts.map +1 -0
  33. package/dist/services/Siopv2MachineService.js +299 -0
  34. package/dist/services/Siopv2MachineService.js.map +1 -0
  35. package/dist/session/OID4VP.d.ts +72 -0
  36. package/dist/session/OID4VP.d.ts.map +1 -0
  37. package/dist/session/OID4VP.js +224 -0
  38. package/dist/session/OID4VP.js.map +1 -0
  39. package/dist/session/OpSession.d.ts +39 -0
  40. package/dist/session/OpSession.d.ts.map +1 -0
  41. package/dist/session/OpSession.js +365 -0
  42. package/dist/session/OpSession.js.map +1 -0
  43. package/dist/session/functions.d.ts +37 -0
  44. package/dist/session/functions.d.ts.map +1 -0
  45. package/dist/session/functions.js +163 -0
  46. package/dist/session/functions.js.map +1 -0
  47. package/dist/session/index.d.ts +4 -0
  48. package/dist/session/index.d.ts.map +1 -0
  49. package/dist/session/index.js +20 -0
  50. package/dist/session/index.js.map +1 -0
  51. package/dist/types/IDidAuthSiopOpAuthenticator.d.ts +120 -0
  52. package/dist/types/IDidAuthSiopOpAuthenticator.d.ts.map +1 -0
  53. package/dist/types/IDidAuthSiopOpAuthenticator.js +10 -0
  54. package/dist/types/IDidAuthSiopOpAuthenticator.js.map +1 -0
  55. package/dist/types/error/index.d.ts +8 -0
  56. package/dist/types/error/index.d.ts.map +1 -0
  57. package/dist/types/error/index.js +3 -0
  58. package/dist/types/error/index.js.map +1 -0
  59. package/dist/types/identifier/index.d.ts +53 -0
  60. package/dist/types/identifier/index.d.ts.map +1 -0
  61. package/dist/types/identifier/index.js +5 -0
  62. package/dist/types/identifier/index.js.map +1 -0
  63. package/dist/types/index.d.ts +6 -0
  64. package/dist/types/index.d.ts.map +1 -0
  65. package/dist/types/index.js +22 -0
  66. package/dist/types/index.js.map +1 -0
  67. package/dist/types/machine/index.d.ts +124 -0
  68. package/dist/types/machine/index.d.ts.map +1 -0
  69. package/dist/types/machine/index.js +57 -0
  70. package/dist/types/machine/index.js.map +1 -0
  71. package/dist/types/siop-service/index.d.ts +80 -0
  72. package/dist/types/siop-service/index.d.ts.map +1 -0
  73. package/dist/types/siop-service/index.js +14 -0
  74. package/dist/types/siop-service/index.js.map +1 -0
  75. package/dist/utils/CredentialUtils.d.ts +23 -0
  76. package/dist/utils/CredentialUtils.d.ts.map +1 -0
  77. package/dist/utils/CredentialUtils.js +65 -0
  78. package/dist/utils/CredentialUtils.js.map +1 -0
  79. package/dist/utils/dcql.d.ts +5 -0
  80. package/dist/utils/dcql.d.ts.map +1 -0
  81. package/dist/utils/dcql.js +37 -0
  82. package/dist/utils/dcql.js.map +1 -0
  83. package/package.json +30 -41
  84. package/src/agent/DidAuthSiopOpAuthenticator.ts +14 -13
  85. package/src/session/OpSession.ts +13 -13
  86. package/dist/index.cjs +0 -2451
  87. package/dist/index.cjs.map +0 -1
  88. package/dist/index.d.cts +0 -559
package/dist/index.js CHANGED
@@ -1,2421 +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
- siopv2_machine_identifier_error_title: "Getting identifier",
13
- siopv2_machine_create_config_error_title: "Creating siopV2 config",
14
- siopv2_machine_get_request_error_title: "Getting siopV2 request",
15
- siopv2_machine_get_selectable_credentials_error_title: "Getting siopV2 selectable credentials",
16
- siopv2_machine_retrieve_contact_error_title: "Retrieve contact",
17
- siopv2_machine_add_contact_identity_error_title: "Add contact identity",
18
- siopv2_machine_send_response_error_title: "Sending siopV2 response"
19
- };
20
- }
21
- });
22
-
23
- // src/localization/translations/nl.json
24
- var require_nl = __commonJS({
25
- "src/localization/translations/nl.json"(exports, module) {
26
- module.exports = {
27
- siopv2_machine_identifier_error_title: "Identifier ophalen",
28
- siopv2_machine_create_config_error_title: "SiopV2 configuratie maken",
29
- siopv2_machine_get_request_error_title: "SiopV2 verzoek ophalen",
30
- siopv2_machine_retrieve_contact_error_title: "Ophalen credential",
31
- siopv2_machine_add_contact_identity_error_title: "Toevoegen identiteit contact",
32
- siopv2_machine_send_response_error_title: "SiopV2 antwoord verzenden"
33
- };
34
- }
35
- });
36
-
37
- // plugin.schema.json
38
- var require_plugin_schema = __commonJS({
39
- "plugin.schema.json"(exports, module) {
40
- module.exports = {
41
- IDidAuthSiopOpAuthenticator: {
42
- components: {
43
- schemas: {
44
- IGetSiopSessionArgs: {
45
- type: "object",
46
- properties: {
47
- sessionId: {
48
- type: "string"
49
- },
50
- additionalProperties: false
51
- },
52
- required: ["sessionId"],
53
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSessionForSiop } "
54
- },
55
- IRegisterSiopSessionArgs: {
56
- type: "object",
57
- properties: {
58
- identifier: {
59
- type: "object",
60
- properties: {
61
- did: {
62
- type: "string"
63
- },
64
- alias: {
65
- type: "string"
66
- },
67
- provider: {
68
- type: "string"
69
- },
70
- controllerKeyId: {
71
- type: "string"
72
- },
73
- keys: {
74
- type: "array",
75
- items: {
76
- type: "object",
77
- properties: {
78
- additionalProperties: true
79
- }
80
- }
81
- },
82
- services: {
83
- type: "array",
84
- items: {
85
- type: "object",
86
- properties: {
87
- additionalProperties: true
88
- }
89
- }
90
- }
91
- },
92
- additionalProperties: false,
93
- required: ["did", "provider", "keys", "services"]
94
- },
95
- sessionId: {
96
- type: "string"
97
- },
98
- expiresIn: {
99
- type: "number"
100
- },
101
- additionalProperties: false
102
- },
103
- required: ["identifier"],
104
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.registerSessionForSiop } "
105
- },
106
- IRemoveSiopSessionArgs: {
107
- type: "object",
108
- properties: {
109
- sessionId: {
110
- type: "string"
111
- },
112
- additionalProperties: false
113
- },
114
- required: ["sessionId"],
115
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.removeSessionForSiop } "
116
- },
117
- IAuthenticateWithSiopArgs: {
118
- type: "object",
119
- properties: {
120
- sessionId: {
121
- type: "string"
122
- },
123
- stateId: {
124
- type: "string"
125
- },
126
- redirectUrl: {
127
- type: "string"
128
- },
129
- additionalProperties: false
130
- },
131
- required: ["sessionId", "stateId", "redirectUrl"],
132
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.authenticateWithSiop } "
133
- },
134
- IResponse: {
135
- type: "object",
136
- properties: {
137
- status: {
138
- type: "number"
139
- },
140
- additionalProperties: true
141
- },
142
- required: ["status"],
143
- description: "Result of {@link DidAuthSiopOpAuthenticator.authenticateWithSiop & DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } "
144
- },
145
- IGetSiopAuthenticationRequestFromRpArgs: {
146
- type: "object",
147
- properties: {
148
- sessionId: {
149
- type: "string"
150
- },
151
- stateId: {
152
- type: "string"
153
- },
154
- redirectUrl: {
155
- type: "string"
156
- },
157
- additionalProperties: false
158
- },
159
- required: ["sessionId", "stateId", "redirectUrl"],
160
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } "
161
- },
162
- ParsedAuthenticationRequestURI: {
163
- type: "object",
164
- properties: {
165
- jwt: {
166
- type: "string"
167
- },
168
- requestPayload: {
169
- type: "object",
170
- properties: {
171
- additionalProperties: true
172
- }
173
- },
174
- registration: {
175
- type: "object",
176
- properties: {
177
- additionalProperties: true
178
- }
179
- },
180
- additionalProperties: false
181
- },
182
- required: ["jwt", "requestPayload", "registration"],
183
- description: "Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestFromRP } "
184
- },
185
- IGetSiopAuthenticationRequestDetailsArgs: {
186
- type: "object",
187
- properties: {
188
- sessionId: {
189
- type: "string"
190
- },
191
- verifiedAuthenticationRequest: {
192
- type: "object",
193
- properties: {
194
- additionalProperties: true
195
- }
196
- },
197
- credentialFilter: {
198
- type: "object",
199
- properties: {
200
- additionalProperties: true
201
- }
202
- },
203
- additionalProperties: false
204
- },
205
- required: ["sessionId", "verifiedAuthenticationRequest"],
206
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } "
207
- },
208
- IAuthRequestDetails: {
209
- type: "object",
210
- properties: {
211
- id: {
212
- type: "string"
213
- },
214
- alsoKnownAs: {
215
- type: "array",
216
- items: {
217
- type: "string"
218
- }
219
- },
220
- vpResponseOpts: {
221
- type: "object",
222
- properties: {
223
- additionalProperties: true
224
- }
225
- },
226
- additionalProperties: false
227
- },
228
- required: ["id", "vpResponseOpts"],
229
- description: "Result of {@link DidAuthSiopOpAuthenticator.getSiopAuthenticationRequestDetails } "
230
- },
231
- IVerifySiopAuthenticationRequestUriArgs: {
232
- type: "object",
233
- properties: {
234
- sessionId: {
235
- type: "string"
236
- },
237
- ParsedAuthenticationRequestURI: {
238
- type: "object",
239
- properties: {
240
- additionalProperties: true
241
- }
242
- },
243
- additionalProperties: false
244
- },
245
- required: ["sessionId", "ParsedAuthenticationRequestURI"],
246
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } "
247
- },
248
- VerifiedAuthorizationRequest: {
249
- type: "object",
250
- properties: {
251
- payload: {
252
- type: "object",
253
- properties: {
254
- additionalProperties: true
255
- }
256
- },
257
- presentationDefinitions: {
258
- type: "object",
259
- properties: {
260
- additionalProperties: true
261
- }
262
- },
263
- verifyOpts: {
264
- type: "object",
265
- properties: {
266
- additionalProperties: true
267
- }
268
- },
269
- additionalProperties: false
270
- },
271
- required: ["payload", "verifyOpts"],
272
- description: "Result of {@link DidAuthSiopOpAuthenticator.verifySiopAuthenticationRequestURI } "
273
- },
274
- ISendSiopAuthenticationResponseArgs: {
275
- type: "object",
276
- properties: {
277
- sessionId: {
278
- type: "string"
279
- },
280
- verifiedAuthenticationRequest: {
281
- type: "object",
282
- properties: {
283
- additionalProperties: true
284
- }
285
- },
286
- verifiablePresentationResponse: {
287
- type: "object",
288
- properties: {
289
- additionalProperties: true
290
- }
291
- },
292
- additionalProperties: false
293
- },
294
- required: ["sessionId", "verifiedAuthenticationRequest"],
295
- description: "Arguments needed for {@link DidAuthSiopOpAuthenticator.sendSiopAuthenticationResponse } "
296
- }
297
- },
298
- methods: {
299
- getSessionForSiop: {
300
- description: "Get SIOP session",
301
- arguments: {
302
- $ref: "#/components/schemas/IGetSiopSessionArgs"
303
- },
304
- returnType: "object"
305
- },
306
- registerSessionForSiop: {
307
- description: "Register SIOP session",
308
- arguments: {
309
- $ref: "#/components/schemas/IRegisterSiopSessionArgs"
310
- },
311
- returnType: "object"
312
- },
313
- removeSessionForSiop: {
314
- description: "Remove SIOP session",
315
- arguments: {
316
- $ref: "#/components/schemas/IRemoveSiopSessionArgs"
317
- },
318
- returnType: "boolean"
319
- },
320
- authenticateWithSiop: {
321
- description: "Authenticate using DID Auth SIOP",
322
- arguments: {
323
- $ref: "#/components/schemas/IAuthenticateWithSiopArgs"
324
- },
325
- returnType: {
326
- $ref: "#/components/schemas/Response"
327
- }
328
- },
329
- getSiopAuthenticationRequestFromRP: {
330
- description: "Get authentication request from RP",
331
- arguments: {
332
- $ref: "#/components/schemas/IGetSiopAuthenticationRequestFromRpArgs"
333
- },
334
- returnType: {
335
- $ref: "#/components/schemas/ParsedAuthenticationRequestURI"
336
- }
337
- },
338
- getSiopAuthenticationRequestDetails: {
339
- description: "Get authentication request details",
340
- arguments: {
341
- $ref: "#/components/schemas/IGetSiopAuthenticationRequestDetailsArgs"
342
- },
343
- returnType: {
344
- $ref: "#/components/schemas/IAuthRequestDetails"
345
- }
346
- },
347
- verifySiopAuthenticationRequestURI: {
348
- description: "Verify authentication request URI",
349
- arguments: {
350
- $ref: "#/components/schemas/IVerifySiopAuthenticationRequestUriArgs"
351
- },
352
- returnType: {
353
- $ref: "#/components/schemas/VerifiedAuthorizationRequest"
354
- }
355
- },
356
- sendSiopAuthenticationResponse: {
357
- description: "Send authentication response",
358
- arguments: {
359
- $ref: "#/components/schemas/ISendSiopAuthenticationResponseArgs"
360
- },
361
- returnType: {
362
- $ref: "#/components/schemas/IRequiredContext"
363
- }
364
- }
365
- }
366
- }
367
- }
368
- };
369
- }
370
- });
371
-
372
- // src/agent/DidAuthSiopOpAuthenticator.ts
373
- import { decodeUriAsJson, SupportedVersion as SupportedVersion3 } from "@sphereon/did-auth-siop";
374
- import { ConnectionType as ConnectionType2, CorrelationIdentifierType, CredentialDocumentFormat, CredentialRole as CredentialRole2, DocumentType, IdentityOrigin } from "@sphereon/ssi-sdk.data-store";
375
- import { Loggers as Loggers4 } from "@sphereon/ssi-types";
376
- import { v4 as uuidv4 } from "uuid";
377
-
378
- // src/session/functions.ts
379
- import { OP, PassBy, ResponseMode, SupportedVersion } from "@sphereon/did-auth-siop";
380
- import { SigningAlgo } from "@sphereon/oid4vc-common";
381
- import { isManagedIdentifierDidOpts, isManagedIdentifierX5cOpts } from "@sphereon/ssi-sdk-ext.identifier-resolution";
382
- import { createPEXPresentationSignCallback } from "@sphereon/ssi-sdk.presentation-exchange";
383
- import { EventEmitter } from "events";
384
- async function createOID4VPPresentationSignCallback({ presentationSignCallback, idOpts: idOpts1, domain, fetchRemoteContexts, challenge, format, context, skipDidResolution }) {
385
- if (typeof presentationSignCallback === "function") {
386
- return presentationSignCallback;
387
- }
388
- return createPEXPresentationSignCallback({
389
- idOpts: idOpts1,
390
- fetchRemoteContexts,
391
- domain,
392
- challenge,
393
- format,
394
- skipDidResolution
395
- }, context);
396
- }
397
- __name(createOID4VPPresentationSignCallback, "createOID4VPPresentationSignCallback");
398
- async function createOPBuilder({ opOptions, idOpts: idOpts1, context }) {
399
- const eventEmitter = opOptions.eventEmitter ?? new EventEmitter();
400
- const builder = OP.builder().withResponseMode(opOptions.responseMode ?? ResponseMode.DIRECT_POST).withSupportedVersions(opOptions.supportedVersions ?? [
401
- SupportedVersion.SIOPv2_ID1,
402
- SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1,
403
- SupportedVersion.SIOPv2_D11,
404
- SupportedVersion.SIOPv2_D12_OID4VP_D18
405
- ]).withExpiresIn(opOptions.expiresIn ?? 300).withEventEmitter(eventEmitter).withRegistration({
406
- passBy: PassBy.VALUE
407
- });
408
- const wellknownDIDVerifyCallback = opOptions.wellknownDIDVerifyCallback ? opOptions.wellknownDIDVerifyCallback : async (args) => {
409
- const result = await context.agent.cvVerifyCredential({
410
- credential: args.credential,
411
- fetchRemoteContexts: true
412
- });
413
- return {
414
- verified: result.result
415
- };
416
- };
417
- builder.withVerifyJwtCallback(opOptions.verifyJwtCallback ? opOptions.verifyJwtCallback : getVerifyJwtCallback({
418
- verifyOpts: {
419
- wellknownDIDVerifyCallback,
420
- checkLinkedDomain: "if_present"
421
- }
422
- }, context));
423
- if (idOpts1) {
424
- if (opOptions.skipDidResolution && isManagedIdentifierDidOpts(idOpts1)) {
425
- idOpts1.offlineWhenNoDIDRegistered = true;
426
- }
427
- const createJwtCallback = createJwtCallbackWithIdOpts(idOpts1, context);
428
- builder.withCreateJwtCallback(createJwtCallback);
429
- builder.withPresentationSignCallback(await createOID4VPPresentationSignCallback({
430
- presentationSignCallback: opOptions.presentationSignCallback,
431
- skipDidResolution: opOptions.skipDidResolution ?? false,
432
- idOpts: idOpts1,
433
- context
434
- }));
435
- } else {
436
- const createJwtCallback = createJwtCallbackWithOpOpts(opOptions, context);
437
- builder.withCreateJwtCallback(createJwtCallback);
438
- }
439
- return builder;
440
- }
441
- __name(createOPBuilder, "createOPBuilder");
442
- function createJwtCallbackWithIdOpts(idOpts1, context) {
443
- return async (jwtIssuer, jwt) => {
444
- let issuer;
445
- if (isManagedIdentifierDidOpts(idOpts1)) {
446
- issuer = {
447
- ...idOpts1,
448
- method: idOpts1.method,
449
- noIdentifierInHeader: false
450
- };
451
- } else if (isManagedIdentifierX5cOpts(idOpts1)) {
452
- issuer = {
453
- ...idOpts1,
454
- method: idOpts1.method,
455
- noIdentifierInHeader: false
456
- };
457
- } else {
458
- return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
459
- }
460
- const result = await context.agent.jwtCreateJwsCompactSignature({
461
- issuer,
462
- protectedHeader: jwt.header,
463
- payload: jwt.payload
464
- });
465
- return result.jwt;
466
- };
467
- }
468
- __name(createJwtCallbackWithIdOpts, "createJwtCallbackWithIdOpts");
469
- function createJwtCallbackWithOpOpts(opOpts, context) {
470
- return async (jwtIssuer, jwt) => {
471
- let identifier;
472
- if (jwtIssuer.method == "did") {
473
- identifier = jwtIssuer.didUrl;
474
- } else if (jwtIssuer.method == "x5c") {
475
- identifier = jwtIssuer.x5c;
476
- } else {
477
- return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
478
- }
479
- const result = await context.agent.jwtCreateJwsCompactSignature({
480
- // FIXME fix cose-key inference
481
- // @ts-ignore
482
- issuer: {
483
- identifier,
484
- kmsKeyRef: idOpts.kmsKeyRef,
485
- noIdentifierInHeader: false
486
- },
487
- // FIXME fix JWK key_ops
488
- // @ts-ignore
489
- protectedHeader: jwt.header,
490
- payload: jwt.payload
491
- });
492
- return result.jwt;
493
- };
494
- }
495
- __name(createJwtCallbackWithOpOpts, "createJwtCallbackWithOpOpts");
496
- function getVerifyJwtCallback(_opts, context) {
497
- return async (_jwtVerifier, jwt) => {
498
- const result = await context.agent.jwtVerifyJwsSignature({
499
- jws: jwt.raw
500
- });
501
- console.log(result.message);
502
- return !result.error;
503
- };
504
- }
505
- __name(getVerifyJwtCallback, "getVerifyJwtCallback");
506
- async function createOP({ opOptions, idOpts: idOpts1, context }) {
507
- return (await createOPBuilder({
508
- opOptions,
509
- idOpts: idOpts1,
510
- context
511
- })).build();
512
- }
513
- __name(createOP, "createOP");
514
- function getSigningAlgo(type) {
515
- switch (type) {
516
- case "Ed25519":
517
- return SigningAlgo.EDDSA;
518
- case "Secp256k1":
519
- return SigningAlgo.ES256K;
520
- case "Secp256r1":
521
- return SigningAlgo.ES256;
522
- // @ts-ignore
523
- case "RSA":
524
- return SigningAlgo.RS256;
525
- default:
526
- throw Error("Key type not yet supported");
527
- }
528
- }
529
- __name(getSigningAlgo, "getSigningAlgo");
530
-
531
- // src/session/OID4VP.ts
532
- import { PresentationExchange } from "@sphereon/did-auth-siop";
533
- import { Status } from "@sphereon/pex";
534
- import { isManagedIdentifierDidResult, isOID4VCIssuerIdentifier } from "@sphereon/ssi-sdk-ext.identifier-resolution";
535
- import { defaultHasher } from "@sphereon/ssi-sdk.core";
536
- import { verifiableCredentialForRoleFilter } from "@sphereon/ssi-sdk.credential-store";
537
-
538
- // src/types/IDidAuthSiopOpAuthenticator.ts
539
- var LOGGER_NAMESPACE = "sphereon:siopv2-oid4vp:op-auth";
540
- var events = /* @__PURE__ */ function(events2) {
541
- events2["DID_SIOP_AUTHENTICATED"] = "didSiopAuthenticated";
542
- return events2;
543
- }({});
544
- var DEFAULT_JWT_PROOF_TYPE = "JwtProof2020";
545
-
546
- // src/types/siop-service/index.ts
547
- var Siopv2HolderEvent = /* @__PURE__ */ function(Siopv2HolderEvent2) {
548
- Siopv2HolderEvent2["CONTACT_IDENTITY_CREATED"] = "contact_identity_created";
549
- Siopv2HolderEvent2["IDENTIFIER_CREATED"] = "identifier_created";
550
- return Siopv2HolderEvent2;
551
- }({});
552
- var SupportedLanguage = /* @__PURE__ */ function(SupportedLanguage2) {
553
- SupportedLanguage2["ENGLISH"] = "en";
554
- SupportedLanguage2["DUTCH"] = "nl";
555
- return SupportedLanguage2;
556
- }({});
557
-
558
- // src/types/machine/index.ts
559
- var Siopv2MachineStates = /* @__PURE__ */ function(Siopv2MachineStates2) {
560
- Siopv2MachineStates2["createConfig"] = "createConfig";
561
- Siopv2MachineStates2["getSiopRequest"] = "getSiopRequest";
562
- Siopv2MachineStates2["getSelectableCredentials"] = "getSelectableCredentials";
563
- Siopv2MachineStates2["retrieveContact"] = "retrieveContact";
564
- Siopv2MachineStates2["transitionFromSetup"] = "transitionFromSetup";
565
- Siopv2MachineStates2["addContact"] = "addContact";
566
- Siopv2MachineStates2["addContactIdentity"] = "addContactIdentity";
567
- Siopv2MachineStates2["selectCredentials"] = "selectCredentials";
568
- Siopv2MachineStates2["sendResponse"] = "sendResponse";
569
- Siopv2MachineStates2["handleError"] = "handleError";
570
- Siopv2MachineStates2["aborted"] = "aborted";
571
- Siopv2MachineStates2["declined"] = "declined";
572
- Siopv2MachineStates2["error"] = "error";
573
- Siopv2MachineStates2["done"] = "done";
574
- return Siopv2MachineStates2;
575
- }({});
576
- var Siopv2MachineAddContactStates = /* @__PURE__ */ function(Siopv2MachineAddContactStates2) {
577
- Siopv2MachineAddContactStates2["idle"] = "idle";
578
- Siopv2MachineAddContactStates2["executing"] = "executing";
579
- Siopv2MachineAddContactStates2["next"] = "next";
580
- return Siopv2MachineAddContactStates2;
581
- }({});
582
- var Siopv2MachineEvents = /* @__PURE__ */ function(Siopv2MachineEvents2) {
583
- Siopv2MachineEvents2["NEXT"] = "NEXT";
584
- Siopv2MachineEvents2["PREVIOUS"] = "PREVIOUS";
585
- Siopv2MachineEvents2["DECLINE"] = "DECLINE";
586
- Siopv2MachineEvents2["SET_CONTACT_ALIAS"] = "SET_CONTACT_ALIAS";
587
- Siopv2MachineEvents2["SET_CONTACT_CONSENT"] = "SET_CONTACT_CONSENT";
588
- Siopv2MachineEvents2["CREATE_CONTACT"] = "CREATE_CONTACT";
589
- Siopv2MachineEvents2["SET_SELECTED_CREDENTIALS"] = "SET_SELECTED_CREDENTIALS";
590
- return Siopv2MachineEvents2;
591
- }({});
592
- var Siopv2MachineGuards = /* @__PURE__ */ function(Siopv2MachineGuards2) {
593
- Siopv2MachineGuards2["hasNoContactGuard"] = "Siopv2HasNoContactGuard";
594
- Siopv2MachineGuards2["createContactGuard"] = "Siopv2CreateContactGuard";
595
- Siopv2MachineGuards2["hasContactGuard"] = "Siopv2HasContactGuard";
596
- Siopv2MachineGuards2["hasAuthorizationRequestGuard"] = "Siopv2HasAuthorizationRequestGuard";
597
- Siopv2MachineGuards2["hasSelectableCredentialsAndContactGuard"] = "Siopv2HasSelectableCredentialsAndContactGuard";
598
- Siopv2MachineGuards2["hasSelectedRequiredCredentialsGuard"] = "Siopv2HasSelectedRequiredCredentialsGuard";
599
- Siopv2MachineGuards2["siopOnlyGuard"] = "Siopv2IsSiopOnlyGuard";
600
- Siopv2MachineGuards2["siopWithOID4VPGuard"] = "Siopv2IsSiopWithOID4VPGuard";
601
- return Siopv2MachineGuards2;
602
- }({});
603
- var Siopv2MachineServices = /* @__PURE__ */ function(Siopv2MachineServices2) {
604
- Siopv2MachineServices2["getSiopRequest"] = "getSiopRequest";
605
- Siopv2MachineServices2["getSelectableCredentials"] = "getSelectableCredentials";
606
- Siopv2MachineServices2["retrieveContact"] = "retrieveContact";
607
- Siopv2MachineServices2["addContactIdentity"] = "addContactIdentity";
608
- Siopv2MachineServices2["sendResponse"] = "sendResponse";
609
- Siopv2MachineServices2["createConfig"] = "createConfig";
610
- return Siopv2MachineServices2;
611
- }({});
612
-
613
- // src/types/identifier/index.ts
614
- var DID_PREFIX = "did";
615
-
616
- // src/session/OID4VP.ts
617
- var OID4VP = class _OID4VP {
618
- static {
619
- __name(this, "OID4VP");
620
- }
621
- session;
622
- allIdentifiers;
623
- hasher;
624
- constructor(args) {
625
- const { session, allIdentifiers, hasher = defaultHasher } = args;
626
- this.session = session;
627
- this.allIdentifiers = allIdentifiers ?? [];
628
- this.hasher = hasher;
629
- }
630
- static async init(session, allIdentifiers, hasher) {
631
- return new _OID4VP({
632
- session,
633
- allIdentifiers: allIdentifiers ?? await session.getSupportedDIDs(),
634
- hasher
635
- });
636
- }
637
- async getPresentationDefinitions() {
638
- const definitions = await this.session.getPresentationDefinitions();
639
- if (definitions) {
640
- PresentationExchange.assertValidPresentationDefinitionWithLocations(definitions);
641
- }
642
- return definitions;
643
- }
644
- getPresentationExchange(args) {
645
- const { verifiableCredentials, allIdentifiers, hasher } = args;
646
- return new PresentationExchange({
647
- allDIDs: allIdentifiers ?? this.allIdentifiers,
648
- allVerifiableCredentials: verifiableCredentials,
649
- hasher: hasher ?? this.hasher
650
- });
651
- }
652
- async createVerifiablePresentations(credentialRole, credentialsWithDefinitions, opts) {
653
- return await Promise.all(credentialsWithDefinitions.map((cred) => this.createVerifiablePresentation(credentialRole, cred, opts)));
654
- }
655
- async createVerifiablePresentation(credentialRole, selectedVerifiableCredentials, opts) {
656
- const { subjectIsHolder, holder, forceNoCredentialsInVP = false } = {
657
- ...opts
658
- };
659
- if (subjectIsHolder && holder) {
660
- throw Error("Cannot both have subject is holder and a holderDID value at the same time (programming error)");
661
- }
662
- if (forceNoCredentialsInVP) {
663
- selectedVerifiableCredentials.credentials = [];
664
- } else if (!selectedVerifiableCredentials?.credentials || selectedVerifiableCredentials.credentials.length === 0) {
665
- throw Error("No verifiable verifiableCredentials provided for presentation definition");
666
- }
667
- const proofOptions = {
668
- ...opts?.proofOpts,
669
- challenge: opts?.proofOpts?.nonce ?? opts?.proofOpts?.challenge ?? this.session.nonce,
670
- domain: opts?.proofOpts?.domain ?? await this.session.getRedirectUri()
671
- };
672
- let idOpts2 = opts?.idOpts;
673
- if (!idOpts2) {
674
- if (opts?.subjectIsHolder) {
675
- if (forceNoCredentialsInVP) {
676
- return Promise.reject(Error(`Cannot have subject is holder, when force no credentials is being used, as we could never determine the holder then. Please provide holderDID`));
677
- }
678
- const firstUniqueDC = selectedVerifiableCredentials.credentials[0];
679
- if (typeof firstUniqueDC !== "object" || !("digitalCredential" in firstUniqueDC)) {
680
- return Promise.reject(Error("If no opts provided, credentials should be of type UniqueDigitalCredential"));
681
- }
682
- idOpts2 = isOID4VCIssuerIdentifier(firstUniqueDC.digitalCredential.kmsKeyRef) ? await this.session.context.agent.identifierManagedGetByIssuer({
683
- identifier: firstUniqueDC.digitalCredential.kmsKeyRef
684
- }) : await this.session.context.agent.identifierManagedGetByKid({
685
- identifier: firstUniqueDC.digitalCredential.kmsKeyRef,
686
- kmsKeyRef: firstUniqueDC.digitalCredential.kmsKeyRef
687
- });
688
- } else if (opts?.holder) {
689
- idOpts2 = {
690
- identifier: opts.holder
691
- };
692
- }
693
- }
694
- const vcs = forceNoCredentialsInVP ? selectedVerifiableCredentials : opts?.applyFilter ? await this.filterCredentials(credentialRole, selectedVerifiableCredentials.definition, {
695
- restrictToFormats: opts?.restrictToFormats,
696
- restrictToDIDMethods: opts?.restrictToDIDMethods,
697
- filterOpts: {
698
- verifiableCredentials: selectedVerifiableCredentials.credentials
699
- }
700
- }) : {
701
- definition: selectedVerifiableCredentials.definition,
702
- credentials: selectedVerifiableCredentials.credentials
703
- };
704
- if (!idOpts2) {
705
- return Promise.reject(Error(`No identifier options present at this point`));
706
- }
707
- const signCallback = await createOID4VPPresentationSignCallback({
708
- presentationSignCallback: this.session.options.presentationSignCallback,
709
- idOpts: idOpts2,
710
- context: this.session.context,
711
- domain: proofOptions.domain,
712
- challenge: proofOptions.challenge,
713
- format: opts?.restrictToFormats ?? selectedVerifiableCredentials.definition.definition.format,
714
- skipDidResolution: opts?.skipDidResolution ?? false
715
- });
716
- const identifier = await this.session.context.agent.identifierManagedGet(idOpts2);
717
- const verifiableCredentials = vcs.credentials.map((credential) => typeof credential === "object" && "digitalCredential" in credential ? credential.originalVerifiableCredential : credential);
718
- const presentationResult = await this.getPresentationExchange({
719
- verifiableCredentials,
720
- allIdentifiers: this.allIdentifiers,
721
- hasher: opts?.hasher
722
- }).createVerifiablePresentation(vcs.definition.definition, verifiableCredentials, signCallback, {
723
- proofOptions,
724
- // fixme: Update to newer siop-vp to not require dids here. But when Veramo is creating the VP it's still looking at this field to pass into didManagerGet
725
- ...identifier && isManagedIdentifierDidResult(identifier) && {
726
- holderDID: identifier.did
727
- }
728
- });
729
- const verifiablePresentations = presentationResult.verifiablePresentations.map((verifiablePresentation) => typeof verifiablePresentation !== "string" && "proof" in verifiablePresentation && "jwt" in verifiablePresentation.proof && verifiablePresentation.proof.jwt ? verifiablePresentation.proof.jwt : verifiablePresentation);
730
- return {
731
- ...presentationResult,
732
- verifiablePresentations,
733
- verifiableCredentials,
734
- definition: selectedVerifiableCredentials.definition,
735
- idOpts: idOpts2
736
- };
737
- }
738
- async filterCredentialsAgainstAllDefinitions(credentialRole, opts) {
739
- const defs = await this.getPresentationDefinitions();
740
- const result = [];
741
- if (defs) {
742
- for (const definition of defs) {
743
- result.push(await this.filterCredentials(credentialRole, definition, opts));
744
- }
745
- }
746
- return result;
747
- }
748
- async filterCredentials(credentialRole, presentationDefinition, opts) {
749
- const udcMap = /* @__PURE__ */ new Map();
750
- opts?.filterOpts?.verifiableCredentials?.forEach((credential) => {
751
- if (typeof credential === "object" && "digitalCredential" in credential) {
752
- udcMap.set(credential.originalVerifiableCredential, credential);
753
- } else {
754
- udcMap.set(credential, credential);
755
- }
756
- });
757
- const credentials = (await this.filterCredentialsWithSelectionStatus(credentialRole, presentationDefinition, {
758
- ...opts,
759
- filterOpts: {
760
- verifiableCredentials: opts?.filterOpts?.verifiableCredentials?.map((credential) => {
761
- if (typeof credential === "object" && "digitalCredential" in credential) {
762
- return credential.originalVerifiableCredential;
763
- } else {
764
- return credential;
765
- }
766
- })
767
- }
768
- })).verifiableCredential;
769
- return {
770
- definition: presentationDefinition,
771
- credentials: credentials?.map((vc) => udcMap.get(vc)) ?? []
772
- };
773
- }
774
- async filterCredentialsWithSelectionStatus(credentialRole, presentationDefinition, opts) {
775
- const selectionResults = await this.getPresentationExchange({
776
- verifiableCredentials: await this.getCredentials(credentialRole, opts?.filterOpts)
777
- }).selectVerifiableCredentialsForSubmission(presentationDefinition.definition, opts);
778
- if (selectionResults.errors && selectionResults.errors.length > 0) {
779
- throw Error(JSON.stringify(selectionResults.errors));
780
- } else if (selectionResults.areRequiredCredentialsPresent === Status.ERROR) {
781
- throw Error(`Not all required credentials are available to satisfy the relying party's request`);
782
- }
783
- const matches = selectionResults.matches;
784
- if (!matches || matches.length === 0 || !selectionResults.verifiableCredential || selectionResults.verifiableCredential.length === 0) {
785
- throw Error(JSON.stringify(selectionResults.errors));
786
- }
787
- return selectionResults;
788
- }
789
- async getCredentials(credentialRole, filterOpts) {
790
- if (filterOpts?.verifiableCredentials && filterOpts.verifiableCredentials.length > 0) {
791
- return filterOpts.verifiableCredentials;
792
- }
793
- const filter = verifiableCredentialForRoleFilter(credentialRole, filterOpts?.filter);
794
- const uniqueCredentials = await this.session.context.agent.crsGetUniqueCredentials({
795
- filter
796
- });
797
- return uniqueCredentials.map((uniqueVC) => {
798
- const vc = uniqueVC.uniformVerifiableCredential;
799
- const proof = Array.isArray(vc.proof) ? vc.proof : [
800
- vc.proof
801
- ];
802
- const jwtProof = proof.find((p) => p?.type === DEFAULT_JWT_PROOF_TYPE);
803
- return jwtProof ? jwtProof.jwt : vc;
804
- });
805
- }
806
- };
807
-
808
- // src/session/OpSession.ts
809
- import { OP as OP2, URI } from "@sphereon/did-auth-siop";
810
- import { getAgentDIDMethods, getAgentResolver } from "@sphereon/ssi-sdk-ext.did-utils";
811
- import { encodeBase64url } from "@sphereon/ssi-sdk.core";
812
- import { CredentialMapper, parseDid } from "@sphereon/ssi-types";
813
- import { v4 } from "uuid";
814
- import { PEX } from "@sphereon/pex";
815
- import { Loggers } from "@sphereon/ssi-types";
816
- var logger = Loggers.DEFAULT.get("sphereon:oid4vp:OpSession");
817
- var OpSession = class _OpSession {
818
- static {
819
- __name(this, "OpSession");
820
- }
821
- ts = (/* @__PURE__ */ new Date()).getDate();
822
- id;
823
- options;
824
- context;
825
- requestJwtOrUri;
826
- verifiedAuthorizationRequest;
827
- _nonce;
828
- _state;
829
- _providedPresentationDefinitions;
830
- constructor(options) {
831
- this.id = options.sessionId;
832
- this.options = options.op;
833
- this.context = options.context;
834
- this.requestJwtOrUri = options.requestJwtOrUri;
835
- this._providedPresentationDefinitions = options.providedPresentationDefinitions;
836
- }
837
- static async init(options) {
838
- return new _OpSession(options);
839
- }
840
- async getAuthorizationRequest() {
841
- if (!this.verifiedAuthorizationRequest) {
842
- const op = await createOP({
843
- opOptions: this.options,
844
- context: this.context
845
- });
846
- this.verifiedAuthorizationRequest = await op.verifyAuthorizationRequest(this.requestJwtOrUri);
847
- this._nonce = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("nonce");
848
- this._state = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("state");
849
- await this.getSupportedDIDMethods();
850
- }
851
- return this.verifiedAuthorizationRequest;
852
- }
853
- async getAuthorizationRequestURI() {
854
- return await URI.fromAuthorizationRequest((await this.getAuthorizationRequest()).authorizationRequest);
855
- }
856
- get nonce() {
857
- if (!this._nonce) {
858
- throw Error("No nonce available. Please get authorization request first");
859
- }
860
- return this._nonce;
861
- }
862
- get state() {
863
- if (!this._state) {
864
- throw Error("No state available. Please get authorization request first");
865
- }
866
- return this._state;
867
- }
868
- clear() {
869
- this._nonce = void 0;
870
- this._state = void 0;
871
- this.verifiedAuthorizationRequest = void 0;
872
- return this;
873
- }
874
- async getSupportedDIDMethods(didPrefix) {
875
- const agentMethods = this.getAgentDIDMethodsSupported({
876
- didPrefix
877
- });
878
- let rpMethods = await this.getRPDIDMethodsSupported({
879
- didPrefix,
880
- agentMethods
881
- });
882
- logger.debug(`RP supports subject syntax types: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
883
- if (rpMethods.dids.length === 0) {
884
- logger.debug(`RP does not support DIDs. Supported: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
885
- return [];
886
- }
887
- let intersection;
888
- if (rpMethods.dids.includes("did")) {
889
- intersection = agentMethods && agentMethods.length > 0 ? agentMethods : (await getAgentDIDMethods(this.context)).map((method) => convertDidMethod(method, didPrefix));
890
- } else if (!agentMethods || agentMethods.length === 0) {
891
- intersection = rpMethods.dids?.map((method) => convertDidMethod(method, didPrefix));
892
- } else {
893
- intersection = agentMethods.filter((value) => rpMethods.dids.includes(value));
894
- }
895
- if (intersection.length === 0) {
896
- throw Error("No matching DID methods between agent and relying party");
897
- }
898
- return intersection.map((value) => convertDidMethod(value, didPrefix));
899
- }
900
- getAgentDIDMethodsSupported(opts) {
901
- const agentMethods = this.options.supportedDIDMethods?.map((method) => convertDidMethod(method, opts.didPrefix));
902
- logger.debug(`agent methods: ${JSON.stringify(agentMethods)}`);
903
- return agentMethods;
904
- }
905
- async getSubjectSyntaxTypesSupported() {
906
- const authReq = await this.getAuthorizationRequest();
907
- const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported;
908
- return subjectSyntaxTypesSupported ?? [];
909
- }
910
- async getRPDIDMethodsSupported(opts) {
911
- let keyType;
912
- const agentMethods = (opts.agentMethods ?? this.getAgentDIDMethodsSupported(opts))?.map((method) => convertDidMethod(method, opts.didPrefix)) ?? [];
913
- logger.debug(`agent methods supported: ${JSON.stringify(agentMethods)}`);
914
- const authReq = await this.getAuthorizationRequest();
915
- const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported?.map((method) => convertDidMethod(method, opts.didPrefix)).filter((val) => !val.startsWith("did"));
916
- logger.debug(`subject syntax types supported in rp method supported: ${JSON.stringify(subjectSyntaxTypesSupported)}`);
917
- const aud = await authReq.authorizationRequest.getMergedProperty("aud");
918
- let rpMethods = [];
919
- if (aud && aud.startsWith("did:")) {
920
- const didMethod = convertDidMethod(parseDid(aud).method, opts.didPrefix);
921
- logger.debug(`aud did method: ${didMethod}`);
922
- if (subjectSyntaxTypesSupported && subjectSyntaxTypesSupported.length > 0 && !subjectSyntaxTypesSupported.includes("did") && !subjectSyntaxTypesSupported.includes(didMethod)) {
923
- throw Error(`The aud DID method ${didMethod} is not in the supported types ${subjectSyntaxTypesSupported}`);
924
- }
925
- rpMethods = [
926
- didMethod
927
- ];
928
- } else if (subjectSyntaxTypesSupported) {
929
- rpMethods = (Array.isArray(subjectSyntaxTypesSupported) ? subjectSyntaxTypesSupported : [
930
- subjectSyntaxTypesSupported
931
- ]).map((method) => convertDidMethod(method, opts.didPrefix));
932
- }
933
- const isEBSI = rpMethods.length === 0 && (authReq.issuer?.includes(".ebsi.eu") || (await authReq.authorizationRequest.getMergedProperty("client_id"))?.includes(".ebsi.eu"));
934
- let codecName = void 0;
935
- if (isEBSI && (!aud || !aud.startsWith("http"))) {
936
- logger.debug(`EBSI detected, adding did:key to supported DID methods for RP`);
937
- const didKeyMethod = convertDidMethod("did:key", opts.didPrefix);
938
- if (!agentMethods?.includes(didKeyMethod)) {
939
- throw Error(`EBSI detected, but agent did not support did:key. Please reconfigure agent`);
940
- }
941
- rpMethods = [
942
- didKeyMethod
943
- ];
944
- keyType = "Secp256r1";
945
- codecName = "jwk_jcs-pub";
946
- }
947
- return {
948
- dids: rpMethods,
949
- codecName,
950
- keyType
951
- };
952
- }
953
- async getSupportedIdentifiers(opts) {
954
- const methods = await this.getSupportedDIDMethods(true);
955
- logger.debug(`supported DID methods (did: prefix = true): ${JSON.stringify(methods)}`);
956
- if (methods.length === 0) {
957
- throw Error(`No DID methods are supported`);
958
- }
959
- const identifiers = await this.context.agent.didManagerFind().then((ids) => ids.filter((id) => methods.includes(id.provider)));
960
- if (identifiers.length === 0) {
961
- logger.debug(`No identifiers available in agent supporting methods ${JSON.stringify(methods)}`);
962
- if (opts?.createInCaseNoDIDFound !== false) {
963
- const { codecName, keyType } = await this.getRPDIDMethodsSupported({
964
- didPrefix: true,
965
- agentMethods: methods
966
- });
967
- const identifier = await this.context.agent.didManagerCreate({
968
- provider: methods[0],
969
- options: {
970
- codecName,
971
- keyType,
972
- type: keyType
973
- }
974
- });
975
- logger.debug(`Created a new identifier for the SIOP interaction: ${identifier.did}`);
976
- identifiers.push(identifier);
977
- }
978
- }
979
- logger.debug(`supported identifiers: ${JSON.stringify(identifiers.map((id) => id.did))}`);
980
- return identifiers;
981
- }
982
- async getSupportedDIDs() {
983
- return (await this.getSupportedIdentifiers()).map((id) => id.did);
984
- }
985
- async getRedirectUri() {
986
- return Promise.resolve(this.verifiedAuthorizationRequest.responseURI);
987
- }
988
- async hasPresentationDefinitions() {
989
- const defs = this._providedPresentationDefinitions ?? (await this.getAuthorizationRequest()).presentationDefinitions;
990
- return defs !== void 0 && defs.length > 0;
991
- }
992
- async getPresentationDefinitions() {
993
- if (!await this.hasPresentationDefinitions()) {
994
- throw Error(`No presentation definitions found`);
995
- }
996
- return this._providedPresentationDefinitions ?? (await this.getAuthorizationRequest()).presentationDefinitions;
997
- }
998
- async getOID4VP(args) {
999
- return await OID4VP.init(this, args.allIdentifiers ?? [], args.hasher);
1000
- }
1001
- createPresentationVerificationCallback(context) {
1002
- async function presentationVerificationCallback(args, presentationSubmission) {
1003
- let result;
1004
- if (CredentialMapper.isSdJwtEncoded(args)) {
1005
- try {
1006
- const sdJwtResult = await context.agent.verifySdJwtPresentation({
1007
- presentation: args
1008
- });
1009
- result = {
1010
- verified: "header" in sdJwtResult,
1011
- error: "header" in sdJwtResult ? void 0 : {
1012
- message: "could not verify SD JWT presentation"
1013
- }
1014
- };
1015
- } catch (error) {
1016
- result = {
1017
- verified: false,
1018
- error: {
1019
- message: error.message
1020
- }
1021
- };
1022
- }
1023
- } else {
1024
- result = await context.agent.verifyPresentation({
1025
- presentation: args
1026
- });
1027
- }
1028
- return result;
1029
- }
1030
- __name(presentationVerificationCallback, "presentationVerificationCallback");
1031
- return presentationVerificationCallback;
1032
- }
1033
- async createJarmResponseCallback({ responseOpts }) {
1034
- const agent = this.context.agent;
1035
- return /* @__PURE__ */ __name(async function jarmResponse(opts) {
1036
- const { clientMetadata, requestObjectPayload, authorizationResponsePayload: authResponse } = opts;
1037
- const jwk = await OP2.extractEncJwksFromClientMetadata(clientMetadata);
1038
- const recipientKey = await agent.identifierExternalResolveByJwk({
1039
- identifier: jwk
1040
- });
1041
- return await agent.jwtEncryptJweCompactJwt({
1042
- recipientKey,
1043
- protectedHeader: {},
1044
- alg: requestObjectPayload.client_metadata.authorization_encrypted_response_alg ?? "ECDH-ES",
1045
- enc: requestObjectPayload.client_metadata.authorization_encrypted_response_enc ?? "A256GCM",
1046
- apv: encodeBase64url(opts.requestObjectPayload.nonce),
1047
- apu: encodeBase64url(v4()),
1048
- payload: authResponse,
1049
- issuer: responseOpts.issuer,
1050
- audience: responseOpts.audience
1051
- }).then((result) => {
1052
- return {
1053
- response: result.jwt
1054
- };
1055
- });
1056
- }, "jarmResponse");
1057
- }
1058
- async sendAuthorizationResponse(args) {
1059
- const resolveOpts = this.options.resolveOpts ?? {
1060
- resolver: getAgentResolver(this.context, {
1061
- uniresolverResolution: true,
1062
- localResolution: true,
1063
- resolverResolution: true
1064
- })
1065
- };
1066
- if (!resolveOpts.subjectSyntaxTypesSupported || resolveOpts.subjectSyntaxTypesSupported.length === 0) {
1067
- resolveOpts.subjectSyntaxTypesSupported = await this.getSupportedDIDMethods(true);
1068
- }
1069
- const verification = {
1070
- presentationVerificationCallback: this.createPresentationVerificationCallback(this.context)
1071
- };
1072
- const request = await this.getAuthorizationRequest();
1073
- const hasDefinitions = await this.hasPresentationDefinitions();
1074
- if (hasDefinitions) {
1075
- const totalInputDescriptors = request.presentationDefinitions?.reduce((sum, pd) => {
1076
- return sum + pd.definition.input_descriptors.length;
1077
- }, 0);
1078
- const totalVCs = args.verifiablePresentations ? this.countVCsInAllVPs(args.verifiablePresentations, args.hasher) : 0;
1079
- if (!request.presentationDefinitions || !args.verifiablePresentations || totalVCs !== totalInputDescriptors) {
1080
- throw Error(`Amount of presentations ${args.verifiablePresentations?.length}, doesn't match expected ${request.presentationDefinitions?.length}`);
1081
- } else if (!args.presentationSubmission) {
1082
- throw Error(`Presentation submission is required when verifiable presentations are required`);
1083
- }
1084
- }
1085
- const verifiablePresentations = args.verifiablePresentations ? args.verifiablePresentations.map((vp) => CredentialMapper.storedPresentationToOriginalFormat(vp)) : [];
1086
- const op = await createOP({
1087
- opOptions: {
1088
- ...this.options,
1089
- resolveOpts: {
1090
- ...this.options.resolveOpts
1091
- },
1092
- eventEmitter: this.options.eventEmitter,
1093
- presentationSignCallback: this.options.presentationSignCallback,
1094
- wellknownDIDVerifyCallback: this.options.wellknownDIDVerifyCallback,
1095
- supportedVersions: request.versions
1096
- },
1097
- idOpts: args.responseSignerOpts,
1098
- context: this.context
1099
- });
1100
- let issuer = args.responseSignerOpts.issuer;
1101
- const responseOpts = {
1102
- verification,
1103
- issuer,
1104
- ...args.isFirstParty && {
1105
- isFirstParty: args.isFirstParty
1106
- },
1107
- ...args.verifiablePresentations && {
1108
- presentationExchange: {
1109
- verifiablePresentations,
1110
- presentationSubmission: args.presentationSubmission
1111
- }
1112
- },
1113
- dcqlQuery: args.dcqlResponse
1114
- };
1115
- const authResponse = await op.createAuthorizationResponse(request, responseOpts);
1116
- const response = await op.submitAuthorizationResponse(authResponse, await this.createJarmResponseCallback({
1117
- responseOpts
1118
- }));
1119
- if (response.status >= 400) {
1120
- throw Error(`Error ${response.status}: ${response.statusText || await response.text()}`);
1121
- } else {
1122
- return response;
1123
- }
1124
- }
1125
- countVCsInAllVPs(verifiablePresentations, hasher) {
1126
- return verifiablePresentations.reduce((sum, vp) => {
1127
- if (CredentialMapper.isMsoMdocDecodedPresentation(vp) || CredentialMapper.isMsoMdocOid4VPEncoded(vp)) {
1128
- return sum + 1;
1129
- }
1130
- const uvp = CredentialMapper.toUniformPresentation(vp, {
1131
- hasher: hasher ?? this.options.hasher
1132
- });
1133
- if (uvp.verifiableCredential?.length) {
1134
- return sum + uvp.verifiableCredential?.length;
1135
- }
1136
- const isSdJWT = CredentialMapper.isSdJwtDecodedCredential(uvp);
1137
- if (isSdJWT || uvp.verifiableCredential && !PEX.allowMultipleVCsPerPresentation(uvp.verifiableCredential)) {
1138
- return sum + 1;
1139
- }
1140
- return sum;
1141
- }, 0);
1142
- }
1143
- };
1144
- function convertDidMethod(didMethod, didPrefix) {
1145
- if (didPrefix === false) {
1146
- return didMethod.startsWith("did:") ? didMethod.toLowerCase().replace("did:", "") : didMethod.toLowerCase();
1147
- }
1148
- return didMethod.startsWith("did:") ? didMethod.toLowerCase() : `did:${didMethod.toLowerCase().replace("did:", "")}`;
1149
- }
1150
- __name(convertDidMethod, "convertDidMethod");
1151
-
1152
- // src/agent/DidAuthSiopOpAuthenticator.ts
1153
- import { PEX as PEX3, Status as Status2 } from "@sphereon/pex";
1154
- import { computeEntryHash } from "@veramo/utils";
1155
- import { DcqlQuery as DcqlQuery2 } from "dcql";
1156
-
1157
- // src/machine/Siopv2Machine.ts
1158
- import { assign, createMachine, interpret } from "xstate";
1159
-
1160
- // src/localization/Localization.ts
1161
- import i18n from "i18n-js";
1162
- import memoize from "lodash.memoize";
1163
- var Localization = class Localization2 {
1164
- static {
1165
- __name(this, "Localization");
1166
- }
1167
- static translationGetters = {
1168
- [SupportedLanguage.ENGLISH]: () => require_en(),
1169
- [SupportedLanguage.DUTCH]: () => require_nl()
1170
- };
1171
- static translate = memoize((key, config) => {
1172
- if (Object.keys(i18n.translations).length === 0) {
1173
- i18n.translations = {
1174
- [SupportedLanguage.ENGLISH]: Localization2.translationGetters[SupportedLanguage.ENGLISH]()
1175
- };
1176
- i18n.locale = SupportedLanguage.ENGLISH;
1177
- } else {
1178
- i18n.translations = {
1179
- [i18n.locale]: {
1180
- ...i18n.translations[i18n.locale],
1181
- ...Localization2.translationGetters[this.findSupportedLanguage(i18n.locale) || SupportedLanguage.ENGLISH]()
1182
- }
1183
- };
1184
- }
1185
- return i18n.t(key, config);
1186
- }, (key, config) => config ? key + JSON.stringify(config) : key);
1187
- static findSupportedLanguage = /* @__PURE__ */ __name((locale) => {
1188
- for (const language of Object.values(SupportedLanguage)) {
1189
- if (language === locale) {
1190
- return language;
1191
- }
1192
- }
1193
- return void 0;
1194
- }, "findSupportedLanguage");
1195
- static getLocale = /* @__PURE__ */ __name(() => {
1196
- return i18n.locale || SupportedLanguage.ENGLISH;
1197
- }, "getLocale");
1198
- };
1199
- var translate = Localization.translate;
1200
-
1201
- // src/machine/Siopv2Machine.ts
1202
- import { Loggers as Loggers2 } from "@sphereon/ssi-types";
1203
- var logger2 = Loggers2.DEFAULT.get(LOGGER_NAMESPACE);
1204
- var Siopv2HasNoContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1205
- const { contact } = _ctx;
1206
- return contact === void 0;
1207
- }, "Siopv2HasNoContactGuard");
1208
- var Siopv2HasContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1209
- const { contact } = _ctx;
1210
- return contact !== void 0;
1211
- }, "Siopv2HasContactGuard");
1212
- var Siopv2HasAuthorizationRequestGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1213
- const { authorizationRequestData } = _ctx;
1214
- return authorizationRequestData !== void 0;
1215
- }, "Siopv2HasAuthorizationRequestGuard");
1216
- var Siopv2HasSelectableCredentialsAndContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1217
- const { authorizationRequestData, contact } = _ctx;
1218
- if (!authorizationRequestData) {
1219
- throw new Error("Missing authorization request data in context");
1220
- }
1221
- if (!contact) {
1222
- throw new Error("Missing contact request data in context");
1223
- }
1224
- return authorizationRequestData.presentationDefinitions !== void 0;
1225
- }, "Siopv2HasSelectableCredentialsAndContactGuard");
1226
- var Siopv2CreateContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1227
- const { contactAlias, hasContactConsent } = _ctx;
1228
- return hasContactConsent && contactAlias !== void 0 && contactAlias.length > 0;
1229
- }, "Siopv2CreateContactGuard");
1230
- var Siopv2HasSelectedRequiredCredentialsGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1231
- const { authorizationRequestData } = _ctx;
1232
- if (authorizationRequestData === void 0) {
1233
- throw new Error("Missing authorization request data in context");
1234
- }
1235
- if (authorizationRequestData.presentationDefinitions === void 0 || authorizationRequestData.presentationDefinitions.length === 0) {
1236
- throw Error("No presentation definitions present");
1237
- }
1238
- return _ctx.selectedCredentials.length > 0;
1239
- }, "Siopv2HasSelectedRequiredCredentialsGuard");
1240
- var Siopv2IsSiopOnlyGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1241
- const { authorizationRequestData } = _ctx;
1242
- if (authorizationRequestData === void 0) {
1243
- throw new Error("Missing authorization request data in context");
1244
- }
1245
- return authorizationRequestData.presentationDefinitions === void 0;
1246
- }, "Siopv2IsSiopOnlyGuard");
1247
- var Siopv2IsSiopWithOID4VPGuard = /* @__PURE__ */ __name((_ctx, _event) => {
1248
- const { authorizationRequestData, selectableCredentialsMap } = _ctx;
1249
- if (!authorizationRequestData) {
1250
- throw new Error("Missing authorization request data in context");
1251
- }
1252
- if (!selectableCredentialsMap) {
1253
- throw new Error("Missing selectableCredentialsMap in context");
1254
- }
1255
- return authorizationRequestData.presentationDefinitions !== void 0;
1256
- }, "Siopv2IsSiopWithOID4VPGuard");
1257
- var createSiopv2Machine = /* @__PURE__ */ __name((opts) => {
1258
- const { url, idOpts: idOpts2 } = opts;
1259
- const initialContext = {
1260
- url: new URL(url).toString(),
1261
- hasContactConsent: true,
1262
- contactAlias: "",
1263
- selectedCredentials: [],
1264
- idOpts: idOpts2
1265
- };
1266
- return createMachine({
1267
- id: opts?.machineId ?? "Siopv2",
1268
- predictableActionArguments: true,
1269
- initial: Siopv2MachineStates.createConfig,
1270
- schema: {
1271
- events: {},
1272
- guards: {},
1273
- services: {}
1274
- },
1275
- context: initialContext,
1276
- states: {
1277
- [Siopv2MachineStates.createConfig]: {
1278
- id: Siopv2MachineStates.createConfig,
1279
- invoke: {
1280
- src: Siopv2MachineServices.createConfig,
1281
- onDone: {
1282
- target: Siopv2MachineStates.getSiopRequest,
1283
- actions: assign({
1284
- didAuthConfig: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "didAuthConfig")
1285
- })
1286
- },
1287
- onError: {
1288
- target: Siopv2MachineStates.handleError,
1289
- actions: assign({
1290
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1291
- title: translate("siopv2_machine_create_config_error_title"),
1292
- message: _event.data.message,
1293
- stack: _event.data.stack
1294
- }), "error")
1295
- })
1296
- }
1297
- }
1298
- },
1299
- [Siopv2MachineStates.getSiopRequest]: {
1300
- id: Siopv2MachineStates.getSiopRequest,
1301
- invoke: {
1302
- src: Siopv2MachineServices.getSiopRequest,
1303
- onDone: {
1304
- target: Siopv2MachineStates.retrieveContact,
1305
- actions: assign({
1306
- authorizationRequestData: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationRequestData")
1307
- })
1308
- },
1309
- onError: {
1310
- target: Siopv2MachineStates.handleError,
1311
- actions: assign({
1312
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1313
- title: translate("siopv2_machine_get_request_error_title"),
1314
- message: _event.data.message,
1315
- stack: _event.data.stack
1316
- }), "error")
1317
- })
1318
- }
1319
- }
1320
- },
1321
- [Siopv2MachineStates.retrieveContact]: {
1322
- id: Siopv2MachineStates.retrieveContact,
1323
- invoke: {
1324
- src: Siopv2MachineServices.retrieveContact,
1325
- onDone: {
1326
- target: Siopv2MachineStates.transitionFromSetup,
1327
- actions: assign({
1328
- contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
1329
- })
1330
- },
1331
- onError: {
1332
- target: Siopv2MachineStates.handleError,
1333
- actions: assign({
1334
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1335
- title: translate("siopv2_machine_retrieve_contact_error_title"),
1336
- message: _event.data.message,
1337
- stack: _event.data.stack
1338
- }), "error")
1339
- })
1340
- }
1341
- }
1342
- },
1343
- [Siopv2MachineStates.transitionFromSetup]: {
1344
- id: Siopv2MachineStates.transitionFromSetup,
1345
- always: [
1346
- {
1347
- target: Siopv2MachineStates.addContact,
1348
- cond: Siopv2MachineGuards.hasNoContactGuard
1349
- },
1350
- {
1351
- target: Siopv2MachineStates.sendResponse,
1352
- cond: Siopv2MachineGuards.siopOnlyGuard
1353
- },
1354
- {
1355
- target: Siopv2MachineStates.getSelectableCredentials,
1356
- cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
1357
- },
1358
- {
1359
- target: Siopv2MachineStates.selectCredentials,
1360
- cond: Siopv2MachineGuards.siopWithOID4VPGuard
1361
- }
1362
- ]
1363
- },
1364
- [Siopv2MachineStates.addContact]: {
1365
- id: Siopv2MachineStates.addContact,
1366
- initial: Siopv2MachineAddContactStates.idle,
1367
- on: {
1368
- [Siopv2MachineEvents.SET_CONTACT_CONSENT]: {
1369
- actions: assign({
1370
- hasContactConsent: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "hasContactConsent")
1371
- })
1372
- },
1373
- [Siopv2MachineEvents.SET_CONTACT_ALIAS]: {
1374
- actions: assign({
1375
- contactAlias: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contactAlias")
1376
- })
1377
- },
1378
- [Siopv2MachineEvents.CREATE_CONTACT]: {
1379
- target: `.${Siopv2MachineAddContactStates.next}`,
1380
- actions: assign({
1381
- contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
1382
- }),
1383
- cond: Siopv2MachineGuards.createContactGuard
1384
- },
1385
- [Siopv2MachineEvents.DECLINE]: {
1386
- target: Siopv2MachineStates.declined
1387
- },
1388
- [Siopv2MachineEvents.PREVIOUS]: {
1389
- target: Siopv2MachineStates.aborted
1390
- }
1391
- },
1392
- states: {
1393
- [Siopv2MachineAddContactStates.idle]: {},
1394
- [Siopv2MachineAddContactStates.next]: {
1395
- always: {
1396
- target: `#${Siopv2MachineStates.transitionFromSetup}`,
1397
- cond: Siopv2MachineGuards.hasContactGuard
1398
- }
1399
- }
1400
- }
1401
- },
1402
- [Siopv2MachineStates.addContactIdentity]: {
1403
- id: Siopv2MachineStates.addContactIdentity,
1404
- invoke: {
1405
- src: Siopv2MachineServices.addContactIdentity,
1406
- onDone: [
1407
- {
1408
- target: Siopv2MachineStates.getSelectableCredentials,
1409
- actions: /* @__PURE__ */ __name((_ctx, _event) => {
1410
- _ctx.contact?.identities.push(_event.data);
1411
- }, "actions"),
1412
- cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
1413
- },
1414
- {
1415
- target: Siopv2MachineStates.sendResponse,
1416
- actions: /* @__PURE__ */ __name((_ctx, _event) => {
1417
- _ctx.contact?.identities.push(_event.data);
1418
- }, "actions"),
1419
- cond: Siopv2MachineGuards.siopOnlyGuard
1420
- }
1421
- ],
1422
- onError: {
1423
- target: Siopv2MachineStates.handleError,
1424
- actions: assign({
1425
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1426
- title: translate("siopv2_machine_add_contact_identity_error_title"),
1427
- message: _event.data.message,
1428
- stack: _event.data.stack
1429
- }), "error")
1430
- })
1431
- }
1432
- }
1433
- },
1434
- [Siopv2MachineStates.getSelectableCredentials]: {
1435
- id: Siopv2MachineStates.getSelectableCredentials,
1436
- invoke: {
1437
- src: Siopv2MachineServices.getSelectableCredentials,
1438
- onDone: {
1439
- target: Siopv2MachineStates.selectCredentials,
1440
- actions: assign({
1441
- selectableCredentialsMap: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectableCredentialsMap")
1442
- })
1443
- },
1444
- onError: {
1445
- target: Siopv2MachineStates.handleError,
1446
- actions: assign({
1447
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1448
- title: translate("siopv2_machine_get_selectable_credentials_error_title"),
1449
- message: _event.data.message,
1450
- stack: _event.data.stack
1451
- }), "error")
1452
- })
1453
- }
1454
- }
1455
- },
1456
- [Siopv2MachineStates.selectCredentials]: {
1457
- id: Siopv2MachineStates.selectCredentials,
1458
- on: {
1459
- [Siopv2MachineEvents.SET_SELECTED_CREDENTIALS]: {
1460
- actions: assign({
1461
- selectedCredentials: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectedCredentials")
1462
- })
1463
- },
1464
- [Siopv2MachineEvents.NEXT]: {
1465
- target: Siopv2MachineStates.sendResponse,
1466
- cond: Siopv2MachineGuards.hasSelectedRequiredCredentialsGuard
1467
- },
1468
- [Siopv2MachineEvents.DECLINE]: {
1469
- target: Siopv2MachineStates.declined
1470
- },
1471
- [Siopv2MachineEvents.PREVIOUS]: {
1472
- target: Siopv2MachineStates.aborted
1473
- }
1474
- }
1475
- },
1476
- [Siopv2MachineStates.sendResponse]: {
1477
- id: Siopv2MachineStates.sendResponse,
1478
- invoke: {
1479
- src: Siopv2MachineServices.sendResponse,
1480
- onDone: {
1481
- target: Siopv2MachineStates.done,
1482
- actions: assign({
1483
- authorizationResponseData: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationResponseData")
1484
- })
1485
- },
1486
- onError: {
1487
- target: Siopv2MachineStates.handleError,
1488
- actions: assign({
1489
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1490
- title: translate("siopv2_machine_send_response_error_title"),
1491
- message: _event.data.message,
1492
- stack: _event.data.stack
1493
- }), "error")
1494
- })
1495
- }
1496
- }
1497
- },
1498
- [Siopv2MachineStates.handleError]: {
1499
- id: Siopv2MachineStates.handleError,
1500
- on: {
1501
- [Siopv2MachineEvents.NEXT]: {
1502
- target: Siopv2MachineStates.error
1503
- },
1504
- [Siopv2MachineEvents.PREVIOUS]: {
1505
- target: Siopv2MachineStates.error
1506
- }
1507
- }
1508
- },
1509
- [Siopv2MachineStates.aborted]: {
1510
- id: Siopv2MachineStates.aborted,
1511
- type: "final"
1512
- },
1513
- [Siopv2MachineStates.declined]: {
1514
- id: Siopv2MachineStates.declined,
1515
- type: "final"
1516
- },
1517
- [Siopv2MachineStates.error]: {
1518
- id: Siopv2MachineStates.error,
1519
- type: "final"
1520
- },
1521
- [Siopv2MachineStates.done]: {
1522
- id: Siopv2MachineStates.done,
1523
- type: "final"
1524
- }
1525
- }
1526
- });
1527
- }, "createSiopv2Machine");
1528
- var Siopv2Machine = class {
1529
- static {
1530
- __name(this, "Siopv2Machine");
1531
- }
1532
- static newInstance(opts) {
1533
- logger2.info("New Siopv2Machine instance");
1534
- const interpreter = interpret(createSiopv2Machine(opts).withConfig({
1535
- services: {
1536
- ...opts?.services
1537
- },
1538
- guards: {
1539
- Siopv2HasNoContactGuard,
1540
- Siopv2HasContactGuard,
1541
- Siopv2HasAuthorizationRequestGuard,
1542
- Siopv2HasSelectableCredentialsAndContactGuard,
1543
- Siopv2HasSelectedRequiredCredentialsGuard,
1544
- Siopv2IsSiopOnlyGuard,
1545
- Siopv2IsSiopWithOID4VPGuard,
1546
- Siopv2CreateContactGuard,
1547
- ...opts?.guards
1548
- }
1549
- }));
1550
- if (typeof opts?.subscription === "function") {
1551
- interpreter.onTransition(opts.subscription);
1552
- }
1553
- if (opts?.requireCustomNavigationHook !== true) {
1554
- interpreter.onTransition((snapshot) => {
1555
- if (opts.stateNavigationListener !== void 0) {
1556
- void opts.stateNavigationListener(interpreter, snapshot);
1557
- }
1558
- });
1559
- }
1560
- interpreter.onTransition((snapshot) => {
1561
- logger2.info("onTransition to new state", snapshot.value);
1562
- });
1563
- return {
1564
- interpreter
1565
- };
1566
- }
1567
- };
1568
-
1569
- // src/services/Siopv2MachineService.ts
1570
- import { SupportedVersion as SupportedVersion2 } from "@sphereon/did-auth-siop";
1571
- import { PEX as PEX2 } from "@sphereon/pex";
1572
- import { isOID4VCIssuerIdentifier as isOID4VCIssuerIdentifier2 } from "@sphereon/ssi-sdk-ext.identifier-resolution";
1573
- import { verifiableCredentialForRoleFilter as verifiableCredentialForRoleFilter2 } from "@sphereon/ssi-sdk.credential-store";
1574
- import { ConnectionType, CredentialRole } from "@sphereon/ssi-sdk.data-store";
1575
- import { CredentialMapper as CredentialMapper4, Loggers as Loggers3 } from "@sphereon/ssi-types";
1576
- import { getOrCreatePrimaryIdentifier, SupportedDidMethodEnum } from "@sphereon/ssi-sdk-ext.did-utils";
1577
- import { defaultHasher as defaultHasher2, encodeJoseBlob } from "@sphereon/ssi-sdk.core";
1578
- import { DcqlPresentation, DcqlQuery } from "dcql";
1579
-
1580
- // src/utils/dcql.ts
1581
- import { CredentialMapper as CredentialMapper3 } from "@sphereon/ssi-types";
1582
-
1583
- // src/utils/CredentialUtils.ts
1584
- import { CredentialMapper as CredentialMapper2 } from "@sphereon/ssi-types";
1585
- var getOriginalVerifiableCredential = /* @__PURE__ */ __name((credential) => {
1586
- if (isUniqueDigitalCredential(credential)) {
1587
- if (!credential.originalVerifiableCredential) {
1588
- throw new Error("originalVerifiableCredential is not defined in UniqueDigitalCredential");
1589
- }
1590
- return getCredentialFromProofOrWrapped(credential.originalVerifiableCredential);
1591
- }
1592
- return getCredentialFromProofOrWrapped(credential);
1593
- }, "getOriginalVerifiableCredential");
1594
- var getCredentialFromProofOrWrapped = /* @__PURE__ */ __name((cred, hasher) => {
1595
- if (typeof cred === "object" && "proof" in cred && "jwt" in cred.proof && CredentialMapper2.isSdJwtEncoded(cred.proof.jwt)) {
1596
- return cred.proof.jwt;
1597
- }
1598
- return CredentialMapper2.toWrappedVerifiableCredential(cred, {
1599
- hasher
1600
- }).original;
1601
- }, "getCredentialFromProofOrWrapped");
1602
- var isUniqueDigitalCredential = /* @__PURE__ */ __name((credential) => {
1603
- return credential.digitalCredential !== void 0;
1604
- }, "isUniqueDigitalCredential");
1605
-
1606
- // src/utils/dcql.ts
1607
- function convertToDcqlCredentials(credential, hasher) {
1608
- let payload;
1609
- if (isUniqueDigitalCredential(credential)) {
1610
- if (!credential.originalVerifiableCredential) {
1611
- throw new Error("originalVerifiableCredential is not defined in UniqueDigitalCredential");
1612
- }
1613
- payload = CredentialMapper3.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher);
1614
- } else {
1615
- payload = CredentialMapper3.decodeVerifiableCredential(credential, hasher);
1616
- }
1617
- if (!payload) {
1618
- throw new Error("No payload found");
1619
- }
1620
- if ("decodedPayload" in payload && payload.decodedPayload) {
1621
- payload = payload.decodedPayload;
1622
- }
1623
- if ("vct" in payload) {
1624
- return {
1625
- vct: payload.vct,
1626
- claims: payload,
1627
- credential_format: "vc+sd-jwt"
1628
- };
1629
- } else if ("docType" in payload && "namespaces" in payload) {
1630
- return {
1631
- docType: payload.docType,
1632
- namespaces: payload.namespaces,
1633
- claims: payload
1634
- };
1635
- } else {
1636
- return {
1637
- claims: payload,
1638
- credential_format: "jwt_vc_json"
1639
- };
1640
- }
1641
- }
1642
- __name(convertToDcqlCredentials, "convertToDcqlCredentials");
1643
-
1644
- // src/services/Siopv2MachineService.ts
1645
- var logger3 = Loggers3.DEFAULT.get(LOGGER_NAMESPACE);
1646
- var createEbsiIdentifier = /* @__PURE__ */ __name(async (agentContext) => {
1647
- logger3.log(`No EBSI key present yet. Creating a new one...`);
1648
- const { result: newIdentifier, created } = await getOrCreatePrimaryIdentifier(agentContext, {
1649
- method: SupportedDidMethodEnum.DID_KEY,
1650
- createOpts: {
1651
- options: {
1652
- codecName: "jwk_jcs-pub",
1653
- type: "Secp256r1"
1654
- }
1655
- }
1656
- });
1657
- logger3.log(`EBSI key created: ${newIdentifier.did}`);
1658
- if (created) {
1659
- await agentContext.agent.emit(Siopv2HolderEvent.IDENTIFIER_CREATED, {
1660
- result: newIdentifier
1661
- });
1662
- }
1663
- return await agentContext.agent.identifierManagedGetByDid({
1664
- identifier: newIdentifier.did
1665
- });
1666
- }, "createEbsiIdentifier");
1667
- var hasEbsiClient = /* @__PURE__ */ __name(async (authorizationRequest) => {
1668
- const clientId = await authorizationRequest.getMergedProperty("client_id");
1669
- const redirectUri = await authorizationRequest.getMergedProperty("redirect_uri");
1670
- return clientId?.toLowerCase().includes(".ebsi.eu") || redirectUri?.toLowerCase().includes(".ebsi.eu");
1671
- }, "hasEbsiClient");
1672
- var siopSendAuthorizationResponse = /* @__PURE__ */ __name(async (connectionType, args, context) => {
1673
- const { agent } = context;
1674
- const agentContext = {
1675
- ...context,
1676
- agent: context.agent
1677
- };
1678
- let { idOpts: idOpts2, isFirstParty, hasher = defaultHasher2 } = args;
1679
- if (connectionType !== ConnectionType.SIOPv2_OpenID4VP) {
1680
- return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`));
1681
- }
1682
- const session = await agent.siopGetOPSession({
1683
- sessionId: args.sessionId
1684
- });
1685
- const request = await session.getAuthorizationRequest();
1686
- const aud = await request.authorizationRequest.getMergedProperty("aud");
1687
- logger3.debug(`AUD: ${aud}`);
1688
- logger3.debug(JSON.stringify(request.authorizationRequest));
1689
- let presentationsAndDefs;
1690
- let presentationSubmission;
1691
- if (await session.hasPresentationDefinitions()) {
1692
- const oid4vp = await session.getOID4VP({
1693
- hasher
1694
- });
1695
- const credentialsAndDefinitions = args.verifiableCredentialsWithDefinition ? args.verifiableCredentialsWithDefinition : await oid4vp.filterCredentialsAgainstAllDefinitions(CredentialRole.HOLDER);
1696
- const domain = await request.authorizationRequest.getMergedProperty("client_id") ?? request.issuer ?? (request.versions.includes(SupportedVersion2.JWT_VC_PRESENTATION_PROFILE_v1) ? "https://self-issued.me/v2/openid-vc" : "https://self-issued.me/v2");
1697
- logger3.log(`NONCE: ${session.nonce}, domain: ${domain}`);
1698
- const firstUniqueDC = credentialsAndDefinitions[0].credentials[0];
1699
- if (typeof firstUniqueDC !== "object" || !("digitalCredential" in firstUniqueDC)) {
1700
- return Promise.reject(Error("SiopMachine only supports UniqueDigitalCredentials for now"));
1701
- }
1702
- let identifier;
1703
- const digitalCredential = firstUniqueDC.digitalCredential;
1704
- const firstVC = firstUniqueDC.uniformVerifiableCredential;
1705
- const holder = CredentialMapper4.isSdJwtDecodedCredential(firstVC) ? firstVC.decodedPayload.cnf?.jwk ? (
1706
- //doesn't apply to did:jwk only, as you can represent any DID key as a JWK. So whenever you encounter a JWK it doesn't mean it had to come from a did:jwk in the system. It just can always be represented as a did:jwk
1707
- `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0`
1708
- ) : firstVC.decodedPayload.sub : Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id;
1709
- if (!digitalCredential.kmsKeyRef) {
1710
- if (!holder) {
1711
- return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`);
1712
- }
1713
- try {
1714
- identifier = await session.context.agent.identifierManagedGet({
1715
- identifier: holder
1716
- });
1717
- } catch (e) {
1718
- logger3.debug(`Holder DID not found: ${holder}`);
1719
- throw e;
1720
- }
1721
- } else if (isOID4VCIssuerIdentifier2(digitalCredential.kmsKeyRef)) {
1722
- identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({
1723
- identifier: firstUniqueDC.digitalCredential.kmsKeyRef
1724
- });
1725
- } else {
1726
- switch (digitalCredential.subjectCorrelationType) {
1727
- case "DID":
1728
- identifier = await session.context.agent.identifierManagedGetByDid({
1729
- identifier: digitalCredential.subjectCorrelationId ?? holder,
1730
- kmsKeyRef: digitalCredential.kmsKeyRef
1731
- });
1732
- break;
1733
- // TODO other implementations?
1734
- default:
1735
- if (digitalCredential.subjectCorrelationId?.startsWith("did:") || holder?.startsWith("did:")) {
1736
- identifier = await session.context.agent.identifierManagedGetByDid({
1737
- identifier: digitalCredential.subjectCorrelationId ?? holder,
1738
- kmsKeyRef: digitalCredential.kmsKeyRef
1739
- });
1740
- } else {
1741
- identifier = await session.context.agent.identifierManagedGetByKid({
1742
- identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,
1743
- kmsKeyRef: digitalCredential.kmsKeyRef
1744
- });
1745
- }
1746
- }
1747
- }
1748
- if (identifier === void 0 && idOpts2 !== void 0 && await hasEbsiClient(request.authorizationRequest)) {
1749
- identifier = await createEbsiIdentifier(agentContext);
1750
- }
1751
- logger3.debug(`Identifier`, identifier);
1752
- presentationsAndDefs = await oid4vp.createVerifiablePresentations(CredentialRole.HOLDER, credentialsAndDefinitions, {
1753
- idOpts: identifier,
1754
- proofOpts: {
1755
- nonce: session.nonce,
1756
- domain
1757
- }
1758
- });
1759
- if (!presentationsAndDefs || presentationsAndDefs.length === 0) {
1760
- throw Error("No verifiable presentations could be created");
1761
- } else if (presentationsAndDefs.length > 1) {
1762
- throw Error(`Only one verifiable presentation supported for now. Got ${presentationsAndDefs.length}`);
1763
- }
1764
- idOpts2 = presentationsAndDefs[0].idOpts;
1765
- presentationSubmission = presentationsAndDefs[0].presentationSubmission;
1766
- logger3.log(`Definitions and locations:`, JSON.stringify(presentationsAndDefs?.[0]?.verifiablePresentations, null, 2));
1767
- logger3.log(`Presentation Submission:`, JSON.stringify(presentationSubmission, null, 2));
1768
- const mergedVerifiablePresentations = presentationsAndDefs?.flatMap((pd) => pd.verifiablePresentations) || [];
1769
- return await session.sendAuthorizationResponse({
1770
- ...presentationsAndDefs && {
1771
- verifiablePresentations: mergedVerifiablePresentations
1772
- },
1773
- ...presentationSubmission && {
1774
- presentationSubmission
1775
- },
1776
- // todo: Change issuer value in case we do not use identifier. Use key.meta.jwkThumbprint then
1777
- responseSignerOpts: idOpts2,
1778
- isFirstParty
1779
- });
1780
- } else if (request.dcqlQuery) {
1781
- if (args.verifiableCredentialsWithDefinition !== void 0 && args.verifiableCredentialsWithDefinition !== null) {
1782
- const vcs = args.verifiableCredentialsWithDefinition.flatMap((vcd) => vcd.credentials);
1783
- const domain = await request.authorizationRequest.getMergedProperty("client_id") ?? request.issuer ?? (request.versions.includes(SupportedVersion2.JWT_VC_PRESENTATION_PROFILE_v1) ? "https://self-issued.me/v2/openid-vc" : "https://self-issued.me/v2");
1784
- logger3.debug(`NONCE: ${session.nonce}, domain: ${domain}`);
1785
- const firstUniqueDC = vcs[0];
1786
- if (typeof firstUniqueDC !== "object" || !("digitalCredential" in firstUniqueDC)) {
1787
- return Promise.reject(Error("SiopMachine only supports UniqueDigitalCredentials for now"));
1788
- }
1789
- let identifier;
1790
- const digitalCredential = firstUniqueDC.digitalCredential;
1791
- const firstVC = firstUniqueDC.uniformVerifiableCredential;
1792
- const holder = CredentialMapper4.isSdJwtDecodedCredential(firstVC) ? firstVC.decodedPayload.cnf?.jwk ? (
1793
- //doesn't apply to did:jwk only, as you can represent any DID key as a JWK. So whenever you encounter a JWK it doesn't mean it had to come from a did:jwk in the system. It just can always be represented as a did:jwk
1794
- `did:jwk:${encodeJoseBlob(firstVC.decodedPayload.cnf?.jwk)}#0`
1795
- ) : firstVC.decodedPayload.sub : Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id;
1796
- if (!digitalCredential.kmsKeyRef) {
1797
- if (!holder) {
1798
- return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`);
1799
- }
1800
- try {
1801
- identifier = await session.context.agent.identifierManagedGet({
1802
- identifier: holder
1803
- });
1804
- } catch (e) {
1805
- logger3.debug(`Holder DID not found: ${holder}`);
1806
- throw e;
1807
- }
1808
- } else if (isOID4VCIssuerIdentifier2(digitalCredential.kmsKeyRef)) {
1809
- identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({
1810
- identifier: firstUniqueDC.digitalCredential.kmsKeyRef
1811
- });
1812
- } else {
1813
- switch (digitalCredential.subjectCorrelationType) {
1814
- case "DID":
1815
- identifier = await session.context.agent.identifierManagedGetByDid({
1816
- identifier: digitalCredential.subjectCorrelationId ?? holder,
1817
- kmsKeyRef: digitalCredential.kmsKeyRef
1818
- });
1819
- break;
1820
- // TODO other implementations?
1821
- default:
1822
- identifier = await session.context.agent.identifierManagedGetByKid({
1823
- identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,
1824
- kmsKeyRef: digitalCredential.kmsKeyRef
1825
- });
1826
- }
1827
- }
1828
- console.log(`Identifier`, identifier);
1829
- const dcqlRepresentations = [];
1830
- vcs.forEach((vc) => {
1831
- const rep = convertToDcqlCredentials(vc, args.hasher);
1832
- if (rep) {
1833
- dcqlRepresentations.push(rep);
1834
- }
1835
- });
1836
- const queryResult = DcqlQuery.query(request.dcqlQuery, dcqlRepresentations);
1837
- const presentation = {};
1838
- for (const [key, value] of Object.entries(queryResult.credential_matches)) {
1839
- const allMatches = Array.isArray(value) ? value : [
1840
- value
1841
- ];
1842
- allMatches.forEach((match) => {
1843
- if (match.success) {
1844
- const originalCredential = getOriginalVerifiableCredential(vcs[match.input_credential_index]);
1845
- if (!originalCredential) {
1846
- throw new Error(`Index ${match.input_credential_index} out of range in credentials array`);
1847
- }
1848
- presentation[key] = originalCredential["compactSdJwtVc"] !== void 0 ? originalCredential.compactSdJwtVc : originalCredential;
1849
- }
1850
- });
1851
- }
1852
- const response = session.sendAuthorizationResponse({
1853
- responseSignerOpts: identifier,
1854
- ...{
1855
- dcqlQuery: {
1856
- dcqlPresentation: DcqlPresentation.parse(presentation)
1857
- }
1858
- }
1859
- });
1860
- logger3.debug(`Response: `, response);
1861
- return response;
1862
- }
1863
- }
1864
- throw Error("Presentation Definition or DCQL is required");
1865
- }, "siopSendAuthorizationResponse");
1866
- function buildPartialPD(inputDescriptor, presentationDefinition) {
1867
- return {
1868
- ...presentationDefinition,
1869
- input_descriptors: [
1870
- inputDescriptor
1871
- ]
1872
- };
1873
- }
1874
- __name(buildPartialPD, "buildPartialPD");
1875
- var getSelectableCredentials = /* @__PURE__ */ __name(async (presentationDefinition, context) => {
1876
- const agentContext = {
1877
- ...context,
1878
- agent: context.agent
1879
- };
1880
- const { agent } = agentContext;
1881
- const pex = new PEX2();
1882
- const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({
1883
- filter: verifiableCredentialForRoleFilter2(CredentialRole.HOLDER)
1884
- });
1885
- const credentialBranding = await agent.ibGetCredentialBranding();
1886
- const selectableCredentialsMap = /* @__PURE__ */ new Map();
1887
- for (const inputDescriptor of presentationDefinition.input_descriptors) {
1888
- const partialPD = buildPartialPD(inputDescriptor, presentationDefinition);
1889
- const originalCredentials = uniqueVerifiableCredentials.map((uniqueVC) => {
1890
- return CredentialMapper4.storedCredentialToOriginalFormat(uniqueVC.originalVerifiableCredential);
1891
- });
1892
- const selectionResults = pex.selectFrom(partialPD, originalCredentials);
1893
- const selectableCredentials = [];
1894
- for (const selectedCredential of selectionResults.verifiableCredential || []) {
1895
- const filteredUniqueVC = uniqueVerifiableCredentials.find((uniqueVC) => {
1896
- const proof = uniqueVC.uniformVerifiableCredential.proof;
1897
- return Array.isArray(proof) ? proof.some((proofItem) => proofItem.jwt === selectedCredential) : proof.jwt === selectedCredential;
1898
- });
1899
- if (filteredUniqueVC) {
1900
- const filteredCredentialBrandings = credentialBranding.filter((cb) => cb.vcHash === filteredUniqueVC.hash);
1901
- const issuerPartyIdentity = await agent.cmGetContacts({
1902
- filter: [
1903
- {
1904
- identities: {
1905
- identifier: {
1906
- correlationId: filteredUniqueVC.uniformVerifiableCredential.issuerDid
1907
- }
1908
- }
1909
- }
1910
- ]
1911
- });
1912
- const subjectPartyIdentity = await agent.cmGetContacts({
1913
- filter: [
1914
- {
1915
- identities: {
1916
- identifier: {
1917
- correlationId: filteredUniqueVC.uniformVerifiableCredential.subjectDid
1918
- }
1919
- }
1920
- }
1921
- ]
1922
- });
1923
- selectableCredentials.push({
1924
- credential: filteredUniqueVC,
1925
- credentialBranding: filteredCredentialBrandings[0]?.localeBranding,
1926
- issuerParty: issuerPartyIdentity?.[0],
1927
- subjectParty: subjectPartyIdentity?.[0]
1928
- });
1929
- }
1930
- }
1931
- selectableCredentialsMap.set(inputDescriptor.id, selectableCredentials);
1932
- }
1933
- return selectableCredentialsMap;
1934
- }, "getSelectableCredentials");
1935
- var translateCorrelationIdToName = /* @__PURE__ */ __name(async (correlationId, context) => {
1936
- const { agent } = context;
1937
- const contacts = await agent.cmGetContacts({
1938
- filter: [
1939
- {
1940
- identities: {
1941
- identifier: {
1942
- correlationId
1943
- }
1944
- }
1945
- }
1946
- ]
1947
- });
1948
- if (contacts.length === 0) {
1949
- return void 0;
1950
- }
1951
- return contacts[0].contact.displayName;
1952
- }, "translateCorrelationIdToName");
1953
-
1954
- // src/agent/DidAuthSiopOpAuthenticator.ts
1955
- var logger4 = Loggers4.DEFAULT.options(LOGGER_NAMESPACE, {}).get(LOGGER_NAMESPACE);
1956
- var didAuthSiopOpAuthenticatorMethods = [
1957
- "cmGetContacts",
1958
- "cmGetContact",
1959
- "cmAddContact",
1960
- "cmAddIdentity",
1961
- "didManagerFind",
1962
- "didManagerGet",
1963
- "keyManagerSign",
1964
- "didManagerGetProviders",
1965
- "dataStoreORMGetVerifiableCredentials",
1966
- "createVerifiablePresentation"
1967
- ];
1968
- var DidAuthSiopOpAuthenticator = class {
1969
- static {
1970
- __name(this, "DidAuthSiopOpAuthenticator");
1971
- }
1972
- schema = schema.IDidAuthSiopOpAuthenticator;
1973
- methods = {
1974
- siopGetOPSession: this.siopGetOPSession.bind(this),
1975
- siopRegisterOPSession: this.siopRegisterOPSession.bind(this),
1976
- siopRemoveOPSession: this.siopRemoveOPSession.bind(this),
1977
- siopRegisterOPCustomApproval: this.siopRegisterOPCustomApproval.bind(this),
1978
- siopRemoveOPCustomApproval: this.siopRemoveOPCustomApproval.bind(this),
1979
- siopGetMachineInterpreter: this.siopGetMachineInterpreter.bind(this),
1980
- siopCreateConfig: this.siopCreateConfig.bind(this),
1981
- siopGetSiopRequest: this.siopGetSiopRequest.bind(this),
1982
- siopRetrieveContact: this.siopRetrieveContact.bind(this),
1983
- siopAddIdentity: this.siopAddContactIdentity.bind(this),
1984
- siopSendResponse: this.siopSendResponse.bind(this),
1985
- siopGetSelectableCredentials: this.siopGetSelectableCredentials.bind(this)
1986
- };
1987
- sessions;
1988
- customApprovals;
1989
- presentationSignCallback;
1990
- onContactIdentityCreated;
1991
- onIdentifierCreated;
1992
- eventEmitter;
1993
- hasher;
1994
- constructor(options) {
1995
- const { onContactIdentityCreated, onIdentifierCreated, hasher, customApprovals = {}, presentationSignCallback } = {
1996
- ...options
1997
- };
1998
- this.hasher = hasher;
1999
- this.onContactIdentityCreated = onContactIdentityCreated;
2000
- this.onIdentifierCreated = onIdentifierCreated;
2001
- this.presentationSignCallback = presentationSignCallback;
2002
- this.sessions = /* @__PURE__ */ new Map();
2003
- this.customApprovals = customApprovals;
2004
- }
2005
- async onEvent(event, context) {
2006
- switch (event.type) {
2007
- case Siopv2HolderEvent.CONTACT_IDENTITY_CREATED:
2008
- this.onContactIdentityCreated?.(event.data);
2009
- break;
2010
- case Siopv2HolderEvent.IDENTIFIER_CREATED:
2011
- this.onIdentifierCreated?.(event.data);
2012
- break;
2013
- default:
2014
- return Promise.reject(Error(`Event type ${event.type} not supported`));
2015
- }
2016
- }
2017
- async siopGetOPSession(args, context) {
2018
- if (!this.sessions.has(args.sessionId)) {
2019
- throw Error(`No session found for id: ${args.sessionId}`);
2020
- }
2021
- return this.sessions.get(args.sessionId);
2022
- }
2023
- async siopRegisterOPSession(args, context) {
2024
- const sessionId = args.sessionId || uuidv4();
2025
- if (this.sessions.has(sessionId)) {
2026
- return Promise.reject(new Error(`Session with id: ${args.sessionId} already present`));
2027
- }
2028
- const opts = {
2029
- ...args,
2030
- sessionId,
2031
- context
2032
- };
2033
- if (!opts.op?.presentationSignCallback) {
2034
- opts.op = {
2035
- ...opts.op,
2036
- presentationSignCallback: this.presentationSignCallback
2037
- };
2038
- }
2039
- const session = await OpSession.init(opts);
2040
- this.sessions.set(sessionId, session);
2041
- return session;
2042
- }
2043
- async siopRemoveOPSession(args, context) {
2044
- return this.sessions.delete(args.sessionId);
2045
- }
2046
- async siopRegisterOPCustomApproval(args, context) {
2047
- if (this.customApprovals[args.key] !== void 0) {
2048
- return Promise.reject(new Error(`Custom approval with key: ${args.key} already present`));
2049
- }
2050
- this.customApprovals[args.key] = args.customApproval;
2051
- }
2052
- async siopRemoveOPCustomApproval(args, context) {
2053
- return delete this.customApprovals[args.key];
2054
- }
2055
- async siopGetMachineInterpreter(opts, context) {
2056
- const { stateNavigationListener, url } = opts;
2057
- const services = {
2058
- createConfig: /* @__PURE__ */ __name((args) => this.siopCreateConfig(args), "createConfig"),
2059
- getSiopRequest: /* @__PURE__ */ __name((args) => this.siopGetSiopRequest(args, context), "getSiopRequest"),
2060
- getSelectableCredentials: /* @__PURE__ */ __name((args) => this.siopGetSelectableCredentials(args, context), "getSelectableCredentials"),
2061
- retrieveContact: /* @__PURE__ */ __name((args) => this.siopRetrieveContact(args, context), "retrieveContact"),
2062
- addContactIdentity: /* @__PURE__ */ __name((args) => this.siopAddContactIdentity(args, context), "addContactIdentity"),
2063
- sendResponse: /* @__PURE__ */ __name((args) => this.siopSendResponse(args, context), "sendResponse"),
2064
- ...opts?.services
2065
- };
2066
- const siopv2MachineOpts = {
2067
- ...opts,
2068
- url,
2069
- stateNavigationListener,
2070
- services: {
2071
- ...services,
2072
- ...opts.services
2073
- }
2074
- };
2075
- return Siopv2Machine.newInstance(siopv2MachineOpts);
2076
- }
2077
- async siopCreateConfig(context) {
2078
- const { url } = context;
2079
- if (!url) {
2080
- return Promise.reject(Error("Missing request uri in context"));
2081
- }
2082
- return {
2083
- id: uuidv4(),
2084
- // FIXME: Update these values in SSI-SDK. Only the URI (not a redirectURI) would be available at this point
2085
- sessionId: uuidv4(),
2086
- redirectUrl: url
2087
- };
2088
- }
2089
- async siopGetSiopRequest(args, context) {
2090
- const { agent } = context;
2091
- const { didAuthConfig } = args;
2092
- if (args.url === void 0) {
2093
- return Promise.reject(Error("Missing request uri in context"));
2094
- }
2095
- if (didAuthConfig === void 0) {
2096
- return Promise.reject(Error("Missing config in context"));
2097
- }
2098
- const { sessionId, redirectUrl } = didAuthConfig;
2099
- const session = await agent.siopGetOPSession({
2100
- sessionId
2101
- }).catch(async () => await agent.siopRegisterOPSession({
2102
- requestJwtOrUri: redirectUrl,
2103
- sessionId,
2104
- op: {
2105
- eventEmitter: this.eventEmitter,
2106
- hasher: this.hasher
2107
- }
2108
- }));
2109
- logger4.debug(`session: ${JSON.stringify(session.id, null, 2)}`);
2110
- const verifiedAuthorizationRequest = await session.getAuthorizationRequest();
2111
- const clientName = verifiedAuthorizationRequest.registrationMetadataPayload?.client_name;
2112
- const url = verifiedAuthorizationRequest.responseURI ?? (args.url.includes("request_uri") ? decodeURIComponent(args.url.split("?request_uri=")[1].trim()) : verifiedAuthorizationRequest.issuer ?? verifiedAuthorizationRequest.registrationMetadataPayload?.client_id);
2113
- const uri = url.includes("://") ? new URL(url) : void 0;
2114
- const correlationId = uri?.hostname ?? await this.determineCorrelationId(uri, verifiedAuthorizationRequest, clientName, context);
2115
- const clientId = await verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("client_id");
2116
- return {
2117
- issuer: verifiedAuthorizationRequest.issuer,
2118
- correlationId,
2119
- registrationMetadataPayload: verifiedAuthorizationRequest.registrationMetadataPayload,
2120
- uri,
2121
- name: clientName,
2122
- clientId,
2123
- presentationDefinitions: await verifiedAuthorizationRequest.authorizationRequest.containsResponseType("vp_token") || verifiedAuthorizationRequest.versions.every((version) => version <= SupportedVersion3.JWT_VC_PRESENTATION_PROFILE_v1) && verifiedAuthorizationRequest.presentationDefinitions && verifiedAuthorizationRequest.presentationDefinitions.length > 0 ? verifiedAuthorizationRequest.presentationDefinitions : void 0,
2124
- dcqlQuery: verifiedAuthorizationRequest.dcqlQuery
2125
- };
2126
- }
2127
- async determineCorrelationId(uri, verifiedAuthorizationRequest, clientName, context) {
2128
- if (uri) {
2129
- return await translateCorrelationIdToName(uri.hostname, context) ?? uri.hostname;
2130
- }
2131
- if (verifiedAuthorizationRequest.issuer) {
2132
- const issuerHostname = verifiedAuthorizationRequest.issuer.split("://")[1];
2133
- return await translateCorrelationIdToName(issuerHostname, context) ?? issuerHostname;
2134
- }
2135
- if (clientName) {
2136
- return clientName;
2137
- }
2138
- throw new Error("Can't determine correlationId from request");
2139
- }
2140
- async siopRetrieveContact(args, context) {
2141
- const { authorizationRequestData } = args;
2142
- const { agent } = context;
2143
- if (authorizationRequestData === void 0) {
2144
- return Promise.reject(Error("Missing authorization request data in context"));
2145
- }
2146
- return agent.cmGetContacts({
2147
- filter: [
2148
- {
2149
- identities: {
2150
- identifier: {
2151
- correlationId: authorizationRequestData.correlationId
2152
- }
2153
- }
2154
- }
2155
- ]
2156
- }).then((contacts) => contacts.length === 1 ? contacts[0] : void 0);
2157
- }
2158
- async siopAddContactIdentity(args, context) {
2159
- const { agent } = context;
2160
- const { contact, authorizationRequestData } = args;
2161
- if (contact === void 0) {
2162
- return Promise.reject(Error("Missing contact in context"));
2163
- }
2164
- if (authorizationRequestData === void 0) {
2165
- return Promise.reject(Error("Missing authorization request data in context"));
2166
- }
2167
- const clientId = authorizationRequestData.clientId ?? authorizationRequestData.issuer;
2168
- const correlationId = clientId ? clientId.startsWith("did:") ? clientId : `${new URL(clientId).protocol}//${new URL(clientId).hostname}` : void 0;
2169
- if (correlationId) {
2170
- const identity = {
2171
- alias: correlationId,
2172
- origin: IdentityOrigin.EXTERNAL,
2173
- roles: [
2174
- CredentialRole2.ISSUER
2175
- ],
2176
- identifier: {
2177
- type: correlationId.startsWith("did:") ? CorrelationIdentifierType.DID : CorrelationIdentifierType.URL,
2178
- correlationId
2179
- }
2180
- };
2181
- const addedIdentity = await agent.cmAddIdentity({
2182
- contactId: contact.id,
2183
- identity
2184
- });
2185
- await context.agent.emit(Siopv2HolderEvent.CONTACT_IDENTITY_CREATED, {
2186
- contactId: contact.id,
2187
- identity: addedIdentity
2188
- });
2189
- logger4.info(`Contact identity created: ${JSON.stringify(addedIdentity)}`);
2190
- }
2191
- }
2192
- async siopSendResponse(args, context) {
2193
- const { didAuthConfig, authorizationRequestData, selectedCredentials, isFirstParty } = args;
2194
- if (didAuthConfig === void 0) {
2195
- return Promise.reject(Error("Missing config in context"));
2196
- }
2197
- if (authorizationRequestData === void 0) {
2198
- return Promise.reject(Error("Missing authorization request data in context"));
2199
- }
2200
- const pex = new PEX3({
2201
- hasher: this.hasher
2202
- });
2203
- const verifiableCredentialsWithDefinition = [];
2204
- const dcqlCredentialsWithCredentials = /* @__PURE__ */ new Map();
2205
- if (Array.isArray(authorizationRequestData.presentationDefinitions) && authorizationRequestData?.presentationDefinitions.length > 0) {
2206
- try {
2207
- authorizationRequestData.presentationDefinitions?.forEach((presentationDefinition) => {
2208
- const { areRequiredCredentialsPresent, verifiableCredential: verifiableCredentials } = pex.selectFrom(presentationDefinition.definition, selectedCredentials.map((udc) => udc.originalVerifiableCredential));
2209
- if (areRequiredCredentialsPresent !== Status2.ERROR && verifiableCredentials) {
2210
- let uniqueDigitalCredentials = [];
2211
- uniqueDigitalCredentials = verifiableCredentials.map((vc) => {
2212
- const hash = typeof vc === "string" ? computeEntryHash(vc.split("~"[0])) : computeEntryHash(vc);
2213
- const udc = selectedCredentials.find((udc2) => udc2.hash == hash || udc2.originalVerifiableCredential == vc);
2214
- if (!udc) {
2215
- throw Error(`UniqueDigitalCredential could not be found in store. Either the credential is not present in the store or the hash is not correct.`);
2216
- }
2217
- return udc;
2218
- });
2219
- verifiableCredentialsWithDefinition.push({
2220
- definition: presentationDefinition,
2221
- credentials: uniqueDigitalCredentials
2222
- });
2223
- }
2224
- });
2225
- } catch (e) {
2226
- return Promise.reject(e);
2227
- }
2228
- if (verifiableCredentialsWithDefinition.length === 0) {
2229
- return Promise.reject(Error("None of the selected credentials match any of the presentation definitions."));
2230
- }
2231
- } else if (authorizationRequestData.dcqlQuery) {
2232
- if (this.hasMDocCredentials(selectedCredentials) || this.hasSdJwtCredentials(selectedCredentials)) {
2233
- try {
2234
- selectedCredentials.forEach((vc) => {
2235
- if (this.isSdJwtCredential(vc)) {
2236
- const payload = vc.originalVerifiableCredential.decodedPayload;
2237
- const result = {
2238
- claims: payload,
2239
- vct: payload.vct,
2240
- credential_format: "vc+sd-jwt"
2241
- };
2242
- dcqlCredentialsWithCredentials.set(result, vc);
2243
- } else {
2244
- throw Error(`Invalid credential format: ${vc.digitalCredential.documentFormat}`);
2245
- }
2246
- });
2247
- } catch (e) {
2248
- return Promise.reject(e);
2249
- }
2250
- const dcqlPresentationRecord = {};
2251
- const queryResult = DcqlQuery2.query(authorizationRequestData.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()));
2252
- for (const [key, value] of Object.entries(queryResult.credential_matches)) {
2253
- if (value.success) {
2254
- dcqlPresentationRecord[key] = this.retrieveEncodedCredential(dcqlCredentialsWithCredentials.get(value.output));
2255
- }
2256
- }
2257
- }
2258
- }
2259
- const response = await siopSendAuthorizationResponse(ConnectionType2.SIOPv2_OpenID4VP, {
2260
- sessionId: didAuthConfig.sessionId,
2261
- ...args.idOpts && {
2262
- idOpts: args.idOpts
2263
- },
2264
- ...authorizationRequestData.presentationDefinitions !== void 0 && {
2265
- verifiableCredentialsWithDefinition
2266
- },
2267
- isFirstParty,
2268
- hasher: this.hasher
2269
- }, context);
2270
- const contentType = response.headers.get("content-type") || "";
2271
- let responseBody = null;
2272
- const text = await response.text();
2273
- if (text) {
2274
- responseBody = contentType.includes("application/json") || text.startsWith("{") ? JSON.parse(text) : text;
2275
- }
2276
- return {
2277
- body: responseBody,
2278
- url: response?.url,
2279
- queryParams: decodeUriAsJson(response?.url)
2280
- };
2281
- }
2282
- hasMDocCredentials = /* @__PURE__ */ __name((credentials) => {
2283
- return credentials.some(this.isMDocCredential);
2284
- }, "hasMDocCredentials");
2285
- isMDocCredential = /* @__PURE__ */ __name((credential) => {
2286
- return credential.digitalCredential.documentFormat === CredentialDocumentFormat.MSO_MDOC && credential.digitalCredential.documentType === DocumentType.VC;
2287
- }, "isMDocCredential");
2288
- hasSdJwtCredentials = /* @__PURE__ */ __name((credentials) => {
2289
- return credentials.some(this.isSdJwtCredential);
2290
- }, "hasSdJwtCredentials");
2291
- isSdJwtCredential = /* @__PURE__ */ __name((credential) => {
2292
- return credential.digitalCredential.documentFormat === CredentialDocumentFormat.SD_JWT && credential.digitalCredential.documentType === DocumentType.VC;
2293
- }, "isSdJwtCredential");
2294
- retrieveEncodedCredential = /* @__PURE__ */ __name((credential) => {
2295
- return credential.originalVerifiableCredential !== void 0 && credential.originalVerifiableCredential !== null && credential?.originalVerifiableCredential?.compactSdJwtVc !== void 0 && credential?.originalVerifiableCredential?.compactSdJwtVc !== null ? credential.originalVerifiableCredential.compactSdJwtVc : credential.originalVerifiableCredential;
2296
- }, "retrieveEncodedCredential");
2297
- async siopGetSelectableCredentials(args, context) {
2298
- const { authorizationRequestData } = args;
2299
- if (!authorizationRequestData || !authorizationRequestData.presentationDefinitions || authorizationRequestData.presentationDefinitions.length === 0) {
2300
- return Promise.reject(Error("Missing required fields in arguments or context"));
2301
- }
2302
- if (authorizationRequestData.presentationDefinitions.length > 1) {
2303
- return Promise.reject(Error("Multiple presentation definitions present"));
2304
- }
2305
- return getSelectableCredentials(authorizationRequestData.presentationDefinitions[0].definition, context);
2306
- }
2307
- };
2308
-
2309
- // src/machine/CallbackStateListener.ts
2310
- import { Loggers as Loggers5, LogLevel, LogMethod } from "@sphereon/ssi-types";
2311
- var logger5 = Loggers5.DEFAULT.options("sphereon:siopv2-oid4vp:op-auth", {
2312
- defaultLogLevel: LogLevel.DEBUG,
2313
- methods: [
2314
- LogMethod.CONSOLE
2315
- ]
2316
- }).get("sphereon:siopv2-oid4vp:op-auth");
2317
- var OID4VPCallbackStateListener = /* @__PURE__ */ __name((callbacks) => {
2318
- return async (oid4vciMachine, state) => {
2319
- if (state._event.type === "internal") {
2320
- logger5.debug("oid4vpCallbackStateListener: internal event");
2321
- return;
2322
- }
2323
- logger5.info(`VP state listener state: ${JSON.stringify(state.value)}`);
2324
- if (!callbacks || callbacks.size === 0) {
2325
- logger5.info(`VP no callbacks registered for state: ${JSON.stringify(state.value)}`);
2326
- return;
2327
- }
2328
- for (const [stateKey, callback] of callbacks) {
2329
- if (state.matches(stateKey)) {
2330
- logger5.log(`VP state callback for state: ${JSON.stringify(state.value)}, will execute...`);
2331
- await callback(oid4vciMachine, state).then(() => logger5.log(`VP state callback executed for state: ${JSON.stringify(state.value)}`)).catch((error) => {
2332
- logger5.error(`VP state callback failed for state: ${JSON.stringify(state.value)}, error: ${JSON.stringify(error?.message)}, ${JSON.stringify(state.event)}`);
2333
- if (error.stack) {
2334
- logger5.error(error.stack);
2335
- }
2336
- });
2337
- break;
2338
- }
2339
- }
2340
- };
2341
- }, "OID4VPCallbackStateListener");
2342
-
2343
- // src/link-handler/index.ts
2344
- import { contextHasPlugin } from "@sphereon/ssi-sdk.agent-config";
2345
- import { LinkHandlerAdapter } from "@sphereon/ssi-sdk.core";
2346
- import { interpreterStartOrResume } from "@sphereon/ssi-sdk.xstate-machine-persistence";
2347
- import { Loggers as Loggers6 } from "@sphereon/ssi-types";
2348
- var logger6 = Loggers6.DEFAULT.options(LOGGER_NAMESPACE, {}).get(LOGGER_NAMESPACE);
2349
- var Siopv2OID4VPLinkHandler = class extends LinkHandlerAdapter {
2350
- static {
2351
- __name(this, "Siopv2OID4VPLinkHandler");
2352
- }
2353
- context;
2354
- stateNavigationListener;
2355
- noStateMachinePersistence;
2356
- idOpts;
2357
- constructor(args) {
2358
- super({
2359
- ...args,
2360
- id: "Siopv2"
2361
- });
2362
- this.context = args.context;
2363
- this.noStateMachinePersistence = args.noStateMachinePersistence === true;
2364
- this.stateNavigationListener = args.stateNavigationListener;
2365
- this.idOpts = args.idOpts;
2366
- }
2367
- async handle(url, opts) {
2368
- logger6.debug(`handling SIOP link: ${url}`);
2369
- const siopv2Machine = await this.context.agent.siopGetMachineInterpreter({
2370
- url,
2371
- idOpts: opts?.idOpts ?? this.idOpts,
2372
- stateNavigationListener: this.stateNavigationListener
2373
- });
2374
- const interpreter = siopv2Machine.interpreter;
2375
- if (!this.noStateMachinePersistence && !opts?.machineState && contextHasPlugin(this.context, "machineStatesFindActive")) {
2376
- const init = await interpreterStartOrResume({
2377
- interpreter,
2378
- context: this.context,
2379
- cleanupAllOtherInstances: true,
2380
- cleanupOnFinalState: true,
2381
- singletonCheck: true,
2382
- noRegistration: this.noStateMachinePersistence
2383
- });
2384
- logger6.debug(`SIOP machine started for link: ${url}`, init);
2385
- } else {
2386
- interpreter.start(opts?.machineState);
2387
- logger6.debug(`SIOP machine started for link: ${url}`);
2388
- }
2389
- }
2390
- };
2391
-
2392
- // src/index.ts
2393
- var schema = require_plugin_schema();
2394
- export {
2395
- DEFAULT_JWT_PROOF_TYPE,
2396
- DID_PREFIX,
2397
- DidAuthSiopOpAuthenticator,
2398
- LOGGER_NAMESPACE,
2399
- OID4VP,
2400
- OID4VPCallbackStateListener,
2401
- OpSession,
2402
- Siopv2HolderEvent,
2403
- Siopv2Machine,
2404
- Siopv2MachineAddContactStates,
2405
- Siopv2MachineEvents,
2406
- Siopv2MachineGuards,
2407
- Siopv2MachineServices,
2408
- Siopv2MachineStates,
2409
- Siopv2OID4VPLinkHandler,
2410
- SupportedLanguage,
2411
- createJwtCallbackWithIdOpts,
2412
- createJwtCallbackWithOpOpts,
2413
- createOID4VPPresentationSignCallback,
2414
- createOP,
2415
- createOPBuilder,
2416
- didAuthSiopOpAuthenticatorMethods,
2417
- events,
2418
- getSigningAlgo,
2419
- schema
2420
- };
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.Siopv2Machine = exports.didAuthSiopOpAuthenticatorMethods = exports.DidAuthSiopOpAuthenticator = exports.schema = void 0;
18
+ /**
19
+ * @public
20
+ */
21
+ const schema = require('../plugin.schema.json');
22
+ exports.schema = schema;
23
+ var DidAuthSiopOpAuthenticator_1 = require("./agent/DidAuthSiopOpAuthenticator");
24
+ Object.defineProperty(exports, "DidAuthSiopOpAuthenticator", { enumerable: true, get: function () { return DidAuthSiopOpAuthenticator_1.DidAuthSiopOpAuthenticator; } });
25
+ Object.defineProperty(exports, "didAuthSiopOpAuthenticatorMethods", { enumerable: true, get: function () { return DidAuthSiopOpAuthenticator_1.didAuthSiopOpAuthenticatorMethods; } });
26
+ var Siopv2Machine_1 = require("./machine/Siopv2Machine");
27
+ Object.defineProperty(exports, "Siopv2Machine", { enumerable: true, get: function () { return Siopv2Machine_1.Siopv2Machine; } });
28
+ __exportStar(require("./machine/CallbackStateListener"), exports);
29
+ __exportStar(require("./session"), exports);
30
+ __exportStar(require("./types"), exports);
31
+ __exportStar(require("./link-handler"), exports);
2421
32
  //# sourceMappingURL=index.js.map