@verana-labs/vs-agent-sdk 2.0.0-dev.10 → 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 (194) hide show
  1. package/README.md +0 -2
  2. package/build/adminApi/AdminApiError.d.ts +28 -0
  3. package/build/adminApi/AdminApiError.js +67 -0
  4. package/build/adminApi/AdminApiError.js.map +1 -0
  5. package/build/adminApi/didcommModules.d.ts +2 -0
  6. package/build/adminApi/didcommModules.js +8 -0
  7. package/build/adminApi/didcommModules.js.map +1 -0
  8. package/build/adminApi/index.d.ts +4 -0
  9. package/build/adminApi/index.js +21 -0
  10. package/build/adminApi/index.js.map +1 -0
  11. package/build/adminApi/moduleEndpoint.d.ts +7 -0
  12. package/build/adminApi/moduleEndpoint.js +21 -0
  13. package/build/adminApi/moduleEndpoint.js.map +1 -0
  14. package/build/adminApi/pagination/PageDto.d.ts +7 -0
  15. package/build/adminApi/pagination/PageDto.js +50 -0
  16. package/build/adminApi/pagination/PageDto.js.map +1 -0
  17. package/build/adminApi/pagination/PaginationQueryDto.d.ts +11 -0
  18. package/build/adminApi/pagination/PaginationQueryDto.js +46 -0
  19. package/build/adminApi/pagination/PaginationQueryDto.js.map +1 -0
  20. package/build/adminApi/pagination/cursor.d.ts +28 -0
  21. package/build/adminApi/pagination/cursor.js +64 -0
  22. package/build/adminApi/pagination/cursor.js.map +1 -0
  23. package/build/adminApi/pagination/index.d.ts +4 -0
  24. package/build/adminApi/pagination/index.js +21 -0
  25. package/build/adminApi/pagination/index.js.map +1 -0
  26. package/build/adminApi/pagination/paginate.d.ts +27 -0
  27. package/build/adminApi/pagination/paginate.js +77 -0
  28. package/build/adminApi/pagination/paginate.js.map +1 -0
  29. package/build/agent/VsAgent.d.ts +27 -34
  30. package/build/agent/VsAgent.js +102 -205
  31. package/build/agent/VsAgent.js.map +1 -1
  32. package/build/agent/createVsAgent.d.ts +9 -6
  33. package/build/agent/createVsAgent.js +5 -5
  34. package/build/agent/createVsAgent.js.map +1 -1
  35. package/build/blockchain/AnonCredsTrustService.d.ts +84 -0
  36. package/build/blockchain/AnonCredsTrustService.js +276 -0
  37. package/build/blockchain/AnonCredsTrustService.js.map +1 -0
  38. package/build/blockchain/AuthorizationService.d.ts +8 -6
  39. package/build/blockchain/AuthorizationService.js +30 -38
  40. package/build/blockchain/AuthorizationService.js.map +1 -1
  41. package/build/blockchain/IndexerWebSocketService.d.ts +7 -2
  42. package/build/blockchain/IndexerWebSocketService.js +67 -36
  43. package/build/blockchain/IndexerWebSocketService.js.map +1 -1
  44. package/build/blockchain/VeranaChainService.d.ts +38 -27
  45. package/build/blockchain/VeranaChainService.js +169 -177
  46. package/build/blockchain/VeranaChainService.js.map +1 -1
  47. package/build/blockchain/VeranaIndexerService.d.ts +14 -1
  48. package/build/blockchain/VeranaIndexerService.js +122 -8
  49. package/build/blockchain/VeranaIndexerService.js.map +1 -1
  50. package/build/blockchain/feePreflight.d.ts +32 -0
  51. package/build/blockchain/feePreflight.js +89 -0
  52. package/build/blockchain/feePreflight.js.map +1 -0
  53. package/build/blockchain/handlers/IndexerHandlerRegistry.d.ts +0 -1
  54. package/build/blockchain/handlers/IndexerHandlerRegistry.js.map +1 -1
  55. package/build/blockchain/handlers/authorizationHandlers.js +2 -2
  56. package/build/blockchain/handlers/authorizationHandlers.js.map +1 -1
  57. package/build/blockchain/handlers/defaultHandlers.js +7 -2
  58. package/build/blockchain/handlers/defaultHandlers.js.map +1 -1
  59. package/build/blockchain/handlers/index.d.ts +1 -0
  60. package/build/blockchain/handlers/index.js +1 -0
  61. package/build/blockchain/handlers/index.js.map +1 -1
  62. package/build/blockchain/handlers/selfIssuanceHandlers.d.ts +13 -0
  63. package/build/blockchain/handlers/selfIssuanceHandlers.js +76 -0
  64. package/build/blockchain/handlers/selfIssuanceHandlers.js.map +1 -0
  65. package/build/blockchain/handlers/stateMutations.d.ts +27 -4
  66. package/build/blockchain/handlers/stateMutations.js +331 -45
  67. package/build/blockchain/handlers/stateMutations.js.map +1 -1
  68. package/build/blockchain/index.d.ts +4 -0
  69. package/build/blockchain/index.js +4 -0
  70. package/build/blockchain/index.js.map +1 -1
  71. package/build/blockchain/indexerMappers.d.ts +3 -0
  72. package/build/blockchain/indexerMappers.js +53 -0
  73. package/build/blockchain/indexerMappers.js.map +1 -0
  74. package/build/blockchain/triggerResolver.d.ts +26 -0
  75. package/build/blockchain/triggerResolver.js +110 -0
  76. package/build/blockchain/triggerResolver.js.map +1 -0
  77. package/build/blockchain/types.d.ts +13 -70
  78. package/build/blockchain/types.js.map +1 -1
  79. package/build/bootstrap/EcsBootstrapService.d.ts +13 -4
  80. package/build/bootstrap/EcsBootstrapService.js +170 -124
  81. package/build/bootstrap/EcsBootstrapService.js.map +1 -1
  82. package/build/connections/InvitationRecord.d.ts +50 -0
  83. package/build/connections/InvitationRecord.js +60 -0
  84. package/build/connections/InvitationRecord.js.map +1 -0
  85. package/build/connections/ParentConnectionModule.d.ts +22 -0
  86. package/build/connections/ParentConnectionModule.js +91 -0
  87. package/build/connections/ParentConnectionModule.js.map +1 -0
  88. package/build/credentials/FullTailsFileService.d.ts +0 -1
  89. package/build/credentials/FullTailsFileService.js +0 -49
  90. package/build/credentials/FullTailsFileService.js.map +1 -1
  91. package/build/did/CachedDocumentLoader.d.ts +3 -0
  92. package/build/did/CachedDocumentLoader.js +7 -1
  93. package/build/did/CachedDocumentLoader.js.map +1 -1
  94. package/build/did/CachedWebDidResolver.d.ts +0 -4
  95. package/build/did/CachedWebDidResolver.js +1 -5
  96. package/build/did/CachedWebDidResolver.js.map +1 -1
  97. package/build/did/artifactServices.d.ts +12 -0
  98. package/build/did/artifactServices.js +48 -0
  99. package/build/did/artifactServices.js.map +1 -0
  100. package/build/did/legacyDidWeb.d.ts +6 -4
  101. package/build/did/legacyDidWeb.js +17 -14
  102. package/build/did/legacyDidWeb.js.map +1 -1
  103. package/build/did/publicDid.d.ts +4 -0
  104. package/build/did/publicDid.js +19 -0
  105. package/build/did/publicDid.js.map +1 -0
  106. package/build/events/BaseMessageEvents.js +138 -14
  107. package/build/events/BaseMessageEvents.js.map +1 -1
  108. package/build/events/ConnectionEvents.js +149 -87
  109. package/build/events/ConnectionEvents.js.map +1 -1
  110. package/build/events/InvitationEvents.d.ts +6 -0
  111. package/build/events/InvitationEvents.js +57 -0
  112. package/build/events/InvitationEvents.js.map +1 -0
  113. package/build/events/VsAgentEvents.d.ts +18 -9
  114. package/build/events/VsAgentEvents.js +9 -1
  115. package/build/events/VsAgentEvents.js.map +1 -1
  116. package/build/events/VtFlowEvents.d.ts +1 -1
  117. package/build/events/VtFlowEvents.js +29 -17
  118. package/build/events/VtFlowEvents.js.map +1 -1
  119. package/build/events/index.d.ts +1 -0
  120. package/build/events/index.js +1 -0
  121. package/build/events/index.js.map +1 -1
  122. package/build/index.d.ts +9 -1
  123. package/build/index.js +20 -2
  124. package/build/index.js.map +1 -1
  125. package/build/plugins/setupBaseDidComm.js +20 -21
  126. package/build/plugins/setupBaseDidComm.js.map +1 -1
  127. package/build/transports/HttpInboundTransport.js +6 -1
  128. package/build/transports/HttpInboundTransport.js.map +1 -1
  129. package/build/transports/VsAgentWsInboundTransport.d.ts +1 -1
  130. package/build/transports/VsAgentWsInboundTransport.js +20 -14
  131. package/build/transports/VsAgentWsInboundTransport.js.map +1 -1
  132. package/build/types.d.ts +14 -13
  133. package/build/types.js +1 -2
  134. package/build/types.js.map +1 -1
  135. package/build/utils/agent.d.ts +42 -4
  136. package/build/utils/agent.js +126 -22
  137. package/build/utils/agent.js.map +1 -1
  138. package/build/utils/boundedFetch.d.ts +13 -0
  139. package/build/utils/boundedFetch.js +47 -0
  140. package/build/utils/boundedFetch.js.map +1 -0
  141. package/build/utils/didReadiness.js +5 -2
  142. package/build/utils/didReadiness.js.map +1 -1
  143. package/build/utils/ecsClaims.d.ts +46 -0
  144. package/build/utils/ecsClaims.js +115 -0
  145. package/build/utils/ecsClaims.js.map +1 -0
  146. package/build/utils/ecsService.d.ts +8 -0
  147. package/build/utils/ecsService.js +23 -0
  148. package/build/utils/ecsService.js.map +1 -0
  149. package/build/utils/index.d.ts +7 -0
  150. package/build/utils/index.js +7 -0
  151. package/build/utils/index.js.map +1 -1
  152. package/build/utils/publishedDidRecord.d.ts +15 -0
  153. package/build/utils/publishedDidRecord.js +83 -0
  154. package/build/utils/publishedDidRecord.js.map +1 -0
  155. package/build/utils/selfIssuedEcsCredential.d.ts +8 -0
  156. package/build/utils/selfIssuedEcsCredential.js +158 -0
  157. package/build/utils/selfIssuedEcsCredential.js.map +1 -0
  158. package/build/utils/setupSelfTr.d.ts +35 -74
  159. package/build/utils/setupSelfTr.js +93 -312
  160. package/build/utils/setupSelfTr.js.map +1 -1
  161. package/build/utils/trustCredentialStore.d.ts +87 -9
  162. package/build/utils/trustCredentialStore.js +343 -137
  163. package/build/utils/trustCredentialStore.js.map +1 -1
  164. package/build/utils/typeMetadata.d.ts +44 -0
  165. package/build/utils/typeMetadata.js +89 -0
  166. package/build/utils/typeMetadata.js.map +1 -0
  167. package/build/utils/util.d.ts +20 -0
  168. package/build/utils/util.js +29 -0
  169. package/build/utils/util.js.map +1 -1
  170. package/build/utils/vcdm2.d.ts +34 -0
  171. package/build/utils/vcdm2.js +60 -0
  172. package/build/utils/vcdm2.js.map +1 -0
  173. package/build/utils/vtjscResolver.d.ts +23 -0
  174. package/build/utils/vtjscResolver.js +53 -0
  175. package/build/utils/vtjscResolver.js.map +1 -0
  176. package/build/vtFlow/VtFlowOrchestrator.d.ts +108 -15
  177. package/build/vtFlow/VtFlowOrchestrator.js +692 -118
  178. package/build/vtFlow/VtFlowOrchestrator.js.map +1 -1
  179. package/build/vtFlow/assertVerifiableService.d.ts +31 -2
  180. package/build/vtFlow/assertVerifiableService.js +68 -10
  181. package/build/vtFlow/assertVerifiableService.js.map +1 -1
  182. package/build/vtFlow/ecsIssuanceExemption.d.ts +12 -0
  183. package/build/vtFlow/ecsIssuanceExemption.js +84 -0
  184. package/build/vtFlow/ecsIssuanceExemption.js.map +1 -0
  185. package/build/vtFlow/index.d.ts +1 -0
  186. package/build/vtFlow/index.js +1 -0
  187. package/build/vtFlow/index.js.map +1 -1
  188. package/package.json +25 -19
  189. package/build/did/migrateWebVhLog.d.ts +0 -34
  190. package/build/did/migrateWebVhLog.js +0 -230
  191. package/build/did/migrateWebVhLog.js.map +0 -1
  192. package/build/did/migrateWebVhVersionTime.d.ts +0 -9
  193. package/build/did/migrateWebVhVersionTime.js +0 -191
  194. package/build/did/migrateWebVhVersionTime.js.map +0 -1
