@sphereon/ssi-sdk.siopv2-oid4vp-op-auth 0.34.1-feature.SSISDK.26.74 → 0.34.1-feature.SSISDK.26.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -428,436 +428,12 @@ var import_ssi_sdk6 = require("@sphereon/ssi-sdk.data-store");
428
428
  var import_ssi_types7 = require("@sphereon/ssi-types");
429
429
  var import_uuid2 = require("uuid");
430
430
 
431
- // src/session/functions.ts
432
- var import_did_auth_siop = require("@sphereon/did-auth-siop");
433
- var import_oid4vc_common = require("@sphereon/oid4vc-common");
434
- var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.identifier-resolution");
435
- var import_ssi_sdk = require("@sphereon/ssi-sdk.presentation-exchange");
436
- var import_events = require("events");
437
- async function createOID4VPPresentationSignCallback({ presentationSignCallback, idOpts: idOpts1, domain, fetchRemoteContexts, challenge, format, context, skipDidResolution }) {
438
- if (typeof presentationSignCallback === "function") {
439
- return presentationSignCallback;
440
- }
441
- return (0, import_ssi_sdk.createPEXPresentationSignCallback)({
442
- idOpts: idOpts1,
443
- fetchRemoteContexts,
444
- domain,
445
- challenge,
446
- format,
447
- skipDidResolution
448
- }, context);
449
- }
450
- __name(createOID4VPPresentationSignCallback, "createOID4VPPresentationSignCallback");
451
- async function createOPBuilder({ opOptions, idOpts: idOpts1, context }) {
452
- const eventEmitter = opOptions.eventEmitter ?? new import_events.EventEmitter();
453
- const builder = import_did_auth_siop.OP.builder().withResponseMode(opOptions.responseMode ?? import_did_auth_siop.ResponseMode.DIRECT_POST).withSupportedVersions(opOptions.supportedVersions ?? [
454
- import_did_auth_siop.SupportedVersion.SIOPv2_ID1,
455
- import_did_auth_siop.SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1,
456
- import_did_auth_siop.SupportedVersion.SIOPv2_D11,
457
- import_did_auth_siop.SupportedVersion.SIOPv2_D12_OID4VP_D18
458
- ]).withExpiresIn(opOptions.expiresIn ?? 300).withEventEmitter(eventEmitter).withRegistration({
459
- passBy: import_did_auth_siop.PassBy.VALUE
460
- });
461
- const wellknownDIDVerifyCallback = opOptions.wellknownDIDVerifyCallback ? opOptions.wellknownDIDVerifyCallback : async (args) => {
462
- const result = await context.agent.cvVerifyCredential({
463
- credential: args.credential,
464
- fetchRemoteContexts: true
465
- });
466
- return {
467
- verified: result.result
468
- };
469
- };
470
- builder.withVerifyJwtCallback(opOptions.verifyJwtCallback ? opOptions.verifyJwtCallback : getVerifyJwtCallback({
471
- verifyOpts: {
472
- wellknownDIDVerifyCallback,
473
- checkLinkedDomain: "if_present"
474
- }
475
- }, context));
476
- if (idOpts1) {
477
- if (opOptions.skipDidResolution && (0, import_ssi_sdk_ext.isManagedIdentifierDidOpts)(idOpts1)) {
478
- idOpts1.offlineWhenNoDIDRegistered = true;
479
- }
480
- const createJwtCallback = createJwtCallbackWithIdOpts(idOpts1, context);
481
- builder.withCreateJwtCallback(createJwtCallback);
482
- builder.withPresentationSignCallback(await createOID4VPPresentationSignCallback({
483
- presentationSignCallback: opOptions.presentationSignCallback,
484
- skipDidResolution: opOptions.skipDidResolution ?? false,
485
- idOpts: idOpts1,
486
- context
487
- }));
488
- } else {
489
- const createJwtCallback = createJwtCallbackWithOpOpts(opOptions, context);
490
- builder.withCreateJwtCallback(createJwtCallback);
491
- }
492
- return builder;
493
- }
494
- __name(createOPBuilder, "createOPBuilder");
495
- function createJwtCallbackWithIdOpts(idOpts1, context) {
496
- return async (jwtIssuer, jwt) => {
497
- let issuer;
498
- if ((0, import_ssi_sdk_ext.isManagedIdentifierDidOpts)(idOpts1)) {
499
- issuer = {
500
- ...idOpts1,
501
- method: idOpts1.method,
502
- noIdentifierInHeader: false
503
- };
504
- } else if ((0, import_ssi_sdk_ext.isManagedIdentifierX5cOpts)(idOpts1)) {
505
- issuer = {
506
- ...idOpts1,
507
- method: idOpts1.method,
508
- noIdentifierInHeader: false
509
- };
510
- } else {
511
- return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
512
- }
513
- const result = await context.agent.jwtCreateJwsCompactSignature({
514
- issuer,
515
- protectedHeader: jwt.header,
516
- payload: jwt.payload
517
- });
518
- return result.jwt;
519
- };
520
- }
521
- __name(createJwtCallbackWithIdOpts, "createJwtCallbackWithIdOpts");
522
- function createJwtCallbackWithOpOpts(opOpts, context) {
523
- return async (jwtIssuer, jwt) => {
524
- let identifier;
525
- if (jwtIssuer.method == "did") {
526
- identifier = jwtIssuer.didUrl;
527
- } else if (jwtIssuer.method == "x5c") {
528
- identifier = jwtIssuer.x5c;
529
- } else {
530
- return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
531
- }
532
- const result = await context.agent.jwtCreateJwsCompactSignature({
533
- // FIXME fix cose-key inference
534
- // @ts-ignore
535
- issuer: {
536
- identifier,
537
- kmsKeyRef: idOpts.kmsKeyRef,
538
- noIdentifierInHeader: false
539
- },
540
- // FIXME fix JWK key_ops
541
- // @ts-ignore
542
- protectedHeader: jwt.header,
543
- payload: jwt.payload
544
- });
545
- return result.jwt;
546
- };
547
- }
548
- __name(createJwtCallbackWithOpOpts, "createJwtCallbackWithOpOpts");
549
- function getVerifyJwtCallback(_opts, context) {
550
- return async (_jwtVerifier, jwt) => {
551
- const result = await context.agent.jwtVerifyJwsSignature({
552
- jws: jwt.raw
553
- });
554
- console.log(result.message);
555
- return !result.error;
556
- };
557
- }
558
- __name(getVerifyJwtCallback, "getVerifyJwtCallback");
559
- async function createOP({ opOptions, idOpts: idOpts1, context }) {
560
- return (await createOPBuilder({
561
- opOptions,
562
- idOpts: idOpts1,
563
- context
564
- })).build();
565
- }
566
- __name(createOP, "createOP");
567
- function getSigningAlgo(type) {
568
- switch (type) {
569
- case "Ed25519":
570
- return import_oid4vc_common.SigningAlgo.EDDSA;
571
- case "Secp256k1":
572
- return import_oid4vc_common.SigningAlgo.ES256K;
573
- case "Secp256r1":
574
- return import_oid4vc_common.SigningAlgo.ES256;
575
- // @ts-ignore
576
- case "RSA":
577
- return import_oid4vc_common.SigningAlgo.RS256;
578
- default:
579
- throw Error("Key type not yet supported");
580
- }
581
- }
582
- __name(getSigningAlgo, "getSigningAlgo");
583
-
584
- // src/session/OID4VP.ts
585
- var OID4VP = class _OID4VP {
586
- static {
587
- __name(this, "OID4VP");
588
- }
589
- //private readonly session: OpSession
590
- // private readonly allIdentifiers: string[]
591
- // private readonly hasher?: HasherSync
592
- constructor(args) {
593
- }
594
- static async init(session, allIdentifiers, hasher) {
595
- return new _OID4VP({
596
- session,
597
- allIdentifiers: allIdentifiers ?? await session.getSupportedDIDs(),
598
- hasher
599
- });
600
- }
601
- };
602
-
603
- // src/session/OpSession.ts
604
- var import_did_auth_siop2 = require("@sphereon/did-auth-siop");
605
- var import_ssi_sdk_ext2 = require("@sphereon/ssi-sdk-ext.did-utils");
606
- var import_ssi_sdk2 = require("@sphereon/ssi-sdk.core");
607
- var import_ssi_types = require("@sphereon/ssi-types");
608
- var import_uuid = require("uuid");
609
- var import_ssi_types2 = require("@sphereon/ssi-types");
610
- var logger = import_ssi_types2.Loggers.DEFAULT.get("sphereon:oid4vp:OpSession");
611
- var OpSession = class _OpSession {
612
- static {
613
- __name(this, "OpSession");
614
- }
615
- ts = (/* @__PURE__ */ new Date()).getDate();
616
- id;
617
- options;
618
- context;
619
- requestJwtOrUri;
620
- verifiedAuthorizationRequest;
621
- _nonce;
622
- _state;
623
- constructor(options) {
624
- this.id = options.sessionId;
625
- this.options = options.op;
626
- this.context = options.context;
627
- this.requestJwtOrUri = options.requestJwtOrUri;
628
- }
629
- static async init(options) {
630
- return new _OpSession(options);
631
- }
632
- async getAuthorizationRequest() {
633
- if (!this.verifiedAuthorizationRequest) {
634
- const op = await createOP({
635
- opOptions: this.options,
636
- context: this.context
637
- });
638
- this.verifiedAuthorizationRequest = await op.verifyAuthorizationRequest(this.requestJwtOrUri);
639
- this._nonce = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("nonce");
640
- this._state = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("state");
641
- await this.getSupportedDIDMethods();
642
- }
643
- return this.verifiedAuthorizationRequest;
644
- }
645
- async getAuthorizationRequestURI() {
646
- return await import_did_auth_siop2.URI.fromAuthorizationRequest((await this.getAuthorizationRequest()).authorizationRequest);
647
- }
648
- get nonce() {
649
- if (!this._nonce) {
650
- throw Error("No nonce available. Please get authorization request first");
651
- }
652
- return this._nonce;
653
- }
654
- get state() {
655
- if (!this._state) {
656
- throw Error("No state available. Please get authorization request first");
657
- }
658
- return this._state;
659
- }
660
- clear() {
661
- this._nonce = void 0;
662
- this._state = void 0;
663
- this.verifiedAuthorizationRequest = void 0;
664
- return this;
665
- }
666
- async getSupportedDIDMethods(didPrefix) {
667
- const agentMethods = this.getAgentDIDMethodsSupported({
668
- didPrefix
669
- });
670
- let rpMethods = await this.getRPDIDMethodsSupported({
671
- didPrefix,
672
- agentMethods
673
- });
674
- logger.debug(`RP supports subject syntax types: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
675
- if (rpMethods.dids.length === 0) {
676
- logger.debug(`RP does not support DIDs. Supported: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
677
- return [];
678
- }
679
- let intersection;
680
- if (rpMethods.dids.includes("did")) {
681
- intersection = agentMethods && agentMethods.length > 0 ? agentMethods : (await (0, import_ssi_sdk_ext2.getAgentDIDMethods)(this.context)).map((method) => convertDidMethod(method, didPrefix));
682
- } else if (!agentMethods || agentMethods.length === 0) {
683
- intersection = rpMethods.dids?.map((method) => convertDidMethod(method, didPrefix));
684
- } else {
685
- intersection = agentMethods.filter((value) => rpMethods.dids.includes(value));
686
- }
687
- if (intersection.length === 0) {
688
- throw Error("No matching DID methods between agent and relying party");
689
- }
690
- return intersection.map((value) => convertDidMethod(value, didPrefix));
691
- }
692
- getAgentDIDMethodsSupported(opts) {
693
- const agentMethods = this.options.supportedDIDMethods?.map((method) => convertDidMethod(method, opts.didPrefix));
694
- logger.debug(`agent methods: ${JSON.stringify(agentMethods)}`);
695
- return agentMethods;
696
- }
697
- async getSubjectSyntaxTypesSupported() {
698
- const authReq = await this.getAuthorizationRequest();
699
- const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported;
700
- return subjectSyntaxTypesSupported ?? [];
701
- }
702
- async getRPDIDMethodsSupported(opts) {
703
- let keyType;
704
- const agentMethods = (opts.agentMethods ?? this.getAgentDIDMethodsSupported(opts))?.map((method) => convertDidMethod(method, opts.didPrefix)) ?? [];
705
- logger.debug(`agent methods supported: ${JSON.stringify(agentMethods)}`);
706
- const authReq = await this.getAuthorizationRequest();
707
- const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported?.map((method) => convertDidMethod(method, opts.didPrefix)).filter((val) => !val.startsWith("did"));
708
- logger.debug(`subject syntax types supported in rp method supported: ${JSON.stringify(subjectSyntaxTypesSupported)}`);
709
- const aud = await authReq.authorizationRequest.getMergedProperty("aud");
710
- let rpMethods = [];
711
- if (aud && aud.startsWith("did:")) {
712
- const didMethod = convertDidMethod((0, import_ssi_types.parseDid)(aud).method, opts.didPrefix);
713
- logger.debug(`aud did method: ${didMethod}`);
714
- if (subjectSyntaxTypesSupported && subjectSyntaxTypesSupported.length > 0 && !subjectSyntaxTypesSupported.includes("did") && !subjectSyntaxTypesSupported.includes(didMethod)) {
715
- throw Error(`The aud DID method ${didMethod} is not in the supported types ${subjectSyntaxTypesSupported}`);
716
- }
717
- rpMethods = [
718
- didMethod
719
- ];
720
- } else if (subjectSyntaxTypesSupported) {
721
- rpMethods = (Array.isArray(subjectSyntaxTypesSupported) ? subjectSyntaxTypesSupported : [
722
- subjectSyntaxTypesSupported
723
- ]).map((method) => convertDidMethod(method, opts.didPrefix));
724
- }
725
- const isEBSI = rpMethods.length === 0 && (authReq.issuer?.includes(".ebsi.eu") || authReq.authorizationRequest.getMergedProperty("client_id")?.includes(".ebsi.eu"));
726
- let codecName = void 0;
727
- if (isEBSI && (!aud || !aud.startsWith("http"))) {
728
- logger.debug(`EBSI detected, adding did:key to supported DID methods for RP`);
729
- const didKeyMethod = convertDidMethod("did:key", opts.didPrefix);
730
- if (!agentMethods?.includes(didKeyMethod)) {
731
- throw Error(`EBSI detected, but agent did not support did:key. Please reconfigure agent`);
732
- }
733
- rpMethods = [
734
- didKeyMethod
735
- ];
736
- keyType = "Secp256r1";
737
- codecName = "jwk_jcs-pub";
738
- }
739
- return {
740
- dids: rpMethods,
741
- codecName,
742
- keyType
743
- };
744
- }
745
- async getSupportedIdentifiers(opts) {
746
- const methods = await this.getSupportedDIDMethods(true);
747
- logger.debug(`supported DID methods (did: prefix = true): ${JSON.stringify(methods)}`);
748
- if (methods.length === 0) {
749
- throw Error(`No DID methods are supported`);
750
- }
751
- const identifiers = await this.context.agent.didManagerFind().then((ids) => ids.filter((id) => methods.includes(id.provider)));
752
- if (identifiers.length === 0) {
753
- logger.debug(`No identifiers available in agent supporting methods ${JSON.stringify(methods)}`);
754
- if (opts?.createInCaseNoDIDFound !== false) {
755
- const { codecName, keyType } = await this.getRPDIDMethodsSupported({
756
- didPrefix: true,
757
- agentMethods: methods
758
- });
759
- const identifier = await this.context.agent.didManagerCreate({
760
- provider: methods[0],
761
- options: {
762
- codecName,
763
- keyType,
764
- type: keyType
765
- }
766
- });
767
- logger.debug(`Created a new identifier for the SIOP interaction: ${identifier.did}`);
768
- identifiers.push(identifier);
769
- }
770
- }
771
- logger.debug(`supported identifiers: ${JSON.stringify(identifiers.map((id) => id.did))}`);
772
- return identifiers;
773
- }
774
- async getSupportedDIDs() {
775
- return (await this.getSupportedIdentifiers()).map((id) => id.did);
776
- }
777
- async getRedirectUri() {
778
- return Promise.resolve(this.verifiedAuthorizationRequest.responseURI);
779
- }
780
- async getOID4VP(args) {
781
- return await OID4VP.init(this, args.allIdentifiers ?? [], args.hasher);
782
- }
783
- async createJarmResponseCallback({ responseOpts }) {
784
- const agent = this.context.agent;
785
- return /* @__PURE__ */ __name(async function jarmResponse(opts) {
786
- const { clientMetadata, requestObjectPayload, authorizationResponsePayload: authResponse } = opts;
787
- const jwk = await import_did_auth_siop2.OP.extractEncJwksFromClientMetadata(clientMetadata);
788
- const recipientKey = await agent.identifierExternalResolveByJwk({
789
- identifier: jwk
790
- });
791
- return await agent.jwtEncryptJweCompactJwt({
792
- recipientKey,
793
- protectedHeader: {},
794
- alg: requestObjectPayload.client_metadata.authorization_encrypted_response_alg ?? "ECDH-ES",
795
- enc: requestObjectPayload.client_metadata.authorization_encrypted_response_enc ?? "A256GCM",
796
- apv: (0, import_ssi_sdk2.encodeBase64url)(opts.requestObjectPayload.nonce),
797
- apu: (0, import_ssi_sdk2.encodeBase64url)((0, import_uuid.v4)()),
798
- payload: authResponse,
799
- issuer: responseOpts.issuer,
800
- audience: responseOpts.audience
801
- }).then((result) => {
802
- return {
803
- response: result.jwt
804
- };
805
- });
806
- }, "jarmResponse");
807
- }
808
- async sendAuthorizationResponse(args) {
809
- const { responseSignerOpts, dcqlResponse, isFirstParty } = args;
810
- const resolveOpts = this.options.resolveOpts ?? {
811
- resolver: (0, import_ssi_sdk_ext2.getAgentResolver)(this.context, {
812
- uniresolverResolution: true,
813
- localResolution: true,
814
- resolverResolution: true
815
- })
816
- };
817
- if (!resolveOpts.subjectSyntaxTypesSupported || resolveOpts.subjectSyntaxTypesSupported.length === 0) {
818
- resolveOpts.subjectSyntaxTypesSupported = await this.getSupportedDIDMethods(true);
819
- }
820
- const request = await this.getAuthorizationRequest();
821
- const op = await createOP({
822
- opOptions: {
823
- ...this.options,
824
- resolveOpts: {
825
- ...this.options.resolveOpts
826
- },
827
- eventEmitter: this.options.eventEmitter,
828
- presentationSignCallback: this.options.presentationSignCallback,
829
- wellknownDIDVerifyCallback: this.options.wellknownDIDVerifyCallback,
830
- supportedVersions: request.versions
831
- },
832
- idOpts: responseSignerOpts,
833
- context: this.context
834
- });
835
- let issuer = responseSignerOpts.issuer;
836
- const responseOpts = {
837
- issuer,
838
- ...isFirstParty && {
839
- isFirstParty
840
- },
841
- dcqlResponse
842
- };
843
- const authResponse = await op.createAuthorizationResponse(request, responseOpts);
844
- const response = await op.submitAuthorizationResponse(authResponse, await this.createJarmResponseCallback({
845
- responseOpts
846
- }));
847
- if (response.status >= 400) {
848
- throw Error(`Error ${response.status}: ${response.statusText || await response.text()}`);
849
- } else {
850
- return response;
851
- }
852
- }
853
- };
854
- function convertDidMethod(didMethod, didPrefix) {
855
- if (didPrefix === false) {
856
- return didMethod.startsWith("did:") ? didMethod.toLowerCase().replace("did:", "") : didMethod.toLowerCase();
857
- }
858
- return didMethod.startsWith("did:") ? didMethod.toLowerCase() : `did:${didMethod.toLowerCase().replace("did:", "")}`;
859
- }
860
- __name(convertDidMethod, "convertDidMethod");
431
+ // src/machine/Siopv2Machine.ts
432
+ var import_xstate = require("xstate");
433
+
434
+ // src/localization/Localization.ts
435
+ var import_i18n_js = __toESM(require("i18n-js"), 1);
436
+ var import_lodash = __toESM(require("lodash.memoize"), 1);
861
437
 
