@verana-labs/vs-agent-sdk 2.0.0-dev.12 → 2.0.0-dev.121

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 (205) 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 +32 -36
  30. package/build/agent/VsAgent.js +179 -221
  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 +115 -0
  36. package/build/blockchain/AnonCredsTrustService.js +287 -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 +5 -1
  42. package/build/blockchain/IndexerWebSocketService.js +42 -21
  43. package/build/blockchain/IndexerWebSocketService.js.map +1 -1
  44. package/build/blockchain/VeranaChainService.d.ts +38 -27
  45. package/build/blockchain/VeranaChainService.js +186 -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 +34 -0
  51. package/build/blockchain/feePreflight.js +96 -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 +28 -4
  66. package/build/blockchain/handlers/stateMutations.js +356 -48
  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 +57 -0
  73. package/build/blockchain/indexerMappers.js.map +1 -0
  74. package/build/blockchain/rpcRetry.d.ts +2 -0
  75. package/build/blockchain/rpcRetry.js +43 -0
  76. package/build/blockchain/rpcRetry.js.map +1 -0
  77. package/build/blockchain/triggerResolver.d.ts +26 -0
  78. package/build/blockchain/triggerResolver.js +110 -0
  79. package/build/blockchain/triggerResolver.js.map +1 -0
  80. package/build/blockchain/types.d.ts +14 -70
  81. package/build/blockchain/types.js +6 -1
  82. package/build/blockchain/types.js.map +1 -1
  83. package/build/bootstrap/EcsBootstrapService.d.ts +13 -4
  84. package/build/bootstrap/EcsBootstrapService.js +176 -124
  85. package/build/bootstrap/EcsBootstrapService.js.map +1 -1
  86. package/build/connections/InvitationRecord.d.ts +50 -0
  87. package/build/connections/InvitationRecord.js +60 -0
  88. package/build/connections/InvitationRecord.js.map +1 -0
  89. package/build/connections/ParentConnectionModule.d.ts +22 -0
  90. package/build/connections/ParentConnectionModule.js +91 -0
  91. package/build/connections/ParentConnectionModule.js.map +1 -0
  92. package/build/credentials/FullTailsFileService.d.ts +0 -1
  93. package/build/credentials/FullTailsFileService.js +0 -49
  94. package/build/credentials/FullTailsFileService.js.map +1 -1
  95. package/build/did/CachedDocumentLoader.d.ts +3 -0
  96. package/build/did/CachedDocumentLoader.js +9 -3
  97. package/build/did/CachedDocumentLoader.js.map +1 -1
  98. package/build/did/CachedWebDidResolver.d.ts +0 -4
  99. package/build/did/CachedWebDidResolver.js +1 -5
  100. package/build/did/CachedWebDidResolver.js.map +1 -1
  101. package/build/did/artifactServices.d.ts +12 -0
  102. package/build/did/artifactServices.js +48 -0
  103. package/build/did/artifactServices.js.map +1 -0
  104. package/build/did/legacyDidWeb.d.ts +6 -4
  105. package/build/did/legacyDidWeb.js +17 -14
  106. package/build/did/legacyDidWeb.js.map +1 -1
  107. package/build/did/publicDid.d.ts +4 -0
  108. package/build/did/publicDid.js +19 -0
  109. package/build/did/publicDid.js.map +1 -0
  110. package/build/did/reusedDidDocument.d.ts +37 -0
  111. package/build/did/reusedDidDocument.js +93 -0
  112. package/build/did/reusedDidDocument.js.map +1 -0
  113. package/build/events/BaseMessageEvents.d.ts +24 -0
  114. package/build/events/BaseMessageEvents.js +368 -14
  115. package/build/events/BaseMessageEvents.js.map +1 -1
  116. package/build/events/ConnectionEvents.js +149 -87
  117. package/build/events/ConnectionEvents.js.map +1 -1
  118. package/build/events/InvitationEvents.d.ts +6 -0
  119. package/build/events/InvitationEvents.js +57 -0
  120. package/build/events/InvitationEvents.js.map +1 -0
  121. package/build/events/VsAgentEvents.d.ts +40 -9
  122. package/build/events/VsAgentEvents.js +10 -1
  123. package/build/events/VsAgentEvents.js.map +1 -1
  124. package/build/events/VtFlowEvents.d.ts +1 -1
  125. package/build/events/VtFlowEvents.js +29 -17
  126. package/build/events/VtFlowEvents.js.map +1 -1
  127. package/build/events/index.d.ts +1 -0
  128. package/build/events/index.js +1 -0
  129. package/build/events/index.js.map +1 -1
  130. package/build/index.d.ts +9 -1
  131. package/build/index.js +20 -2
  132. package/build/index.js.map +1 -1
  133. package/build/plugins/setupBaseDidComm.js +24 -22
  134. package/build/plugins/setupBaseDidComm.js.map +1 -1
  135. package/build/transports/HttpInboundTransport.js +6 -1
  136. package/build/transports/HttpInboundTransport.js.map +1 -1
  137. package/build/transports/VsAgentWsInboundTransport.d.ts +1 -1
  138. package/build/transports/VsAgentWsInboundTransport.js +20 -14
  139. package/build/transports/VsAgentWsInboundTransport.js.map +1 -1
  140. package/build/types.d.ts +14 -13
  141. package/build/types.js +1 -2
  142. package/build/types.js.map +1 -1
  143. package/build/utils/agent.d.ts +42 -4
  144. package/build/utils/agent.js +126 -22
  145. package/build/utils/agent.js.map +1 -1
  146. package/build/utils/boundedFetch.d.ts +13 -0
  147. package/build/utils/boundedFetch.js +47 -0
  148. package/build/utils/boundedFetch.js.map +1 -0
  149. package/build/utils/didReadiness.js +5 -2
  150. package/build/utils/didReadiness.js.map +1 -1
  151. package/build/utils/ecsClaims.d.ts +46 -0
  152. package/build/utils/ecsClaims.js +115 -0
  153. package/build/utils/ecsClaims.js.map +1 -0
  154. package/build/utils/ecsService.d.ts +8 -0
  155. package/build/utils/ecsService.js +23 -0
  156. package/build/utils/ecsService.js.map +1 -0
  157. package/build/utils/index.d.ts +7 -0
  158. package/build/utils/index.js +7 -0
  159. package/build/utils/index.js.map +1 -1
  160. package/build/utils/publishedDidRecord.d.ts +15 -0
  161. package/build/utils/publishedDidRecord.js +83 -0
  162. package/build/utils/publishedDidRecord.js.map +1 -0
  163. package/build/utils/selfIssuedEcsCredential.d.ts +8 -0
  164. package/build/utils/selfIssuedEcsCredential.js +158 -0
  165. package/build/utils/selfIssuedEcsCredential.js.map +1 -0
  166. package/build/utils/setupSelfTr.d.ts +34 -74
  167. package/build/utils/setupSelfTr.js +79 -321
  168. package/build/utils/setupSelfTr.js.map +1 -1
  169. package/build/utils/trustCredentialStore.d.ts +86 -9
  170. package/build/utils/trustCredentialStore.js +342 -137
  171. package/build/utils/trustCredentialStore.js.map +1 -1
  172. package/build/utils/typeMetadata.d.ts +44 -0
  173. package/build/utils/typeMetadata.js +89 -0
  174. package/build/utils/typeMetadata.js.map +1 -0
  175. package/build/utils/util.d.ts +20 -0
  176. package/build/utils/util.js +32 -1
  177. package/build/utils/util.js.map +1 -1
  178. package/build/utils/vcdm2.d.ts +34 -0
  179. package/build/utils/vcdm2.js +60 -0
  180. package/build/utils/vcdm2.js.map +1 -0
  181. package/build/utils/vtjscResolver.d.ts +23 -0
  182. package/build/utils/vtjscResolver.js +53 -0
  183. package/build/utils/vtjscResolver.js.map +1 -0
  184. package/build/vtFlow/VtFlowOrchestrator.d.ts +134 -16
  185. package/build/vtFlow/VtFlowOrchestrator.js +965 -138
  186. package/build/vtFlow/VtFlowOrchestrator.js.map +1 -1
  187. package/build/vtFlow/assertVerifiableService.d.ts +31 -2
  188. package/build/vtFlow/assertVerifiableService.js +68 -10
  189. package/build/vtFlow/assertVerifiableService.js.map +1 -1
  190. package/build/vtFlow/ecsIssuanceExemption.d.ts +12 -0
  191. package/build/vtFlow/ecsIssuanceExemption.js +63 -0
  192. package/build/vtFlow/ecsIssuanceExemption.js.map +1 -0
  193. package/build/vtFlow/index.d.ts +2 -0
  194. package/build/vtFlow/index.js +2 -0
  195. package/build/vtFlow/index.js.map +1 -1
  196. package/build/vtFlow/issuanceRepair.d.ts +4 -0
  197. package/build/vtFlow/issuanceRepair.js +181 -0
  198. package/build/vtFlow/issuanceRepair.js.map +1 -0
  199. package/package.json +27 -19
  200. package/build/did/migrateWebVhLog.d.ts +0 -34
  201. package/build/did/migrateWebVhLog.js +0 -230
  202. package/build/did/migrateWebVhLog.js.map +0 -1
  203. package/build/did/migrateWebVhVersionTime.d.ts +0 -9
  204. package/build/did/migrateWebVhVersionTime.js +0 -191
  205. package/build/did/migrateWebVhVersionTime.js.map +0 -1
@@ -1,12 +1,59 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VtFlowOrchestrator = void 0;
3
+ exports.VtFlowOrchestrator = exports.FAILED_SUBMISSION_RETRY_INTERVAL_MS = void 0;
4
4
  const core_1 = require("@credo-ts/core");
5
+ const didcomm_1 = require("@credo-ts/didcomm");
5
6
  const credo_ts_didcomm_vt_flow_1 = require("@verana-labs/credo-ts-didcomm-vt-flow");
7
+ const verana_types_1 = require("@verana-labs/verana-types");
6
8
  const verre_1 = require("@verana-labs/verre");
9
+ const vs_agent_model_1 = require("@verana-labs/vs-agent-model");
10
+ const adminApi_1 = require("../adminApi");
11
+ const ecsIssuanceExemption_1 = require("./ecsIssuanceExemption");
12
+ const feePreflight_1 = require("../blockchain/feePreflight");
7
13
  const types_1 = require("../blockchain/types");
