@verana-labs/vs-agent-plugin-openid4vc 1.12.0-oidc4vc.6 → 2.0.0-dev.100

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 (109) hide show
  1. package/README.md +175 -164
  2. package/build/config.d.ts +19 -3
  3. package/build/config.js +161 -242
  4. package/build/config.js.map +1 -1
  5. package/build/events/openId4VcEvents.d.ts +6 -0
  6. package/build/events/openId4VcEvents.js +17 -0
  7. package/build/events/openId4VcEvents.js.map +1 -0
  8. package/build/index.d.ts +20 -12
  9. package/build/index.js +39 -16
  10. package/build/index.js.map +1 -1
  11. package/build/nestjs/OpenId4VcPlugin.js +27 -43
  12. package/build/nestjs/OpenId4VcPlugin.js.map +1 -1
  13. package/build/nestjs/V2OpenId4VcCredentialExchangesController.d.ts +19 -0
  14. package/build/nestjs/V2OpenId4VcCredentialExchangesController.js +161 -0
  15. package/build/nestjs/V2OpenId4VcCredentialExchangesController.js.map +1 -0
  16. package/build/nestjs/V2OpenId4VcPresentationsController.d.ts +19 -0
  17. package/build/nestjs/V2OpenId4VcPresentationsController.js +147 -0
  18. package/build/nestjs/V2OpenId4VcPresentationsController.js.map +1 -0
  19. package/build/nestjs/V2OpenId4VcSigningCertificatesController.d.ts +17 -0
  20. package/build/nestjs/V2OpenId4VcSigningCertificatesController.js +58 -0
  21. package/build/nestjs/V2OpenId4VcSigningCertificatesController.js.map +1 -0
  22. package/build/nestjs/dto/credential-exchange.dto.d.ts +31 -0
  23. package/build/nestjs/dto/credential-exchange.dto.js +150 -0
  24. package/build/nestjs/dto/credential-exchange.dto.js.map +1 -0
  25. package/build/nestjs/dto/index.d.ts +3 -0
  26. package/build/nestjs/dto/index.js +20 -0
  27. package/build/nestjs/dto/index.js.map +1 -0
  28. package/build/nestjs/dto/presentation.dto.d.ts +57 -0
  29. package/build/nestjs/dto/presentation.dto.js +246 -0
  30. package/build/nestjs/dto/presentation.dto.js.map +1 -0
  31. package/build/nestjs/dto/signing-certificate.dto.d.ts +8 -0
  32. package/build/nestjs/dto/signing-certificate.dto.js +40 -0
  33. package/build/nestjs/dto/signing-certificate.dto.js.map +1 -0
  34. package/build/nestjs/mappers.d.ts +5 -0
  35. package/build/nestjs/mappers.js +31 -0
  36. package/build/nestjs/mappers.js.map +1 -0
  37. package/build/sdk/credentialConfigurationHandlers.d.ts +4 -0
  38. package/build/sdk/credentialConfigurationHandlers.js +57 -0
  39. package/build/sdk/credentialConfigurationHandlers.js.map +1 -0
  40. package/build/sdk/setupOpenId4Vc.d.ts +8 -12
  41. package/build/sdk/setupOpenId4Vc.js +88 -80
  42. package/build/sdk/setupOpenId4Vc.js.map +1 -1
  43. package/build/services/CertificateService.d.ts +6 -22
  44. package/build/services/CertificateService.js +104 -71
  45. package/build/services/CertificateService.js.map +1 -1
  46. package/build/services/IssuerService.d.ts +57 -44
  47. package/build/services/IssuerService.js +284 -103
  48. package/build/services/IssuerService.js.map +1 -1
  49. package/build/services/VerifierService.d.ts +44 -44
  50. package/build/services/VerifierService.js +227 -223
  51. package/build/services/VerifierService.js.map +1 -1
  52. package/build/services/credentialConfigurationBuilder.d.ts +10 -0
  53. package/build/services/credentialConfigurationBuilder.js +88 -0
  54. package/build/services/credentialConfigurationBuilder.js.map +1 -0
  55. package/build/services/presentationRequest.d.ts +51 -0
  56. package/build/services/presentationRequest.js +72 -0
  57. package/build/services/presentationRequest.js.map +1 -0
  58. package/build/services/presentationVerification.d.ts +12 -0
  59. package/build/services/presentationVerification.js +13 -0
  60. package/build/services/presentationVerification.js.map +1 -0
  61. package/build/services/typeMetadataIntegrity.d.ts +6 -0
  62. package/build/services/typeMetadataIntegrity.js +32 -0
  63. package/build/services/typeMetadataIntegrity.js.map +1 -0
  64. package/build/trust/CertificateTrust.d.ts +1 -4
  65. package/build/trust/CertificateTrust.js +10 -15
  66. package/build/trust/CertificateTrust.js.map +1 -1
  67. package/build/trust/keyBinding.d.ts +15 -16
  68. package/build/trust/keyBinding.js +54 -174
  69. package/build/trust/keyBinding.js.map +1 -1
  70. package/build/trust/presentedIssuer.d.ts +9 -0
  71. package/build/trust/presentedIssuer.js +23 -0
  72. package/build/trust/presentedIssuer.js.map +1 -0
  73. package/build/trust/trustDecision.d.ts +31 -0
  74. package/build/trust/trustDecision.js +204 -0
  75. package/build/trust/trustDecision.js.map +1 -0
  76. package/build/trust/types.d.ts +7 -16
  77. package/build/trust/types.js +8 -0
  78. package/build/trust/types.js.map +1 -1
  79. package/build/types.d.ts +29 -51
  80. package/build/types.js +4 -0
  81. package/build/types.js.map +1 -1
  82. package/build/utils/isRecord.d.ts +1 -0
  83. package/build/utils/isRecord.js +7 -0
  84. package/build/utils/isRecord.js.map +1 -0
  85. package/build/utils/serviceDisplay.d.ts +8 -0
  86. package/build/utils/serviceDisplay.js +11 -0
  87. package/build/utils/serviceDisplay.js.map +1 -0
  88. package/package.json +10 -8
  89. package/build/nestjs/CertificatesController.d.ts +0 -11
  90. package/build/nestjs/CertificatesController.js +0 -58
  91. package/build/nestjs/CertificatesController.js.map +0 -1
  92. package/build/nestjs/IssuerController.d.ts +0 -8
  93. package/build/nestjs/IssuerController.js +0 -66
  94. package/build/nestjs/IssuerController.js.map +0 -1
  95. package/build/nestjs/VerifierController.d.ts +0 -8
  96. package/build/nestjs/VerifierController.js +0 -66
  97. package/build/nestjs/VerifierController.js.map +0 -1
  98. package/build/nestjs/dto.d.ts +0 -7
  99. package/build/nestjs/dto.js +0 -34
  100. package/build/nestjs/dto.js.map +0 -1
  101. package/build/services/StatusListService.d.ts +0 -42
  102. package/build/services/StatusListService.js +0 -132
  103. package/build/services/StatusListService.js.map +0 -1
  104. package/build/trust/TrustClient.d.ts +0 -12
  105. package/build/trust/TrustClient.js +0 -120
  106. package/build/trust/TrustClient.js.map +0 -1
  107. package/build/trust/verdict.d.ts +0 -2
  108. package/build/trust/verdict.js +0 -13
  109. package/build/trust/verdict.js.map +0 -1