@@ -3,10 +3,38 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VtFlowOrchestrator = void 0;
4
4
  const core_1 = require("@credo-ts/core");
5
5
  const credo_ts_didcomm_vt_flow_1 = require("@verana-labs/credo-ts-didcomm-vt-flow");
6
+ const verana_types_1 = require("@verana-labs/verana-types");
6
7
  const verre_1 = require("@verana-labs/verre");
8
+ const vs_agent_model_1 = require("@verana-labs/vs-agent-model");
9
+ const adminApi_1 = require("../adminApi");
10
+ const ecsIssuanceExemption_1 = require("./ecsIssuanceExemption");
11
+ const feePreflight_1 = require("../blockchain/feePreflight");
7
12
  const types_1 = require("../blockchain/types");
8
13
  const types_2 = require("../types");
9
14
  const utils_1 = require("../utils");
15
+ // The chain carries a fee discount as an integer from 0 to 10000. The API and the indexer carry it
16
+ // as a decimal from 0 to 1, so only the message is scaled.
17
+ const DISCOUNT_SCALE = 10000;
18
+ const TX_LOOKUP_TIMEOUT_MS = 60000;
19
+ const TX_LOOKUP_INTERVAL_MS = 3000;
20
+ // the notification handler and the tx lookup can both reach markValidated for one flow at the same time
21
+ const markingValidated = new Set();
22
+ const continuingAfterValidated = new Map();
23
+ const FEE_KEYS = ['validationFees', 'issuanceFees', 'verificationFees'];
24
+ const DISCOUNT_KEYS = ['issuanceFeeDiscount', 'verificationFeeDiscount'];
25
+ function invalidInput(message) {
26
+ return new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidInput, 400, message);
27
+ }
28
+ function invalidState(message) {
29
+ return new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidState, 409, message);
30
+ }
31
+ function sameTerm(key, given, onEntry) {
32
+ const scale = DISCOUNT_KEYS.includes(key) ? DISCOUNT_SCALE : 1;
33
+ return Math.round(given * scale) === Math.round(onEntry * scale);
34
+ }
35
+ function errorMessage(error) {
36
+ return error instanceof Error ? error.message : String(error);
37
+ }
10
38
  class VtFlowOrchestrator {
11
39
  constructor(agent, options = {}) {
12
40
  this.agent = agent;
@@ -14,10 +42,10 @@ class VtFlowOrchestrator {
14
42
  }
15
43
  async startOnboardingProcess(input) {
16
44
  var _a, _b, _c, _d;
17
- const chain = this.requireChain();
45
+ this.requireChain();
18
46
  if (!this.agent.did)
19
47
  throw new Error('Agent has no public DID');
20
- const holderParticipant = await chain.getParticipant(input.applicantParticipantId);
48
+ const holderParticipant = await this.agent.indexer.findParticipant(input.applicantParticipantId);
21
49
  if (!holderParticipant) {
22
50
  throw new Error(`Applicant participant ${input.applicantParticipantId} not found on chain`);
23
51
  }
@@ -37,7 +65,7 @@ class VtFlowOrchestrator {
37
65
  if (!holderParticipant.validatorParticipantId) {
38
66
  throw new Error(`Applicant participant ${input.applicantParticipantId} has no validator_participant_id`);
39
67
  }
40
- const validatorParticipant = await chain.getParticipant(Number(holderParticipant.validatorParticipantId));
68
+ const validatorParticipant = await this.agent.indexer.findParticipant(Number(holderParticipant.validatorParticipantId));
41
69
  if (!(validatorParticipant === null || validatorParticipant === void 0 ? void 0 : validatorParticipant.did)) {
42
70
  throw new Error(`Validator participant ${holderParticipant.validatorParticipantId} not resolvable`);
43
71
  }
@@ -47,46 +75,58 @@ class VtFlowOrchestrator {
47
75
  // Renewals resend the OR with the same session id so the validator re-attaches the finished flow.
48
76
  const vtFlowApi = this.resolveVtFlowApi();
49
77
  const [latest] = (await vtFlowApi.findAllByQuery({
50
- participantId: String(holderParticipant.id),
78
+ applicantParticipantId: String(holderParticipant.id),
51
79
  role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Applicant,
52
80
  flowVariant: credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess,
53
81
  }))
54
82
  .filter(record => !(0, credo_ts_didcomm_vt_flow_1.isVtFlowTerminalState)(record.state))
55
83
  .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
56
- if (latest && latest.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Completed && latest.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.CredRevoked) {
57
- this.agent.config.logger.info(`[vt-flow] onboarding flow ${latest.id} for participant ${holderParticipant.id} is already in progress (state ${latest.state}); not resending`);
58
- return latest;
59
- }
60
- const existing = latest;
84
+ const running = latest !== undefined && !(0, credo_ts_didcomm_vt_flow_1.isVtFlowRenewable)(latest);
61
85
  let connectionId;
62
- if (existing) {
63
- const connection = await this.agent.didcomm.connections.findById(existing.connectionId);
64
- if (connection === null || connection === void 0 ? void 0 : connection.isReady)
86
+ if (latest) {
87
+ const connection = await this.agent.didcomm.connections.findById(latest.connectionId);
88
+ if (connection && (0, utils_1.isUsableConnectionTo)(connection, validatorParticipant.did))
65
89
  connectionId = connection.id;
66
90
  }
91
+ const undelivered = running && latest.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OrSent && holderParticipant.opState === types_1.ValidationState.PENDING;
92
+ if (running && connectionId && !undelivered) {
93
+ this.agent.config.logger.info(`[vt-flow] onboarding flow ${latest.id} for participant ${holderParticipant.id} is in progress (state ${latest.state}) on an open connection, not resending`);
94
+ return latest;
95
+ }
67
96
  if (!connectionId) {
68
- const { connectionRecord } = await this.agent.didcomm.oob.receiveImplicitInvitation({
69
- did: validatorParticipant.did,
70
- ourDid: this.agent.did,
71
- label: this.agent.label,
72
- didCommVersion: 'v2',
73
- });
74
- if (!connectionRecord)
75
- throw new Error('Failed to establish DIDComm connection to validator');
76
- const ready = await this.agent.didcomm.connections.returnWhenIsConnected(connectionRecord.id);
77
- connectionId = ready.id;
97
+ connectionId = await (0, utils_1.connectToPublicDid)(this.agent, validatorParticipant.did);
98
+ }
99
+ if (running) {
100
+ this.agent.config.logger.info(`[vt-flow] resending the onboarding request of flow ${latest.id} (state ${latest.state}) on ${connectionId === latest.connectionId ? 'its' : 'a new'} connection`);
101
+ return vtFlowApi.resendOnboardingRequest({ vtFlowRecordId: latest.id, connectionId });
78
102
  }
79
103
  return vtFlowApi.sendOnboardingRequest({
80
104
  connectionId,
81
- participantSessionId: (_b = (_a = input.participantSessionId) !== null && _a !== void 0 ? _a : existing === null || existing === void 0 ? void 0 : existing.participantSessionId) !== null && _b !== void 0 ? _b : core_1.utils.uuid(),
82
- participantId: String(holderParticipant.id),
105
+ participantSessionId: (_b = (_a = input.participantSessionId) !== null && _a !== void 0 ? _a : latest === null || latest === void 0 ? void 0 : latest.participantSessionId) !== null && _b !== void 0 ? _b : core_1.utils.uuid(),
106
+ applicantParticipantId: String(holderParticipant.id),
107
+ applicantParticipantRole: Number(holderParticipant.role),
108
+ validatorParticipantId: String(holderParticipant.validatorParticipantId),
109
+ schemaId: String(holderParticipant.schemaId),
83
110
  agentParticipantId: String((_c = this.options.agentParticipantId) !== null && _c !== void 0 ? _c : 0),
84
111
  walletAgentParticipantId: String((_d = this.options.walletAgentParticipantId) !== null && _d !== void 0 ? _d : 0),
85
112
  claims: input.claims,
86
113
  });
87
114
  }
88
- async validateAndOfferCredential(input) {
89
- var _a;
115
+ /**
116
+ * Validate an onboarding process: record the outcome on-chain, accept the onboarding request and
117
+ * move the record to VALIDATED. It sends no credential. Only a HOLDER takes part in a credential
118
+ * exchange; an ISSUER, a VERIFIER or a grantor joins the Ecosystem, and SetParticipantOPToValidated
119
+ * is the whole of it. The caller decides what follows, from the role of the returned participant.
120
+ *
121
+ * For a HOLDER it builds the credential before the chain write, and returns it for
122
+ * offerOnboardingCredential. Claims that do not satisfy the schema, or a schema fetch that fails,
123
+ * must stop the process while the chain holds no outcome yet and the caller can repeat the call.
124
+ *
125
+ * A record that is already VALIDATED and has no credential exchange keeps the chain outcome and
126
+ * only builds the credential again. A repeat call thus re-drives an offer that did not complete.
127
+ */
128
+ async validateOnboardingProcess(input) {
129
+ var _a, _b;
90
130
  const chain = this.requireChain();
91
131
  if (!this.agent.did)
92
132
  throw new Error('Agent has no public DID');
@@ -99,43 +139,509 @@ class VtFlowOrchestrator {
99
139
  if (record.variant !== credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess) {
100
140
  throw new Error(`Record variant is '${record.variant}', expected OnboardingProcess`);
101
141
  }
102
- if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr) {
103
- throw new Error(`Record state is '${record.state}', expected '${credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr}'`);
104
- }
105
- if (!record.participantId)
106
- throw new Error('Record has no participantId');
107
- const holderParticipantId = Number(record.participantId);
108
- const holderParticipant = await chain.getParticipant(holderParticipantId);
109
- if (!holderParticipant)
110
- throw new Error(`Holder participant ${holderParticipantId} not found on chain`);
111
- if (!holderParticipant.did)
112
- throw new Error('Holder participant has no DID');
113
- const unsignedCredentialJson = await this.buildCredential({
114
- credentialSchemaId: input.credentialSchemaId,
115
- subjectDid: holderParticipant.did,
116
- claims: ((_a = record.claims) !== null && _a !== void 0 ? _a : {}),
117
- credentialType: input.credentialType,
118
- credentialContext: input.credentialContext,
119
- });
142
+ const resumeOffer = record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.Validated && !record.credentialExchangeRecordId;
143
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr && !resumeOffer) {
144
+ throw new Error(`Record state is '${record.state}', expected '${credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr}', or ` +
145
+ `'${credo_ts_didcomm_vt_flow_1.VtFlowState.Validated}' with no credential exchange`);
146
+ }
147
+ if (!record.applicantParticipantId)
148
+ throw new Error('Record has no applicantParticipantId');
149
+ const participantId = Number(record.applicantParticipantId);
150
+ const participant = await this.agent.indexer.findParticipant(participantId);
151
+ if (!participant)
152
+ throw new Error(`Applicant participant ${participantId} not found on chain`);
153
+ if (!participant.did)
154
+ throw new Error('Applicant participant has no DID');
155
+ const credential = Number(participant.role) === types_2.HOLDER_PARTICIPANT_TYPE
156
+ ? await this.buildCredential({
157
+ credentialSchemaId: (_a = input.credentialSchemaId) !== null && _a !== void 0 ? _a : String(participant.schemaId),
158
+ subjectDid: participant.did,
159
+ claims: ((_b = record.claims) !== null && _b !== void 0 ? _b : {}),
160
+ credentialType: input.credentialType,
161
+ credentialContext: input.credentialContext,
162
+ })
163
+ : undefined;
164
+ if (resumeOffer)
165
+ return { record, participant, credential };
120
166
  // op_summary_digest (MOD-PP-MSG-3) digests the applicant's submission, not the credential
121
- await chain.setParticipantOPToValidated({
122
- id: holderParticipantId,
123
- corporation: holderParticipant.corporation,
124
- });
167
+ await chain.setParticipantOPToValidated({ id: participantId, corporation: participant.corporation });
125
168
  await vtFlowApi.acceptOnboardingRequest(record.id);
126
- await vtFlowApi.markValidated(record.id);
169
+ const validated = await vtFlowApi.markValidated(record.id);
170
+ return { record: validated, participant, credential };
171
+ }
172
+ /**
173
+ * Offer the credential of an onboarding process to its applicant. Call it only for a HOLDER, and
174
+ * only after validateOnboardingProcess has moved the record to VALIDATED. Give it the credential
175
+ * that validateOnboardingProcess built, so that the process does not build the credential twice.
176
+ */
177
+ async offerOnboardingCredential(input) {
178
+ var _a, _b, _c, _d, _e;
179
+ this.requireChain();
180
+ const vtFlowApi = this.resolveVtFlowApi();
181
+ const record = await vtFlowApi.findById(input.vtFlowRecordId);
182
+ if (!record)
183
+ throw new Error(`vt-flow record ${input.vtFlowRecordId} not found`);
184
+ if (!record.applicantParticipantId)
185
+ throw new Error('Record has no applicantParticipantId');
186
+ const participant = (_a = input.participant) !== null && _a !== void 0 ? _a : (await this.agent.indexer.findParticipant(Number(record.applicantParticipantId)));
187
+ if (!(participant === null || participant === void 0 ? void 0 : participant.did))
188
+ throw new Error('Applicant participant has no DID');
189
+ const unsignedCredentialJson = (_b = input.credential) !== null && _b !== void 0 ? _b : (await this.buildCredential({
190
+ credentialSchemaId: (_c = input.credentialSchemaId) !== null && _c !== void 0 ? _c : String(participant.schemaId),
191
+ subjectDid: participant.did,
192
+ claims: ((_d = record.claims) !== null && _d !== void 0 ? _d : {}),
193
+ credentialType: input.credentialType,
194
+ credentialContext: input.credentialContext,
195
+ // [VSA-VTI-FLOW-FMT-1]: markValidated sets it from the entry on every pass, a renewal included
196
+ validUntil: (_e = record.validation) === null || _e === void 0 ? void 0 : _e.effectiveUntil,
197
+ }));
198
+ // W3C Data Integrity attachment format (RFC 0809). The applicant DID is the credential subject
199
+ // and the exchange runs over its authenticated connection, so no extra binding is required. The
200
+ // cryptosuite is the issuer's choice and is applied when the credential is issued.
127
201
  const { record: offered } = await vtFlowApi.offerCredentialForSession({
128
202
  vtFlowRecordId: record.id,
129
- issuerParticipantId: Number(holderParticipant.validatorParticipantId),
203
+ issuerParticipantId: Number(participant.validatorParticipantId),
130
204
  credentialFormats: {
131
- jsonld: {
132
- credential: unsignedCredentialJson,
133
- options: { proofType: 'Ed25519Signature2020', proofPurpose: 'assertionMethod' },
134
- },
205
+ dataIntegrity: { credential: unsignedCredentialJson, bindingRequired: false },
135
206
  },
136
207
  });
137
208
  return offered;
138
209
  }
210
+ /**
211
+ * Close an onboarding process that carries no credential exchange, on the validator side. The
212
+ * applicant reaches the same state from the SetParticipantOPToValidated chain event.
213
+ */
214
+ async completeOnboardingProcess(vtFlowRecordId) {
215
+ return this.resolveVtFlowApi().markCompleted(vtFlowRecordId);
216
+ }
217
+ /** [VSA-ADM-VT-FL-VALIDATE] */
218
+ async validateFlow(input) {
219
+ var _a, _b;
220
+ this.requireChain();
221
+ const vtFlowApi = this.resolveVtFlowApi();
222
+ const record = await vtFlowApi.findById(input.vtFlowRecordId);
223
+ if (!record) {
224
+ throw new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.UnknownId, 404, `no flow with id "${input.vtFlowRecordId}"`);
225
+ }
226
+ if (record.role !== credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator)
227
+ throw invalidState('validate is a validator action');
228
+ const reissue = record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered && ((_b = (_a = record.issuance) === null || _a === void 0 ? void 0 : _a.tx) === null || _b === void 0 ? void 0 : _b.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed;
229
+ if (reissue && record.credentialExchangeRecordId) {
230
+ const { record: issued } = await vtFlowApi.issueCredentialForSession({
231
+ vtFlowRecordId: record.id,
232
+ credentialExchangeRecordId: record.credentialExchangeRecordId,
233
+ });
234
+ return issued;
235
+ }
236
+ if (record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.DirectIssuance)
237
+ return this.validateDirectIssuance(record);
238
+ if (!record.applicantParticipantId)
239
+ throw invalidState('the flow names no applicant participant');
240
+ const applicant = await this.agent.indexer.getParticipant(record.applicantParticipantId);
241
+ const entryValidated = applicant.op_state === 'VALIDATED';
242
+ const rejectedInFlight = entryValidated && (await this.isRejectedInFlight(record));
243
+ if (!rejectedInFlight) {
244
+ this.assertValidateState(record, entryValidated);
245
+ if (record.connectionTerminated)
246
+ throw invalidState('the flow connection is TERMINATED until the applicant reconnects');
247
+ }
248
+ const terms = this.validationTerms(input, applicant, record);
249
+ await this.assertClaimsAndTerm(record, applicant, terms);
250
+ // [VSA-VTI-FLOW-OP-ISSUE-6]: the connection stays TERMINATED, so issuance waits for the applicant to reconnect
251
+ if (rejectedInFlight)
252
+ return this.markValidated(record.id, applicant);
253
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending)
254
+ await this.sendValidating(record);
255
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims)
256
+ return this.continueAfterValidated(record.id);
257
+ if (entryValidated) {
258
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validated)
259
+ await this.markValidated(record.id, applicant);
260
+ return this.continueAfterValidated(record.id);
261
+ }
262
+ const validation = Object.assign({ decidedAt: new Date().toISOString(), submission: await this.submissionPath(applicant) }, terms);
263
+ if (validation.submission === credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator) {
264
+ return vtFlowApi.recordValidation(record.id, validation, credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingValidationTx);
265
+ }
266
+ return this.submitValidation(record.id, applicant, validation);
267
+ }
268
+ // A Direct Issuance flow has no entry to validate, so no transaction: check the claims, then offer.
269
+ async validateDirectIssuance(record) {
270
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validating && record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending) {
271
+ throw invalidState(`the flow is '${record.state}', which validate does not accept`);
272
+ }
273
+ if (!record.schemaId)
274
+ throw invalidState('the flow names no credential schema');
275
+ const connection = await this.agent.didcomm.connections.findById(record.connectionId);
276
+ if (!(connection === null || connection === void 0 ? void 0 : connection.theirDid))
277
+ throw invalidState('the flow connection has no peer DID');
278
+ const schema = await this.agent.indexer.getCredentialSchema(record.schemaId);
279
+ this.assertClaims(schema.json_schema, connection.theirDid, record.claims);
280
+ const vtFlowApi = this.resolveVtFlowApi();
281
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending)
282
+ await this.sendValidating(record);
283
+ const offer = await this.buildDirectIssuanceOffer(record.id);
284
+ if (!offer)
285
+ throw invalidState('the agent holds no active ISSUER participant for the schema of the flow');
286
+ const { record: offered } = await vtFlowApi.offerCredentialForSession(Object.assign({ vtFlowRecordId: record.id }, offer));
287
+ return offered;
288
+ }
289
+ // [VSA-ADM-VT-FL-START]: checked before the flow moves, as a failed send would leave it in VALIDATING
290
+ async sendValidating(record) {
291
+ const connection = await this.agent.didcomm.connections.findById(record.connectionId);
292
+ if (!(connection === null || connection === void 0 ? void 0 : connection.isReady))
293
+ throw invalidState('the flow connection is not ESTABLISHED');
294
+ await this.resolveVtFlowApi().sendValidating(record.id);
295
+ }
296
+ assertClaims(jsonSchema, subjectDid, claims) {
297
+ const violations = (0, utils_1.schemaViolations)(JSON.parse(jsonSchema), Object.assign({ id: subjectDid }, (claims !== null && claims !== void 0 ? claims : {})));
298
+ if (violations.length > 0) {
299
+ throw new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidClaims, 422, 'the claim set does not satisfy the json_schema', { violations });
300
+ }
301
+ }
302
+ assertValidateState(record, entryValidated) {
303
+ const accepted = [
304
+ credo_ts_didcomm_vt_flow_1.VtFlowState.Validating,
305
+ credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending,
306
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed,
307
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims,
308
+ ];
309
+ // Once the entry is VALIDATED on chain any validator-side state resumes into issuance, which is
310
+ // how a backend that disabled the default notification handler drives the flow ([VSA-ADM-VT-FL-VALIDATE-11]).
311
+ const acceptedOnceValidated = [
312
+ credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr,
313
+ credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingValidationTx,
314
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted,
315
+ credo_ts_didcomm_vt_flow_1.VtFlowState.Validated,
316
+ ];
317
+ if (accepted.includes(record.state))
318
+ return;
319
+ if (entryValidated && acceptedOnceValidated.includes(record.state))
320
+ return;
321
+ throw invalidState(`the flow is '${record.state}', which validate does not accept`);
322
+ }
323
+ validationTerms(input, applicant, record) {
324
+ var _a, _b, _c, _d, _e, _f, _g, _h;
325
+ for (const key of FEE_KEYS) {
326
+ const fee = input[key];
327
+ if (fee !== undefined && !(Number.isInteger(fee) && fee >= 0)) {
328
+ throw invalidInput(`${key} must be a non-negative integer`);
329
+ }
330
+ }
331
+ for (const key of DISCOUNT_KEYS) {
332
+ const discount = input[key];
333
+ if (discount !== undefined && !(discount >= 0 && discount <= 1)) {
334
+ throw invalidInput(`${key} must be between 0 and 1`);
335
+ }
336
+ }
337
+ if (input.effectiveUntil !== undefined && Number.isNaN(Date.parse(input.effectiveUntil))) {
338
+ throw invalidInput('effectiveUntil must be an ISO 8601 datetime');
339
+ }
340
+ const onEntry = {
341
+ validationFees: (_a = applicant.validation_fees) !== null && _a !== void 0 ? _a : 0,
342
+ issuanceFees: (_b = applicant.issuance_fees) !== null && _b !== void 0 ? _b : 0,
343
+ verificationFees: (_c = applicant.verification_fees) !== null && _c !== void 0 ? _c : 0,
344
+ issuanceFeeDiscount: (_d = applicant.issuance_fee_discount) !== null && _d !== void 0 ? _d : 0,
345
+ verificationFeeDiscount: (_e = applicant.verification_fee_discount) !== null && _e !== void 0 ? _e : 0,
346
+ };
347
+ const renewal = !!applicant.effective_from;
348
+ const recorded = record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed ? record.validation : undefined;
349
+ const terms = {
350
+ effectiveUntil: (_f = input.effectiveUntil) !== null && _f !== void 0 ? _f : recorded === null || recorded === void 0 ? void 0 : recorded.effectiveUntil,
351
+ opSummaryDigest: (_g = input.opSummaryDigest) !== null && _g !== void 0 ? _g : recorded === null || recorded === void 0 ? void 0 : recorded.opSummaryDigest,
352
+ };
353
+ for (const key of [...FEE_KEYS, ...DISCOUNT_KEYS]) {
354
+ const given = input[key];
355
+ if (renewal) {
356
+ if (given !== undefined && !sameTerm(key, given, onEntry[key])) {
357
+ throw invalidInput(`${key} differs from the entry, and a renewal keeps the agreed value`);
358
+ }
359
+ terms[key] = onEntry[key];
360
+ }
361
+ else {
362
+ terms[key] = (_h = given !== null && given !== void 0 ? given : recorded === null || recorded === void 0 ? void 0 : recorded[key]) !== null && _h !== void 0 ? _h : 0;
363
+ }
364
+ }
365
+ return terms;
366
+ }
367
+ async assertClaimsAndTerm(record, applicant, terms) {
368
+ var _a;
369
+ if (applicant.role !== types_1.ParticipantRole.Holder)
370
+ return;
371
+ if (!applicant.did)
372
+ throw invalidState('the applicant entry has no DID to issue to');
373
+ const schema = await this.agent.indexer.getCredentialSchema(applicant.schema_id);
374
+ this.assertClaims(schema.json_schema, applicant.did, record.claims);
375
+ // [VSA-ADM-VT-FL-VALIDATE-2]: a schema that requires validUntil needs an effective_until. With
376
+ // a validity period of 0 the VPR sets none, so the call has to carry one.
377
+ const needsValidUntil = (0, vs_agent_model_1.schemaRequiresValidUntil)(schema.json_schema);
378
+ if (needsValidUntil && ((_a = schema.holder_validation_validity_period) !== null && _a !== void 0 ? _a : 0) === 0 && !terms.effectiveUntil) {
379
+ throw invalidInput('this schema has no validity period, so effectiveUntil is required');
380
+ }
381
+ }
382
+ async submissionPath(applicant) {
383
+ const authorization = this.agent.authorizationService;
384
+ if (!authorization || applicant.validator_participant_id == null)
385
+ return credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
386
+ const validator = await this.agent.indexer
387
+ .getParticipant(applicant.validator_participant_id)
388
+ .catch(() => undefined);
389
+ if (!validator)
390
+ return credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
391
+ await authorization.refreshForOperator().catch(() => undefined);
392
+ return authorization.canSign(validator, verana_types_1.veranaTypeUrls.MsgSetParticipantOPToValidated)
393
+ ? credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Agent
394
+ : credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
395
+ }
396
+ async submitValidation(recordId, applicant, validation) {
397
+ var _a, _b;
398
+ const chain = this.requireChain();
399
+ const vtFlowApi = this.resolveVtFlowApi();
400
+ const fail = (reason, error) => vtFlowApi.recordValidation(recordId, Object.assign(Object.assign({}, validation), { tx: { status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason, error } }), credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed);
401
+ const message = chain.setParticipantOPToValidatedMsg({
402
+ id: applicant.id,
403
+ effectiveUntil: validation.effectiveUntil ? new Date(validation.effectiveUntil) : undefined,
404
+ validationFees: validation.validationFees,
405
+ issuanceFees: validation.issuanceFees,
406
+ verificationFees: validation.verificationFees,
407
+ issuanceFeeDiscount: Math.round(((_a = validation.issuanceFeeDiscount) !== null && _a !== void 0 ? _a : 0) * DISCOUNT_SCALE),
408
+ verificationFeeDiscount: Math.round(((_b = validation.verificationFeeDiscount) !== null && _b !== void 0 ? _b : 0) * DISCOUNT_SCALE),
409
+ opSummaryDigest: validation.opSummaryDigest,
410
+ });
411
+ const checked = await this.preflight(message, applicant.validator_participant_id);
412
+ if ('reason' in checked)
413
+ return fail(checked.reason, checked.error);
414
+ let hash;
415
+ try {
416
+ hash = await chain.broadcastWithoutWaiting([message], checked.fee);
417
+ }
418
+ catch (error) {
419
+ return fail(credo_ts_didcomm_vt_flow_1.VtFlowTxReason.BroadcastError, errorMessage(error));
420
+ }
421
+ const submitted = await vtFlowApi.recordValidation(recordId, Object.assign(Object.assign({}, validation), { tx: { hash, submittedAt: new Date().toISOString(), status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted } }), credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted);
422
+ void this.resolveValidationTx(recordId).catch(error => this.agent.config.logger.error(`[vt-flow] resolving the validation of ${recordId} failed`, {
423
+ error: errorMessage(error),
424
+ }));
425
+ return submitted;
426
+ }
427
+ // [VSA-ADM-VT-FL-VALIDATE-6]: the fee payer is the Corporation when the grant of the entry has with_feegrant
428
+ preflight(message, participantId) {
429
+ return (0, feePreflight_1.preflightFee)(this.requireChain(), message, (0, feePreflight_1.feeGranterFor)(this.agent, participantId));
430
+ }
431
+ // [VSA-VTI-FLOW-ISSUE-1]: [VSA-ADM-VT-FL-VALIDATE-6] to -9 applied to the anchoring, which the delivery waits for.
432
+ // A transaction left SUBMITTED by a restart is looked up again, not broadcast twice.
433
+ async anchor(record, message, issuerParticipantId) {
434
+ var _a, _b, _c;
435
+ const chain = this.requireChain();
436
+ const pending = ((_b = (_a = record.issuance) === null || _a === void 0 ? void 0 : _a.tx) === null || _b === void 0 ? void 0 : _b.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted ? record.issuance.tx : undefined;
437
+ let hash = pending === null || pending === void 0 ? void 0 : pending.hash;
438
+ let submittedAt = (_c = pending === null || pending === void 0 ? void 0 : pending.submittedAt) !== null && _c !== void 0 ? _c : new Date().toISOString();
439
+ if (!hash) {
440
+ const checked = await this.preflight(message, issuerParticipantId);
441
+ if ('reason' in checked)
442
+ return Object.assign({ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed }, checked);
443
+ try {
444
+ hash = await chain.broadcastWithoutWaiting([message], checked.fee);
445
+ }
446
+ catch (error) {
447
+ return {
448
+ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed,
449
+ reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.BroadcastError,
450
+ error: errorMessage(error),
451
+ };
452
+ }
453
+ submittedAt = new Date().toISOString();
454
+ await this.resolveVtFlowApi().recordIssuance(record.id, {
455
+ tx: { hash, submittedAt, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted },
456
+ });
457
+ }
458
+ for (;;) {
459
+ const tx = await chain.findTx(hash).catch(() => undefined);
460
+ if ((tx === null || tx === void 0 ? void 0 : tx.code) === 0)
461
+ return { hash, submittedAt, height: tx.height, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded };
462
+ if (tx) {
463
+ const failure = { status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed, error: tx.rawLog };
464
+ return Object.assign({ hash, submittedAt, height: tx.height }, failure);
465
+ }
466
+ if (Date.now() - Date.parse(submittedAt) >= TX_LOOKUP_TIMEOUT_MS) {
467
+ const error = 'not found 60 seconds after the broadcast';
468
+ return { hash, submittedAt, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxNotFound, error };
469
+ }
470
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
471
+ }
472
+ }
473
+ // [VSA-ADM-VT-FL-VALIDATE-8]. Leaving VALIDATION_TX_SUBMITTED ends the loop, so the notification
474
+ // handler moving the flow first wins the race.
475
+ async resolveValidationTx(recordId) {
476
+ var _a, _b, _c;
477
+ const chain = this.requireChain();
478
+ const vtFlowApi = this.resolveVtFlowApi();
479
+ let landed;
480
+ for (;;) {
481
+ const record = await vtFlowApi.findById(recordId);
482
+ const validation = record === null || record === void 0 ? void 0 : record.validation;
483
+ const hash = (_a = validation === null || validation === void 0 ? void 0 : validation.tx) === null || _a === void 0 ? void 0 : _a.hash;
484
+ if (!(record === null || record === void 0 ? void 0 : record.applicantParticipantId) || !validation || !hash)
485
+ return;
486
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted)
487
+ return;
488
+ const tx = landed !== null && landed !== void 0 ? landed : (await chain.findTx(hash).catch(() => undefined));
489
+ if (tx && tx.code === 0) {
490
+ landed = tx;
491
+ // the indexer can lag the block of the transaction, and the fill needs the validated entry
492
+ const entry = await this.agent.indexer.getParticipant(record.applicantParticipantId);
493
+ if (entry.op_state === 'VALIDATED') {
494
+ await this.markValidated(recordId, entry, { hash, height: tx.height });
495
+ await this.continueAfterValidated(recordId);
496
+ return;
497
+ }
498
+ }
499
+ else if (tx) {
500
+ return this.failUnlessValidated(record, validation, credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed, tx.rawLog, tx.height);
501
+ }
502
+ const submittedAt = (_c = (_b = validation.tx) === null || _b === void 0 ? void 0 : _b.submittedAt) !== null && _c !== void 0 ? _c : validation.decidedAt;
503
+ if (Date.now() - Date.parse(submittedAt) >= TX_LOOKUP_TIMEOUT_MS) {
504
+ if (tx) {
505
+ this.agent.config.logger.warn(`[vt-flow] the transaction of flow ${recordId} landed, but the indexer does not show the entry VALIDATED yet: its notification completes the flow`);
506
+ return;
507
+ }
508
+ return this.failUnlessValidated(record, validation, credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxNotFound, 'not found 60 seconds after the broadcast');
509
+ }
510
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
511
+ }
512
+ }
513
+ // The VPR has no distinct error for a second SetParticipantOPtoValidated, so the entry tells a
514
+ // rejected duplicate apart from a real failure.
515
+ async failUnlessValidated(record, validation, reason, error, height) {
516
+ var _a;
517
+ const vtFlowApi = this.resolveVtFlowApi();
518
+ const applicant = record.applicantParticipantId
519
+ ? await this.agent.indexer.getParticipant(record.applicantParticipantId)
520
+ : undefined;
521
+ const failed = Object.assign(Object.assign({}, validation), { tx: Object.assign(Object.assign({}, validation.tx), { height, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason, error }) });
522
+ if ((applicant === null || applicant === void 0 ? void 0 : applicant.op_state) === 'VALIDATED') {
523
+ // the notification handler may have moved the flow while the tx and the entry were read
524
+ if (((_a = (await vtFlowApi.findById(record.id))) === null || _a === void 0 ? void 0 : _a.state) !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted)
525
+ return;
526
+ if (reason === credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed)
527
+ await vtFlowApi.recordValidation(record.id, failed);
528
+ await this.markValidated(record.id, applicant);
529
+ await this.continueAfterValidated(record.id);
530
+ return;
531
+ }
532
+ await vtFlowApi.recordValidation(record.id, failed, credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed);
533
+ }
534
+ /**
535
+ * [VSA-VTI-FLOW-OP-ISSUE]: moves the flow to VALIDATED and fills `validation` from the validated
536
+ * entry. Without the landed transaction, a recorded broadcast keeps its tx, and its submission
537
+ * unless that tx failed.
538
+ */
539
+ async markValidated(recordId, entry, landed) {
540
+ var _a, _b, _c, _d, _e;
541
+ const vtFlowApi = this.resolveVtFlowApi();
542
+ if (markingValidated.has(recordId))
543
+ throw invalidState('the flow is already moving to VALIDATED');
544
+ markingValidated.add(recordId);
545
+ try {
546
+ const record = await vtFlowApi.findById(recordId);
547
+ if (!record)
548
+ throw new Error(`vt-flow record ${recordId} not found`);
549
+ if (!credo_ts_didcomm_vt_flow_1.VtFlowValidatedFromStates.has(record.state) &&
550
+ record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.TerminatedByValidator) {
551
+ throw invalidState(`the flow is '${record.state}', which does not precede VALIDATED`);
552
+ }
553
+ const recorded = record.validation;
554
+ const agentTx = landed && ((_a = recorded === null || recorded === void 0 ? void 0 : recorded.tx) === null || _a === void 0 ? void 0 : _a.hash) === landed.hash ? recorded.tx : undefined;
555
+ const validation = Object.assign(Object.assign(Object.assign({}, recorded), { decidedAt: (_c = (_b = recorded === null || recorded === void 0 ? void 0 : recorded.decidedAt) !== null && _b !== void 0 ? _b : landed === null || landed === void 0 ? void 0 : landed.timestamp) !== null && _c !== void 0 ? _c : entry.modified, submission: !landed && ((_d = recorded === null || recorded === void 0 ? void 0 : recorded.tx) === null || _d === void 0 ? void 0 : _d.hash) && recorded.tx.reason !== credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed
556
+ ? recorded.submission
557
+ : agentTx
558
+ ? credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Agent
559
+ : credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator, validationFees: entry.validation_fees, issuanceFees: entry.issuance_fees, verificationFees: entry.verification_fees, issuanceFeeDiscount: entry.issuance_fee_discount, verificationFeeDiscount: entry.verification_fee_discount, effectiveUntil: (_e = entry.effective_until) !== null && _e !== void 0 ? _e : undefined }), (agentTx && {
560
+ tx: {
561
+ hash: agentTx.hash,
562
+ submittedAt: agentTx.submittedAt,
563
+ height: landed === null || landed === void 0 ? void 0 : landed.height,
564
+ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded,
565
+ },
566
+ }));
567
+ return await vtFlowApi.recordValidation(recordId, validation, credo_ts_didcomm_vt_flow_1.VtFlowState.Validated);
568
+ }
569
+ finally {
570
+ markingValidated.delete(recordId);
571
+ }
572
+ }
573
+ /** rejectFlow ended the flow with its transaction in flight, and no newer flow of the applicant replaced it ([VSA-ADM-VT-FL-REJECT-2]). */
574
+ async isRejectedInFlight(record) {
575
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.TerminatedByValidator || !record.validation)
576
+ return false;
577
+ if (!record.applicantParticipantId)
578
+ return false;
579
+ const [latest] = (await this.resolveVtFlowApi().findAllByQuery({
580
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
581
+ applicantParticipantId: record.applicantParticipantId,
582
+ })).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
583
+ return (latest === null || latest === void 0 ? void 0 : latest.id) === record.id;
584
+ }
585
+ // one run at a time per flow: two callers at once would both read VALIDATED and offer twice
586
+ async continueAfterValidated(recordId) {
587
+ var _a;
588
+ const previous = (_a = continuingAfterValidated.get(recordId)) !== null && _a !== void 0 ? _a : Promise.resolve();
589
+ const run = previous.then(() => this.issuanceAfterValidated(recordId));
590
+ const settled = run.then(() => undefined, () => undefined);
591
+ continuingAfterValidated.set(recordId, settled);
592
+ try {
593
+ return await run;
594
+ }
595
+ finally {
596
+ if (continuingAfterValidated.get(recordId) === settled)
597
+ continuingAfterValidated.delete(recordId);
598
+ }
599
+ }
600
+ async issuanceAfterValidated(recordId) {
601
+ var _a;
602
+ const vtFlowApi = this.resolveVtFlowApi();
603
+ const record = await vtFlowApi.findById(recordId);
604
+ if (!record)
605
+ throw new Error(`vt-flow record ${recordId} not found`);
606
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validated && record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims) {
607
+ return record;
608
+ }
609
+ const participant = await this.agent.indexer.findParticipant(Number(record.applicantParticipantId));
610
+ if (!participant)
611
+ throw new Error(`Applicant participant ${record.applicantParticipantId} not found`);
612
+ if (Number(participant.role) !== types_2.HOLDER_PARTICIPANT_TYPE)
613
+ return record;
614
+ const schema = await this.agent.indexer.getCredentialSchema(participant.schemaId);
615
+ const violations = (0, utils_1.schemaViolations)(JSON.parse(schema.json_schema), Object.assign({ id: participant.did }, ((_a = record.claims) !== null && _a !== void 0 ? _a : {})));
616
+ if (violations.length > 0) {
617
+ this.agent.config.logger.error(`[vt-flow] not offering the credential of flow ${recordId}: its claims do not satisfy the ` +
618
+ `json_schema of schema ${participant.schemaId}: ${violations.map(v => `${v.path} ${v.message}`.trim()).join(', ')}`);
619
+ return record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.Validated ? vtFlowApi.markPendingClaims(recordId) : record;
620
+ }
621
+ return this.offerOnboardingCredential({ vtFlowRecordId: recordId, participant });
622
+ }
623
+ /** [VSA-ADM-VT-FL-VALIDATE-8]: at startup, resume every flow left in VALIDATION_TX_SUBMITTED. */
624
+ async resumeValidationSubmissions() {
625
+ const pending = await this.resolveVtFlowApi().findAllByQuery({
626
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
627
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted,
628
+ });
629
+ await Promise.all(pending.map(record => this.resolveValidationTx(record.id)));
630
+ }
631
+ /** [VSA-VTI-FLOW-ISSUE-1]: at startup, resume every anchoring left SUBMITTED through the stored issued credential. */
632
+ async resumeIssuanceSubmissions() {
633
+ const vtFlowApi = this.resolveVtFlowApi();
634
+ const offered = await vtFlowApi.findAllByQuery({
635
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
636
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered,
637
+ });
638
+ await Promise.all(offered.map(({ id, issuance, credentialExchangeRecordId }) => {
639
+ var _a;
640
+ return ((_a = issuance === null || issuance === void 0 ? void 0 : issuance.tx) === null || _a === void 0 ? void 0 : _a.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted && credentialExchangeRecordId
641
+ ? vtFlowApi.issueCredentialForSession({ vtFlowRecordId: id, credentialExchangeRecordId })
642
+ : undefined;
643
+ }));
644
+ }
139
645
  async acceptCredential(input) {
140
646
  const vtFlowApi = this.resolveVtFlowApi();
141
647
  const record = await vtFlowApi.findById(input.vtFlowRecordId);
@@ -154,7 +660,7 @@ class VtFlowOrchestrator {
154
660
  const chain = this.requireChain();
155
661
  if (!this.agent.did)
156
662
  throw new Error('Agent has no public DID');
157
- const indexer = this.requireIndexer();
663
+ const indexer = this.agent.indexer;
158
664
  const vtFlowApi = this.resolveVtFlowApi();
159
665
  const record = await vtFlowApi.findById(vtFlowRecordId);
160
666
  if (!record)
@@ -185,53 +691,51 @@ class VtFlowOrchestrator {
185
691
  });
186
692
  return {
187
693
  credentialFormats: {
188
- jsonld: {
189
- credential: unsignedCredentialJson,
190
- options: { proofType: 'Ed25519Signature2020', proofPurpose: 'assertionMethod' },
191
- },
694
+ dataIntegrity: { credential: unsignedCredentialJson, bindingRequired: false },
192
695
  },
193
696
  issuerParticipantId: issuer.id,
194
697
  };
195
698
  }
699
+ /**
700
+ * Builds the unsigned VC Data Model 2.0 credential that goes into the offer. RFC 0809 derives the
701
+ * advertised data model version from its context, and the issuer secures it with a
702
+ * DataIntegrityProof once the applicant requests it.
703
+ */
196
704
  async buildCredential(input) {
197
- var _a, _b, _c;
198
- const chain = this.requireChain();
199
- const didRecords = await this.agent.dids.getCreatedDids({ did: this.agent.did });
200
- const didRecord = didRecords[0];
201
- if (!didRecord)
202
- throw new Error('Agent DID record not found');
203
- const schemaRef = `vpr:verana:${chain.getChainId}:cs:${input.credentialSchemaId}`;
204
- const entry = await (0, utils_1.findMetadataEntry)(didRecord, '_vt/jsc', '', schemaRef);
205
- if (!entry)
206
- throw new Error(`No stored VTJSC found for ${schemaRef}`);
207
- const { data } = entry;
705
+ var _a;
706
+ const jsonSchemaCredentialId = await this.resolveJsonSchemaCredentialId(input.credentialSchemaId);
208
707
  // A credential whose claims don't satisfy the schema's required fields is not a valid
209
708
  // instance of that credential type — reject it here rather than issue an empty shell.
210
- const schema = await this.requireIndexer().getCredentialSchema(input.credentialSchemaId);
709
+ const schema = await this.agent.indexer.getCredentialSchema(input.credentialSchemaId);
211
710
  (0, utils_1.validateSchema)(JSON.parse(schema.json_schema), Object.assign({ id: input.subjectDid }, input.claims));
212
- const unsignedCredential = (0, utils_1.createCredential)({
711
+ // Data model 2.0 holds the claims on the credential subject itself; the applicant DID wins over
712
+ // any `id` claim so the credential can never name a different subject
713
+ const unsignedCredential = (0, utils_1.createW3cV2Credential)({
213
714
  id: `${this.agent.did}#${core_1.utils.uuid()}`,
214
715
  type: (_a = input.credentialType) !== null && _a !== void 0 ? _a : ['VerifiableCredential', 'VerifiableTrustCredential'],
215
716
  issuer: this.agent.did,
216
- credentialSubject: { id: input.subjectDid, claims: input.claims },
717
+ context: input.credentialContext,
718
+ credentialSubject: Object.assign(Object.assign({}, input.claims), { id: input.subjectDid }),
719
+ credentialSchema: { id: jsonSchemaCredentialId, type: 'JsonSchemaCredential' },
720
+ validUntil: input.validUntil,
217
721
  });
218
- if (input.credentialContext)
219
- unsignedCredential.context = input.credentialContext;
220
- unsignedCredential.credentialSchema = {
221
- id: (_c = (_b = data.verifiableCredential) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.id,
222
- type: 'JsonSchemaCredential',
223
- };
224
- return core_1.JsonTransformer.toJSON(unsignedCredential);
722
+ return (0, utils_1.toOfferedCredentialJson)(unsignedCredential);
723
+ }
724
+ async resolveJsonSchemaCredentialId(credentialSchemaId) {
725
+ return (0, utils_1.resolveJsonSchemaCredentialId)(this.agent, this.agent.indexer, credentialSchemaId, this.requireChain().getChainId);
225
726
  }
226
727
  /** Per the spec the algorithm comes from the schema, never from the digest value. */
227
728
  async digestAlgorithmForSchema(schemaId) {
228
- const schema = await this.requireIndexer().getCredentialSchema(schemaId);
729
+ return (await this.credentialSchema(schemaId)).digestAlgorithm;
730
+ }
731
+ async credentialSchema(schemaId) {
732
+ const schema = await this.agent.indexer.getCredentialSchema(schemaId);
229
733
  if (!schema.digest_algorithm) {
230
734
  throw new Error(`Credential schema ${schemaId} has no digest_algorithm`);
231
735
  }
232
- return schema.digest_algorithm;
736
+ return { digestAlgorithm: schema.digest_algorithm, ecsKey: await (0, vs_agent_model_1.classifyEcsSchema)(schema.json_schema) };
233
737
  }
234
- /** Fired after signing and before delivery, so a failure here must abort the issuance. */
738
+ /** Fired after signing and before delivery. A failed anchoring comes back in `issuance`, and the credential stays undelivered. */
235
739
  async onCredentialIssued(vtFlowRecordId, signedCredential) {
236
740
  var _a, _b;
237
741
  const chain = this.requireChain();
@@ -242,17 +746,20 @@ class VtFlowOrchestrator {
242
746
  if (record.issuerParticipantId == null) {
243
747
  throw new Error(`vt-flow record ${vtFlowRecordId} has no issuerParticipantId to anchor against`);
244
748
  }
245
- const issuer = await this.requireIndexer().getParticipant(record.issuerParticipantId);
749
+ const issuer = await this.agent.indexer.getParticipant(record.issuerParticipantId);
246
750
  const algorithm = await this.digestAlgorithmForSchema(issuer.schema_id);
247
751
  const digest = (0, verre_1.computeCredentialDigestJCS)(signedCredential, algorithm);
248
- await chain.createOrUpdateParticipantSession({
752
+ const message = chain.createOrUpdateParticipantSessionMsg({
249
753
  id: record.participantSessionId,
250
754
  issuerParticipantId: record.issuerParticipantId,
251
755
  agentParticipantId: Number((_a = record.agentParticipantId) !== null && _a !== void 0 ? _a : 0) || 0,
252
756
  walletAgentParticipantId: Number((_b = record.walletAgentParticipantId) !== null && _b !== void 0 ? _b : 0) || 0,
253
757
  digest,
254
758
  });
255
- return digest;
759
+ return {
760
+ credentialDigest: digest,
761
+ issuance: { tx: await this.anchor(record, message, record.issuerParticipantId) },
762
+ };
256
763
  }
257
764
  async verifyOfferedCredential(vtFlowRecordId) {
258
765
  var _a, _b;
@@ -265,7 +772,7 @@ class VtFlowOrchestrator {
265
772
  if (!record.credentialExchangeRecordId) {
266
773
  throw new Error('Record has no credentialExchangeRecordId; nothing to verify');
267
774
  }
268
- const indexer = this.requireIndexer();
775
+ const indexer = this.agent.indexer;
269
776
  const session = await indexer.getParticipantSession(record.participantSessionId);
270
777
  if (!session) {
271
778
  throw new Error(`ParticipantSession ${record.participantSessionId} not found on indexer`);
@@ -286,22 +793,50 @@ class VtFlowOrchestrator {
286
793
  if (record.schemaId != null && Number(issuer.schema_id) !== Number(record.schemaId)) {
287
794
  throw new Error(`Issuer participant schema ${issuer.schema_id} does not match credential schema ${record.schemaId}`);
288
795
  }
289
- const credentialJson = await this.getOfferedCredentialJson(record.credentialExchangeRecordId);
290
- const algorithm = await this.digestAlgorithmForSchema(issuer.schema_id);
291
- const digest = (0, verre_1.computeCredentialDigestJCS)(credentialJson, algorithm);
796
+ const credentialJson = await this.getReceivedCredentialJson(record.credentialExchangeRecordId);
797
+ await this.assertFlowCredentialFormat(credentialJson, issuer);
798
+ const { digestAlgorithm, ecsKey } = await this.credentialSchema(issuer.schema_id);
799
+ const digest = (0, verre_1.computeCredentialDigestJCS)(credentialJson, digestAlgorithm);
292
800
  const anchored = await indexer.getDigest(digest);
293
801
  if (!anchored) {
294
802
  throw new Error(`Credential digest ${digest} is not anchored on-chain`);
295
803
  }
804
+ if (ecsKey)
805
+ await vtFlowApi.setEcsSchemaKey(record.id, ecsKey);
806
+ }
807
+ /** [VSA-VTI-FLOW-FMT-1]. Credo already verified the proof and its assertionMethod key, for data model 2.0 only. */
808
+ async assertFlowCredentialFormat(credential, issuer) {
809
+ var _a, _b, _c;
810
+ if (!(0, utils_1.isVcdm2Credential)(credential)) {
811
+ throw new Error('Received credential is not a VC Data Model 2.0 credential');
812
+ }
813
+ const verificationMethod = (_a = credential.proof) === null || _a === void 0 ? void 0 : _a.verificationMethod;
814
+ if (!issuer.did || (verificationMethod === null || verificationMethod === void 0 ? void 0 : verificationMethod.split('#')[0]) !== issuer.did) {
815
+ throw new Error(`Proof verification method ${verificationMethod} is not one of the validator ${issuer.did}`);
816
+ }
817
+ const subjectId = (_b = credential.credentialSubject) === null || _b === void 0 ? void 0 : _b.id;
818
+ if (subjectId !== this.agent.did) {
819
+ throw new Error(`Credential subject ${subjectId} is not the applicant ${this.agent.did}`);
820
+ }
821
+ const schemaRef = (_c = credential.credentialSchema) === null || _c === void 0 ? void 0 : _c.id;
822
+ const jsonSchemaCredentialId = await this.resolveJsonSchemaCredentialId(String(issuer.schema_id));
823
+ if (schemaRef !== jsonSchemaCredentialId) {
824
+ throw new Error(`Credential schema ${schemaRef} is not the VTJSC ${jsonSchemaCredentialId} of the flow`);
825
+ }
296
826
  }
297
827
  async onCredentialRevoked(vtFlowRecordId) {
298
828
  const vtFlowApi = this.resolveVtFlowApi();
299
829
  const record = await vtFlowApi.findById(vtFlowRecordId);
300
830
  if (!record || record.role !== credo_ts_didcomm_vt_flow_1.VtFlowRole.Applicant)
301
831
  return;
302
- if (!this.options.publicApiBaseUrl || !record.credentialExchangeRecordId)
832
+ if (!this.options.publicApiBaseUrl)
833
+ return;
834
+ if (!record.credentialId && !record.credentialExchangeRecordId)
303
835
  return;
304
- const credentialId = await (0, utils_1.removeStoredTrustCredential)(this.agent, this.options.publicApiBaseUrl, record.credentialExchangeRecordId);
836
+ const credentialId = await (0, utils_1.removeStoredTrustCredential)(this.agent, {
837
+ credentialId: record.credentialId,
838
+ credentialExchangeRecordId: record.credentialExchangeRecordId,
839
+ });
305
840
  if (credentialId) {
306
841
  this.agent.config.logger.info(`[vt-flow] removed revoked credential and its linked VP (${credentialId})`);
307
842
  }
@@ -315,33 +850,67 @@ class VtFlowOrchestrator {
315
850
  return;
316
851
  if (!this.options.publicApiBaseUrl)
317
852
  return;
853
+ // [VSA-VT-LVP-5]: the publication writes the DID record, and that write sends TriggerResolver
318
854
  await this.publishCredentialAsLinkedVp(vtFlowRecordId);
319
- await this.triggerResolver(record);
320
855
  }
321
- async triggerResolver(record) {
322
- const chain = this.agent.veranaChain;
323
- if (!chain || !chain.autoTriggerResolverEnabled)
324
- return;
325
- if (record.participantId == null)
326
- return;
327
- await chain.triggerResolver(Number(record.participantId));
328
- }
329
- async getOfferedCredentialJson(credentialExchangeRecordId) {
330
- var _a;
856
+ /** The signed credential as the issuer attached it, which is the exact JSON its digest covers. */
857
+ async getReceivedCredentialJson(credentialExchangeRecordId) {
858
+ var _a, _b;
331
859
  const formatData = await this.agent.didcomm.credentials.getFormatData(credentialExchangeRecordId);
332
- const credentialJson = (_a = formatData.credential) === null || _a === void 0 ? void 0 : _a.jsonld;
860
+ const credentialJson = (_b = (_a = formatData.credential) === null || _a === void 0 ? void 0 : _a.dataIntegrity) === null || _b === void 0 ? void 0 : _b.credential;
333
861
  if (!credentialJson)
334
- throw new Error('Offered credential has no JSON-LD body to verify');
862
+ throw new Error('Received credential has no data integrity credential body');
335
863
  return credentialJson;
336
864
  }
337
- requireIndexer() {
338
- if (!this.options.indexer) {
339
- throw new Error('Agent has no indexer configured (set VERANA_INDEXER_BASE_URL)');
865
+ // VS-CONN-VS gate: consulted only after trust resolution rejected the peer.
866
+ async checkEcsIssuanceExemption(context) {
867
+ return (0, ecsIssuanceExemption_1.isEcsIssuanceExempt)({
868
+ indexer: this.agent.indexer,
869
+ agent: this.agent,
870
+ trustedEcosystemDids: this.agent.trustedEcosystemDids,
871
+ }, context);
872
+ }
873
+ // the indexer can still lag the applicant's own transaction, so wait for it as a tx lookup does
874
+ async checkParticipantId({ record }) {
875
+ if (!record.applicantParticipantId || !this.agent.did)
876
+ return false;
877
+ const deadline = Date.now() + TX_LOOKUP_TIMEOUT_MS;
878
+ let validatedAtFirstRead;
879
+ for (;;) {
880
+ const entry = await this.agent.indexer
881
+ .getParticipant(record.applicantParticipantId)
882
+ .catch(() => undefined);
883
+ validatedAtFirstRead !== null && validatedAtFirstRead !== void 0 ? validatedAtFirstRead : (validatedAtFirstRead = (entry === null || entry === void 0 ? void 0 : entry.op_state) === 'VALIDATED');
884
+ if (entry) {
885
+ if (entry.revoked || entry.slashed || entry.validator_participant_id == null)
886
+ return false;
887
+ const validator = await this.agent.indexer
888
+ .getParticipant(entry.validator_participant_id)
889
+ .catch(() => undefined);
890
+ if (validator && validator.did !== this.agent.did)
891
+ return false;
892
+ if (validator && entry.op_state === 'PENDING')
893
+ return true;
894
+ if (validator && entry.op_state === 'VALIDATED') {
895
+ const flow = await this.resolveVtFlowApi().findById(record.id);
896
+ // the flow has moved on, or another path is moving it to VALIDATED and continues it itself
897
+ if ((flow === null || flow === void 0 ? void 0 : flow.state) !== credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr || markingValidated.has(record.id))
898
+ return 'validated';
899
+ // VALIDATED at the first read can be the round before this request, which it does not settle
900
+ if (!validatedAtFirstRead) {
901
+ await this.markValidated(record.id, entry);
902
+ await this.continueAfterValidated(record.id);
903
+ return 'validated';
904
+ }
905
+ }
906
+ }
907
+ if (Date.now() >= deadline)
908
+ return false;
909
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
340
910
  }
341
- return this.options.indexer;
342
911
  }
343
912
  async publishCredentialAsLinkedVp(vtFlowRecordId) {
344
- var _a, _b;
913
+ var _a;
345
914
  if (!this.options.publicApiBaseUrl) {
346
915
  throw new Error('publicApiBaseUrl is required to publish a LinkedVerifiablePresentation');
347
916
  }
@@ -354,18 +923,23 @@ class VtFlowOrchestrator {
354
923
  if (!record.credentialExchangeRecordId) {
355
924
  throw new Error(`vt-flow record ${vtFlowRecordId} has no credentialExchangeRecordId`);
356
925
  }
357
- const formatData = await this.agent.didcomm.credentials.getFormatData(record.credentialExchangeRecordId);
358
- const jsonld = (_a = formatData.credential) === null || _a === void 0 ? void 0 : _a.jsonld;
359
- if (!jsonld) {
360
- throw new Error(`No jsonld credential in exchange ${record.credentialExchangeRecordId}`);
361
- }
362
- const schemaRef = (_b = jsonld.credentialSchema) === null || _b === void 0 ? void 0 : _b.id;
926
+ const credentialJson = await this.getReceivedCredentialJson(record.credentialExchangeRecordId);
927
+ const schemaRef = (_a = credentialJson.credentialSchema) === null || _a === void 0 ? void 0 : _a.id;
363
928
  const schemaBaseId = schemaRef ? this.extractSchemaBaseId(schemaRef) : undefined;
364
929
  if (!schemaBaseId) {
365
930
  throw new Error(`Cannot publish Linked VP: credential has no extractable schema base id (credentialSchema.id=${schemaRef !== null && schemaRef !== void 0 ? schemaRef : 'undefined'})`);
366
931
  }
367
- const w3cCredential = core_1.JsonTransformer.fromJSON(jsonld, core_1.W3cJsonLdVerifiableCredential);
368
- await (0, utils_1.createVtc)(this.agent, this.options.publicApiBaseUrl, schemaBaseId, w3cCredential);
932
+ // A data model 2.0 credential arrives secured with a DataIntegrityProof; a validator still on
933
+ // data model 1.1 sends a linked data proof, and both are published the same way
934
+ const credential = (0, utils_1.isVcdm2Credential)(credentialJson)
935
+ ? core_1.W3cV2DataIntegrityVerifiableCredential.fromObject(credentialJson)
936
+ : core_1.JsonTransformer.fromJSON(credentialJson, core_1.W3cJsonLdVerifiableCredential);
937
+ await (0, utils_1.createVtc)(this.agent, this.options.publicApiBaseUrl, record.ecsSchemaKey ? (0, utils_1.linkedVpSchemaId)(record.ecsSchemaKey) : schemaBaseId, credential);
938
+ // [VSA-VT-LVP-3]: the record keeps the id of the published credential.
939
+ // Then the agent can remove that credential without the exchange.
940
+ const credentialId = credentialJson.id;
941
+ if (typeof credentialId === 'string')
942
+ await vtFlowApi.setCredentialId(record.id, credentialId);
369
943
  }
370
944
  extractSchemaBaseId(jscUrl) {
371
945
  var _a;