8
14
  const types_2 = require("../types");
9
15
  const utils_1 = require("../utils");
16
+ // The chain carries a fee discount as an integer from 0 to 10000. The API and the indexer carry it
17
+ // as a decimal from 0 to 1, so only the message is scaled.
18
+ const DISCOUNT_SCALE = 10000;
19
+ const TX_LOOKUP_TIMEOUT_MS = 60000;
20
+ const TX_LOOKUP_INTERVAL_MS = 3000;
21
+ exports.FAILED_SUBMISSION_RETRY_INTERVAL_MS = 60000;
22
+ // the notification handler and the tx lookup can both reach markValidated for one flow at the same time
23
+ const markingValidated = new Set();
24
+ const continuingAfterValidated = new Map();
25
+ const validatingFlows = new Map();
26
+ const FEE_KEYS = ['validationFees', 'issuanceFees', 'verificationFees'];
27
+ const DISCOUNT_KEYS = ['issuanceFeeDiscount', 'verificationFeeDiscount'];
28
+ function invalidInput(message) {
29
+ return new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidInput, 400, message);
30
+ }
31
+ function invalidState(message) {
32
+ return new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidState, 409, message);
33
+ }
34
+ function sameTerm(key, given, onEntry) {
35
+ const scale = DISCOUNT_KEYS.includes(key) ? DISCOUNT_SCALE : 1;
36
+ return Math.round(given * scale) === Math.round(onEntry * scale);
37
+ }
38
+ function errorMessage(error) {
39
+ return error instanceof Error ? error.message : String(error);
40
+ }
41
+ const REASONS_AFTER_BROADCAST = new Set([
42
+ credo_ts_didcomm_vt_flow_1.VtFlowTxReason.BroadcastError,
43
+ credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed,
44
+ credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxNotFound,
45
+ ]);
46
+ // A transaction that failed in the pre-flight: a repeat cannot put a second transaction on chain.
47
+ function failedInPreflight(tx) {
48
+ return (tx === null || tx === void 0 ? void 0 : tx.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed && !REASONS_AFTER_BROADCAST.has(tx.reason);
49
+ }
50
+ function repeatsOnInterval(tx) {
51
+ return (tx === null || tx === void 0 ? void 0 : tx.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed && tx.reason === credo_ts_didcomm_vt_flow_1.VtFlowTxReason.ServiceUnavailable;
52
+ }
53
+ function flowTx(record) {
54
+ var _a, _b;
55
+ return record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered ? (_a = record.issuance) === null || _a === void 0 ? void 0 : _a.tx : (_b = record.validation) === null || _b === void 0 ? void 0 : _b.tx;
56
+ }
10
57
  class VtFlowOrchestrator {
11
58
  constructor(agent, options = {}) {
12
59
  this.agent = agent;
@@ -14,10 +61,10 @@ class VtFlowOrchestrator {
14
61
  }
15
62
  async startOnboardingProcess(input) {
16
63
  var _a, _b, _c, _d;
17
- const chain = this.requireChain();
64
+ this.requireChain();
18
65
  if (!this.agent.did)
19
66
  throw new Error('Agent has no public DID');
20
- const holderParticipant = await chain.getParticipant(input.applicantParticipantId);
67
+ const holderParticipant = await this.agent.indexer.findParticipant(input.applicantParticipantId);
21
68
  if (!holderParticipant) {
22
69
  throw new Error(`Applicant participant ${input.applicantParticipantId} not found on chain`);
23
70
  }
@@ -37,7 +84,7 @@ class VtFlowOrchestrator {
37
84
  if (!holderParticipant.validatorParticipantId) {
38
85
  throw new Error(`Applicant participant ${input.applicantParticipantId} has no validator_participant_id`);
39
86
  }
40
- const validatorParticipant = await chain.getParticipant(Number(holderParticipant.validatorParticipantId));
87
+ const validatorParticipant = await this.agent.indexer.findParticipant(Number(holderParticipant.validatorParticipantId));
41
88
  if (!(validatorParticipant === null || validatorParticipant === void 0 ? void 0 : validatorParticipant.did)) {
42
89
  throw new Error(`Validator participant ${holderParticipant.validatorParticipantId} not resolvable`);
43
90
  }
@@ -47,46 +94,59 @@ class VtFlowOrchestrator {
47
94
  // Renewals resend the OR with the same session id so the validator re-attaches the finished flow.
48
95
  const vtFlowApi = this.resolveVtFlowApi();
49
96
  const [latest] = (await vtFlowApi.findAllByQuery({
50
- participantId: String(holderParticipant.id),
97
+ applicantParticipantId: String(holderParticipant.id),
51
98
  role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Applicant,
52
99
  flowVariant: credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess,
53
100
  }))
54
101
  .filter(record => !(0, credo_ts_didcomm_vt_flow_1.isVtFlowTerminalState)(record.state))
55
102
  .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;
103
+ const offerReplaced = (latest === null || latest === void 0 ? void 0 : latest.state) === credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered && holderParticipant.opState === types_1.ValidationState.PENDING;
104
+ const running = latest !== undefined && !(0, credo_ts_didcomm_vt_flow_1.isVtFlowRenewable)(latest) && !offerReplaced;
61
105
  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)
106
+ if (latest) {
107
+ const connection = await this.agent.didcomm.connections.findById(latest.connectionId);
108
+ if (connection && (0, utils_1.isUsableConnectionTo)(connection, validatorParticipant.did))
65
109
  connectionId = connection.id;
66
110
  }
111
+ const undelivered = running && latest.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OrSent && holderParticipant.opState === types_1.ValidationState.PENDING;
112
+ if (running && connectionId && !undelivered) {
113
+ 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`);
114
+ return latest;
115
+ }
67
116
  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;
117
+ connectionId = await (0, utils_1.connectToPublicDid)(this.agent, validatorParticipant.did);
118
+ }
119
+ if (running) {
120
+ 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`);
121
+ return vtFlowApi.resendOnboardingRequest({ vtFlowRecordId: latest.id, connectionId });
78
122
  }
79
123
  return vtFlowApi.sendOnboardingRequest({
80
124
  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),
125
+ 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(),
126
+ applicantParticipantId: String(holderParticipant.id),
127
+ applicantParticipantRole: Number(holderParticipant.role),
128
+ validatorParticipantId: String(holderParticipant.validatorParticipantId),
129
+ schemaId: String(holderParticipant.schemaId),
83
130
  agentParticipantId: String((_c = this.options.agentParticipantId) !== null && _c !== void 0 ? _c : 0),
84
131
  walletAgentParticipantId: String((_d = this.options.walletAgentParticipantId) !== null && _d !== void 0 ? _d : 0),
85
132
  claims: input.claims,
86
133
  });
87
134
  }
88
- async validateAndOfferCredential(input) {
89
- var _a;
135
+ /**
136
+ * Validate an onboarding process: record the outcome on-chain, accept the onboarding request and
137
+ * move the record to VALIDATED. It sends no credential. Only a HOLDER takes part in a credential
138
+ * exchange; an ISSUER, a VERIFIER or a grantor joins the Ecosystem, and SetParticipantOPToValidated
139
+ * is the whole of it. The caller decides what follows, from the role of the returned participant.
140
+ *
141
+ * For a HOLDER it builds the credential before the chain write, and returns it for
142
+ * offerOnboardingCredential. Claims that do not satisfy the schema, or a schema fetch that fails,
143
+ * must stop the process while the chain holds no outcome yet and the caller can repeat the call.
144
+ *
145
+ * A record that is already VALIDATED and has no credential exchange keeps the chain outcome and
146
+ * only builds the credential again. A repeat call thus re-drives an offer that did not complete.
147
+ */
148
+ async validateOnboardingProcess(input) {
149
+ var _a, _b;
90
150
  const chain = this.requireChain();
91
151
  if (!this.agent.did)
92
152
  throw new Error('Agent has no public DID');
@@ -99,43 +159,648 @@ class VtFlowOrchestrator {
99
159
  if (record.variant !== credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess) {
100
160
  throw new Error(`Record variant is '${record.variant}', expected OnboardingProcess`);
101
161
  }
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
- });
162
+ const resumeOffer = record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.Validated && !record.credentialExchangeRecordId;
163
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr && !resumeOffer) {
164
+ throw new Error(`Record state is '${record.state}', expected '${credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr}', or ` +
165
+ `'${credo_ts_didcomm_vt_flow_1.VtFlowState.Validated}' with no credential exchange`);
166
+ }
167
+ if (!record.applicantParticipantId)
168
+ throw new Error('Record has no applicantParticipantId');
169
+ const participantId = Number(record.applicantParticipantId);
170
+ const participant = await this.agent.indexer.findParticipant(participantId);
171
+ if (!participant)
172
+ throw new Error(`Applicant participant ${participantId} not found on chain`);
173
+ if (!participant.did)
174
+ throw new Error('Applicant participant has no DID');
175
+ const credential = Number(participant.role) === types_2.HOLDER_PARTICIPANT_TYPE
176
+ ? await this.buildCredential({
177
+ credentialSchemaId: (_a = input.credentialSchemaId) !== null && _a !== void 0 ? _a : String(participant.schemaId),
178
+ subjectDid: participant.did,
179
+ claims: ((_b = record.claims) !== null && _b !== void 0 ? _b : {}),
180
+ credentialType: input.credentialType,
181
+ credentialContext: input.credentialContext,
182
+ })
183
+ : undefined;
184
+ if (resumeOffer)
185
+ return { record, participant, credential };
120
186
  // 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
- });
187
+ await chain.setParticipantOPToValidated({ id: participantId, corporation: participant.corporation });
125
188
  await vtFlowApi.acceptOnboardingRequest(record.id);
126
- await vtFlowApi.markValidated(record.id);
189
+ const validated = await vtFlowApi.markValidated(record.id);
190
+ return { record: validated, participant, credential };
191
+ }
192
+ /**
193
+ * Offer the credential of an onboarding process to its applicant. Call it only for a HOLDER, and
194
+ * only after validateOnboardingProcess has moved the record to VALIDATED. Give it the credential
195
+ * that validateOnboardingProcess built, so that the process does not build the credential twice.
196
+ */
197
+ async offerOnboardingCredential(input) {
198
+ var _a, _b, _c, _d, _e;
199
+ this.requireChain();
200
+ const vtFlowApi = this.resolveVtFlowApi();
201
+ const record = await vtFlowApi.findById(input.vtFlowRecordId);
202
+ if (!record)
203
+ throw new Error(`vt-flow record ${input.vtFlowRecordId} not found`);
204
+ if (!record.applicantParticipantId)
205
+ throw new Error('Record has no applicantParticipantId');
206
+ const participant = (_a = input.participant) !== null && _a !== void 0 ? _a : (await this.agent.indexer.findParticipant(Number(record.applicantParticipantId)));
207
+ if (!(participant === null || participant === void 0 ? void 0 : participant.did))
208
+ throw new Error('Applicant participant has no DID');
209
+ const unsignedCredentialJson = (_b = input.credential) !== null && _b !== void 0 ? _b : (await this.buildCredential({
210
+ credentialSchemaId: (_c = input.credentialSchemaId) !== null && _c !== void 0 ? _c : String(participant.schemaId),
211
+ subjectDid: participant.did,
212
+ claims: ((_d = record.claims) !== null && _d !== void 0 ? _d : {}),
213
+ credentialType: input.credentialType,
214
+ credentialContext: input.credentialContext,
215
+ // [VSA-VTI-FLOW-FMT-1]: markValidated sets it from the entry on every pass, a renewal included
216
+ validUntil: (_e = record.validation) === null || _e === void 0 ? void 0 : _e.effectiveUntil,
217
+ }));
218
+ // W3C Data Integrity attachment format (RFC 0809). The applicant DID is the credential subject
219
+ // and the exchange runs over its authenticated connection, so no extra binding is required. The
220
+ // cryptosuite is the issuer's choice and is applied when the credential is issued.
127
221
  const { record: offered } = await vtFlowApi.offerCredentialForSession({
128
222
  vtFlowRecordId: record.id,
129
- issuerParticipantId: Number(holderParticipant.validatorParticipantId),
223
+ issuerParticipantId: Number(participant.validatorParticipantId),
130
224
  credentialFormats: {
131
- jsonld: {
132
- credential: unsignedCredentialJson,
133
- options: { proofType: 'Ed25519Signature2020', proofPurpose: 'assertionMethod' },
134
- },
225
+ dataIntegrity: { credential: unsignedCredentialJson, bindingRequired: false },
135
226
  },
136
227
  });
137
228
  return offered;
138
229
  }