@@ -1,62 +1,62 @@
1
- import type { TrustVerdict } from '../trust/types';
2
- import type { OpenId4VcPluginOptions } from '../types';
3
- import type { BaseAgent } from '@credo-ts/core';
4
- import type { OpenId4VcVerificationSessionRecord, OpenId4VcVerifierApi } from '@credo-ts/openid4vc';
1
+ import type { OpenId4VcAgent, OpenId4VcPluginOptions } from '../types';
2
+ import type { OnModuleInit } from '@nestjs/common';
3
+ import type { DidTrustResolver } from '@verana-labs/vs-agent-sdk';
4
+ import { OpenId4VcVerificationSessionState } from '@credo-ts/openid4vc';
5
5
  import { type SigningCertificateInfo } from './CertificateService';
6
- type VerifierApi = Pick<OpenId4VcVerifierApi, 'getVerifierByVerifierId' | 'createVerifier' | 'updateVerifierMetadata' | 'createAuthorizationRequest' | 'getVerificationSessionById' | 'getVerifiedAuthorizationResponse'>;
7
- export type OpenId4VcVerifierAgent = Pick<BaseAgent, 'dids' | 'genericRecords' | 'kms' | 'x509'> & {
8
- did?: string;
9
- modules: {
10
- openId4Vc?: {
11
- verifier?: VerifierApi;
12
- };
13
- };
14
- };
6
+ import { type OpenId4VcQueryLanguage } from './presentationRequest';
7
+ import type { PresentationDecision } from './presentationVerification';
15
8
  export interface OpenId4VcVerificationRequest {
16
9
  authorizationRequest: string;
17
10
  verificationSessionId: string;
18
11
  }