862
438
  // src/types/IDidAuthSiopOpAuthenticator.ts
863
439
  var LOGGER_NAMESPACE = "sphereon:siopv2-oid4vp:op-auth";
@@ -933,12 +509,7 @@ var Siopv2MachineServices = /* @__PURE__ */ function(Siopv2MachineServices2) {
933
509
  // src/types/identifier/index.ts
934
510
  var DID_PREFIX = "did";
935
511
 
936
- // src/machine/Siopv2Machine.ts
937
- var import_xstate = require("xstate");
938
-
939
512
  // src/localization/Localization.ts
940
- var import_i18n_js = __toESM(require("i18n-js"), 1);
941
- var import_lodash = __toESM(require("lodash.memoize"), 1);
942
513
  var Localization = class Localization2 {
943
514
  static {
944
515
  __name(this, "Localization");
@@ -978,8 +549,8 @@ var Localization = class Localization2 {
978
549
  var translate = Localization.translate;
979
550
 
980
551
  // src/machine/Siopv2Machine.ts
981
- var import_ssi_types3 = require("@sphereon/ssi-types");
982
- var logger2 = import_ssi_types3.Loggers.DEFAULT.get(LOGGER_NAMESPACE);
552
+ var import_ssi_types = require("@sphereon/ssi-types");
553
+ var logger = import_ssi_types.Loggers.DEFAULT.get(LOGGER_NAMESPACE);
983
554
  var Siopv2HasNoContactGuard = /* @__PURE__ */ __name((_ctx, _event) => {
984
555
  const { contact } = _ctx;
985
556
  return contact === void 0;
@@ -1111,7 +682,120 @@ var createSiopv2Machine = /* @__PURE__ */ __name((opts) => {
1111
682
  target: Siopv2MachineStates.handleError,
1112
683
  actions: (0, import_xstate.assign)({
1113
684
  error: /* @__PURE__ */ __name((_ctx, _event) => ({
1114
- title: translate("siopv2_machine_retrieve_contact_error_title"),
685
+ title: translate("siopv2_machine_retrieve_contact_error_title"),
686
+ message: _event.data.message,
687
+ stack: _event.data.stack
688
+ }), "error")
689
+ })
690
+ }
691
+ }
692
+ },
693
+ [Siopv2MachineStates.transitionFromSetup]: {
694
+ id: Siopv2MachineStates.transitionFromSetup,
695
+ always: [
696
+ {
697
+ target: Siopv2MachineStates.addContact,
698
+ cond: Siopv2MachineGuards.hasNoContactGuard
699
+ },
700
+ {
701
+ target: Siopv2MachineStates.sendResponse,
702
+ cond: Siopv2MachineGuards.siopOnlyGuard
703
+ },
704
+ {
705
+ target: Siopv2MachineStates.getSelectableCredentials,
706
+ cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
707
+ },
708
+ {
709
+ target: Siopv2MachineStates.selectCredentials,
710
+ cond: Siopv2MachineGuards.siopWithOID4VPGuard
711
+ }
712
+ ]
713
+ },
714
+ [Siopv2MachineStates.addContact]: {
715
+ id: Siopv2MachineStates.addContact,
716
+ initial: Siopv2MachineAddContactStates.idle,
717
+ on: {
718
+ [Siopv2MachineEvents.SET_CONTACT_CONSENT]: {
719
+ actions: (0, import_xstate.assign)({
720
+ hasContactConsent: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "hasContactConsent")
721
+ })
722
+ },
723
+ [Siopv2MachineEvents.SET_CONTACT_ALIAS]: {
724
+ actions: (0, import_xstate.assign)({
725
+ contactAlias: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contactAlias")
726
+ })
727
+ },
728
+ [Siopv2MachineEvents.CREATE_CONTACT]: {
729
+ target: `.${Siopv2MachineAddContactStates.next}`,
730
+ actions: (0, import_xstate.assign)({
731
+ contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
732
+ }),
733
+ cond: Siopv2MachineGuards.createContactGuard
734
+ },
735
+ [Siopv2MachineEvents.DECLINE]: {
736
+ target: Siopv2MachineStates.declined
737
+ },
738
+ [Siopv2MachineEvents.PREVIOUS]: {
739
+ target: Siopv2MachineStates.aborted
740
+ }
741
+ },
742
+ states: {
743
+ [Siopv2MachineAddContactStates.idle]: {},
744
+ [Siopv2MachineAddContactStates.next]: {
745
+ always: {
746
+ target: `#${Siopv2MachineStates.transitionFromSetup}`,
747
+ cond: Siopv2MachineGuards.hasContactGuard
748
+ }
749
+ }
750
+ }
751
+ },
752
+ [Siopv2MachineStates.addContactIdentity]: {
753
+ id: Siopv2MachineStates.addContactIdentity,
754
+ invoke: {
755
+ src: Siopv2MachineServices.addContactIdentity,
756
+ onDone: [
757
+ {
758
+ target: Siopv2MachineStates.getSelectableCredentials,
759
+ actions: /* @__PURE__ */ __name((_ctx, _event) => {
760
+ _ctx.contact?.identities.push(_event.data);
761
+ }, "actions"),
762
+ cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
763
+ },
764
+ {
765
+ target: Siopv2MachineStates.sendResponse,
766
+ actions: /* @__PURE__ */ __name((_ctx, _event) => {
767
+ _ctx.contact?.identities.push(_event.data);
768
+ }, "actions"),
769
+ cond: Siopv2MachineGuards.siopOnlyGuard
770
+ }
771
+ ],
772
+ onError: {
773
+ target: Siopv2MachineStates.handleError,
774
+ actions: (0, import_xstate.assign)({
775
+ error: /* @__PURE__ */ __name((_ctx, _event) => ({
776
+ title: translate("siopv2_machine_add_contact_identity_error_title"),
777
+ message: _event.data.message,
778
+ stack: _event.data.stack
779
+ }), "error")
780
+ })
781
+ }
782
+ }
783
+ },
784
+ [Siopv2MachineStates.getSelectableCredentials]: {
785
+ id: Siopv2MachineStates.getSelectableCredentials,
786
+ invoke: {
787
+ src: Siopv2MachineServices.getSelectableCredentials,
788
+ onDone: {
789
+ target: Siopv2MachineStates.selectCredentials,
790
+ actions: (0, import_xstate.assign)({
791
+ selectableCredentialsMap: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectableCredentialsMap")
792
+ })
793
+ },
794
+ onError: {
795
+ target: Siopv2MachineStates.handleError,
796
+ actions: (0, import_xstate.assign)({
797
+ error: /* @__PURE__ */ __name((_ctx, _event) => ({
798
+ title: translate("siopv2_machine_get_selectable_credentials_error_title"),
1115
799
  message: _event.data.message,
1116
800
  stack: _event.data.stack
1117
801
  }), "error")
@@ -1119,454 +803,772 @@ var createSiopv2Machine = /* @__PURE__ */ __name((opts) => {
1119
803
  }
1120
804
  }
1121
805
  },
1122
- [Siopv2MachineStates.transitionFromSetup]: {
1123
- id: Siopv2MachineStates.transitionFromSetup,
1124
- always: [
1125
- {
1126
- target: Siopv2MachineStates.addContact,
1127
- cond: Siopv2MachineGuards.hasNoContactGuard
806
+ [Siopv2MachineStates.selectCredentials]: {
807
+ id: Siopv2MachineStates.selectCredentials,
808
+ on: {
809
+ [Siopv2MachineEvents.SET_SELECTED_CREDENTIALS]: {
810
+ actions: (0, import_xstate.assign)({
811
+ selectedCredentials: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectedCredentials")
812
+ })
1128
813
  },
1129
- {
814
+ [Siopv2MachineEvents.NEXT]: {
1130
815
  target: Siopv2MachineStates.sendResponse,
1131
- cond: Siopv2MachineGuards.siopOnlyGuard
816
+ cond: Siopv2MachineGuards.hasSelectedRequiredCredentialsGuard
1132
817
  },
1133
- {
1134
- target: Siopv2MachineStates.getSelectableCredentials,
1135
- cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
818
+ [Siopv2MachineEvents.DECLINE]: {
819
+ target: Siopv2MachineStates.declined
1136
820
  },
1137
- {
1138
- target: Siopv2MachineStates.selectCredentials,
1139
- cond: Siopv2MachineGuards.siopWithOID4VPGuard
821
+ [Siopv2MachineEvents.PREVIOUS]: {
822
+ target: Siopv2MachineStates.aborted
1140
823
  }
1141
- ]
824
+ }
1142
825
  },
1143
- [Siopv2MachineStates.addContact]: {
1144
- id: Siopv2MachineStates.addContact,
1145
- initial: Siopv2MachineAddContactStates.idle,
1146
- on: {
1147
- [Siopv2MachineEvents.SET_CONTACT_CONSENT]: {
826
+ [Siopv2MachineStates.sendResponse]: {
827
+ id: Siopv2MachineStates.sendResponse,
828
+ invoke: {
829
+ src: Siopv2MachineServices.sendResponse,
830
+ onDone: {
831
+ target: Siopv2MachineStates.done,
1148
832
  actions: (0, import_xstate.assign)({
1149
- hasContactConsent: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "hasContactConsent")
833
+ authorizationResponseData: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationResponseData")
1150
834
  })
1151
835
  },
1152
- [Siopv2MachineEvents.SET_CONTACT_ALIAS]: {
836
+ onError: {
837
+ target: Siopv2MachineStates.handleError,
1153
838
  actions: (0, import_xstate.assign)({
1154
- contactAlias: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contactAlias")
839
+ error: /* @__PURE__ */ __name((_ctx, _event) => ({
840
+ title: translate("siopv2_machine_send_response_error_title"),
841
+ message: _event.data.message,
842
+ stack: _event.data.stack
843
+ }), "error")
1155
844
  })
1156
- },
1157
- [Siopv2MachineEvents.CREATE_CONTACT]: {
1158
- target: `.${Siopv2MachineAddContactStates.next}`,
1159
- actions: (0, import_xstate.assign)({
1160
- contact: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "contact")
1161
- }),
1162
- cond: Siopv2MachineGuards.createContactGuard
1163
- },
1164
- [Siopv2MachineEvents.DECLINE]: {
1165
- target: Siopv2MachineStates.declined
845
+ }
846
+ }
847
+ },
848
+ [Siopv2MachineStates.handleError]: {
849
+ id: Siopv2MachineStates.handleError,
850
+ on: {
851
+ [Siopv2MachineEvents.NEXT]: {
852
+ target: Siopv2MachineStates.error
1166
853
  },
1167
854
  [Siopv2MachineEvents.PREVIOUS]: {
1168
- target: Siopv2MachineStates.aborted
855
+ target: Siopv2MachineStates.error
1169
856
  }
1170
- },
1171
- states: {
1172
- [Siopv2MachineAddContactStates.idle]: {},
1173
- [Siopv2MachineAddContactStates.next]: {
1174
- always: {
1175
- target: `#${Siopv2MachineStates.transitionFromSetup}`,
1176
- cond: Siopv2MachineGuards.hasContactGuard
857
+ }
858
+ },
859
+ [Siopv2MachineStates.aborted]: {
860
+ id: Siopv2MachineStates.aborted,
861
+ type: "final"
862
+ },
863
+ [Siopv2MachineStates.declined]: {
864
+ id: Siopv2MachineStates.declined,
865
+ type: "final"
866
+ },
867
+ [Siopv2MachineStates.error]: {
868
+ id: Siopv2MachineStates.error,
869
+ type: "final"
870
+ },
871
+ [Siopv2MachineStates.done]: {
872
+ id: Siopv2MachineStates.done,
873
+ type: "final"
874
+ }
875
+ }
876
+ });
877
+ }, "createSiopv2Machine");
878
+ var Siopv2Machine = class {
879
+ static {
880
+ __name(this, "Siopv2Machine");
881
+ }
882
+ static newInstance(opts) {
883
+ logger.info("New Siopv2Machine instance");
884
+ const interpreter = (0, import_xstate.interpret)(createSiopv2Machine(opts).withConfig({
885
+ services: {
886
+ ...opts?.services
887
+ },
888
+ guards: {
889
+ Siopv2HasNoContactGuard,
890
+ Siopv2HasContactGuard,
891
+ Siopv2HasAuthorizationRequestGuard,
892
+ Siopv2HasSelectableCredentialsAndContactGuard,
893
+ Siopv2HasSelectedRequiredCredentialsGuard,
894
+ Siopv2IsSiopOnlyGuard,
895
+ Siopv2IsSiopWithOID4VPGuard,
896
+ Siopv2CreateContactGuard,
897
+ ...opts?.guards
898
+ }
899
+ }));
900
+ if (typeof opts?.subscription === "function") {
901
+ interpreter.onTransition(opts.subscription);
902
+ }
903
+ if (opts?.requireCustomNavigationHook !== true) {
904
+ interpreter.onTransition((snapshot) => {
905
+ if (opts.stateNavigationListener !== void 0) {
906
+ void opts.stateNavigationListener(interpreter, snapshot);
907
+ }
908
+ });
909
+ }
910
+ interpreter.onTransition((snapshot) => {
911
+ logger.info("onTransition to new state", snapshot.value);
912
+ });
913
+ return {
914
+ interpreter
915
+ };
916
+ }
917
+ };
918
+
919
+ // src/services/Siopv2MachineService.ts
920
+ var import_did_auth_siop2 = require("@sphereon/did-auth-siop");
921
+ var import_ssi_sdk_ext = require("@sphereon/ssi-sdk-ext.identifier-resolution");
922
+ var import_ssi_sdk = require("@sphereon/ssi-sdk.credential-store");
923
+ var import_ssi_sdk2 = require("@sphereon/ssi-sdk.data-store");
924
+ var import_ssi_types4 = require("@sphereon/ssi-types");
925
+ var import_ssi_sdk3 = require("@sphereon/ssi-sdk.core");
926
+ var import_dcql = require("dcql");
927
+
928
+ // src/utils/dcql.ts
929
+ var import_ssi_types3 = require("@sphereon/ssi-types");
930
+ var import_did_auth_siop = require("@sphereon/did-auth-siop");
931
+
932
+ // src/utils/CredentialUtils.ts
933
+ var import_ssi_types2 = require("@sphereon/ssi-types");
934
+ var isUniqueDigitalCredential = /* @__PURE__ */ __name((credential) => {
935
+ return credential.digitalCredential !== void 0;
936
+ }, "isUniqueDigitalCredential");
937
+
938
+ // src/utils/dcql.ts
939
+ function convertToDcqlCredentials(credential, hasher) {
940
+ let originalVerifiableCredential;
941
+ if (isUniqueDigitalCredential(credential)) {
942
+ if (!credential.originalVerifiableCredential) {
943
+ throw new Error("originalVerifiableCredential is not defined in UniqueDigitalCredential");
944
+ }
945
+ originalVerifiableCredential = import_ssi_types3.CredentialMapper.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher);
946
+ } else {
947
+ originalVerifiableCredential = import_ssi_types3.CredentialMapper.decodeVerifiableCredential(credential, hasher);
948
+ }
949
+ if (!originalVerifiableCredential) {
950
+ throw new Error("No payload found");
951
+ }
952
+ if (import_ssi_types3.CredentialMapper.isJwtDecodedCredential(originalVerifiableCredential)) {
953
+ return import_did_auth_siop.Dcql.toDcqlJwtCredential(import_ssi_types3.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
954
+ } else if (import_ssi_types3.CredentialMapper.isSdJwtDecodedCredential(originalVerifiableCredential)) {
955
+ return import_did_auth_siop.Dcql.toDcqlSdJwtCredential(import_ssi_types3.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
956
+ } else if (import_ssi_types3.CredentialMapper.isMsoMdocDecodedCredential(originalVerifiableCredential)) {
957
+ return import_did_auth_siop.Dcql.toDcqlMdocCredential(import_ssi_types3.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
958
+ } else if (import_ssi_types3.CredentialMapper.isW3cCredential(originalVerifiableCredential)) {
959
+ return import_did_auth_siop.Dcql.toDcqlJsonLdCredential(import_ssi_types3.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
960
+ }
961
+ throw Error(`Unable to map credential to DCQL credential. Credential: ${JSON.stringify(originalVerifiableCredential)}`);
962
+ }
963
+ __name(convertToDcqlCredentials, "convertToDcqlCredentials");
964
+
965
+ // src/services/Siopv2MachineService.ts
966
+ var import_ssi_sdk_ext2 = require("@sphereon/ssi-sdk-ext.did-utils");
967
+ var logger2 = import_ssi_types4.Loggers.DEFAULT.get(LOGGER_NAMESPACE);
968
+ var siopSendAuthorizationResponse = /* @__PURE__ */ __name(async (connectionType, args, context) => {
969
+ const { agent } = context;
970
+ const { credentials } = args;
971
+ if (connectionType !== import_ssi_sdk2.ConnectionType.SIOPv2_OpenID4VP) {
972
+ return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`));
973
+ }
974
+ const session = await agent.siopGetOPSession({
975
+ sessionId: args.sessionId
976
+ });
977
+ const request = await session.getAuthorizationRequest();
978
+ const aud = request.authorizationRequest.getMergedProperty("aud");
979
+ logger2.debug(`AUD: ${aud}`);
980
+ logger2.debug(JSON.stringify(request.authorizationRequest));
981
+ const domain = await request.authorizationRequest.getMergedProperty("client_id") ?? request.issuer ?? (request.versions.includes(import_did_auth_siop2.SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1) ? "https://self-issued.me/v2/openid-vc" : "https://self-issued.me/v2");
982
+ logger2.debug(`NONCE: ${session.nonce}, domain: ${domain}`);
983
+ const firstUniqueDC = credentials[0];
984
+ if (typeof firstUniqueDC !== "object" || !("digitalCredential" in firstUniqueDC)) {
985
+ return Promise.reject(Error("SiopMachine only supports UniqueDigitalCredentials for now"));
986
+ }
987
+ let identifier;
988
+ const digitalCredential = firstUniqueDC.digitalCredential;
989
+ const firstVC = firstUniqueDC.uniformVerifiableCredential;
990
+ const holder = import_ssi_types4.CredentialMapper.isSdJwtDecodedCredential(firstVC) ? firstVC.decodedPayload.cnf?.jwk ? (
991
+ //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
992
+ `did:jwk:${(0, import_ssi_sdk3.encodeJoseBlob)(firstVC.decodedPayload.cnf?.jwk)}#0`
993
+ ) : firstVC.decodedPayload.sub : Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id;
994
+ if (!digitalCredential.kmsKeyRef) {
995
+ if (!holder) {
996
+ return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`);
997
+ }
998
+ try {
999
+ identifier = await session.context.agent.identifierManagedGet({
1000
+ identifier: holder
1001
+ });
1002
+ } catch (e) {
1003
+ logger2.debug(`Holder DID not found: ${holder}`);
1004
+ throw e;
1005
+ }
1006
+ } else if ((0, import_ssi_sdk_ext.isOID4VCIssuerIdentifier)(digitalCredential.kmsKeyRef)) {
1007
+ identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({
1008
+ identifier: firstUniqueDC.digitalCredential.kmsKeyRef
1009
+ });
1010
+ } else {
1011
+ switch (digitalCredential.subjectCorrelationType) {
1012
+ case "DID":
1013
+ identifier = await session.context.agent.identifierManagedGetByDid({
1014
+ identifier: digitalCredential.subjectCorrelationId ?? holder,
1015
+ kmsKeyRef: digitalCredential.kmsKeyRef
1016
+ });
1017
+ break;
1018
+ // TODO other implementations?
1019
+ default:
1020
+ identifier = await session.context.agent.identifierManagedGetByKid({
1021
+ identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,
1022
+ kmsKeyRef: digitalCredential.kmsKeyRef
1023
+ });
1024
+ }
1025
+ }
1026
+ const dcqlCredentialsWithCredentials = new Map(credentials.map((vc) => [
1027
+ convertToDcqlCredentials(vc),
1028
+ vc
1029
+ ]));
1030
+ const queryResult = import_dcql.DcqlQuery.query(request.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()));
1031
+ if (!queryResult.can_be_satisfied) {
1032
+ return Promise.reject(Error("Credentials do not match required query request"));
1033
+ }
1034
+ const presentation = {};
1035
+ const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values());
1036
+ for (const [key, value] of Object.entries(queryResult.credential_matches)) {
1037
+ if (value.success) {
1038
+ const matchedCredentials = value.valid_credentials.map((cred) => uniqueCredentials[cred.input_credential_index]);
1039
+ const vc = matchedCredentials[0];
1040
+ if (!vc) {
1041
+ continue;
1042
+ }
1043
+ const originalVc = retrieveEncodedCredential(vc);
1044
+ if (!originalVc) {
1045
+ continue;
1046
+ }
1047
+ if (originalVc) {
1048
+ presentation[key] = originalVc;
1049
+ }
1050
+ }
1051
+ }
1052
+ const dcqlPresentation = import_dcql.DcqlPresentation.parse(presentation);
1053
+ const response = session.sendAuthorizationResponse({
1054
+ responseSignerOpts: identifier,
1055
+ dcqlResponse: {
1056
+ dcqlPresentation
1057
+ }
1058
+ });
1059
+ logger2.debug(`Response: `, response);
1060
+ return response;
1061
+ }, "siopSendAuthorizationResponse");
1062
+ var retrieveEncodedCredential = /* @__PURE__ */ __name((credential) => {
1063
+ return credential.originalVerifiableCredential !== void 0 && credential.originalVerifiableCredential !== null && credential?.originalVerifiableCredential?.compactSdJwtVc !== void 0 && credential?.originalVerifiableCredential?.compactSdJwtVc !== null ? credential.originalVerifiableCredential.compactSdJwtVc : credential.originalVerifiableCredential;
1064
+ }, "retrieveEncodedCredential");
1065
+ var getSelectableCredentials = /* @__PURE__ */ __name(async (dcqlQuery, context) => {
1066
+ const agentContext = {
1067
+ ...context,
1068
+ agent: context.agent
1069
+ };
1070
+ const { agent } = agentContext;
1071
+ const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({
1072
+ filter: (0, import_ssi_sdk.verifiableCredentialForRoleFilter)(import_ssi_sdk2.CredentialRole.HOLDER)
1073
+ });
1074
+ const branding = await agent.ibGetCredentialBranding();
1075
+ const dcqlCredentialsWithCredentials = new Map(uniqueVerifiableCredentials.map((vc) => [
1076
+ convertToDcqlCredentials(vc),
1077
+ vc
1078
+ ]));
1079
+ const queryResult = import_dcql.DcqlQuery.query(dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()));
1080
+ const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values());
1081
+ const selectableCredentialsMap = /* @__PURE__ */ new Map();
1082
+ for (const [key, value] of Object.entries(queryResult.credential_matches)) {
1083
+ if (!value.valid_credentials) {
1084
+ continue;
1085
+ }
1086
+ const mapSelectableCredentialPromises = value.valid_credentials.map(async (cred) => {
1087
+ const matchedCredential = uniqueCredentials[cred.input_credential_index];
1088
+ const credentialBranding = branding.filter((cb) => cb.vcHash === matchedCredential.hash);
1089
+ const issuerPartyIdentity = await agent.cmGetContacts({
1090
+ filter: [
1091
+ {
1092
+ identities: {
1093
+ identifier: {
1094
+ correlationId: matchedCredential.uniformVerifiableCredential.issuerDid
1095
+ }
1177
1096
  }
1178
1097
  }
1179
- }
1180
- },
1181
- [Siopv2MachineStates.addContactIdentity]: {
1182
- id: Siopv2MachineStates.addContactIdentity,
1183
- invoke: {
1184
- src: Siopv2MachineServices.addContactIdentity,
1185
- onDone: [
1186
- {
1187
- target: Siopv2MachineStates.getSelectableCredentials,
1188
- actions: /* @__PURE__ */ __name((_ctx, _event) => {
1189
- _ctx.contact?.identities.push(_event.data);
1190
- }, "actions"),
1191
- cond: Siopv2MachineGuards.hasSelectableCredentialsAndContactGuard
1192
- },
1193
- {
1194
- target: Siopv2MachineStates.sendResponse,
1195
- actions: /* @__PURE__ */ __name((_ctx, _event) => {
1196
- _ctx.contact?.identities.push(_event.data);
1197
- }, "actions"),
1198
- cond: Siopv2MachineGuards.siopOnlyGuard
1098
+ ]
1099
+ });
1100
+ const subjectPartyIdentity = await agent.cmGetContacts({
1101
+ filter: [
1102
+ {
1103
+ identities: {
1104
+ identifier: {
1105
+ correlationId: matchedCredential.uniformVerifiableCredential.subjectDid
1106
+ }
1199
1107
  }
1200
- ],
1201
- onError: {
1202
- target: Siopv2MachineStates.handleError,
1203
- actions: (0, import_xstate.assign)({
1204
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1205
- title: translate("siopv2_machine_add_contact_identity_error_title"),
1206
- message: _event.data.message,
1207
- stack: _event.data.stack
1208
- }), "error")
1209
- })
1210
- }
1211
- }
1212
- },
1213
- [Siopv2MachineStates.getSelectableCredentials]: {
1214
- id: Siopv2MachineStates.getSelectableCredentials,
1215
- invoke: {
1216
- src: Siopv2MachineServices.getSelectableCredentials,
1217
- onDone: {
1218
- target: Siopv2MachineStates.selectCredentials,
1219
- actions: (0, import_xstate.assign)({
1220
- selectableCredentialsMap: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectableCredentialsMap")
1221
- })
1222
- },
1223
- onError: {
1224
- target: Siopv2MachineStates.handleError,
1225
- actions: (0, import_xstate.assign)({
1226
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1227
- title: translate("siopv2_machine_get_selectable_credentials_error_title"),
1228
- message: _event.data.message,
1229
- stack: _event.data.stack
1230
- }), "error")
1231
- })
1232
- }
1233
- }
1234
- },
1235
- [Siopv2MachineStates.selectCredentials]: {
1236
- id: Siopv2MachineStates.selectCredentials,
1237
- on: {
1238
- [Siopv2MachineEvents.SET_SELECTED_CREDENTIALS]: {
1239
- actions: (0, import_xstate.assign)({
1240
- selectedCredentials: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "selectedCredentials")
1241
- })
1242
- },
1243
- [Siopv2MachineEvents.NEXT]: {
1244
- target: Siopv2MachineStates.sendResponse,
1245
- cond: Siopv2MachineGuards.hasSelectedRequiredCredentialsGuard
1246
- },
1247
- [Siopv2MachineEvents.DECLINE]: {
1248
- target: Siopv2MachineStates.declined
1249
- },
1250
- [Siopv2MachineEvents.PREVIOUS]: {
1251
- target: Siopv2MachineStates.aborted
1252
- }
1253
- }
1254
- },
1255
- [Siopv2MachineStates.sendResponse]: {
1256
- id: Siopv2MachineStates.sendResponse,
1257
- invoke: {
1258
- src: Siopv2MachineServices.sendResponse,
1259
- onDone: {
1260
- target: Siopv2MachineStates.done,
1261
- actions: (0, import_xstate.assign)({
1262
- authorizationResponseData: /* @__PURE__ */ __name((_ctx, _event) => _event.data, "authorizationResponseData")
1263
- })
1264
- },
1265
- onError: {
1266
- target: Siopv2MachineStates.handleError,
1267
- actions: (0, import_xstate.assign)({
1268
- error: /* @__PURE__ */ __name((_ctx, _event) => ({
1269
- title: translate("siopv2_machine_send_response_error_title"),
1270
- message: _event.data.message,
1271
- stack: _event.data.stack
1272
- }), "error")
1273
- })
1274
1108
  }
1275
- }
1276
- },
1277
- [Siopv2MachineStates.handleError]: {
1278
- id: Siopv2MachineStates.handleError,
1279
- on: {
1280
- [Siopv2MachineEvents.NEXT]: {
1281
- target: Siopv2MachineStates.error
1282
- },
1283
- [Siopv2MachineEvents.PREVIOUS]: {
1284
- target: Siopv2MachineStates.error
1109
+ ]
1110
+ });
1111
+ return {
1112
+ credential: matchedCredential,
1113
+ credentialBranding: credentialBranding[0]?.localeBranding,
1114
+ issuerParty: issuerPartyIdentity?.[0],
1115
+ subjectParty: subjectPartyIdentity?.[0]
1116
+ };
1117
+ });
1118
+ const selectableCredentials = await Promise.all(mapSelectableCredentialPromises);
1119
+ selectableCredentialsMap.set(key, selectableCredentials);
1120
+ }
1121
+ return selectableCredentialsMap;
1122
+ }, "getSelectableCredentials");
1123
+ var translateCorrelationIdToName = /* @__PURE__ */ __name(async (correlationId, context) => {
1124
+ const { agent } = context;
1125
+ const contacts = await agent.cmGetContacts({
1126
+ filter: [
1127
+ {
1128
+ identities: {
1129
+ identifier: {
1130
+ correlationId
1285
1131
  }
1286
1132
  }
1287
- },
1288
- [Siopv2MachineStates.aborted]: {
1289
- id: Siopv2MachineStates.aborted,
1290
- type: "final"
1291
- },
1292
- [Siopv2MachineStates.declined]: {
1293
- id: Siopv2MachineStates.declined,
1294
- type: "final"
1295
- },
1296
- [Siopv2MachineStates.error]: {
1297
- id: Siopv2MachineStates.error,
1298
- type: "final"
1299
- },
1300
- [Siopv2MachineStates.done]: {
1301
- id: Siopv2MachineStates.done,
1302
- type: "final"
1303
1133
  }
1304
- }
1134
+ ]
1305
1135
  });
1306
- }, "createSiopv2Machine");
1307
- var Siopv2Machine = class {
1308
- static {
1309
- __name(this, "Siopv2Machine");
1136
+ if (contacts.length === 0) {
1137
+ return void 0;
1310
1138
  }
1311
- static newInstance(opts) {
1312
- logger2.info("New Siopv2Machine instance");
1313
- const interpreter = (0, import_xstate.interpret)(createSiopv2Machine(opts).withConfig({
1314
- services: {
1315
- ...opts?.services
1316
- },
1317
- guards: {
1318
- Siopv2HasNoContactGuard,
1319
- Siopv2HasContactGuard,
1320
- Siopv2HasAuthorizationRequestGuard,
1321
- Siopv2HasSelectableCredentialsAndContactGuard,
1322
- Siopv2HasSelectedRequiredCredentialsGuard,
1323
- Siopv2IsSiopOnlyGuard,
1324
- Siopv2IsSiopWithOID4VPGuard,
1325
- Siopv2CreateContactGuard,
1326
- ...opts?.guards
1327
- }
1139
+ return contacts[0].contact.displayName;
1140
+ }, "translateCorrelationIdToName");
1141
+
1142
+ // src/session/functions.ts
1143
+ var import_did_auth_siop3 = require("@sphereon/did-auth-siop");
1144
+ var import_oid4vc_common = require("@sphereon/oid4vc-common");
1145
+ var import_ssi_sdk_ext3 = require("@sphereon/ssi-sdk-ext.identifier-resolution");
1146
+ var import_ssi_sdk4 = require("@sphereon/ssi-sdk.presentation-exchange");
1147
+ var import_events = require("events");
1148
+ async function createOID4VPPresentationSignCallback({ presentationSignCallback, idOpts: idOpts1, domain, fetchRemoteContexts, challenge, format, context, skipDidResolution }) {
1149
+ if (typeof presentationSignCallback === "function") {
1150
+ return presentationSignCallback;
1151
+ }
1152
+ return (0, import_ssi_sdk4.createPEXPresentationSignCallback)({
1153
+ idOpts: idOpts1,
1154
+ fetchRemoteContexts,
1155
+ domain,
1156
+ challenge,
1157
+ format,
1158
+ skipDidResolution
1159
+ }, context);
1160
+ }
1161
+ __name(createOID4VPPresentationSignCallback, "createOID4VPPresentationSignCallback");
1162
+ async function createOPBuilder({ opOptions, idOpts: idOpts1, context }) {
1163
+ const eventEmitter = opOptions.eventEmitter ?? new import_events.EventEmitter();
1164
+ const builder = import_did_auth_siop3.OP.builder().withResponseMode(opOptions.responseMode ?? import_did_auth_siop3.ResponseMode.DIRECT_POST).withSupportedVersions(opOptions.supportedVersions ?? [
1165
+ import_did_auth_siop3.SupportedVersion.SIOPv2_ID1,
1166
+ import_did_auth_siop3.SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1,
1167
+ import_did_auth_siop3.SupportedVersion.SIOPv2_D11,
1168
+ import_did_auth_siop3.SupportedVersion.SIOPv2_D12_OID4VP_D18
1169
+ ]).withExpiresIn(opOptions.expiresIn ?? 300).withEventEmitter(eventEmitter).withRegistration({
1170
+ passBy: import_did_auth_siop3.PassBy.VALUE
1171
+ });
1172
+ const wellknownDIDVerifyCallback = opOptions.wellknownDIDVerifyCallback ? opOptions.wellknownDIDVerifyCallback : async (args) => {
1173
+ const result = await context.agent.cvVerifyCredential({
1174
+ credential: args.credential,
1175
+ fetchRemoteContexts: true
1176
+ });
1177
+ return {
1178
+ verified: result.result
1179
+ };
1180
+ };
1181
+ builder.withVerifyJwtCallback(opOptions.verifyJwtCallback ? opOptions.verifyJwtCallback : getVerifyJwtCallback({
1182
+ verifyOpts: {
1183
+ wellknownDIDVerifyCallback,
1184
+ checkLinkedDomain: "if_present"
1185
+ }
1186
+ }, context));
1187
+ if (idOpts1) {
1188
+ if (opOptions.skipDidResolution && (0, import_ssi_sdk_ext3.isManagedIdentifierDidOpts)(idOpts1)) {
1189
+ idOpts1.offlineWhenNoDIDRegistered = true;
1190
+ }
1191
+ const createJwtCallback = createJwtCallbackWithIdOpts(idOpts1, context);
1192
+ builder.withCreateJwtCallback(createJwtCallback);
1193
+ builder.withPresentationSignCallback(await createOID4VPPresentationSignCallback({
1194
+ presentationSignCallback: opOptions.presentationSignCallback,
1195
+ skipDidResolution: opOptions.skipDidResolution ?? false,
1196
+ idOpts: idOpts1,
1197
+ context
1328
1198
  }));
1329
- if (typeof opts?.subscription === "function") {
1330
- interpreter.onTransition(opts.subscription);
1199
+ } else {
1200
+ const createJwtCallback = createJwtCallbackWithOpOpts(opOptions, context);
1201
+ builder.withCreateJwtCallback(createJwtCallback);
1202
+ }
1203
+ return builder;
1204
+ }
1205
+ __name(createOPBuilder, "createOPBuilder");
1206
+ function createJwtCallbackWithIdOpts(idOpts1, context) {
1207
+ return async (jwtIssuer, jwt) => {
1208
+ let issuer;
1209
+ if ((0, import_ssi_sdk_ext3.isManagedIdentifierDidOpts)(idOpts1)) {
1210
+ issuer = {
1211
+ ...idOpts1,
1212
+ method: idOpts1.method,
1213
+ noIdentifierInHeader: false
1214
+ };
1215
+ } else if ((0, import_ssi_sdk_ext3.isManagedIdentifierX5cOpts)(idOpts1)) {
1216
+ issuer = {
1217
+ ...idOpts1,
1218
+ method: idOpts1.method,
1219
+ noIdentifierInHeader: false
1220
+ };
1221
+ } else {
1222
+ return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
1331
1223
  }
1332
- if (opts?.requireCustomNavigationHook !== true) {
1333
- interpreter.onTransition((snapshot) => {
1334
- if (opts.stateNavigationListener !== void 0) {
1335
- void opts.stateNavigationListener(interpreter, snapshot);
1336
- }
1337
- });
1224
+ const result = await context.agent.jwtCreateJwsCompactSignature({
1225
+ issuer,
1226
+ protectedHeader: jwt.header,
1227
+ payload: jwt.payload
1228
+ });
1229
+ return result.jwt;
1230
+ };
1231
+ }
1232
+ __name(createJwtCallbackWithIdOpts, "createJwtCallbackWithIdOpts");
1233
+ function createJwtCallbackWithOpOpts(opOpts, context) {
1234
+ return async (jwtIssuer, jwt) => {
1235
+ let identifier;
1236
+ if (jwtIssuer.method == "did") {
1237
+ identifier = jwtIssuer.didUrl;
1238
+ } else if (jwtIssuer.method == "x5c") {
1239
+ identifier = jwtIssuer.x5c;
1240
+ } else {
1241
+ return Promise.reject(Error(`JWT issuer method ${jwtIssuer.method} not yet supported`));
1338
1242
  }
1339
- interpreter.onTransition((snapshot) => {
1340
- logger2.info("onTransition to new state", snapshot.value);
1243
+ const result = await context.agent.jwtCreateJwsCompactSignature({
1244
+ // FIXME fix cose-key inference
1245
+ // @ts-ignore
1246
+ issuer: {
1247
+ identifier,
1248
+ kmsKeyRef: idOpts.kmsKeyRef,
1249
+ noIdentifierInHeader: false
1250
+ },
1251
+ // FIXME fix JWK key_ops
1252
+ // @ts-ignore
1253
+ protectedHeader: jwt.header,
1254
+ payload: jwt.payload
1255
+ });
1256
+ return result.jwt;
1257
+ };
1258
+ }
1259
+ __name(createJwtCallbackWithOpOpts, "createJwtCallbackWithOpOpts");
1260
+ function getVerifyJwtCallback(_opts, context) {
1261
+ return async (_jwtVerifier, jwt) => {
1262
+ const result = await context.agent.jwtVerifyJwsSignature({
1263
+ jws: jwt.raw
1264
+ });
1265
+ console.log(result.message);
1266
+ return !result.error;
1267
+ };
1268
+ }
1269
+ __name(getVerifyJwtCallback, "getVerifyJwtCallback");
1270
+ async function createOP({ opOptions, idOpts: idOpts1, context }) {
1271
+ return (await createOPBuilder({
1272
+ opOptions,
1273
+ idOpts: idOpts1,
1274
+ context
1275
+ })).build();
1276
+ }
1277
+ __name(createOP, "createOP");
1278
+ function getSigningAlgo(type) {
1279
+ switch (type) {
1280
+ case "Ed25519":
1281
+ return import_oid4vc_common.SigningAlgo.EDDSA;
1282
+ case "Secp256k1":
1283
+ return import_oid4vc_common.SigningAlgo.ES256K;
1284
+ case "Secp256r1":
1285
+ return import_oid4vc_common.SigningAlgo.ES256;
1286
+ // @ts-ignore
1287
+ case "RSA":
1288
+ return import_oid4vc_common.SigningAlgo.RS256;
1289
+ default:
1290
+ throw Error("Key type not yet supported");
1291
+ }
1292
+ }
1293
+ __name(getSigningAlgo, "getSigningAlgo");
1294
+
1295
+ // src/session/OID4VP.ts
1296
+ var OID4VP = class _OID4VP {
1297
+ static {
1298
+ __name(this, "OID4VP");
1299
+ }
1300
+ //private readonly session: OpSession
1301
+ // private readonly allIdentifiers: string[]
1302
+ // private readonly hasher?: HasherSync
1303
+ constructor(args) {
1304
+ }
1305
+ static async init(session, allIdentifiers, hasher) {
1306
+ return new _OID4VP({
1307
+ session,
1308
+ allIdentifiers: allIdentifiers ?? await session.getSupportedDIDs(),
1309
+ hasher
1341
1310
  });
1342
- return {
1343
- interpreter
1344
- };
1345
1311
  }
1346
1312
  };
1347
1313
 
1348
- // src/services/Siopv2MachineService.ts
1314
+ // src/session/OpSession.ts
1349
1315
  var import_did_auth_siop4 = require("@sphereon/did-auth-siop");
1350
- var import_ssi_sdk_ext3 = require("@sphereon/ssi-sdk-ext.identifier-resolution");
1351
- var import_ssi_sdk3 = require("@sphereon/ssi-sdk.credential-store");
1352
- var import_ssi_sdk4 = require("@sphereon/ssi-sdk.data-store");
1353
- var import_ssi_types6 = require("@sphereon/ssi-types");
1316
+ var import_ssi_sdk_ext4 = require("@sphereon/ssi-sdk-ext.did-utils");
1354
1317
  var import_ssi_sdk5 = require("@sphereon/ssi-sdk.core");
1355
- var import_dcql = require("dcql");
1356
-
1357
- // src/utils/dcql.ts
1358
1318
  var import_ssi_types5 = require("@sphereon/ssi-types");
1359
- var import_did_auth_siop3 = require("@sphereon/did-auth-siop");
1360
-
1361
- // src/utils/CredentialUtils.ts
1362
- var import_ssi_types4 = require("@sphereon/ssi-types");
1363
- var isUniqueDigitalCredential = /* @__PURE__ */ __name((credential) => {
1364
- return credential.digitalCredential !== void 0;
1365
- }, "isUniqueDigitalCredential");
1366
-
1367
- // src/utils/dcql.ts
1368
- function convertToDcqlCredentials(credential, hasher) {
1369
- let originalVerifiableCredential;
1370
- if (isUniqueDigitalCredential(credential)) {
1371
- if (!credential.originalVerifiableCredential) {
1372
- throw new Error("originalVerifiableCredential is not defined in UniqueDigitalCredential");
1373
- }
1374
- originalVerifiableCredential = import_ssi_types5.CredentialMapper.decodeVerifiableCredential(credential.originalVerifiableCredential, hasher);
1375
- } else {
1376
- originalVerifiableCredential = import_ssi_types5.CredentialMapper.decodeVerifiableCredential(credential, hasher);
1319
+ var import_uuid = require("uuid");
1320
+ var import_ssi_types6 = require("@sphereon/ssi-types");
1321
+ var logger3 = import_ssi_types6.Loggers.DEFAULT.get("sphereon:oid4vp:OpSession");
1322
+ var OpSession = class _OpSession {
1323
+ static {
1324
+ __name(this, "OpSession");
1377
1325
  }
1378
- if (!originalVerifiableCredential) {
1379
- throw new Error("No payload found");
1326
+ ts = (/* @__PURE__ */ new Date()).getDate();
1327
+ id;
1328
+ options;
1329
+ context;
1330
+ requestJwtOrUri;
1331
+ verifiedAuthorizationRequest;
1332
+ _nonce;
1333
+ _state;
1334
+ constructor(options) {
1335
+ this.id = options.sessionId;
1336
+ this.options = options.op;
1337
+ this.context = options.context;
1338
+ this.requestJwtOrUri = options.requestJwtOrUri;
1380
1339
  }
1381
- if (import_ssi_types5.CredentialMapper.isJwtDecodedCredential(originalVerifiableCredential)) {
1382
- return import_did_auth_siop3.Dcql.toDcqlJwtCredential(import_ssi_types5.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
1383
- } else if (import_ssi_types5.CredentialMapper.isSdJwtDecodedCredential(originalVerifiableCredential)) {
1384
- return import_did_auth_siop3.Dcql.toDcqlSdJwtCredential(import_ssi_types5.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
1385
- } else if (import_ssi_types5.CredentialMapper.isMsoMdocDecodedCredential(originalVerifiableCredential)) {
1386
- return import_did_auth_siop3.Dcql.toDcqlMdocCredential(import_ssi_types5.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
1387
- } else if (import_ssi_types5.CredentialMapper.isW3cCredential(originalVerifiableCredential)) {
1388
- return import_did_auth_siop3.Dcql.toDcqlJsonLdCredential(import_ssi_types5.CredentialMapper.toWrappedVerifiableCredential(originalVerifiableCredential));
1340
+ static async init(options) {
1341
+ return new _OpSession(options);
1389
1342
  }
1390
- throw Error(`Unable to map credential to DCQL credential. Credential: ${JSON.stringify(originalVerifiableCredential)}`);
1391
- }
1392
- __name(convertToDcqlCredentials, "convertToDcqlCredentials");
1393
-
1394
- // src/services/Siopv2MachineService.ts
1395
- var import_ssi_sdk_ext4 = require("@sphereon/ssi-sdk-ext.did-utils");
1396
- var logger3 = import_ssi_types6.Loggers.DEFAULT.get(LOGGER_NAMESPACE);
1397
- var siopSendAuthorizationResponse = /* @__PURE__ */ __name(async (connectionType, args, context) => {
1398
- const { agent } = context;
1399
- const { credentials } = args;
1400
- if (connectionType !== import_ssi_sdk4.ConnectionType.SIOPv2_OpenID4VP) {
1401
- return Promise.reject(Error(`No supported authentication provider for type: ${connectionType}`));
1343
+ async getAuthorizationRequest() {
1344
+ if (!this.verifiedAuthorizationRequest) {
1345
+ const op = await createOP({
1346
+ opOptions: this.options,
1347
+ context: this.context
1348
+ });
1349
+ this.verifiedAuthorizationRequest = await op.verifyAuthorizationRequest(this.requestJwtOrUri);
1350
+ this._nonce = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("nonce");
1351
+ this._state = await this.verifiedAuthorizationRequest.authorizationRequest.getMergedProperty("state");
1352
+ await this.getSupportedDIDMethods();
1353
+ }
1354
+ return this.verifiedAuthorizationRequest;
1402
1355
  }
1403
- const session = await agent.siopGetOPSession({
1404
- sessionId: args.sessionId
1405
- });
1406
- const request = await session.getAuthorizationRequest();
1407
- const aud = request.authorizationRequest.getMergedProperty("aud");
1408
- logger3.debug(`AUD: ${aud}`);
1409
- logger3.debug(JSON.stringify(request.authorizationRequest));
1410
- const domain = await request.authorizationRequest.getMergedProperty("client_id") ?? request.issuer ?? (request.versions.includes(import_did_auth_siop4.SupportedVersion.JWT_VC_PRESENTATION_PROFILE_v1) ? "https://self-issued.me/v2/openid-vc" : "https://self-issued.me/v2");
1411
- logger3.debug(`NONCE: ${session.nonce}, domain: ${domain}`);
1412
- const firstUniqueDC = credentials[0];
1413
- if (typeof firstUniqueDC !== "object" || !("digitalCredential" in firstUniqueDC)) {
1414
- return Promise.reject(Error("SiopMachine only supports UniqueDigitalCredentials for now"));
1356
+ async getAuthorizationRequestURI() {
1357
+ return await import_did_auth_siop4.URI.fromAuthorizationRequest((await this.getAuthorizationRequest()).authorizationRequest);
1415
1358
  }
1416
- let identifier;
1417
- const digitalCredential = firstUniqueDC.digitalCredential;
1418
- const firstVC = firstUniqueDC.uniformVerifiableCredential;
1419
- const holder = import_ssi_types6.CredentialMapper.isSdJwtDecodedCredential(firstVC) ? firstVC.decodedPayload.cnf?.jwk ? (
1420
- //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
1421
- `did:jwk:${(0, import_ssi_sdk5.encodeJoseBlob)(firstVC.decodedPayload.cnf?.jwk)}#0`
1422
- ) : firstVC.decodedPayload.sub : Array.isArray(firstVC.credentialSubject) ? firstVC.credentialSubject[0].id : firstVC.credentialSubject.id;
1423
- if (!digitalCredential.kmsKeyRef) {
1424
- if (!holder) {
1425
- return Promise.reject(`No holder found and no kmsKeyRef in DB. Cannot determine identifier to use`);
1359
+ get nonce() {
1360
+ if (!this._nonce) {
1361
+ throw Error("No nonce available. Please get authorization request first");
1426
1362
  }
1427
- try {
1428
- identifier = await session.context.agent.identifierManagedGet({
1429
- identifier: holder
1430
- });
1431
- } catch (e) {
1432
- logger3.debug(`Holder DID not found: ${holder}`);
1433
- throw e;
1363
+ return this._nonce;
1364
+ }
1365
+ get state() {
1366
+ if (!this._state) {
1367
+ throw Error("No state available. Please get authorization request first");
1434
1368
  }
1435
- } else if ((0, import_ssi_sdk_ext3.isOID4VCIssuerIdentifier)(digitalCredential.kmsKeyRef)) {
1436
- identifier = await session.context.agent.identifierManagedGetByOID4VCIssuer({
1437
- identifier: firstUniqueDC.digitalCredential.kmsKeyRef
1369
+ return this._state;
1370
+ }
1371
+ clear() {
1372
+ this._nonce = void 0;
1373
+ this._state = void 0;
1374
+ this.verifiedAuthorizationRequest = void 0;
1375
+ return this;
1376
+ }
1377
+ async getSupportedDIDMethods(didPrefix) {
1378
+ const agentMethods = this.getAgentDIDMethodsSupported({
1379
+ didPrefix
1438
1380
  });
1439
- } else {
1440
- switch (digitalCredential.subjectCorrelationType) {
1441
- case "DID":
1442
- identifier = await session.context.agent.identifierManagedGetByDid({
1443
- identifier: digitalCredential.subjectCorrelationId ?? holder,
1444
- kmsKeyRef: digitalCredential.kmsKeyRef
1445
- });
1446
- break;
1447
- // TODO other implementations?
1448
- default:
1449
- identifier = await session.context.agent.identifierManagedGetByKid({
1450
- identifier: digitalCredential.subjectCorrelationId ?? holder ?? digitalCredential.kmsKeyRef,
1451
- kmsKeyRef: digitalCredential.kmsKeyRef
1452
- });
1381
+ let rpMethods = await this.getRPDIDMethodsSupported({
1382
+ didPrefix,
1383
+ agentMethods
1384
+ });
1385
+ logger3.debug(`RP supports subject syntax types: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
1386
+ if (rpMethods.dids.length === 0) {
1387
+ logger3.debug(`RP does not support DIDs. Supported: ${JSON.stringify(this.getSubjectSyntaxTypesSupported())}`);
1388
+ return [];
1389
+ }
1390
+ let intersection;
1391
+ if (rpMethods.dids.includes("did")) {
1392
+ intersection = agentMethods && agentMethods.length > 0 ? agentMethods : (await (0, import_ssi_sdk_ext4.getAgentDIDMethods)(this.context)).map((method) => convertDidMethod(method, didPrefix));
1393
+ } else if (!agentMethods || agentMethods.length === 0) {
1394
+ intersection = rpMethods.dids?.map((method) => convertDidMethod(method, didPrefix));
1395
+ } else {
1396
+ intersection = agentMethods.filter((value) => rpMethods.dids.includes(value));
1453
1397
  }
1398
+ if (intersection.length === 0) {
1399
+ throw Error("No matching DID methods between agent and relying party");
1400
+ }
1401
+ return intersection.map((value) => convertDidMethod(value, didPrefix));
1454
1402
  }
1455
- const dcqlCredentialsWithCredentials = new Map(credentials.map((vc) => [
1456
- convertToDcqlCredentials(vc),
1457
- vc
1458
- ]));
1459
- const queryResult = import_dcql.DcqlQuery.query(request.dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()));
1460
- if (!queryResult.can_be_satisfied) {
1461
- return Promise.reject(Error("Credentials do not match required query request"));
1403
+ getAgentDIDMethodsSupported(opts) {
1404
+ const agentMethods = this.options.supportedDIDMethods?.map((method) => convertDidMethod(method, opts.didPrefix));
1405
+ logger3.debug(`agent methods: ${JSON.stringify(agentMethods)}`);
1406
+ return agentMethods;
1462
1407
  }
1463
- const presentation = {};
1464
- const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values());
1465
- for (const [key, value] of Object.entries(queryResult.credential_matches)) {
1466
- if (value.success) {
1467
- const matchedCredentials = value.valid_credentials.map((cred) => uniqueCredentials[cred.input_credential_index]);
1468
- const vc = matchedCredentials[0];
1469
- if (!vc) {
1470
- continue;
1471
- }
1472
- const originalVc = retrieveEncodedCredential(vc);
1473
- if (!originalVc) {
1474
- continue;
1408
+ async getSubjectSyntaxTypesSupported() {
1409
+ const authReq = await this.getAuthorizationRequest();
1410
+ const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported;
1411
+ return subjectSyntaxTypesSupported ?? [];
1412
+ }
1413
+ async getRPDIDMethodsSupported(opts) {
1414
+ let keyType;
1415
+ const agentMethods = (opts.agentMethods ?? this.getAgentDIDMethodsSupported(opts))?.map((method) => convertDidMethod(method, opts.didPrefix)) ?? [];
1416
+ logger3.debug(`agent methods supported: ${JSON.stringify(agentMethods)}`);
1417
+ const authReq = await this.getAuthorizationRequest();
1418
+ const subjectSyntaxTypesSupported = authReq.registrationMetadataPayload?.subject_syntax_types_supported?.map((method) => convertDidMethod(method, opts.didPrefix)).filter((val) => !val.startsWith("did"));
1419
+ logger3.debug(`subject syntax types supported in rp method supported: ${JSON.stringify(subjectSyntaxTypesSupported)}`);
1420
+ const aud = await authReq.authorizationRequest.getMergedProperty("aud");
1421
+ let rpMethods = [];
1422
+ if (aud && aud.startsWith("did:")) {
1423
+ const didMethod = convertDidMethod((0, import_ssi_types5.parseDid)(aud).method, opts.didPrefix);
1424
+ logger3.debug(`aud did method: ${didMethod}`);
1425
+ if (subjectSyntaxTypesSupported && subjectSyntaxTypesSupported.length > 0 && !subjectSyntaxTypesSupported.includes("did") && !subjectSyntaxTypesSupported.includes(didMethod)) {
1426
+ throw Error(`The aud DID method ${didMethod} is not in the supported types ${subjectSyntaxTypesSupported}`);
1475
1427
  }
1476
- if (originalVc) {
1477
- presentation[key] = originalVc;
1428
+ rpMethods = [
1429
+ didMethod
1430
+ ];
1431
+ } else if (subjectSyntaxTypesSupported) {
1432
+ rpMethods = (Array.isArray(subjectSyntaxTypesSupported) ? subjectSyntaxTypesSupported : [
1433
+ subjectSyntaxTypesSupported
1434
+ ]).map((method) => convertDidMethod(method, opts.didPrefix));
1435
+ }
1436
+ const isEBSI = rpMethods.length === 0 && (authReq.issuer?.includes(".ebsi.eu") || authReq.authorizationRequest.getMergedProperty("client_id")?.includes(".ebsi.eu"));
1437
+ let codecName = void 0;
1438
+ if (isEBSI && (!aud || !aud.startsWith("http"))) {
1439
+ logger3.debug(`EBSI detected, adding did:key to supported DID methods for RP`);
1440
+ const didKeyMethod = convertDidMethod("did:key", opts.didPrefix);
1441
+ if (!agentMethods?.includes(didKeyMethod)) {
1442
+ throw Error(`EBSI detected, but agent did not support did:key. Please reconfigure agent`);
1478
1443
  }
1444
+ rpMethods = [
1445
+ didKeyMethod
1446
+ ];
1447
+ keyType = "Secp256r1";
1448
+ codecName = "jwk_jcs-pub";
1479
1449
  }
1450
+ return {
1451
+ dids: rpMethods,
1452
+ codecName,
1453
+ keyType
1454
+ };
1480
1455
  }
1481
- const dcqlPresentation = import_dcql.DcqlPresentation.parse(presentation);
1482
- const response = session.sendAuthorizationResponse({
1483
- responseSignerOpts: identifier,
1484
- dcqlResponse: {
1485
- dcqlPresentation
1486
- }
1487
- });
1488
- logger3.debug(`Response: `, response);
1489
- return response;
1490
- }, "siopSendAuthorizationResponse");
1491
- var retrieveEncodedCredential = /* @__PURE__ */ __name((credential) => {
1492
- return credential.originalVerifiableCredential !== void 0 && credential.originalVerifiableCredential !== null && credential?.originalVerifiableCredential?.compactSdJwtVc !== void 0 && credential?.originalVerifiableCredential?.compactSdJwtVc !== null ? credential.originalVerifiableCredential.compactSdJwtVc : credential.originalVerifiableCredential;
1493
- }, "retrieveEncodedCredential");
1494
- var getSelectableCredentials = /* @__PURE__ */ __name(async (dcqlQuery, context) => {
1495
- const agentContext = {
1496
- ...context,
1497
- agent: context.agent
1498
- };
1499
- const { agent } = agentContext;
1500
- const uniqueVerifiableCredentials = await agent.crsGetUniqueCredentials({
1501
- filter: (0, import_ssi_sdk3.verifiableCredentialForRoleFilter)(import_ssi_sdk4.CredentialRole.HOLDER)
1502
- });
1503
- const branding = await agent.ibGetCredentialBranding();
1504
- const dcqlCredentialsWithCredentials = new Map(uniqueVerifiableCredentials.map((vc) => [
1505
- convertToDcqlCredentials(vc),
1506
- vc
1507
- ]));
1508
- const queryResult = import_dcql.DcqlQuery.query(dcqlQuery, Array.from(dcqlCredentialsWithCredentials.keys()));
1509
- const uniqueCredentials = Array.from(dcqlCredentialsWithCredentials.values());
1510
- const selectableCredentialsMap = /* @__PURE__ */ new Map();
1511
- for (const [key, value] of Object.entries(queryResult.credential_matches)) {
1512
- if (!value.valid_credentials) {
1513
- continue;
1456
+ async getSupportedIdentifiers(opts) {
1457
+ const methods = await this.getSupportedDIDMethods(true);
1458
+ logger3.debug(`supported DID methods (did: prefix = true): ${JSON.stringify(methods)}`);
1459
+ if (methods.length === 0) {
1460
+ throw Error(`No DID methods are supported`);
1514
1461
  }
1515
- const mapSelectableCredentialPromises = value.valid_credentials.map(async (cred) => {
1516
- const matchedCredential = uniqueCredentials[cred.input_credential_index];
1517
- const credentialBranding = branding.filter((cb) => cb.vcHash === matchedCredential.hash);
1518
- const issuerPartyIdentity = await agent.cmGetContacts({
1519
- filter: [
1520
- {
1521
- identities: {
1522
- identifier: {
1523
- correlationId: matchedCredential.uniformVerifiableCredential.issuerDid
1524
- }
1525
- }
1462
+ const identifiers = await this.context.agent.didManagerFind().then((ids) => ids.filter((id) => methods.includes(id.provider)));
1463
+ if (identifiers.length === 0) {
1464
+ logger3.debug(`No identifiers available in agent supporting methods ${JSON.stringify(methods)}`);
1465
+ if (opts?.createInCaseNoDIDFound !== false) {
1466
+ const { codecName, keyType } = await this.getRPDIDMethodsSupported({
1467
+ didPrefix: true,
1468
+ agentMethods: methods
1469
+ });
1470
+ const identifier = await this.context.agent.didManagerCreate({
1471
+ provider: methods[0],
1472
+ options: {
1473
+ codecName,
1474
+ keyType,
1475
+ type: keyType
1526
1476
  }
1527
- ]
1477
+ });
1478
+ logger3.debug(`Created a new identifier for the SIOP interaction: ${identifier.did}`);
1479
+ identifiers.push(identifier);
1480
+ }
1481
+ }
1482
+ logger3.debug(`supported identifiers: ${JSON.stringify(identifiers.map((id) => id.did))}`);
1483
+ return identifiers;
1484
+ }
1485
+ async getSupportedDIDs() {
1486
+ return (await this.getSupportedIdentifiers()).map((id) => id.did);
1487
+ }
1488
+ async getRedirectUri() {
1489
+ return Promise.resolve(this.verifiedAuthorizationRequest.responseURI);
1490
+ }
1491
+ async getOID4VP(args) {
1492
+ return await OID4VP.init(this, args.allIdentifiers ?? [], args.hasher);
1493
+ }
1494
+ async createJarmResponseCallback({ responseOpts }) {
1495
+ const agent = this.context.agent;
1496
+ return /* @__PURE__ */ __name(async function jarmResponse(opts) {
1497
+ const { clientMetadata, requestObjectPayload, authorizationResponsePayload: authResponse } = opts;
1498
+ const jwk = await import_did_auth_siop4.OP.extractEncJwksFromClientMetadata(clientMetadata);
1499
+ const recipientKey = await agent.identifierExternalResolveByJwk({
1500
+ identifier: jwk
1528
1501
  });
1529
- const subjectPartyIdentity = await agent.cmGetContacts({
1530
- filter: [
1531
- {
1532
- identities: {
1533
- identifier: {
1534
- correlationId: matchedCredential.uniformVerifiableCredential.subjectDid
1535
- }
1536
- }
1537
- }
1538
- ]
1502
+ return await agent.jwtEncryptJweCompactJwt({
1503
+ recipientKey,
1504
+ protectedHeader: {},
1505
+ alg: requestObjectPayload.client_metadata.authorization_encrypted_response_alg ?? "ECDH-ES",
1506
+ enc: requestObjectPayload.client_metadata.authorization_encrypted_response_enc ?? "A256GCM",
1507
+ apv: (0, import_ssi_sdk5.encodeBase64url)(opts.requestObjectPayload.nonce),
1508
+ apu: (0, import_ssi_sdk5.encodeBase64url)((0, import_uuid.v4)()),
1509
+ payload: authResponse,
1510
+ issuer: responseOpts.issuer,
1511
+ audience: responseOpts.audience
1512
+ }).then((result) => {
1513
+ return {
1514
+ response: result.jwt
1515
+ };
1539
1516
  });
1540
- return {
1541
- credential: matchedCredential,
1542
- credentialBranding: credentialBranding[0]?.localeBranding,
1543
- issuerParty: issuerPartyIdentity?.[0],
1544
- subjectParty: subjectPartyIdentity?.[0]
1545
- };
1517
+ }, "jarmResponse");
1518
+ }
1519
+ async sendAuthorizationResponse(args) {
1520
+ const { responseSignerOpts, dcqlResponse, isFirstParty } = args;
1521
+ const resolveOpts = this.options.resolveOpts ?? {
1522
+ resolver: (0, import_ssi_sdk_ext4.getAgentResolver)(this.context, {
1523
+ uniresolverResolution: true,
1524
+ localResolution: true,
1525
+ resolverResolution: true
1526
+ })
1527
+ };
1528
+ if (!resolveOpts.subjectSyntaxTypesSupported || resolveOpts.subjectSyntaxTypesSupported.length === 0) {
1529
+ resolveOpts.subjectSyntaxTypesSupported = await this.getSupportedDIDMethods(true);
1530
+ }
1531
+ const request = await this.getAuthorizationRequest();
1532
+ const op = await createOP({
1533
+ opOptions: {
1534
+ ...this.options,
1535
+ resolveOpts: {
1536
+ ...this.options.resolveOpts
1537
+ },
1538
+ eventEmitter: this.options.eventEmitter,
1539
+ presentationSignCallback: this.options.presentationSignCallback,
1540
+ wellknownDIDVerifyCallback: this.options.wellknownDIDVerifyCallback,
1541
+ supportedVersions: request.versions
1542
+ },
1543
+ idOpts: responseSignerOpts,
1544
+ context: this.context
1546
1545
  });
1547
- const selectableCredentials = await Promise.all(mapSelectableCredentialPromises);
1548
- selectableCredentialsMap.set(key, selectableCredentials);
1546
+ let issuer = responseSignerOpts.issuer;
1547
+ const responseOpts = {
1548
+ issuer,
1549
+ ...isFirstParty && {
1550
+ isFirstParty
1551
+ },
1552
+ dcqlResponse
1553
+ };
1554
+ const authResponse = await op.createAuthorizationResponse(request, responseOpts);
1555
+ const response = await op.submitAuthorizationResponse(authResponse, await this.createJarmResponseCallback({
1556
+ responseOpts
1557
+ }));
1558
+ if (response.status >= 400) {
1559
+ throw Error(`Error ${response.status}: ${response.statusText || await response.text()}`);
1560
+ } else {
1561
+ return response;
1562
+ }
1549
1563
  }
1550
- return selectableCredentialsMap;
1551
- }, "getSelectableCredentials");
1552
- var translateCorrelationIdToName = /* @__PURE__ */ __name(async (correlationId, context) => {
1553
- const { agent } = context;
1554
- const contacts = await agent.cmGetContacts({
1555
- filter: [
1556
- {
1557
- identities: {
1558
- identifier: {
1559
- correlationId
1560
- }
1561
- }
1562
- }
1563
- ]
1564
- });
1565
- if (contacts.length === 0) {
1566
- return void 0;
1564
+ };
1565
+ function convertDidMethod(didMethod, didPrefix) {
1566
+ if (didPrefix === false) {
1567
+ return didMethod.startsWith("did:") ? didMethod.toLowerCase().replace("did:", "") : didMethod.toLowerCase();
1567
1568
  }
1568
- return contacts[0].contact.displayName;
1569
- }, "translateCorrelationIdToName");
1569
+ return didMethod.startsWith("did:") ? didMethod.toLowerCase() : `did:${didMethod.toLowerCase().replace("did:", "")}`;
1570
+ }
1571
+ __name(convertDidMethod, "convertDidMethod");
1570
1572
 
1571
1573
  // src/agent/DidAuthSiopOpAuthenticator.ts
1572
1574
  var logger4 = import_ssi_types7.Loggers.DEFAULT.options(LOGGER_NAMESPACE, {}).get(LOGGER_NAMESPACE);