230
+ /**
231
+ * Close an onboarding process that carries no credential exchange, on the validator side. The
232
+ * applicant reaches the same state from the SetParticipantOPToValidated chain event.
233
+ */
234
+ async completeOnboardingProcess(vtFlowRecordId) {
235
+ return this.resolveVtFlowApi().markCompleted(vtFlowRecordId);
236
+ }
237
+ /** [VSA-ADM-VT-FL-VALIDATE] */
238
+ async validateFlow(input) {
239
+ return this.oneAtATime(input.vtFlowRecordId, () => this.validateFlowOnce(input), validatingFlows);
240
+ }
241
+ async validateFlowOnce(input) {
242
+ var _a, _b;
243
+ this.requireChain();
244
+ const vtFlowApi = this.resolveVtFlowApi();
245
+ const record = await vtFlowApi.findById(input.vtFlowRecordId);
246
+ if (!record) {
247
+ throw new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.UnknownId, 404, `no flow with id "${input.vtFlowRecordId}"`);
248
+ }
249
+ if (record.role !== credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator)
250
+ throw invalidState('validate is a validator action');
251
+ 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;
252
+ if (reissue && record.credentialExchangeRecordId) {
253
+ const { record: issued } = await vtFlowApi.issueCredentialForSession({
254
+ vtFlowRecordId: record.id,
255
+ credentialExchangeRecordId: record.credentialExchangeRecordId,
256
+ });
257
+ return issued;
258
+ }
259
+ if (record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.DirectIssuance)
260
+ return this.validateDirectIssuance(record);
261
+ if (!record.applicantParticipantId)
262
+ throw invalidState('the flow names no applicant participant');
263
+ const applicant = await this.agent.indexer.getParticipant(record.applicantParticipantId);
264
+ const entryValidated = applicant.op_state === 'VALIDATED';
265
+ const rejectedInFlight = entryValidated && (await this.isRejectedInFlight(record));
266
+ if (!rejectedInFlight) {
267
+ this.assertValidateState(record, entryValidated);
268
+ if (record.connectionTerminated)
269
+ throw invalidState('the flow connection is TERMINATED until the applicant reconnects');
270
+ }
271
+ const terms = this.validationTerms(input, applicant, record);
272
+ await this.assertClaimsAndTerm(record, applicant, terms);
273
+ // [VSA-VTI-FLOW-OP-ISSUE-6]: the connection stays TERMINATED, so issuance waits for the applicant to reconnect
274
+ if (rejectedInFlight)
275
+ return this.markValidated(record.id, applicant);
276
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending)
277
+ await this.sendValidating(record);
278
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims)
279
+ return this.continueAfterValidated(record.id);
280
+ if (entryValidated) {
281
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validated)
282
+ await this.markValidated(record.id, applicant);
283
+ return this.continueAfterValidated(record.id);
284
+ }
285
+ const validation = Object.assign({ decidedAt: new Date().toISOString(), submission: await this.submissionPath(applicant) }, terms);
286
+ if (validation.submission === credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator) {
287
+ return vtFlowApi.recordValidation(record.id, validation, credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingValidationTx);
288
+ }
289
+ return this.submitValidation(record.id, applicant, validation);
290
+ }
291
+ // A Direct Issuance flow has no entry to validate, so no transaction: check the claims, then offer.
292
+ async validateDirectIssuance(record) {
293
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validating && record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending) {
294
+ throw invalidState(`the flow is '${record.state}', which validate does not accept`);
295
+ }
296
+ if (!record.schemaId)
297
+ throw invalidState('the flow names no credential schema');
298
+ const connection = await this.agent.didcomm.connections.findById(record.connectionId);
299
+ if (!(connection === null || connection === void 0 ? void 0 : connection.theirDid))
300
+ throw invalidState('the flow connection has no peer DID');
301
+ const schema = await this.agent.indexer.getCredentialSchema(record.schemaId);
302
+ this.assertClaims(schema.json_schema, connection.theirDid, record.claims);
303
+ // built before validating is sent, so a flow that cannot be offered tells the applicant nothing
304
+ const offer = await this.buildDirectIssuanceOffer(record.id, schema);
305
+ if (!offer) {
306
+ throw invalidState('the schema of the flow is not open to Direct Issuance, or the agent holds no active ISSUER participant for it');
307
+ }
308
+ const vtFlowApi = this.resolveVtFlowApi();
309
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending)
310
+ await this.sendValidating(record);
311
+ const { record: offered } = await vtFlowApi.offerCredentialForSession(Object.assign({ vtFlowRecordId: record.id }, offer));
312
+ return offered;
313
+ }
314
+ // [VSA-ADM-VT-FL-START]: checked before the flow moves, as a failed send would leave it in VALIDATING
315
+ async sendValidating(record) {
316
+ const connection = await this.agent.didcomm.connections.findById(record.connectionId);
317
+ if (!(connection === null || connection === void 0 ? void 0 : connection.isReady))
318
+ throw invalidState('the flow connection is not ESTABLISHED');
319
+ await this.resolveVtFlowApi().sendValidating(record.id);
320
+ }
321
+ assertClaims(jsonSchema, subjectDid, claims) {
322
+ const violations = (0, utils_1.schemaViolations)(JSON.parse(jsonSchema), Object.assign({ id: subjectDid }, (claims !== null && claims !== void 0 ? claims : {})));
323
+ if (violations.length > 0) {
324
+ throw new adminApi_1.AdminApiError(adminApi_1.AdminApiErrorCode.InvalidClaims, 422, 'the claim set does not satisfy the json_schema', { violations });
325
+ }
326
+ }
327
+ assertValidateState(record, entryValidated) {
328
+ const accepted = [
329
+ credo_ts_didcomm_vt_flow_1.VtFlowState.Validating,
330
+ credo_ts_didcomm_vt_flow_1.VtFlowState.OobPending,
331
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed,
332
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims,
333
+ ];
334
+ // Once the entry is VALIDATED on chain any validator-side state resumes into issuance, which is
335
+ // how a backend that disabled the default notification handler drives the flow ([VSA-ADM-VT-FL-VALIDATE-11]).
336
+ const acceptedOnceValidated = [
337
+ credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr,
338
+ credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingValidationTx,
339
+ credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted,
340
+ credo_ts_didcomm_vt_flow_1.VtFlowState.Validated,
341
+ ];
342
+ if (accepted.includes(record.state))
343
+ return;
344
+ if (entryValidated && acceptedOnceValidated.includes(record.state))
345
+ return;
346
+ throw invalidState(`the flow is '${record.state}', which validate does not accept`);
347
+ }
348
+ validationTerms(input, applicant, record) {
349
+ var _a, _b, _c, _d, _e, _f, _g, _h;
350
+ for (const key of FEE_KEYS) {
351
+ const fee = input[key];
352
+ if (fee !== undefined && !(Number.isInteger(fee) && fee >= 0)) {
353
+ throw invalidInput(`${key} must be a non-negative integer`);
354
+ }
355
+ }
356
+ for (const key of DISCOUNT_KEYS) {
357
+ const discount = input[key];
358
+ if (discount !== undefined && !(discount >= 0 && discount <= 1)) {
359
+ throw invalidInput(`${key} must be between 0 and 1`);
360
+ }
361
+ }
362
+ if (input.effectiveUntil !== undefined && Number.isNaN(Date.parse(input.effectiveUntil))) {
363
+ throw invalidInput('effectiveUntil must be an ISO 8601 datetime');
364
+ }
365
+ const onEntry = {
366
+ validationFees: (_a = applicant.validation_fees) !== null && _a !== void 0 ? _a : 0,
367
+ issuanceFees: (_b = applicant.issuance_fees) !== null && _b !== void 0 ? _b : 0,
368
+ verificationFees: (_c = applicant.verification_fees) !== null && _c !== void 0 ? _c : 0,
369
+ issuanceFeeDiscount: (_d = applicant.issuance_fee_discount) !== null && _d !== void 0 ? _d : 0,
370
+ verificationFeeDiscount: (_e = applicant.verification_fee_discount) !== null && _e !== void 0 ? _e : 0,
371
+ };
372
+ const renewal = !!applicant.effective_from;
373
+ const recorded = record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed ? record.validation : undefined;
374
+ const terms = {
375
+ effectiveUntil: (_f = input.effectiveUntil) !== null && _f !== void 0 ? _f : recorded === null || recorded === void 0 ? void 0 : recorded.effectiveUntil,
376
+ opSummaryDigest: (_g = input.opSummaryDigest) !== null && _g !== void 0 ? _g : recorded === null || recorded === void 0 ? void 0 : recorded.opSummaryDigest,
377
+ };
378
+ for (const key of [...FEE_KEYS, ...DISCOUNT_KEYS]) {
379
+ const given = input[key];
380
+ if (renewal) {
381
+ if (given !== undefined && !sameTerm(key, given, onEntry[key])) {
382
+ throw invalidInput(`${key} differs from the entry, and a renewal keeps the agreed value`);
383
+ }
384
+ terms[key] = onEntry[key];
385
+ }
386
+ else {
387
+ terms[key] = (_h = given !== null && given !== void 0 ? given : recorded === null || recorded === void 0 ? void 0 : recorded[key]) !== null && _h !== void 0 ? _h : 0;
388
+ }
389
+ }
390
+ return terms;
391
+ }
392
+ async assertClaimsAndTerm(record, applicant, terms) {
393
+ var _a;
394
+ if (applicant.role !== types_1.ParticipantRole.Holder)
395
+ return;
396
+ if (!applicant.did)
397
+ throw invalidState('the applicant entry has no DID to issue to');
398
+ const schema = await this.agent.indexer.getCredentialSchema(applicant.schema_id);
399
+ this.assertClaims(schema.json_schema, applicant.did, record.claims);
400
+ // [VSA-ADM-VT-FL-VALIDATE-2]: a schema that requires validUntil needs an effective_until. With
401
+ // a validity period of 0 the VPR sets none, so the call has to carry one.
402
+ const needsValidUntil = (0, vs_agent_model_1.schemaRequiresValidUntil)(schema.json_schema);
403
+ if (needsValidUntil && ((_a = schema.holder_validation_validity_period) !== null && _a !== void 0 ? _a : 0) === 0 && !terms.effectiveUntil) {
404
+ throw invalidInput('this schema has no validity period, so effectiveUntil is required');
405
+ }
406
+ }
407
+ async submissionPath(applicant) {
408
+ const authorization = this.agent.authorizationService;
409
+ if (!authorization || applicant.validator_participant_id == null)
410
+ return credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
411
+ const validator = await this.agent.indexer
412
+ .getParticipant(applicant.validator_participant_id)
413
+ .catch(() => undefined);
414
+ if (!validator)
415
+ return credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
416
+ await authorization.refreshForOperator().catch(() => undefined);
417
+ return authorization.canSign(validator, verana_types_1.veranaTypeUrls.MsgSetParticipantOPToValidated)
418
+ ? credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Agent
419
+ : credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Operator;
420
+ }
421
+ async submitValidation(recordId, applicant, validation) {
422
+ var _a, _b;
423
+ const chain = this.requireChain();
424
+ const vtFlowApi = this.resolveVtFlowApi();
425
+ 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);
426
+ const message = chain.setParticipantOPToValidatedMsg({
427
+ id: applicant.id,
428
+ effectiveUntil: validation.effectiveUntil ? new Date(validation.effectiveUntil) : undefined,
429
+ validationFees: validation.validationFees,
430
+ issuanceFees: validation.issuanceFees,
431
+ verificationFees: validation.verificationFees,
432
+ issuanceFeeDiscount: Math.round(((_a = validation.issuanceFeeDiscount) !== null && _a !== void 0 ? _a : 0) * DISCOUNT_SCALE),
433
+ verificationFeeDiscount: Math.round(((_b = validation.verificationFeeDiscount) !== null && _b !== void 0 ? _b : 0) * DISCOUNT_SCALE),
434
+ opSummaryDigest: validation.opSummaryDigest,
435
+ });
436
+ const checked = await this.preflight(message, applicant.validator_participant_id);
437
+ if ('reason' in checked)
438
+ return fail(checked.reason, checked.error);
439
+ let hash;
440
+ try {
441
+ hash = await chain.broadcastWithoutWaiting([message], checked.fee);
442
+ }
443
+ catch (error) {
444
+ return fail(credo_ts_didcomm_vt_flow_1.VtFlowTxReason.BroadcastError, errorMessage(error));
445
+ }
446
+ 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);
447
+ void this.resolveValidationTx(recordId).catch(error => this.agent.config.logger.error(`[vt-flow] resolving the validation of ${recordId} failed`, {
448
+ error: errorMessage(error),
449
+ }));
450
+ return submitted;
451
+ }
452
+ // [VSA-ADM-VT-FL-VALIDATE-6]: the fee payer is the Corporation when the grant of the entry has with_feegrant
453
+ preflight(message, participantId) {
454
+ return (0, feePreflight_1.preflightFee)(this.requireChain(), message, (0, feePreflight_1.feeGranterFor)(this.agent, participantId));
455
+ }
456
+ // [VSA-VTI-FLOW-ISSUE-1]: [VSA-ADM-VT-FL-VALIDATE-6] to -9 applied to the anchoring, which the delivery waits for.
457
+ // A transaction left SUBMITTED by a restart is looked up again, not broadcast twice.
458
+ async anchor(record, message, issuerParticipantId) {
459
+ var _a, _b, _c;
460
+ const chain = this.requireChain();
461
+ 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;
462
+ let hash = pending === null || pending === void 0 ? void 0 : pending.hash;
463
+ let submittedAt = (_c = pending === null || pending === void 0 ? void 0 : pending.submittedAt) !== null && _c !== void 0 ? _c : new Date().toISOString();
464
+ if (!hash) {
465
+ const checked = await this.preflight(message, issuerParticipantId);
466
+ if ('reason' in checked)
467
+ return Object.assign({ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed }, checked);
468
+ try {
469
+ hash = await chain.broadcastWithoutWaiting([message], checked.fee);
470
+ }
471
+ catch (error) {
472
+ return {
473
+ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed,
474
+ reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.BroadcastError,
475
+ error: errorMessage(error),
476
+ };
477
+ }
478
+ submittedAt = new Date().toISOString();
479
+ await this.resolveVtFlowApi().recordIssuance(record.id, {
480
+ tx: { hash, submittedAt, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted },
481
+ });
482
+ }
483
+ for (;;) {
484
+ const tx = await chain.findTx(hash).catch(() => undefined);
485
+ if ((tx === null || tx === void 0 ? void 0 : tx.code) === 0)
486
+ return { hash, submittedAt, height: tx.height, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded };
487
+ if (tx) {
488
+ const failure = { status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed, error: tx.rawLog };
489
+ return Object.assign({ hash, submittedAt, height: tx.height }, failure);
490
+ }
491
+ if (Date.now() - Date.parse(submittedAt) >= TX_LOOKUP_TIMEOUT_MS) {
492
+ const error = 'not found 60 seconds after the broadcast';
493
+ return { hash, submittedAt, status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed, reason: credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxNotFound, error };
494
+ }
495
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
496
+ }
497
+ }
498
+ // [VSA-ADM-VT-FL-VALIDATE-8]. Leaving VALIDATION_TX_SUBMITTED ends the loop, so the notification
499
+ // handler moving the flow first wins the race.
500
+ async resolveValidationTx(recordId) {
501
+ var _a, _b, _c;
502
+ const chain = this.requireChain();
503
+ const vtFlowApi = this.resolveVtFlowApi();
504
+ let landed;
505
+ for (;;) {
506
+ const record = await vtFlowApi.findById(recordId);
507
+ const validation = record === null || record === void 0 ? void 0 : record.validation;
508
+ const hash = (_a = validation === null || validation === void 0 ? void 0 : validation.tx) === null || _a === void 0 ? void 0 : _a.hash;
509
+ if (!(record === null || record === void 0 ? void 0 : record.applicantParticipantId) || !validation || !hash)
510
+ return;
511
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted)
512
+ return;
513
+ const tx = landed !== null && landed !== void 0 ? landed : (await chain.findTx(hash).catch(() => undefined));
514
+ if (tx && tx.code === 0) {
515
+ landed = tx;
516
+ // the indexer can lag the block of the transaction, and the fill needs the validated entry
517
+ const entry = await this.agent.indexer.getParticipant(record.applicantParticipantId);
518
+ if (entry.op_state === 'VALIDATED') {
519
+ await this.markValidated(recordId, entry, { hash, height: tx.height });
520
+ await this.continueAfterValidated(recordId);
521
+ return;
522
+ }
523
+ }
524
+ else if (tx) {
525
+ return this.failUnlessValidated(record, validation, credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed, tx.rawLog, tx.height);
526
+ }
527
+ const submittedAt = (_c = (_b = validation.tx) === null || _b === void 0 ? void 0 : _b.submittedAt) !== null && _c !== void 0 ? _c : validation.decidedAt;
528
+ if (Date.now() - Date.parse(submittedAt) >= TX_LOOKUP_TIMEOUT_MS) {
529
+ if (tx) {
530
+ 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`);
531
+ return;
532
+ }
533
+ return this.failUnlessValidated(record, validation, credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxNotFound, 'not found 60 seconds after the broadcast');
534
+ }
535
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
536
+ }
537
+ }
538
+ // The VPR has no distinct error for a second SetParticipantOPtoValidated, so the entry tells a
539
+ // rejected duplicate apart from a real failure.
540
+ async failUnlessValidated(record, validation, reason, error, height) {
541
+ var _a;
542
+ const vtFlowApi = this.resolveVtFlowApi();
543
+ const applicant = record.applicantParticipantId
544
+ ? await this.agent.indexer.getParticipant(record.applicantParticipantId)
545
+ : undefined;
546
+ 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 }) });
547
+ if ((applicant === null || applicant === void 0 ? void 0 : applicant.op_state) === 'VALIDATED') {
548
+ // the notification handler may have moved the flow while the tx and the entry were read
549
+ if (((_a = (await vtFlowApi.findById(record.id))) === null || _a === void 0 ? void 0 : _a.state) !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted)
550
+ return;
551
+ if (reason === credo_ts_didcomm_vt_flow_1.VtFlowTxReason.TxFailed)
552
+ await vtFlowApi.recordValidation(record.id, failed);
553
+ await this.markValidated(record.id, applicant);
554
+ await this.continueAfterValidated(record.id);
555
+ return;
556
+ }
557
+ await vtFlowApi.recordValidation(record.id, failed, credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed);
558
+ }
559
+ /**
560
+ * [VSA-VTI-FLOW-OP-ISSUE]: moves the flow to VALIDATED and fills `validation` from the validated
561
+ * entry. Without the landed transaction, a recorded broadcast keeps its tx, and its submission
562
+ * unless that tx failed.
563
+ */
564
+ async markValidated(recordId, entry, landed) {
565
+ var _a, _b, _c, _d, _e;
566
+ const vtFlowApi = this.resolveVtFlowApi();
567
+ if (markingValidated.has(recordId))
568
+ throw invalidState('the flow is already moving to VALIDATED');
569
+ markingValidated.add(recordId);
570
+ try {
571
+ const record = await vtFlowApi.findById(recordId);
572
+ if (!record)
573
+ throw new Error(`vt-flow record ${recordId} not found`);
574
+ if (!credo_ts_didcomm_vt_flow_1.VtFlowValidatedFromStates.has(record.state) &&
575
+ record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.TerminatedByValidator) {
576
+ throw invalidState(`the flow is '${record.state}', which does not precede VALIDATED`);
577
+ }
578
+ const recorded = record.validation;
579
+ 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;
580
+ 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
581
+ ? recorded.submission
582
+ : agentTx
583
+ ? credo_ts_didcomm_vt_flow_1.VtFlowSubmission.Agent
584
+ : 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 && {
585
+ tx: {
586
+ hash: agentTx.hash,
587
+ submittedAt: agentTx.submittedAt,
588
+ height: landed === null || landed === void 0 ? void 0 : landed.height,
589
+ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded,
590
+ },
591
+ }));
592
+ return await vtFlowApi.recordValidation(recordId, validation, credo_ts_didcomm_vt_flow_1.VtFlowState.Validated);
593
+ }
594
+ finally {
595
+ markingValidated.delete(recordId);
596
+ }
597
+ }
598
+ /** rejectFlow ended the flow with its transaction in flight, and no newer flow of the applicant replaced it ([VSA-ADM-VT-FL-REJECT-2]). */
599
+ async isRejectedInFlight(record) {
600
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.TerminatedByValidator || !record.validation)
601
+ return false;
602
+ if (!record.applicantParticipantId)
603
+ return false;
604
+ const [latest] = (await this.resolveVtFlowApi().findAllByQuery({
605
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
606
+ applicantParticipantId: record.applicantParticipantId,
607
+ })).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
608
+ return (latest === null || latest === void 0 ? void 0 : latest.id) === record.id;
609
+ }
610
+ // one run at a time per flow: two callers at once would both read VALIDATED and offer twice
611
+ async continueAfterValidated(recordId) {
612
+ return this.oneAtATime(recordId, () => this.issuanceAfterValidated(recordId));
613
+ }
614
+ async oneAtATime(recordId, task, runs = continuingAfterValidated) {
615
+ var _a;
616
+ const previous = (_a = runs.get(recordId)) !== null && _a !== void 0 ? _a : Promise.resolve();
617
+ const run = previous.then(task);
618
+ const settled = run.then(() => undefined, () => undefined);
619
+ runs.set(recordId, settled);
620
+ try {
621
+ return await run;
622
+ }
623
+ finally {
624
+ if (runs.get(recordId) === settled)
625
+ runs.delete(recordId);
626
+ }
627
+ }
628
+ async issuanceAfterValidated(recordId) {
629
+ var _a;
630
+ const vtFlowApi = this.resolveVtFlowApi();
631
+ const record = await vtFlowApi.findById(recordId);
632
+ if (!record)
633
+ throw new Error(`vt-flow record ${recordId} not found`);
634
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.Validated && record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.ValidatedPendingClaims) {
635
+ return record;
636
+ }
637
+ const participant = await this.agent.indexer.findParticipant(Number(record.applicantParticipantId));
638
+ if (!participant)
639
+ throw new Error(`Applicant participant ${record.applicantParticipantId} not found`);
640
+ if (Number(participant.role) !== types_2.HOLDER_PARTICIPANT_TYPE)
641
+ return record;
642
+ const schema = await this.agent.indexer.getCredentialSchema(participant.schemaId);
643
+ const violations = (0, utils_1.schemaViolations)(JSON.parse(schema.json_schema), Object.assign({ id: participant.did }, ((_a = record.claims) !== null && _a !== void 0 ? _a : {})));
644
+ if (violations.length > 0) {
645
+ this.agent.config.logger.error(`[vt-flow] not offering the credential of flow ${recordId}: its claims do not satisfy the ` +
646
+ `json_schema of schema ${participant.schemaId}: ${violations.map(v => `${v.path} ${v.message}`.trim()).join(', ')}`);
647
+ return record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.Validated ? vtFlowApi.markPendingClaims(recordId) : record;
648
+ }
649
+ return this.offerOnboardingCredential({ vtFlowRecordId: recordId, participant });
650
+ }
651
+ /** [VSA-ADM-VT-FL-VALIDATE-8]: at startup, resume every flow left in VALIDATION_TX_SUBMITTED. */
652
+ async resumeValidationSubmissions() {
653
+ const pending = await this.resolveVtFlowApi().findAllByQuery({
654
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
655
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted,
656
+ });
657
+ await Promise.all(pending.map(record => this.resolveValidationTx(record.id)));
658
+ }
659
+ /** [VSA-VTI-FLOW-ISSUE-1]: at startup, resume through the stored issued credential every anchoring left SUBMITTED. */
660
+ async resumeIssuanceSubmissions() {
661
+ const vtFlowApi = this.resolveVtFlowApi();
662
+ const offered = await vtFlowApi.findAllByQuery({
663
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
664
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered,
665
+ });
666
+ await Promise.all(offered.map(({ id, issuance, credentialExchangeRecordId }) => {
667
+ var _a;
668
+ 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
669
+ ? vtFlowApi.issueCredentialForSession({ vtFlowRecordId: id, credentialExchangeRecordId })
670
+ : undefined;
671
+ }));
672
+ }
673
+ async resumeIssuance(recordId, reoffer = true) {
674
+ return this.oneAtATime(recordId, () => this.resumeIssuanceRun(recordId, reoffer));
675
+ }
676
+ async resumeIssuanceRun(recordId, reoffer) {
677
+ var _a, _b, _c;
678
+ const vtFlowApi = this.resolveVtFlowApi();
679
+ const record = await vtFlowApi.findById(recordId);
680
+ if (!record || record.role !== credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator)
681
+ return record;
682
+ if (record.state === credo_ts_didcomm_vt_flow_1.VtFlowState.Validated)
683
+ return this.issuanceAfterValidated(record.id);
684
+ if (record.state !== credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered)
685
+ return record;
686
+ const tx = (_a = record.issuance) === null || _a === void 0 ? void 0 : _a.tx;
687
+ const sent = (0, credo_ts_didcomm_vt_flow_1.isVtFlowTxSent)(tx);
688
+ if (sent && (tx === null || tx === void 0 ? void 0 : tx.status) !== credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded)
689
+ return record;
690
+ const exchange = record.credentialExchangeRecordId
691
+ ? await this.agent.didcomm.credentials.findById(record.credentialExchangeRecordId)
692
+ : null;
693
+ // Credo cannot continue a run whose messages used an earlier connection.
694
+ const elsewhere = !!exchange && exchange.connectionId !== record.connectionId;
695
+ if (!elsewhere &&
696
+ ((exchange === null || exchange === void 0 ? void 0 : exchange.state) === didcomm_1.DidCommCredentialState.RequestReceived ||
697
+ (exchange === null || exchange === void 0 ? void 0 : exchange.state) === didcomm_1.DidCommCredentialState.CredentialIssued)) {
698
+ return (await vtFlowApi.issueCredentialForSession({
699
+ vtFlowRecordId: record.id,
700
+ credentialExchangeRecordId: exchange.id,
701
+ })).record;
702
+ }
703
+ const anchored = (tx === null || tx === void 0 ? void 0 : tx.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded &&
704
+ !!exchange &&
705
+ (elsewhere || (reoffer && exchange.state === didcomm_1.DidCommCredentialState.OfferSent));
706
+ if (!anchored &&
707
+ (sent || (exchange && !elsewhere && (!reoffer || exchange.state !== didcomm_1.DidCommCredentialState.OfferSent))))
708
+ return record;
709
+ // [VSA-VTI-FLOW-ISSUE-3]: the new run signs the same credential again, so its digest is the anchored one.
710
+ const offered = anchored
711
+ ? (_c = (_b = (await this.agent.didcomm.credentials.getFormatData(exchange.id)).offer) === null || _b === void 0 ? void 0 : _b.dataIntegrity) === null || _c === void 0 ? void 0 : _c.credential
712
+ : undefined;
713
+ if (anchored && !offered)
714
+ throw new Error(`the anchored run of flow ${record.id} has no offered credential`);
715
+ await vtFlowApi.abandonIssuanceRun(record.id);
716
+ if (offered) {
717
+ const { record: reoffered } = await vtFlowApi.offerCredentialForSession({
718
+ vtFlowRecordId: record.id,
719
+ issuerParticipantId: record.issuerParticipantId,
720
+ credentialFormats: { dataIntegrity: { credential: offered, bindingRequired: false } },
721
+ });
722
+ return reoffered;
723
+ }
724
+ if (record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.DirectIssuance) {
725
+ const offer = await this.buildDirectIssuanceOffer(record.id);
726
+ if (!offer)
727
+ return vtFlowApi.findById(record.id);
728
+ return (await vtFlowApi.offerCredentialForSession(Object.assign({ vtFlowRecordId: record.id }, offer))).record;
729
+ }
730
+ return this.offerOnboardingCredential({ vtFlowRecordId: record.id });
731
+ }
732
+ async resumeIssuanceRuns() {
733
+ const vtFlowApi = this.resolveVtFlowApi();
734
+ const offered = await vtFlowApi.findAllByQuery({
735
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
736
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered,
737
+ });
738
+ const validated = await vtFlowApi.findAllByQuery({
739
+ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator,
740
+ flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.Validated,
741
+ });
742
+ const resumable = [
743
+ ...offered.filter(record => { var _a; return !((_a = record.issuance) === null || _a === void 0 ? void 0 : _a.tx); }),
744
+ ...validated.filter(record => record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess &&
745
+ !record.credentialExchangeRecordId &&
746
+ !record.connectionTerminated &&
747
+ (record.applicantParticipantRole === undefined ||
748
+ record.applicantParticipantRole === types_2.HOLDER_PARTICIPANT_TYPE)),
749
+ ];
750
+ for (const record of resumable) {
751
+ try {
752
+ const connection = await this.agent.didcomm.connections.findById(record.connectionId);
753
+ // A slow holder can still answer an old Direct Issuance offer.
754
+ const reoffer = record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.OnboardingProcess;
755
+ if (connection === null || connection === void 0 ? void 0 : connection.isReady)
756
+ await this.resumeIssuance(record.id, reoffer);
757
+ }
758
+ catch (error) {
759
+ this.agent.config.logger.warn(`[vt-flow] could not resume the issuance of flow ${record.id}: ${errorMessage(error)}`);
760
+ }
761
+ }
762
+ }
763
+ /**
764
+ * [VSA-ADM-VT-FL-VALIDATE-12], [VSA-VTI-FLOW-ISSUE-3]: repeat validateFlow for each anchoring and
765
+ * validation that failed in the pre-flight. The first run repeats each of them one time. A later run
766
+ * repeats only SERVICE_UNAVAILABLE. A run stops after a validation it broadcasts, as its inclusion
767
+ * is not awaited and a second signature would reuse the account sequence. The flows that the first
768
+ * run did not reach stay for the subsequent runs.
769
+ */
770
+ async resumeFailedSubmissions() {
771
+ const vtFlowApi = this.resolveVtFlowApi();
772
+ const [offered, failedValidations] = await Promise.all([
773
+ vtFlowApi.findAllByQuery({ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator, flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.CredOffered }),
774
+ vtFlowApi.findAllByQuery({ role: credo_ts_didcomm_vt_flow_1.VtFlowRole.Validator, flowState: credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxFailed }),
775
+ ]);
776
+ const failed = [
777
+ ...offered.filter(record => record.credentialExchangeRecordId),
778
+ ...failedValidations.filter(record => !record.connectionTerminated),
779
+ ].filter(record => failedInPreflight(flowTx(record)));
780
+ const failedIds = new Set(failed.map(record => record.id));
781
+ if (!this.startupRepeats)
782
+ this.startupRepeats = failedIds;
783
+ for (const id of this.startupRepeats)
784
+ if (!failedIds.has(id))
785
+ this.startupRepeats.delete(id);
786
+ for (const record of failed) {
787
+ if (!this.startupRepeats.has(record.id) && !repeatsOnInterval(flowTx(record)))
788
+ continue;
789
+ if (validatingFlows.has(record.id))
790
+ continue;
791
+ this.startupRepeats.delete(record.id);
792
+ const warn = (details) => this.agent.config.logger.warn(`[vt-flow] retrying the transaction of flow ${record.id} failed`, details);
793
+ const retried = await this.validateFlow({ vtFlowRecordId: record.id }).catch(error => {
794
+ warn({ error: errorMessage(error) });
795
+ return undefined;
796
+ });
797
+ const tx = retried && flowTx(retried);
798
+ if ((tx === null || tx === void 0 ? void 0 : tx.status) === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed)
799
+ warn({ reason: tx.reason, error: tx.error });
800
+ if ((retried === null || retried === void 0 ? void 0 : retried.state) === credo_ts_didcomm_vt_flow_1.VtFlowState.ValidationTxSubmitted)
801
+ return;
802
+ }
803
+ }
139
804
  async acceptCredential(input) {
140
805
  const vtFlowApi = this.resolveVtFlowApi();
141
806
  const record = await vtFlowApi.findById(input.vtFlowRecordId);
@@ -149,12 +814,9 @@ class VtFlowOrchestrator {
149
814
  await this.verifyOfferedCredential(input.vtFlowRecordId);
150
815
  return vtFlowApi.acceptReceivedCredential(input.vtFlowRecordId);
151
816
  }
152
- async buildDirectIssuanceOffer(vtFlowRecordId) {
817
+ /** `schema` saves the indexer reads when the caller already fetched the schema of the flow. */
818
+ async buildDirectIssuanceOffer(vtFlowRecordId, schema) {
153
819
  var _a;
154
- const chain = this.requireChain();
155
- if (!this.agent.did)
156
- throw new Error('Agent has no public DID');
157
- const indexer = this.requireIndexer();
158
820
  const vtFlowApi = this.resolveVtFlowApi();
159
821
  const record = await vtFlowApi.findById(vtFlowRecordId);
160
822
  if (!record)
@@ -164,17 +826,11 @@ class VtFlowOrchestrator {
164
826
  }
165
827
  if (!record.schemaId)
166
828
  throw new Error('Record has no schemaId');
167
- const issuers = await indexer.listParticipants({
168
- did: this.agent.did,
169
- schemaId: Number(record.schemaId),
170
- role: types_1.ParticipantRole.Issuer,
171
- participantState: types_1.ParticipantState.Active,
172
- });
173
- const issuer = issuers.find(p => !p.revoked && !p.slashed && p.vs_operator === chain.address);
174
- if (!issuer) {
175
- this.agent.config.logger.warn(`[vt-flow] no active issuer participant with vs_operator ${chain.address} for schema ${record.schemaId}; not offering`);
829
+ const fetched = schema && String(schema.id) === record.schemaId ? schema : undefined;
830
+ // checked here too: checkSchemaId is optional, and the chain can change after the request was accepted
831
+ const issuer = await this.directIssuanceIssuer(record.schemaId, fetched);
832
+ if (!issuer)
176
833
  return null;
177
- }
178
834
  const connection = await this.agent.didcomm.connections.findById(record.connectionId);
179
835
  if (!(connection === null || connection === void 0 ? void 0 : connection.theirDid))
180
836
  throw new Error('Flow connection has no peer DID');
@@ -182,58 +838,91 @@ class VtFlowOrchestrator {
182
838
  credentialSchemaId: String(record.schemaId),
183
839
  subjectDid: connection.theirDid,
184
840
  claims: ((_a = record.claims) !== null && _a !== void 0 ? _a : {}),
841
+ schema: fetched,
185
842
  });
186
843
  return {
187
844
  credentialFormats: {
188
- jsonld: {
189
- credential: unsignedCredentialJson,
190
- options: { proofType: 'Ed25519Signature2020', proofPurpose: 'assertionMethod' },
191
- },
845
+ dataIntegrity: { credential: unsignedCredentialJson, bindingRequired: false },
192
846
  },
193
847
  issuerParticipantId: issuer.id,
194
848
  };
195
849
  }
196
- async buildCredential(input) {
197
- var _a, _b, _c;
850
+ /**
851
+ * The ISSUER entry under which this agent issues the schema by Direct Issuance, if any.
852
+ * [VSA-VTI-FLOW-DI]: Direct Issuance is only for a schema with holder_onboarding_mode =
853
+ * PERMISSIONLESS, and the ECS schemas use ISSUER_ONBOARDING_PROCESS. The chain accepts the
854
+ * anchoring CreateOrUpdateParticipantSession only from the vs_operator of the entry.
855
+ */
856
+ async directIssuanceIssuer(schemaId, fetched) {
857
+ var _a;
198
858
  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;
859
+ if (!this.agent.did)
860
+ throw new Error('Agent has no public DID');
861
+ const logger = this.agent.config.logger;
862
+ const id = /^[1-9]\d*$/.test(schemaId) ? Number(schemaId) : Number.NaN;
863
+ if (!Number.isSafeInteger(id)) {
864
+ logger.warn(`[vt-flow] ${JSON.stringify(schemaId)} is not a credential schema id`);
865
+ return undefined;
866
+ }
867
+ const schema = fetched !== null && fetched !== void 0 ? fetched : (await this.agent.indexer.getCredentialSchema(id, { allowNotFound: true }));
868
+ if (!schema || schema.archived || schema.holder_onboarding_mode !== types_1.HolderOnboardingMode.Permissionless) {
869
+ logger.warn(`[vt-flow] schema ${id} is not open to Direct Issuance (holder_onboarding_mode: ${(_a = schema === null || schema === void 0 ? void 0 : schema.holder_onboarding_mode) !== null && _a !== void 0 ? _a : 'unknown'})`);
870
+ return undefined;
871
+ }
872
+ const issuers = await this.agent.indexer.listParticipants({
873
+ did: this.agent.did,
874
+ schemaId: id,
875
+ role: types_1.ParticipantRole.Issuer,
876
+ participantState: types_1.ParticipantState.Active,
877
+ });
878
+ const issuer = issuers.find(p => !p.revoked && !p.slashed && p.vs_operator === chain.address);
879
+ if (!issuer) {
880
+ logger.warn(`[vt-flow] no active issuer participant with vs_operator ${chain.address} for schema ${id}`);
881
+ }
882
+ return issuer;
883
+ }
884
+ /**
885
+ * Builds the unsigned VC Data Model 2.0 credential that goes into the offer. RFC 0809 derives the
886
+ * advertised data model version from its context, and the issuer secures it with a
887
+ * DataIntegrityProof once the applicant requests it.
888
+ */
889
+ async buildCredential(input) {
890
+ var _a, _b;
891
+ const jsonSchemaCredentialId = await this.resolveJsonSchemaCredentialId(input.credentialSchemaId);
208
892
  // A credential whose claims don't satisfy the schema's required fields is not a valid
209
893
  // instance of that credential type — reject it here rather than issue an empty shell.
210
- const schema = await this.requireIndexer().getCredentialSchema(input.credentialSchemaId);
894
+ const schema = (_a = input.schema) !== null && _a !== void 0 ? _a : (await this.agent.indexer.getCredentialSchema(input.credentialSchemaId));
211
895
  (0, utils_1.validateSchema)(JSON.parse(schema.json_schema), Object.assign({ id: input.subjectDid }, input.claims));
212
- const unsignedCredential = (0, utils_1.createCredential)({
896
+ // Data model 2.0 holds the claims on the credential subject itself; the applicant DID wins over
897
+ // any `id` claim so the credential can never name a different subject
898
+ const unsignedCredential = (0, utils_1.createW3cV2Credential)({
213
899
  id: `${this.agent.did}#${core_1.utils.uuid()}`,
214
- type: (_a = input.credentialType) !== null && _a !== void 0 ? _a : ['VerifiableCredential', 'VerifiableTrustCredential'],
900
+ type: (_b = input.credentialType) !== null && _b !== void 0 ? _b : ['VerifiableCredential', 'VerifiableTrustCredential'],
215
901
  issuer: this.agent.did,
216
- credentialSubject: { id: input.subjectDid, claims: input.claims },
902
+ context: input.credentialContext,
903
+ credentialSubject: Object.assign(Object.assign({}, input.claims), { id: input.subjectDid }),
904
+ credentialSchema: { id: jsonSchemaCredentialId, type: 'JsonSchemaCredential' },
905
+ validUntil: input.validUntil,
217
906
  });
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);
907
+ return (0, utils_1.toOfferedCredentialJson)(unsignedCredential);
908
+ }
909
+ async resolveJsonSchemaCredentialId(credentialSchemaId) {
910
+ return (0, utils_1.resolveJsonSchemaCredentialId)(this.agent, this.agent.indexer, credentialSchemaId, this.requireChain().getChainId);
225
911
  }