19
- export interface OpenId4VcVerifiedCredentialResult {
20
- vct: string;
21
- disclosedClaims: Record<string, unknown>;
22
- }
23
- export interface OpenId4VcVerificationResult {
24
- state: OpenId4VcVerificationSessionRecord['state'];
25
- cryptographicVerified: boolean;
26
- accepted: boolean;
27
- trust?: TrustVerdict;
28
- credential?: OpenId4VcVerifiedCredentialResult;
12
+ export interface OpenId4VcVerificationSessionFilters {
13
+ jsonSchemaCredentialId?: string;
14
+ state?: OpenId4VcVerificationSessionState;
29
15
  }
30
- export declare class OpenId4VcVerifierRequestError extends Error {
16
+ export declare const OPENID4VC_REQUEST_SIGNERS: readonly ["x5c", "did"];
17
+ export type OpenId4VcRequestSigner = (typeof OPENID4VC_REQUEST_SIGNERS)[number];
18
+ export interface OpenId4VcCreatePresentationRequestOptions {
19
+ jsonSchemaCredentialId: string;
20
+ requestedClaims?: string[];
21
+ queryLanguage?: OpenId4VcQueryLanguage;
22
+ requestSigner?: OpenId4VcRequestSigner;
31
23
  }
32
- export declare class UnknownVerificationSessionError extends Error {
33
- }
34
- export declare class VerifierService {
24
+ export type OpenId4VcVerificationSessionSummary = PresentationDecision & {
25
+ id: string;
26
+ jsonSchemaCredentialId?: string;
27
+ requestedClaims?: string[];
28
+ state: OpenId4VcVerificationSessionState;
29
+ createdAt: Date;
30
+ updatedAt: Date;
31
+ errorMessage?: string;
32
+ };
33
+ export declare class VerifierService implements OnModuleInit {
35
34
  private readonly agent;
36
35
  private readonly options;
36
+ private readonly resolveDidTrust;
37
37
  private initialization?;
38
38
  private signingCertificate?;
39
- private initialized;
40
- private readonly trustClient;
41
- constructor(agent: OpenId4VcVerifierAgent, options: OpenId4VcPluginOptions);
39
+ private readonly decisions;
40
+ constructor(agent: OpenId4VcAgent, options: OpenId4VcPluginOptions, resolveDidTrust: DidTrustResolver);
41
+ onModuleInit(): Promise<void>;
42
42
  ensureInitialized(): Promise<void>;
43
- createRequest(policyId: string): Promise<OpenId4VcVerificationRequest>;
44
- /** Public signing-certificate material, for operators wiring verifier
45
- * fingerprint pins (never includes private keys). */
46
- getCertificateInfo(): SigningCertificateInfo;
47
- getResult(sessionId: string): Promise<OpenId4VcVerificationResult>;
43
+ createRequest({ jsonSchemaCredentialId, requestedClaims, queryLanguage, requestSigner, }: OpenId4VcCreatePresentationRequestOptions): Promise<OpenId4VcVerificationRequest>;
44
+ getCertificateInfo(): Promise<SigningCertificateInfo>;
45
+ getVerificationSession(id: string): Promise<OpenId4VcVerificationSessionSummary>;
46
+ listVerificationSessions(filters?: OpenId4VcVerificationSessionFilters): Promise<OpenId4VcVerificationSessionSummary[]>;
47
+ deleteVerificationSession(id: string): Promise<void>;
48
+ private findOwnedSession;
49
+ private presentationStateUpdated;
50
+ private decide;
51
+ private decideAndStore;
52
+ private presentedCredential;
53
+ private toSummary;
54
+ private storedRequest;
55
+ private storedDecision;
56
+ private sessionRepository;
48
57
  private initialize;
49
58
  private createOrUpdateVerifier;
50
- private getSession;
51
- private getVerifiedResponse;
52
- private assertSessionOwnership;
53
- private assertStableVerifiedSession;
54
- private matchConfiguredPolicy;
55
- private blockedResult;
56
59
  private verifierApi;
57
- private verifierOptions;
58
- private trustOptions;
59
60
  private signingCertificateHandle;
60
61
  private buildRequestSigner;
61
62
  }
62
- export {};
@@ -1,168 +1,253 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VerifierService = exports.UnknownVerificationSessionError = exports.OpenId4VcVerifierRequestError = void 0;
15
+ exports.VerifierService = exports.OPENID4VC_REQUEST_SIGNERS = void 0;
4
16
  const core_1 = require("@credo-ts/core");
17
+ const common_1 = require("@nestjs/common");
5
18
  const openid4vc_1 = require("@credo-ts/openid4vc");
19
+ const vs_agent_sdk_1 = require("@verana-labs/vs-agent-sdk");
6
20
  const config_1 = require("../config");
7
- const TrustClient_1 = require("../trust/TrustClient");
21
+ const openId4VcEvents_1 = require("../events/openId4VcEvents");
22
+ const mappers_1 = require("../nestjs/mappers");
8
23
  const keyBinding_1 = require("../trust/keyBinding");
24
+ const presentedIssuer_1 = require("../trust/presentedIssuer");
25
+ const trustDecision_1 = require("../trust/trustDecision");
26
+ const types_1 = require("../types");
27
+ const serviceDisplay_1 = require("../utils/serviceDisplay");
9
28
  const CertificateService_1 = require("./CertificateService");
10
- class OpenId4VcVerifierRequestError extends Error {
11
- }
12
- exports.OpenId4VcVerifierRequestError = OpenId4VcVerifierRequestError;
13
- class UnknownVerificationSessionError extends Error {
14
- }
15
- exports.UnknownVerificationSessionError = UnknownVerificationSessionError;
16
- class VerifierService {
17
- constructor(agent, options) {
29
+ const credentialConfigurationBuilder_1 = require("./credentialConfigurationBuilder");
30
+ const presentationRequest_1 = require("./presentationRequest");
31
+ exports.OPENID4VC_REQUEST_SIGNERS = ['x5c', 'did'];
32
+ const BAD_REQUEST = 400;
33
+ const NOT_FOUND = 404;
34
+ const CONFLICT = 409;
35
+ const JSON_SCHEMA_CREDENTIAL_ID_TAG = 'jsonSchemaCredentialId';
36
+ const CREDENTIAL_SCHEMA_ID_TAG = 'credentialSchemaId';
37
+ const REQUESTED_CLAIMS_TAG = 'requestedClaims';
38
+ const OUTCOME_METADATA_KEY = 'openid4vc/verificationOutcome';
39
+ const UNVERIFIED = { cryptographicVerified: false, accepted: false };
40
+ const UNDECIDED = { cryptographicVerified: true, accepted: false };
41
+ let VerifierService = class VerifierService {
42
+ constructor(agent, options, resolveDidTrust) {
18
43
  this.agent = agent;
19
44
  this.options = options;
20
- this.initialized = false;
21
- const trust = this.options.trust;
22
- if (!trust)
23
- throw new Error('OpenID4VC verifier requires trust configuration');
24
- this.trustClient = new TrustClient_1.TrustClient(trust);
45
+ this.resolveDidTrust = resolveDidTrust;
46
+ this.decisions = new Map();
47
+ }
48
+ async onModuleInit() {
49
+ this.agent.events.on(openid4vc_1.OpenId4VcVerifierEvents.VerificationSessionStateChanged, ({ payload: { verificationSession, previousState } }) => {
50
+ // credo announces a new session before createRequest tags it with its type, so createRequest announces it
51
+ if (verificationSession.verifierId !== config_1.VERIFIER_CAPABILITY_ID || previousState === null)
52
+ return;
53
+ this.presentationStateUpdated(verificationSession, previousState);
54
+ });
55
+ await this.ensureInitialized();
25
56
  }
26
57
  ensureInitialized() {
27
58
  var _a;
28
- // A rejected initialization must not be cached: a transient boot-time
29
- // failure (KMS or storage not ready yet) would otherwise wedge the
30
- // process until restart. Reset so the next call retries.
31
59
  (_a = this.initialization) !== null && _a !== void 0 ? _a : (this.initialization = this.initialize().catch(error => {
32
60
  this.initialization = undefined;
33
61
  throw error;
34
62
  }));
35
63
  return this.initialization;
36
64
  }
37
- async createRequest(policyId) {
65
+ async createRequest({ jsonSchemaCredentialId, requestedClaims, queryLanguage = 'dcql', requestSigner, }) {
38
66
  await this.ensureInitialized();
39
- const policy = (0, config_1.findVerifierPolicy)(this.options, policyId);
40
- if (!policy) {
41
- throw new OpenId4VcVerifierRequestError(`unknown verifier policy '${policyId}'`);
67
+ let configuration;
68
+ try {
69
+ configuration = await (0, credentialConfigurationBuilder_1.resolveCredentialType)(this.agent, jsonSchemaCredentialId);
42
70
  }
43
- const configuration = (0, config_1.findCredentialConfiguration)(this.options, policy.credentialConfigurationId);
44
- if (!configuration) {
45
- throw new OpenId4VcVerifierRequestError(`verifier policy '${policyId}' references an unknown credential configuration`);
71
+ catch (error) {
72
+ throw (0, vs_agent_sdk_1.trustDecisionError)(error, 'agent', vs_agent_sdk_1.AdminApiErrorCode.UnknownId);
46
73
  }
47
- const { authorizationRequest, verificationSession } = await this.verifierApi().createAuthorizationRequest({
48
- verifierId: this.verifierOptions().id,
49
- requestSigner: await this.buildRequestSigner(),
50
- responseMode: 'direct_post.jwt',
51
- dcql: {
52
- query: {
53
- credentials: [
54
- {
55
- id: configuration.id,
56
- format: 'dc+sd-jwt',
57
- meta: { vct_values: [configuration.vct] },
58
- claims: policy.requestedClaims.map(name => ({ path: [name] })),
59
- },
60
- ],
61
- },
62
- },
63
- });
74
+ const claims = requestedClaims !== null && requestedClaims !== void 0 ? requestedClaims : configuration.claims;
75
+ assertRequestedClaims(claims, configuration.claims);
76
+ // [VSA-VTI-FLOW-VERIFY-AC-5] for OpenID4VP: the agent asks for a type only where the Ecosystem
77
+ // accredits it as a verifier
78
+ try {
79
+ await this.agent.anonCredsTrust.assertOwnAuthorization({
80
+ role: vs_agent_sdk_1.ParticipantRole.Verifier,
81
+ credentialSchemaId: configuration.credentialSchemaId,
82
+ });
83
+ }
84
+ catch (error) {
85
+ throw (0, vs_agent_sdk_1.trustDecisionError)(error, 'agent');
86
+ }
87
+ const { authorizationRequest, verificationSession } = await this.verifierApi().createAuthorizationRequest(Object.assign({ verifierId: config_1.VERIFIER_CAPABILITY_ID, requestSigner: await this.buildRequestSigner(queryLanguage, requestSigner),
88
+ // JARM (direct_post.jwt) is DCQL-only: Presentation Exchange wallets can't build the JWE it needs.
89
+ responseMode: queryLanguage === 'presentation_exchange' ? 'direct_post' : 'direct_post.jwt' }, (0, presentationRequest_1.presentationQueryFor)(configuration, claims, queryLanguage)));
90
+ verificationSession.setTag(JSON_SCHEMA_CREDENTIAL_ID_TAG, jsonSchemaCredentialId);
91
+ verificationSession.setTag(CREDENTIAL_SCHEMA_ID_TAG, String(configuration.credentialSchemaId));
92
+ verificationSession.setTag(REQUESTED_CLAIMS_TAG, claims);
93
+ await this.sessionRepository().update(this.agent.context, verificationSession);
94
+ this.presentationStateUpdated(verificationSession, null);
64
95
  return {
65
96
  authorizationRequest,
66
97
  verificationSessionId: verificationSession.id,
67
98
  };
68
99
  }
69
- /** Public signing-certificate material, for operators wiring verifier
70
- * fingerprint pins (never includes private keys). */
71
- getCertificateInfo() {
100
+ async getCertificateInfo() {
101
+ await this.ensureInitialized();
72
102
  return (0, CertificateService_1.signingCertificateInfo)('verifier', this.signingCertificateHandle());
73
103
  }
74
- async getResult(sessionId) {
75
- var _a, _b;
76
- const session = await this.getSession(sessionId);
77
- this.assertSessionOwnership(session, sessionId);
78
- if (session.state !== openid4vc_1.OpenId4VcVerificationSessionState.ResponseVerified) {
79
- return {
80
- state: session.state,
81
- cryptographicVerified: false,
82
- accepted: false,
83
- };
84
- }
85
- const verified = await this.getVerifiedResponse(sessionId);
86
- this.assertStableVerifiedSession(verified, sessionId);
87
- const matched = this.matchConfiguredPolicy(verified);
88
- if (!matched) {
89
- return this.blockedResult(session.state, null, null, 'unbound');
90
- }
91
- const { policy } = matched;
92
- const configuration = (0, config_1.findCredentialConfiguration)(this.options, policy.credentialConfigurationId);
93
- if (!configuration) {
94
- return this.blockedResult(session.state, null, null, 'unbound');
95
- }
96
- const presentation = (_b = (_a = verified.dcql) === null || _a === void 0 ? void 0 : _a.presentations[configuration.id]) === null || _b === void 0 ? void 0 : _b[0];
97
- if (!isX5cSdJwtDcPresentation(presentation)) {
98
- return this.blockedResult(session.state, null, configuration.vtjscId, 'unbound');
104
+ async getVerificationSession(id) {
105
+ await this.ensureInitialized();
106
+ const session = await this.findOwnedSession(id);
107
+ return this.decide(session);
108
+ }
109
+ // [VSA-ADM-OID-PR-LIST]: a list reports the stored verdict and never decides
110
+ async listVerificationSessions(filters = {}) {
111
+ await this.ensureInitialized();
112
+ const sessions = await this.verifierApi().findVerificationSessionsByQuery({
113
+ verifierId: config_1.VERIFIER_CAPABILITY_ID,
114
+ state: filters.state,
115
+ [JSON_SCHEMA_CREDENTIAL_ID_TAG]: filters.jsonSchemaCredentialId,
116
+ });
117
+ return sessions.map(session => { var _a; return this.toSummary(session, (_a = this.storedDecision(session)) !== null && _a !== void 0 ? _a : UNDECIDED); });
118
+ }
119
+ async deleteVerificationSession(id) {
120
+ await this.ensureInitialized();
121
+ await this.findOwnedSession(id);
122
+ await this.verifierApi().deleteVerificationSessionById(id);
123
+ }
124
+ async findOwnedSession(id) {
125
+ let session;
126
+ try {
127
+ session = await this.verifierApi().getVerificationSessionById(id);
99
128
  }
100
- const disclosedClaims = configuredDisclosedClaims(presentation.prettyClaims, policy.requestedClaims);
101
- if (presentation.prettyClaims.vct !== configuration.vct || !disclosedClaims) {
102
- return this.blockedResult(session.state, null, configuration.vtjscId, 'unbound');
129
+ catch (error) {
130
+ if (error instanceof core_1.RecordNotFoundError) {
131
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.UnknownId, NOT_FOUND, `no presentation with id "${id}"`);
132
+ }
133
+ throw error;
103
134
  }
104
- const issuerCertificate = presentation.issuer.x5c[0];
105
- let issuerDid;
106
- let issuerPublicJwk;
107
- try {
108
- issuerDid = (0, CertificateService_1.didFromValidatedCertificate)(issuerCertificate);
109
- issuerPublicJwk = issuerCertificate.publicJwk.toJson();
135
+ if (session.verifierId !== config_1.VERIFIER_CAPABILITY_ID) {
136
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.UnknownId, NOT_FOUND, `no presentation with id "${id}"`);
110
137
  }
111
- catch (_c) {
112
- return this.blockedResult(session.state, null, configuration.vtjscId, 'unbound');
138
+ return session;
139
+ }
140
+ // [VSA-EVT-CAT]: the event carries the record as getPresentation returns it, so it decides like a read
141
+ presentationStateUpdated(session, previousState) {
142
+ (0, openId4VcEvents_1.emitStateUpdated)(this.agent, openId4VcEvents_1.OpenId4VcEventType.PresentationStateUpdated, async () => {
143
+ const summary = await this.decide(session).catch(error => {
144
+ this.agent.config.logger.error(`[OpenID4VC] presentation ${session.id} could not be decided`, {
145
+ cause: error,
146
+ });
147
+ return this.toSummary(session, UNDECIDED);
148
+ });
149
+ return (0, mappers_1.toPresentationDto)(summary);
150
+ }, previousState);
151
+ }
152
+ // [VSA-ADM-OID-PR-GET]: the verdict is computed once, on the first read or the ResponseVerified event,
153
+ // and stored with the session; RESOLVER_UNAVAILABLE is never stored, so the next read retries the resolver
154
+ async decide(session) {
155
+ const stored = this.storedDecision(session);
156
+ if (stored)
157
+ return this.toSummary(session, stored);
158
+ let summary = this.decisions.get(session.id);
159
+ if (!summary) {
160
+ summary = this.decideAndStore(session).finally(() => this.decisions.delete(session.id));
161
+ this.decisions.set(session.id, summary);
113
162
  }
114
- const credential = { vct: configuration.vct, disclosedClaims };
115
- const binding = await (0, keyBinding_1.verifyKeyBoundToDid)(this.agent, issuerDid, issuerPublicJwk, ['assertionMethod'], {
116
- allowedWebHosts: this.trustOptions().allowedDidWebHosts,
117
- timeoutMs: this.trustOptions().timeoutMs,
163
+ return summary;
164
+ }
165
+ async decideAndStore({ id, }) {
166
+ var _a;
167
+ // a caller can hold a copy read before a concurrent decision stored its verdict
168
+ const session = await this.verifierApi().getVerificationSessionById(id);
169
+ const stored = this.storedDecision(session);
170
+ if (stored)
171
+ return this.toSummary(session, stored);
172
+ const decision = await (0, trustDecision_1.decidePresentationTrust)(await this.presentedCredential(session), this.storedRequest(session), {
173
+ agent: this.agent,
174
+ readTypeMetadata: vct => (0, vs_agent_sdk_1.fetchBoundedBytes)(vct),
175
+ resolveDidTrust: this.resolveDidTrust,
176
+ assertAuthorized: options => this.agent.anonCredsTrust.assertAuthorized(options),
118
177
  });
119
- if (binding !== 'bound') {
120
- return {
121
- state: session.state,
122
- cryptographicVerified: true,
123
- accepted: false,
124
- trust: (0, keyBinding_1.blockingBindingVerdict)(issuerDid, configuration.vtjscId, binding),
125
- credential,
126
- };
178
+ if (((_a = decision.trust) === null || _a === void 0 ? void 0 : _a.verdict) !== 'RESOLVER_UNAVAILABLE') {
179
+ session.metadata.set(OUTCOME_METADATA_KEY, decision);
180
+ await this.sessionRepository().update(this.agent.context, session);
127
181
  }
128
- const trust = await this.trustClient.verdictFor('issuer', issuerDid, configuration.vtjscId);
129
- return {
130
- state: session.state,
131
- cryptographicVerified: true,
132
- accepted: trust.verdict === 'TRUSTED_AUTHORIZED',
133
- trust,
134
- credential,
135
- };
182
+ return this.toSummary(session, decision);
183
+ }
184
+ async presentedCredential(session) {
185
+ var _a, _b, _c, _d;
186
+ const verified = await this.verifierApi().getVerifiedAuthorizationResponse(session.id);
187
+ const presentations = [
188
+ ...Object.values((_b = (_a = verified.dcql) === null || _a === void 0 ? void 0 : _a.presentations) !== null && _b !== void 0 ? _b : {}).flat(),
189
+ ...((_d = (_c = verified.presentationExchange) === null || _c === void 0 ? void 0 : _c.presentations) !== null && _d !== void 0 ? _d : []),
190
+ ];
191
+ const credential = presentations.find((presentation) => presentation.claimFormat === core_1.ClaimFormat.SdJwtDc);
192
+ if (!credential)
193
+ throw new Error(`the verification session "${session.id}" carries no SD-JWT VC`);
194
+ return credential;
195
+ }
196
+ toSummary(session, decision) {
197
+ var _a;
198
+ const jsonSchemaCredentialId = session.getTag(JSON_SCHEMA_CREDENTIAL_ID_TAG);
199
+ const requestedClaims = session.getTag(REQUESTED_CLAIMS_TAG);
200
+ return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ id: session.id }, (typeof jsonSchemaCredentialId === 'string' ? { jsonSchemaCredentialId } : {})), (Array.isArray(requestedClaims) ? { requestedClaims } : {})), { state: session.state, createdAt: session.createdAt, updatedAt: (_a = session.updatedAt) !== null && _a !== void 0 ? _a : session.createdAt }), (session.errorMessage ? { errorMessage: session.errorMessage } : {})), decision);
201
+ }
202
+ storedRequest(session) {
203
+ const jsonSchemaCredentialId = session.getTag(JSON_SCHEMA_CREDENTIAL_ID_TAG);
204
+ const credentialSchemaId = session.getTag(CREDENTIAL_SCHEMA_ID_TAG);
205
+ if (typeof jsonSchemaCredentialId !== 'string' || typeof credentialSchemaId !== 'string') {
206
+ throw new Error(`the verification session "${session.id}" carries no credential type`);
207
+ }
208
+ return { jsonSchemaCredentialId, credentialSchemaId: Number(credentialSchemaId) };
209
+ }
210
+ storedDecision(session) {
211
+ var _a;
212
+ if (session.state !== openid4vc_1.OpenId4VcVerificationSessionState.ResponseVerified)
213
+ return UNVERIFIED;
214
+ return (_a = session.metadata.get(OUTCOME_METADATA_KEY)) !== null && _a !== void 0 ? _a : undefined;
215
+ }
216
+ sessionRepository() {
217
+ return this.agent.context.dependencyManager.resolve(openid4vc_1.OpenId4VcVerificationSessionRepository);
136
218
  }
137
219
  async initialize() {
220
+ var _a;
138
221
  const agentDid = this.agent.did;
139
222
  if (!agentDid)
140
223
  throw new Error('OpenID4VC verifier initialization requires an agent DID');
141
- const signingCertificate = await (0, CertificateService_1.loadSigningCertificate)(this.agent, this.verifierOptions().signing, this.options.publicApiBaseUrl, 'verifier');
224
+ const signingCertificate = await (0, CertificateService_1.loadSigningCertificate)(this.agent, (_a = this.options.verifier) === null || _a === void 0 ? void 0 : _a.signing, this.options.publicApiBaseUrl, 'verifier');
142
225
  const certificateDid = (0, CertificateService_1.didFromValidatedCertificate)(signingCertificate.certificate);
143
226
  if (certificateDid !== agentDid) {
144
227
  throw new Error('OpenID4VC verifier certificate DID does not match the agent DID');
145
228
  }
146
- await (0, CertificateService_1.publishDevelopmentSigningKey)(this.agent, signingCertificate, 'verifier');
147
- const binding = await (0, keyBinding_1.verifyKeyBoundToDid)(this.agent, agentDid, signingCertificate.certificate.publicJwk.toJson(), ['authentication'], (0, keyBinding_1.ownDidResolutionPolicy)(agentDid, this.trustOptions().timeoutMs));
229
+ const publishedMethodId = await (0, CertificateService_1.publishDevelopmentSigningKey)(this.agent, signingCertificate, 'verifier');
230
+ const binding = await (0, keyBinding_1.verifyKeyBoundToDid)(this.agent, agentDid, signingCertificate.certificate.publicJwk.toJson(), ['authentication']);
148
231
  if (binding === 'unresolvable') {
149
232
  throw new Error('OpenID4VC verifier DID could not be resolved for authentication key binding');
150
233
  }
151
234
  if (binding !== 'bound') {
152
235
  throw new Error('OpenID4VC verifier certificate key is not bound to the agent DID authentication');
153
236
  }
237
+ this.agent.config.setTrustedIssuersForVerification(presentedIssuer_1.trustedIssuersForPresentation);
154
238
  await this.createOrUpdateVerifier();
155
239
  this.signingCertificate = signingCertificate;
156
- this.initialized = true;
240
+ this.agent.config.logger.info(`[OpenID4VC] verifier signs with a ${signingCertificate.development ? 'development' : 'configured'} certificate${publishedMethodId ? `, published as ${publishedMethodId}` : ''}`);
157
241
  }
158
242
  async createOrUpdateVerifier() {
159
- const verifier = this.verifierOptions();
160
- const metadata = {
161
- verifierId: verifier.id,
162
- clientMetadata: { client_name: verifier.displayName },
163
- };
243
+ const display = (0, serviceDisplay_1.serviceDisplay)(this.agent);
244
+ const metadata = Object.assign({ verifierId: config_1.VERIFIER_CAPABILITY_ID }, (display
245
+ ? {
246
+ clientMetadata: Object.assign({ client_name: display.name }, (display.logoUri ? { logo_uri: display.logoUri } : {})),
247
+ }
248
+ : {}));
164
249
  try {
165
- await this.verifierApi().getVerifierByVerifierId(verifier.id);
250
+ await this.verifierApi().getVerifierByVerifierId(config_1.VERIFIER_CAPABILITY_ID);
166
251
  }
167
252
  catch (error) {
168
253
  if (!(error instanceof core_1.RecordNotFoundError))
@@ -172,72 +257,6 @@ class VerifierService {
172
257
  }
173
258
  await this.verifierApi().updateVerifierMetadata(metadata);
174
259
  }
175
- async getSession(sessionId) {
176
- try {
177
- return await this.verifierApi().getVerificationSessionById(sessionId);
178
- }
179
- catch (error) {
180
- if (error instanceof core_1.RecordNotFoundError) {
181
- throw new UnknownVerificationSessionError(`OpenID4VC verification session '${sessionId}' was not found`);
182
- }
183
- throw error;
184
- }
185
- }
186
- async getVerifiedResponse(sessionId) {
187
- try {
188
- return await this.verifierApi().getVerifiedAuthorizationResponse(sessionId);
189
- }
190
- catch (error) {
191
- if (error instanceof core_1.RecordNotFoundError) {
192
- throw new UnknownVerificationSessionError(`OpenID4VC verification session '${sessionId}' was not found`);
193
- }
194
- throw error;
195
- }
196
- }
197
- assertSessionOwnership(session, sessionId) {
198
- if (session.verifierId !== this.verifierOptions().id) {
199
- throw new UnknownVerificationSessionError(`OpenID4VC verification session '${sessionId}' was not found`);
200
- }
201
- }
202
- assertStableVerifiedSession(verified, sessionId) {
203
- if (verified.verificationSession.id !== sessionId ||
204
- verified.verificationSession.verifierId !== this.verifierOptions().id ||
205
- verified.verificationSession.state !== openid4vc_1.OpenId4VcVerificationSessionState.ResponseVerified) {
206
- throw new Error('OpenID4VC verification session changed while reading its verified result');
207
- }
208
- }
209
- matchConfiguredPolicy(verified) {
210
- var _a, _b, _c, _d;
211
- const credentials = (_a = verified.dcql) === null || _a === void 0 ? void 0 : _a.query.credentials;
212
- if (!credentials || credentials.length !== 1)
213
- return undefined;
214
- const query = credentials[0];
215
- if (query.format !== 'dc+sd-jwt')
216
- return undefined;
217
- const configuration = (0, config_1.findCredentialConfiguration)(this.options, query.id);
218
- if (!configuration)
219
- return undefined;
220
- if (((_c = (_b = query.meta) === null || _b === void 0 ? void 0 : _b.vct_values) === null || _c === void 0 ? void 0 : _c.length) !== 1 || query.meta.vct_values[0] !== configuration.vct) {
221
- return undefined;
222
- }
223
- const requestedClaims = (_d = query.claims) === null || _d === void 0 ? void 0 : _d.map(claim => {
224
- const path = claim.path;
225
- return path.length === 1 && typeof path[0] === 'string' ? path[0] : undefined;
226
- });
227
- if (!requestedClaims || requestedClaims.some(claim => claim === undefined))
228
- return undefined;
229
- const policy = this.options.verifierPolicies.find(candidate => candidate.credentialConfigurationId === configuration.id &&
230
- equalStrings(candidate.requestedClaims, requestedClaims));
231
- return policy ? { policy } : undefined;
232
- }
233
- blockedResult(state, did, vtjscId, binding) {
234
- return {
235
- state,
236
- cryptographicVerified: true,
237
- accepted: false,
238
- trust: (0, keyBinding_1.blockingBindingVerdict)(did, vtjscId, binding),
239
- };
240
- }
241
260
  verifierApi() {
242
261
  var _a;
243
262
  const verifier = (_a = this.agent.modules.openId4Vc) === null || _a === void 0 ? void 0 : _a.verifier;
@@ -245,65 +264,50 @@ class VerifierService {
245
264
  throw new Error('OpenID4VC verifier API is not enabled on this agent');
246
265
  return verifier;
247
266
  }
248
- verifierOptions() {
249
- const verifier = this.options.verifier;
250
- if (!verifier)
251
- throw new Error('OpenID4VC verifier capability is not configured');
252
- return verifier;
253
- }
254
- trustOptions() {
255
- const trust = this.options.trust;
256
- if (!trust)
257
- throw new Error('OpenID4VC verifier requires trust configuration');
258
- return trust;
259
- }
260
267
  signingCertificateHandle() {
261
- if (!this.initialized || !this.signingCertificate) {
268
+ const signingCertificate = this.signingCertificate;
269
+ if (!signingCertificate)
262
270
  throw new Error('OpenID4VC verifier service is not initialized');
263
- }
264
- return this.signingCertificate;
271
+ return signingCertificate;
265
272
  }
266
- async buildRequestSigner() {
273
+ async buildRequestSigner(queryLanguage, override) {
267
274
  var _a;
268
275
  const certificate = this.signingCertificateHandle();
269
- if (this.verifierOptions().requestSigner !== 'did') {
270
- return { method: 'x5c', x5c: certificate.chain, clientIdPrefix: 'x509_hash' };
276
+ if (override !== 'did') {
277
+ const host = new URL(this.options.publicApiBaseUrl).hostname;
278
+ if (queryLanguage === 'presentation_exchange' && !certificate.certificate.sanDnsNames.includes(host)) {
279
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.InvalidState, CONFLICT, `a presentation_exchange request needs a verifier certificate that carries ${host} as a DNS SAN`);
280
+ }
281
+ return {
282
+ method: 'x5c',
283
+ x5c: (0, CertificateService_1.x5cCertificateChain)(certificate),
284
+ // Draft 21 predates x509_hash: Credo would send client_id_scheme=x509_hash and then refuse to parse its own request.
285
+ clientIdPrefix: queryLanguage === 'presentation_exchange' ? 'x509_san_dns' : 'x509_hash',
286
+ };
271
287
  }
272
288
  const did = (_a = this.agent.did) !== null && _a !== void 0 ? _a : null;
273
- const didUrl = await (0, keyBinding_1.findBoundVerificationMethodId)(this.agent, did, certificate.certificate.publicJwk.toJson(), ['authentication'], (0, keyBinding_1.ownDidResolutionPolicy)(did !== null && did !== void 0 ? did : '', this.trustOptions().timeoutMs));
289
+ const didUrl = await (0, keyBinding_1.findBoundVerificationMethodId)(this.agent, did, certificate.certificate.publicJwk.toJson(), ['authentication']);
274
290
  if (!didUrl) {
275
- throw new OpenId4VcVerifierRequestError('verifier is configured to sign requests with its DID, but the DID does not publish the signing key for authentication');
291
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.InvalidState, CONFLICT, 'verifier is configured to sign requests with its DID, but the DID does not publish the signing key for authentication');
276
292
  }
277
293
  return { method: 'did', didUrl };
278
294
  }
279
- }
295
+ };
280
296
  exports.VerifierService = VerifierService;
281
- function isX5cSdJwtDcPresentation(value) {
282
- if (!isRecord(value) || value.claimFormat !== core_1.ClaimFormat.SdJwtDc || !isRecord(value.prettyClaims)) {
283
- return false;
284
- }
285
- if (!isRecord(value.issuer) || value.issuer.method !== 'x5c' || !Array.isArray(value.issuer.x5c)) {
286
- return false;
297
+ exports.VerifierService = VerifierService = __decorate([
298
+ (0, common_1.Injectable)(),
299
+ __param(0, (0, common_1.Inject)('VSAGENT')),
300
+ __param(1, (0, common_1.Inject)(types_1.OPENID4VC_OPTIONS)),
301
+ __param(2, (0, common_1.Inject)(types_1.OPENID4VC_DID_TRUST_RESOLVER)),
302
+ __metadata("design:paramtypes", [Object, Object, Function])
303
+ ], VerifierService);
304
+ function assertRequestedClaims(requestedClaims, configuredClaims) {
305
+ if (new Set(requestedClaims).size !== requestedClaims.length) {
306
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.InvalidInput, BAD_REQUEST, 'requestedClaims must not contain a duplicate');
287
307
  }
288
- const leaf = value.issuer.x5c[0];
289
- return (isRecord(leaf) &&
290
- Array.isArray(leaf.sanUriNames) &&
291
- isRecord(leaf.publicJwk) &&
292
- typeof leaf.publicJwk.toJson === 'function');
293
- }
294
- function configuredDisclosedClaims(claims, requestedClaims) {
295
- const disclosedClaims = {};
296
- for (const name of requestedClaims) {
297
- if (!Object.prototype.hasOwnProperty.call(claims, name))
298
- return undefined;
299
- disclosedClaims[name] = claims[name];
308
+ const unknownClaim = requestedClaims.find(claim => !configuredClaims.includes(claim));
309
+ if (unknownClaim) {
310
+ throw new vs_agent_sdk_1.AdminApiError(vs_agent_sdk_1.AdminApiErrorCode.InvalidInput, BAD_REQUEST, `unknown claim '${unknownClaim}'`);
300
311
  }
301
- return disclosedClaims;
302
- }
303
- function equalStrings(left, right) {
304
- return left.length === right.length && left.every((value, index) => value === right[index]);
305
- }
306
- function isRecord(value) {
307
- return value !== null && typeof value === 'object' && !Array.isArray(value);
308
312
  }
309
313
  //# sourceMappingURL=VerifierService.js.map