226
912
  /** Per the spec the algorithm comes from the schema, never from the digest value. */
227
913
  async digestAlgorithmForSchema(schemaId) {
228
- const schema = await this.requireIndexer().getCredentialSchema(schemaId);
914
+ return (await this.credentialSchema(schemaId)).digestAlgorithm;
915
+ }
916
+ async credentialSchema(schemaId) {
917
+ const schema = await this.agent.indexer.getCredentialSchema(schemaId);
229
918
  if (!schema.digest_algorithm) {
230
919
  throw new Error(`Credential schema ${schemaId} has no digest_algorithm`);
231
920
  }
232
- return schema.digest_algorithm;
921
+ return { digestAlgorithm: schema.digest_algorithm, ecsKey: await (0, vs_agent_model_1.classifyEcsSchema)(schema.json_schema) };
233
922
  }
234
- /** Fired after signing and before delivery, so a failure here must abort the issuance. */
923
+ /** Fired after signing and before delivery. A failed anchoring comes back in `issuance`, and the credential stays undelivered. */
235
924
  async onCredentialIssued(vtFlowRecordId, signedCredential) {
236
- var _a, _b;
925
+ var _a, _b, _c, _d, _e, _f;
237
926
  const chain = this.requireChain();
238
927
  const vtFlowApi = this.resolveVtFlowApi();
239
928
  const record = await vtFlowApi.findById(vtFlowRecordId);
@@ -242,17 +931,45 @@ class VtFlowOrchestrator {
242
931
  if (record.issuerParticipantId == null) {
243
932
  throw new Error(`vt-flow record ${vtFlowRecordId} has no issuerParticipantId to anchor against`);
244
933
  }
245
- const issuer = await this.requireIndexer().getParticipant(record.issuerParticipantId);
934
+ // [VSA-VTI-FLOW-DI]: checked again before anchoring, as the chain can change after the offer
935
+ if (record.variant === credo_ts_didcomm_vt_flow_1.VtFlowVariant.DirectIssuance &&
936
+ !(record.schemaId && (await this.directIssuanceIssuer(record.schemaId)))) {
937
+ throw new Error(`vt-flow record ${vtFlowRecordId}: this agent does not issue schema ${record.schemaId} by Direct Issuance, credential not anchored`);
938
+ }
939
+ const issuer = await this.agent.indexer.getParticipant(record.issuerParticipantId);
246
940
  const algorithm = await this.digestAlgorithmForSchema(issuer.schema_id);
247
941
  const digest = (0, verre_1.computeCredentialDigestJCS)(signedCredential, algorithm);
248
- await chain.createOrUpdateParticipantSession({
942
+ const anchored = ((_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.Succeeded ? record.issuance.tx : undefined;
943
+ if (anchored && digest !== record.credentialDigest) {
944
+ throw new Error(`the credential of flow ${record.id} does not have the digest that the flow anchored`);
945
+ }
946
+ let tx = anchored;
947
+ if (!tx && ((_d = (_c = record.issuance) === null || _c === void 0 ? void 0 : _c.tx) === null || _d === void 0 ? void 0 : _d.status) !== credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Submitted) {
948
+ // An earlier attempt can anchor the credential and stop before it records the tx.
949
+ try {
950
+ if (await this.agent.indexer.getDigest(digest))
951
+ tx = { status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Succeeded };
952
+ }
953
+ catch (error) {
954
+ tx = {
955
+ status: credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed,
956
+ reason: (0, feePreflight_1.preflightFailureReason)(error),
957
+ error: `the digest lookup failed: ${errorMessage(error)}`,
958
+ };
959
+ }
960
+ }
961
+ const message = chain.createOrUpdateParticipantSessionMsg({
249
962
  id: record.participantSessionId,
250
963
  issuerParticipantId: record.issuerParticipantId,
251
- agentParticipantId: Number((_a = record.agentParticipantId) !== null && _a !== void 0 ? _a : 0) || 0,
252
- walletAgentParticipantId: Number((_b = record.walletAgentParticipantId) !== null && _b !== void 0 ? _b : 0) || 0,
964
+ agentParticipantId: Number((_e = record.agentParticipantId) !== null && _e !== void 0 ? _e : 0) || 0,
965
+ walletAgentParticipantId: Number((_f = record.walletAgentParticipantId) !== null && _f !== void 0 ? _f : 0) || 0,
253
966
  digest,
254
967
  });
255
- return digest;
968
+ tx !== null && tx !== void 0 ? tx : (tx = await this.anchor(record, message, record.issuerParticipantId));
969
+ if (tx.status === credo_ts_didcomm_vt_flow_1.VtFlowTxStatus.Failed) {
970
+ this.agent.config.logger.error(`[vt-flow] the anchoring of the credential of flow ${record.id} (session ${record.participantSessionId}) failed, credential not delivered: ${tx.reason}: ${tx.error}`);
971
+ }
972
+ return { credentialDigest: digest, issuance: { tx } };
256
973
  }
257
974
  async verifyOfferedCredential(vtFlowRecordId) {
258
975
  var _a, _b;
@@ -265,7 +982,7 @@ class VtFlowOrchestrator {
265
982
  if (!record.credentialExchangeRecordId) {
266
983
  throw new Error('Record has no credentialExchangeRecordId; nothing to verify');
267
984
  }
268
- const indexer = this.requireIndexer();
985
+ const indexer = this.agent.indexer;
269
986
  const session = await indexer.getParticipantSession(record.participantSessionId);
270
987
  if (!session) {
271
988
  throw new Error(`ParticipantSession ${record.participantSessionId} not found on indexer`);
@@ -286,24 +1003,52 @@ class VtFlowOrchestrator {
286
1003
  if (record.schemaId != null && Number(issuer.schema_id) !== Number(record.schemaId)) {
287
1004
  throw new Error(`Issuer participant schema ${issuer.schema_id} does not match credential schema ${record.schemaId}`);
288
1005
  }
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);
1006
+ const credentialJson = await this.getReceivedCredentialJson(record.credentialExchangeRecordId);
1007
+ await this.assertFlowCredentialFormat(credentialJson, issuer);
1008
+ const { digestAlgorithm, ecsKey } = await this.credentialSchema(issuer.schema_id);
1009
+ const digest = (0, verre_1.computeCredentialDigestJCS)(credentialJson, digestAlgorithm);
292
1010
  const anchored = await indexer.getDigest(digest);
293
1011
  if (!anchored) {
294
1012
  throw new Error(`Credential digest ${digest} is not anchored on-chain`);
295
1013
  }
1014
+ if (ecsKey)
1015
+ await vtFlowApi.setEcsSchemaKey(record.id, ecsKey);
1016
+ }
1017
+ /** [VSA-VTI-FLOW-FMT-1]. Credo already verified the proof and its assertionMethod key, for data model 2.0 only. */
1018
+ async assertFlowCredentialFormat(credential, issuer) {
1019
+ var _a, _b, _c;
1020
+ if (!(0, utils_1.isVcdm2Credential)(credential)) {
1021
+ throw new Error('Received credential is not a VC Data Model 2.0 credential');
1022
+ }
1023
+ const verificationMethod = (_a = credential.proof) === null || _a === void 0 ? void 0 : _a.verificationMethod;
1024
+ if (!issuer.did || (verificationMethod === null || verificationMethod === void 0 ? void 0 : verificationMethod.split('#')[0]) !== issuer.did) {
1025
+ throw new Error(`Proof verification method ${verificationMethod} is not one of the validator ${issuer.did}`);
1026
+ }
1027
+ const subjectId = (_b = credential.credentialSubject) === null || _b === void 0 ? void 0 : _b.id;
1028
+ if (subjectId !== this.agent.did) {
1029
+ throw new Error(`Credential subject ${subjectId} is not the applicant ${this.agent.did}`);
1030
+ }
1031
+ const schemaRef = (_c = credential.credentialSchema) === null || _c === void 0 ? void 0 : _c.id;
1032
+ const jsonSchemaCredentialId = await this.resolveJsonSchemaCredentialId(String(issuer.schema_id));
1033
+ if (schemaRef !== jsonSchemaCredentialId) {
1034
+ throw new Error(`Credential schema ${schemaRef} is not the VTJSC ${jsonSchemaCredentialId} of the flow`);
1035
+ }
296
1036
  }
297
1037
  async onCredentialRevoked(vtFlowRecordId) {
298
1038
  const vtFlowApi = this.resolveVtFlowApi();
299
1039
  const record = await vtFlowApi.findById(vtFlowRecordId);
300
1040
  if (!record || record.role !== credo_ts_didcomm_vt_flow_1.VtFlowRole.Applicant)
301
1041
  return;
302
- if (!this.options.publicApiBaseUrl || !record.credentialExchangeRecordId)
1042
+ if (!this.options.publicApiBaseUrl)
1043
+ return;
1044
+ if (!record.credentialId && !record.credentialExchangeRecordId)
303
1045
  return;
304
- const credentialId = await (0, utils_1.removeStoredTrustCredential)(this.agent, this.options.publicApiBaseUrl, record.credentialExchangeRecordId);
1046
+ const credentialId = await (0, utils_1.removeStoredTrustCredential)(this.agent, {
1047
+ credentialId: record.credentialId,
1048
+ credentialExchangeRecordId: record.credentialExchangeRecordId,
1049
+ });
305
1050
  if (credentialId) {
306
- this.agent.config.logger.info(`[vt-flow] removed revoked credential and its linked VP (${credentialId})`);
1051
+ this.agent.config.logger.info(`[vt-flow] removed revoked credential (${credentialId})`);
307
1052
  }
308
1053
  }
309
1054
  async onCredentialCompleted(vtFlowRecordId) {
@@ -315,33 +1060,104 @@ class VtFlowOrchestrator {
315
1060
  return;
316
1061
  if (!this.options.publicApiBaseUrl)
317
1062
  return;
1063
+ // [VSA-VT-LVP-5]: the publication writes the DID record, and that write sends TriggerResolver
318
1064
  await this.publishCredentialAsLinkedVp(vtFlowRecordId);
319
- await this.triggerResolver(record);
320
1065
  }
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;
1066
+ /** The signed credential as the issuer attached it, which is the exact JSON its digest covers. */
1067
+ async getReceivedCredentialJson(credentialExchangeRecordId) {
1068
+ var _a, _b;
331
1069
  const formatData = await this.agent.didcomm.credentials.getFormatData(credentialExchangeRecordId);
332
- const credentialJson = (_a = formatData.credential) === null || _a === void 0 ? void 0 : _a.jsonld;
1070
+ const credentialJson = (_b = (_a = formatData.credential) === null || _a === void 0 ? void 0 : _a.dataIntegrity) === null || _b === void 0 ? void 0 : _b.credential;
333
1071
  if (!credentialJson)
334
- throw new Error('Offered credential has no JSON-LD body to verify');
1072
+ throw new Error('Received credential has no data integrity credential body');
335
1073
  return credentialJson;
336
1074
  }
337
- requireIndexer() {
338
- if (!this.options.indexer) {
339
- throw new Error('Agent has no indexer configured (set VERANA_INDEXER_BASE_URL)');
1075
+ // VS-CONN-VS gate: consulted only after trust resolution rejected the peer.
1076
+ async checkEcsIssuanceExemption(context) {
1077
+ return (0, ecsIssuanceExemption_1.isEcsIssuanceExempt)({
1078
+ indexer: this.agent.indexer,
1079
+ agent: this.agent,
1080
+ trustedEcosystemDids: this.agent.trustedEcosystemDids,
1081
+ }, context);
1082
+ }
1083
+ // the indexer can still lag the applicant's own transaction, so wait for it as a tx lookup does
1084
+ async checkParticipantId({ record }) {
1085
+ if (!record.applicantParticipantId || !this.agent.did)
1086
+ return false;
1087
+ const deadline = Date.now() + TX_LOOKUP_TIMEOUT_MS;
1088
+ let validatedAtFirstRead;
1089
+ for (;;) {
1090
+ const entry = await this.agent.indexer
1091
+ .getParticipant(record.applicantParticipantId)
1092
+ .catch(() => undefined);
1093
+ validatedAtFirstRead !== null && validatedAtFirstRead !== void 0 ? validatedAtFirstRead : (validatedAtFirstRead = (entry === null || entry === void 0 ? void 0 : entry.op_state) === 'VALIDATED');
1094
+ if (entry) {
1095
+ if (entry.revoked || entry.slashed || entry.validator_participant_id == null)
1096
+ return false;
1097
+ const validator = await this.agent.indexer
1098
+ .getParticipant(entry.validator_participant_id)
1099
+ .catch(() => undefined);
1100
+ if (validator && validator.did !== this.agent.did)
1101
+ return false;
1102
+ if (validator && entry.op_state === 'PENDING')
1103
+ return true;
1104
+ if (validator && entry.op_state === 'VALIDATED') {
1105
+ const flow = await this.resolveVtFlowApi().findById(record.id);
1106
+ // the flow has moved on, or another path is moving it to VALIDATED and continues it itself
1107
+ if ((flow === null || flow === void 0 ? void 0 : flow.state) !== credo_ts_didcomm_vt_flow_1.VtFlowState.AwaitingOr || markingValidated.has(record.id))
1108
+ return 'validated';
1109
+ // VALIDATED at the first read can be the round before this request, which it does not settle
1110
+ if (!validatedAtFirstRead) {
1111
+ await this.markValidated(record.id, entry);
1112
+ await this.continueAfterValidated(record.id);
1113
+ return 'validated';
1114
+ }
1115
+ }
1116
+ }
1117
+ if (Date.now() >= deadline)
1118
+ return false;
1119
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
1120
+ }
1121
+ }
1122
+ // the indexer can still lag the applicant's RenewParticipantOP, so wait for it as checkParticipantId does
1123
+ async isParticipantPending({ record }) {
1124
+ if (!record.applicantParticipantId)
1125
+ return false;
1126
+ const deadline = Date.now() + TX_LOOKUP_TIMEOUT_MS;
1127
+ for (;;) {
1128
+ const entry = await this.agent.indexer
1129
+ .getParticipant(record.applicantParticipantId)
1130
+ .catch(() => undefined);
1131
+ if ((entry === null || entry === void 0 ? void 0 : entry.revoked) || (entry === null || entry === void 0 ? void 0 : entry.slashed))
1132
+ return false;
1133
+ if ((entry === null || entry === void 0 ? void 0 : entry.op_state) === 'PENDING')
1134
+ return true;
1135
+ if (Date.now() >= deadline)
1136
+ return false;
1137
+ await new Promise(resolve => setTimeout(resolve, TX_LOOKUP_INTERVAL_MS));
1138
+ }
1139
+ }
1140
+ // [VSA-VTI-FLOW-DI]: an issuance-request is refused before the flow moves unless this agent can
1141
+ // issue its schema by Direct Issuance
1142
+ async checkSchemaId({ record }) {
1143
+ if (!record.schemaId)
1144
+ return false;
1145
+ const logger = this.agent.config.logger;
1146
+ if (!this.agent.veranaChain || !this.agent.did) {
1147
+ logger.warn(`[vt-flow] refusing the issuance-request of flow ${record.id}: the agent has no Verana chain or public DID to issue with`);
1148
+ return false;
1149
+ }
1150
+ try {
1151
+ return (await this.directIssuanceIssuer(record.schemaId)) !== undefined;
1152
+ }
1153
+ catch (error) {
1154
+ // vt-flow has no retryable "try later" code, so this is still vt-flow.invalid-schema-id; the applicant can resend
1155
+ logger.warn(`[vt-flow] refusing the issuance-request of flow ${record.id} because the indexer could not be reached, not because of schema ${record.schemaId}: ${errorMessage(error)}`);
1156
+ return false;
340
1157
  }
341
- return this.options.indexer;
342
1158
  }
343
1159
  async publishCredentialAsLinkedVp(vtFlowRecordId) {
344
- var _a, _b;
1160
+ var _a;
345
1161
  if (!this.options.publicApiBaseUrl) {
346
1162
  throw new Error('publicApiBaseUrl is required to publish a LinkedVerifiablePresentation');
347
1163
  }
@@ -354,18 +1170,29 @@ class VtFlowOrchestrator {
354
1170
  if (!record.credentialExchangeRecordId) {
355
1171
  throw new Error(`vt-flow record ${vtFlowRecordId} has no credentialExchangeRecordId`);
356
1172
  }
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;
1173
+ const credentialJson = await this.getReceivedCredentialJson(record.credentialExchangeRecordId);
1174
+ const schemaRef = (_a = credentialJson.credentialSchema) === null || _a === void 0 ? void 0 : _a.id;
363
1175
  const schemaBaseId = schemaRef ? this.extractSchemaBaseId(schemaRef) : undefined;
364
1176
  if (!schemaBaseId) {
365
1177
  throw new Error(`Cannot publish Linked VP: credential has no extractable schema base id (credentialSchema.id=${schemaRef !== null && schemaRef !== void 0 ? schemaRef : 'undefined'})`);
366
1178
  }
367
- const w3cCredential = core_1.JsonTransformer.fromJSON(jsonld, core_1.W3cJsonLdVerifiableCredential);
368
- await (0, utils_1.createVtc)(this.agent, this.options.publicApiBaseUrl, schemaBaseId, w3cCredential);
1179
+ // A data model 2.0 credential arrives secured with a DataIntegrityProof; a validator still on
1180
+ // data model 1.1 sends a linked data proof, and both are published the same way
1181
+ const credential = (0, utils_1.isVcdm2Credential)(credentialJson)
1182
+ ? core_1.W3cV2DataIntegrityVerifiableCredential.fromObject(credentialJson)
1183
+ : core_1.JsonTransformer.fromJSON(credentialJson, core_1.W3cJsonLdVerifiableCredential);
1184
+ if (record.ecsSchemaKey && !(0, vs_agent_model_1.isPublicServiceEcs)(record.ecsSchemaKey)) {
1185
+ // [VSA-VT-LVP-1]: the agent stores this credential but does not publish it.
1186
+ this.agent.config.logger.info(`[vt-flow] Flow ${record.id}: stored the ${record.ecsSchemaKey} credential, published no linked VP`);
1187
+ }
1188
+ else {
1189
+ await (0, utils_1.createVtc)(this.agent, this.options.publicApiBaseUrl, record.ecsSchemaKey ? (0, utils_1.linkedVpSchemaId)(record.ecsSchemaKey) : schemaBaseId, credential);
1190
+ }
1191
+ // [VSA-VT-LVP-3]: the record keeps the id of the credential.
1192
+ // Then the agent can remove that credential without the exchange.
1193
+ const credentialId = credentialJson.id;
1194
+ if (typeof credentialId === 'string')
1195
+ await vtFlowApi.setCredentialId(record.id, credentialId);
369
1196
  }
370
1197
  extractSchemaBaseId(jscUrl) {
371
1198
  var _a;