@verana-labs/vs-agent-sdk 2.0.0-dev.5 → 2.0.0-dev.51

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 (123) hide show
  1. package/build/agent/VsAgent.d.ts +11 -16
  2. package/build/agent/VsAgent.js +82 -172
  3. package/build/agent/VsAgent.js.map +1 -1
  4. package/build/agent/createVsAgent.d.ts +5 -0
  5. package/build/agent/createVsAgent.js +3 -0
  6. package/build/agent/createVsAgent.js.map +1 -1
  7. package/build/blockchain/AnonCredsTrustService.d.ts +53 -0
  8. package/build/blockchain/AnonCredsTrustService.js +238 -0
  9. package/build/blockchain/AnonCredsTrustService.js.map +1 -0
  10. package/build/blockchain/AuthorizationService.d.ts +5 -3
  11. package/build/blockchain/AuthorizationService.js +17 -29
  12. package/build/blockchain/AuthorizationService.js.map +1 -1
  13. package/build/blockchain/IndexerWebSocketService.d.ts +7 -1
  14. package/build/blockchain/IndexerWebSocketService.js +68 -36
  15. package/build/blockchain/IndexerWebSocketService.js.map +1 -1
  16. package/build/blockchain/VeranaChainService.d.ts +2 -13
  17. package/build/blockchain/VeranaChainService.js +8 -113
  18. package/build/blockchain/VeranaChainService.js.map +1 -1
  19. package/build/blockchain/VeranaIndexerService.d.ts +14 -1
  20. package/build/blockchain/VeranaIndexerService.js +122 -8
  21. package/build/blockchain/VeranaIndexerService.js.map +1 -1
  22. package/build/blockchain/handlers/authorizationHandlers.js +2 -2
  23. package/build/blockchain/handlers/authorizationHandlers.js.map +1 -1
  24. package/build/blockchain/handlers/defaultHandlers.js +2 -0
  25. package/build/blockchain/handlers/defaultHandlers.js.map +1 -1
  26. package/build/blockchain/handlers/index.d.ts +1 -0
  27. package/build/blockchain/handlers/index.js +1 -0
  28. package/build/blockchain/handlers/index.js.map +1 -1
  29. package/build/blockchain/handlers/selfIssuanceHandlers.d.ts +13 -0
  30. package/build/blockchain/handlers/selfIssuanceHandlers.js +71 -0
  31. package/build/blockchain/handlers/selfIssuanceHandlers.js.map +1 -0
  32. package/build/blockchain/handlers/stateMutations.d.ts +21 -2
  33. package/build/blockchain/handlers/stateMutations.js +272 -34
  34. package/build/blockchain/handlers/stateMutations.js.map +1 -1
  35. package/build/blockchain/index.d.ts +2 -0
  36. package/build/blockchain/index.js +2 -0
  37. package/build/blockchain/index.js.map +1 -1
  38. package/build/blockchain/indexerMappers.d.ts +3 -0
  39. package/build/blockchain/indexerMappers.js +53 -0
  40. package/build/blockchain/indexerMappers.js.map +1 -0
  41. package/build/blockchain/types.d.ts +5 -57
  42. package/build/blockchain/types.js.map +1 -1
  43. package/build/bootstrap/EcsBootstrapService.d.ts +16 -3
  44. package/build/bootstrap/EcsBootstrapService.js +202 -77
  45. package/build/bootstrap/EcsBootstrapService.js.map +1 -1
  46. package/build/did/CachedWebDidResolver.d.ts +0 -4
  47. package/build/did/CachedWebDidResolver.js +1 -5
  48. package/build/did/CachedWebDidResolver.js.map +1 -1
  49. package/build/did/artifactServices.d.ts +11 -0
  50. package/build/did/artifactServices.js +48 -0
  51. package/build/did/artifactServices.js.map +1 -0
  52. package/build/did/legacyDidWeb.d.ts +6 -4
  53. package/build/did/legacyDidWeb.js +17 -14
  54. package/build/did/legacyDidWeb.js.map +1 -1
  55. package/build/did/migrations/index.d.ts +22 -0
  56. package/build/did/migrations/index.js +103 -0
  57. package/build/did/migrations/index.js.map +1 -0
  58. package/build/did/migrations/migrateWebVhLog.js.map +1 -0
  59. package/build/did/migrations/migrateWebVhVersionTime.js.map +1 -0
  60. package/build/events/BaseMessageEvents.js +109 -0
  61. package/build/events/BaseMessageEvents.js.map +1 -1
  62. package/build/events/ConnectionEvents.js +110 -82
  63. package/build/events/ConnectionEvents.js.map +1 -1
  64. package/build/events/VsAgentEvents.d.ts +1 -8
  65. package/build/events/VsAgentEvents.js +0 -1
  66. package/build/events/VsAgentEvents.js.map +1 -1
  67. package/build/events/VtFlowEvents.d.ts +1 -1
  68. package/build/events/VtFlowEvents.js +2 -19
  69. package/build/events/VtFlowEvents.js.map +1 -1
  70. package/build/index.d.ts +2 -0
  71. package/build/index.js +5 -1
  72. package/build/index.js.map +1 -1
  73. package/build/plugins/setupBaseDidComm.js +4 -6
  74. package/build/plugins/setupBaseDidComm.js.map +1 -1
  75. package/build/transports/VsAgentWsInboundTransport.d.ts +1 -1
  76. package/build/transports/VsAgentWsInboundTransport.js +20 -14
  77. package/build/transports/VsAgentWsInboundTransport.js.map +1 -1
  78. package/build/utils/agent.d.ts +27 -3
  79. package/build/utils/agent.js +78 -19
  80. package/build/utils/agent.js.map +1 -1
  81. package/build/utils/didReadiness.d.ts +9 -0
  82. package/build/utils/didReadiness.js +42 -0
  83. package/build/utils/didReadiness.js.map +1 -0
  84. package/build/utils/ecsClaims.d.ts +47 -0
  85. package/build/utils/ecsClaims.js +120 -0
  86. package/build/utils/ecsClaims.js.map +1 -0
  87. package/build/utils/index.d.ts +2 -0
  88. package/build/utils/index.js +2 -0
  89. package/build/utils/index.js.map +1 -1
  90. package/build/utils/selfIssuedEcsCredential.d.ts +4 -0
  91. package/build/utils/selfIssuedEcsCredential.js +140 -0
  92. package/build/utils/selfIssuedEcsCredential.js.map +1 -0
  93. package/build/utils/setupSelfTr.d.ts +3 -56
  94. package/build/utils/setupSelfTr.js +41 -249
  95. package/build/utils/setupSelfTr.js.map +1 -1
  96. package/build/utils/trustCredentialStore.d.ts +32 -6
  97. package/build/utils/trustCredentialStore.js +183 -82
  98. package/build/utils/trustCredentialStore.js.map +1 -1
  99. package/build/utils/util.d.ts +10 -0
  100. package/build/utils/util.js +16 -0
  101. package/build/utils/util.js.map +1 -1
  102. package/build/utils/vtjscResolver.d.ts +18 -0
  103. package/build/utils/vtjscResolver.js +54 -0
  104. package/build/utils/vtjscResolver.js.map +1 -0
  105. package/build/vtFlow/VtFlowOrchestrator.d.ts +47 -9
  106. package/build/vtFlow/VtFlowOrchestrator.js +99 -58
  107. package/build/vtFlow/VtFlowOrchestrator.js.map +1 -1
  108. package/build/vtFlow/assertVerifiableService.d.ts +1 -0
  109. package/build/vtFlow/assertVerifiableService.js +45 -5
  110. package/build/vtFlow/assertVerifiableService.js.map +1 -1
  111. package/build/vtFlow/ecsIssuanceExemption.d.ts +12 -0
  112. package/build/vtFlow/ecsIssuanceExemption.js +84 -0
  113. package/build/vtFlow/ecsIssuanceExemption.js.map +1 -0
  114. package/build/vtFlow/index.d.ts +1 -0
  115. package/build/vtFlow/index.js +1 -0
  116. package/build/vtFlow/index.js.map +1 -1
  117. package/package.json +11 -11
  118. package/build/did/migrateWebVhLog.js.map +0 -1
  119. package/build/did/migrateWebVhVersionTime.js.map +0 -1
  120. /package/build/did/{migrateWebVhLog.d.ts → migrations/migrateWebVhLog.d.ts} +0 -0
  121. /package/build/did/{migrateWebVhLog.js → migrations/migrateWebVhLog.js} +0 -0
  122. /package/build/did/{migrateWebVhVersionTime.d.ts → migrations/migrateWebVhVersionTime.d.ts} +0 -0
  123. /package/build/did/{migrateWebVhVersionTime.js → migrations/migrateWebVhVersionTime.js} +0 -0
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AnonCredsTrustService = exports.AnonCredsTrustError = exports.AnonCredsTrustErrorReason = exports.AnonCredsTrustProblemCode = exports.REQUESTED_CREDENTIAL_SCHEMAS_METADATA = void 0;
4
+ const core_1 = require("@credo-ts/core");
5
+ const util_1 = require("../utils/util");
6
+ const types_1 = require("./types");
7
+ const VTJSC_FETCH_TIMEOUT_MS = 30000;
8
+ const CREDENTIAL_SCHEMA_REFERENCE = /^vpr:verana:([^:/]+):cs:(\d+)$/;
9
+ const RELATED_JSON_SCHEMA_CREDENTIAL_ID_TAG = 'relatedJsonSchemaCredentialId';
10
+ exports.REQUESTED_CREDENTIAL_SCHEMAS_METADATA = '_2060/requestedCredentialSchemas';
11
+ var AnonCredsTrustProblemCode;
12
+ (function (AnonCredsTrustProblemCode) {
13
+ AnonCredsTrustProblemCode["IssuerNotAuthorized"] = "e.p.issuer-not-authorized";
14
+ AnonCredsTrustProblemCode["TrustResolutionUnavailable"] = "e.p.trust-resolution-unavailable";
15
+ })(AnonCredsTrustProblemCode || (exports.AnonCredsTrustProblemCode = AnonCredsTrustProblemCode = {}));
16
+ var AnonCredsTrustErrorReason;
17
+ (function (AnonCredsTrustErrorReason) {
18
+ AnonCredsTrustErrorReason["NotDerivable"] = "not-derivable";
19
+ AnonCredsTrustErrorReason["NotAuthorized"] = "not-authorized";
20
+ AnonCredsTrustErrorReason["Unavailable"] = "unavailable";
21
+ })(AnonCredsTrustErrorReason || (exports.AnonCredsTrustErrorReason = AnonCredsTrustErrorReason = {}));
22
+ class AnonCredsTrustError extends Error {
23
+ constructor(reason, message) {
24
+ super(message);
25
+ this.reason = reason;
26
+ this.name = 'AnonCredsTrustError';
27
+ }
28
+ }
29
+ exports.AnonCredsTrustError = AnonCredsTrustError;
30
+ function notDerivable(message) {
31
+ return new AnonCredsTrustError(AnonCredsTrustErrorReason.NotDerivable, message);
32
+ }
33
+ function notAuthorized(message) {
34
+ return new AnonCredsTrustError(AnonCredsTrustErrorReason.NotAuthorized, message);
35
+ }
36
+ function unavailable(message) {
37
+ return new AnonCredsTrustError(AnonCredsTrustErrorReason.Unavailable, message);
38
+ }
39
+ function relatedJsonSchemaCredentialIdOf(metadata) {
40
+ const value = metadata[RELATED_JSON_SCHEMA_CREDENTIAL_ID_TAG];
41
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
42
+ }
43
+ class AnonCredsTrustService {
44
+ constructor(agent) {
45
+ this.agent = agent;
46
+ this.derivations = new Map();
47
+ this.credentialSchemaLinks = new Map();
48
+ }
49
+ async deriveCredentialSchema(reference) {
50
+ const key = 'credentialDefinitionId' in reference
51
+ ? `credentialDefinition:${reference.credentialDefinitionId}`
52
+ : `schema:${reference.schemaId}`;
53
+ const cached = this.derivations.get(key);
54
+ if (cached)
55
+ return cached;
56
+ const object = await this.resolveAnonCredsObject(reference);
57
+ const link = await this.resolveCredentialSchemaLink(object.jsonSchemaCredentialId);
58
+ const derived = {
59
+ credentialSchemaId: link.credentialSchemaId,
60
+ ecosystemDid: link.ecosystemDid,
61
+ jsonSchemaCredentialId: object.jsonSchemaCredentialId,
62
+ anonCredsSchemaId: object.anonCredsSchemaId,
63
+ issuerId: object.issuerId,
64
+ };
65
+ this.derivations.set(key, derived);
66
+ return derived;
67
+ }
68
+ async assertAuthorized(options) {
69
+ const { did, role, credentialSchemaId } = options;
70
+ let participants;
71
+ try {
72
+ participants = await this.agent.indexer.listParticipants({
73
+ did,
74
+ role,
75
+ schemaId: credentialSchemaId,
76
+ participantState: types_1.ParticipantState.Active,
77
+ });
78
+ }
79
+ catch (error) {
80
+ throw unavailable(`the agent cannot read the Participant entries of "${did}" for the CredentialSchema ${credentialSchemaId}: ${error}`);
81
+ }
82
+ const authorized = (participants !== null && participants !== void 0 ? participants : []).some(participant => participant.did === did &&
83
+ participant.role === role &&
84
+ Number(participant.schema_id) === credentialSchemaId &&
85
+ participant.participant_state === types_1.ParticipantState.Active);
86
+ if (!authorized) {
87
+ throw notAuthorized(`"${did}" holds no active ${role} Participant for the CredentialSchema ${credentialSchemaId}`);
88
+ }
89
+ }
90
+ async assertOwnAuthorization(options) {
91
+ if (!this.agent.did) {
92
+ throw unavailable('the agent has no public DID, so it cannot check its own Participant entry');
93
+ }
94
+ await this.assertAuthorized(Object.assign({ did: this.agent.did }, options));
95
+ }
96
+ async findUnaccreditedDids(dids, role, credentialSchemaId) {
97
+ const unaccredited = [];
98
+ const unchecked = [];
99
+ for (const did of new Set(dids)) {
100
+ try {
101
+ await this.assertAuthorized({ did, role, credentialSchemaId });
102
+ }
103
+ catch (error) {
104
+ if (!(error instanceof AnonCredsTrustError))
105
+ throw error;
106
+ if (error.reason === AnonCredsTrustErrorReason.Unavailable)
107
+ unchecked.push(did);
108
+ else
109
+ unaccredited.push(did);
110
+ }
111
+ }
112
+ return { unaccredited, unchecked };
113
+ }
114
+ async resolveAnonCredsObject(reference) {
115
+ var _a, _b;
116
+ const anoncreds = this.agent.modules.anoncreds;
117
+ if ('credentialDefinitionId' in reference) {
118
+ const { credentialDefinitionId } = reference;
119
+ const [record] = await anoncreds.getCreatedCredentialDefinitions({ credentialDefinitionId });
120
+ const localId = record === null || record === void 0 ? void 0 : record.getTag(RELATED_JSON_SCHEMA_CREDENTIAL_ID_TAG);
121
+ if (record && typeof localId === 'string' && localId.length > 0) {
122
+ return {
123
+ jsonSchemaCredentialId: localId,
124
+ anonCredsSchemaId: record.credentialDefinition.schemaId,
125
+ issuerId: record.credentialDefinition.issuerId,
126
+ };
127
+ }
128
+ const result = await anoncreds.getCredentialDefinition(credentialDefinitionId, {
129
+ useLocalRecord: false,
130
+ });
131
+ if (!result.credentialDefinition) {
132
+ throw unavailable(`the agent cannot resolve the credential definition "${credentialDefinitionId}": ${(_a = result.resolutionMetadata.message) !== null && _a !== void 0 ? _a : result.resolutionMetadata.error}`);
133
+ }
134
+ const jsonSchemaCredentialId = relatedJsonSchemaCredentialIdOf(result.credentialDefinitionMetadata);
135
+ if (!jsonSchemaCredentialId) {
136
+ throw notDerivable(`the credential definition "${credentialDefinitionId}" carries no relatedJsonSchemaCredentialId, so it binds to no CredentialSchema`);
137
+ }
138
+ return {
139
+ jsonSchemaCredentialId,
140
+ anonCredsSchemaId: result.credentialDefinition.schemaId,
141
+ issuerId: result.credentialDefinition.issuerId,
142
+ };
143
+ }
144
+ const { schemaId } = reference;
145
+ const [record] = await anoncreds.getCreatedSchemas({ schemaId });
146
+ const localId = record === null || record === void 0 ? void 0 : record.getTag(RELATED_JSON_SCHEMA_CREDENTIAL_ID_TAG);
147
+ if (record && typeof localId === 'string' && localId.length > 0) {
148
+ return { jsonSchemaCredentialId: localId, anonCredsSchemaId: schemaId };
149
+ }
150
+ const result = await anoncreds.getSchema(schemaId, { useLocalRecord: false });
151
+ if (!result.schema) {
152
+ throw unavailable(`the agent cannot resolve the AnonCreds schema "${schemaId}": ${(_b = result.resolutionMetadata.message) !== null && _b !== void 0 ? _b : result.resolutionMetadata.error}`);
153
+ }
154
+ const jsonSchemaCredentialId = relatedJsonSchemaCredentialIdOf(result.schemaMetadata);
155
+ if (!jsonSchemaCredentialId) {
156
+ throw notDerivable(`the AnonCreds schema "${schemaId}" carries no relatedJsonSchemaCredentialId, so it binds to no CredentialSchema`);
157
+ }
158
+ return { jsonSchemaCredentialId, anonCredsSchemaId: schemaId };
159
+ }
160
+ async resolveCredentialSchemaLink(jsonSchemaCredentialId) {
161
+ var _a, _b, _c;
162
+ const cached = this.credentialSchemaLinks.get(jsonSchemaCredentialId);
163
+ if (cached)
164
+ return cached;
165
+ let document;
166
+ try {
167
+ document = await (0, util_1.fetchJson)(jsonSchemaCredentialId, VTJSC_FETCH_TIMEOUT_MS);
168
+ }
169
+ catch (error) {
170
+ throw unavailable(`the agent cannot read the VTJSC "${jsonSchemaCredentialId}": ${error}`);
171
+ }
172
+ await this.verifyVtjscProof(jsonSchemaCredentialId, document);
173
+ const subject = Array.isArray(document.credentialSubject)
174
+ ? document.credentialSubject[0]
175
+ : document.credentialSubject;
176
+ const schemaReference = (_a = subject === null || subject === void 0 ? void 0 : subject.jsonSchema) === null || _a === void 0 ? void 0 : _a.$ref;
177
+ const parsed = schemaReference === null || schemaReference === void 0 ? void 0 : schemaReference.match(CREDENTIAL_SCHEMA_REFERENCE);
178
+ if (!parsed) {
179
+ throw notDerivable(`the VTJSC "${jsonSchemaCredentialId}" names "${schemaReference !== null && schemaReference !== void 0 ? schemaReference : 'no'}" in credentialSubject.jsonSchema.$ref, which is no "vpr:verana:<chain>:cs:<id>" reference`);
180
+ }
181
+ const chainId = (_b = this.agent.veranaChain) === null || _b === void 0 ? void 0 : _b.getChainId;
182
+ if (!chainId) {
183
+ throw unavailable(`the agent runs on no chain, so it cannot read the CredentialSchema of the VTJSC "${jsonSchemaCredentialId}"`);
184
+ }
185
+ if (parsed[1] !== chainId) {
186
+ throw notDerivable(`the VTJSC "${jsonSchemaCredentialId}" names the chain "${parsed[1]}", and the agent runs on "${chainId}"`);
187
+ }
188
+ const credentialSchemaId = Number(parsed[2]);
189
+ const credentialSchema = await this.requireFromIndexer(() => this.agent.indexer.getCredentialSchema(credentialSchemaId, { allowNotFound: true }), `CredentialSchema ${credentialSchemaId}, which the VTJSC "${jsonSchemaCredentialId}" names`);
190
+ const ecosystem = await this.requireFromIndexer(() => this.agent.indexer.getEcosystem(credentialSchema.ecosystem_id, { allowNotFound: true }), `Ecosystem ${credentialSchema.ecosystem_id}, which the CredentialSchema ${credentialSchemaId} names`);
191
+ const ecosystemDid = ecosystem.did;
192
+ if (!ecosystemDid) {
193
+ throw notDerivable(`the Ecosystem of the CredentialSchema ${credentialSchemaId} carries no DID`);
194
+ }
195
+ const issuer = typeof document.issuer === 'string' ? document.issuer : (_c = document.issuer) === null || _c === void 0 ? void 0 : _c.id;
196
+ if (issuer !== ecosystemDid) {
197
+ throw notDerivable(`the VTJSC "${jsonSchemaCredentialId}" carries the issuer "${issuer}", and the Ecosystem of the CredentialSchema ${credentialSchemaId} is "${ecosystemDid}"`);
198
+ }
199
+ const link = { credentialSchemaId, ecosystemDid };
200
+ this.credentialSchemaLinks.set(jsonSchemaCredentialId, link);
201
+ return link;
202
+ }
203
+ async requireFromIndexer(read, describe) {
204
+ let value;
205
+ try {
206
+ value = await read();
207
+ }
208
+ catch (error) {
209
+ throw unavailable(`the agent cannot read the ${describe}: ${error}`);
210
+ }
211
+ if (!value)
212
+ throw notDerivable(`the VPR holds no ${describe}`);
213
+ return value;
214
+ }
215
+ async verifyVtjscProof(jsonSchemaCredentialId, document) {
216
+ var _a;
217
+ let credential;
218
+ try {
219
+ credential = core_1.JsonTransformer.fromJSON(document, core_1.W3cJsonLdVerifiableCredential);
220
+ }
221
+ catch (error) {
222
+ throw notDerivable(`the document at "${jsonSchemaCredentialId}" is no verifiable credential: ${error}`);
223
+ }
224
+ try {
225
+ const result = await this.agent.w3cCredentials.verifyCredential({ credential });
226
+ if (result.isValid)
227
+ return;
228
+ throw notDerivable(`the proof of the VTJSC "${jsonSchemaCredentialId}" is invalid: ${(_a = result.error) !== null && _a !== void 0 ? _a : 'the verification failed'}`);
229
+ }
230
+ catch (error) {
231
+ if (error instanceof AnonCredsTrustError)
232
+ throw error;
233
+ throw unavailable(`the agent cannot verify the proof of the VTJSC "${jsonSchemaCredentialId}": ${error}`);
234
+ }
235
+ }
236
+ }
237
+ exports.AnonCredsTrustService = AnonCredsTrustService;
238
+ //# sourceMappingURL=AnonCredsTrustService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AnonCredsTrustService.js","sourceRoot":"","sources":["../../src/blockchain/AnonCredsTrustService.ts"],"names":[],"mappings":";;;AAEA,yCAA+E;AAE/E,wCAAyC;AAEzC,mCAA2E;AAE3E,MAAM,sBAAsB,GAAG,KAAM,CAAA;AAErC,MAAM,2BAA2B,GAAG,gCAAgC,CAAA;AAEpE,MAAM,qCAAqC,GAAG,+BAA+B,CAAA;AAEhE,QAAA,qCAAqC,GAAG,kCAAkC,CAAA;AAEvF,IAAY,yBAGX;AAHD,WAAY,yBAAyB;IACnC,8EAAiD,CAAA;IACjD,4FAA+D,CAAA;AACjE,CAAC,EAHW,yBAAyB,yCAAzB,yBAAyB,QAGpC;AAED,IAAY,yBAIX;AAJD,WAAY,yBAAyB;IACnC,2DAA8B,CAAA;IAC9B,6DAAgC,CAAA;IAChC,wDAA2B,CAAA;AAC7B,CAAC,EAJW,yBAAyB,yCAAzB,yBAAyB,QAIpC;AAED,MAAa,mBAAoB,SAAQ,KAAK;IAC5C,YACkB,MAAiC,EACjD,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAA;QAHE,WAAM,GAAN,MAAM,CAA2B;QAIjD,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAA;IACnC,CAAC;CACF;AARD,kDAQC;AAqCD,SAAS,YAAY,CAAC,OAAe;IACnC,OAAO,IAAI,mBAAmB,CAAC,yBAAyB,CAAC,YAAY,EAAE,OAAO,CAAC,CAAA;AACj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AQ,EAAE,CAAC,CAAA;QAC9D,OAAO,KAAK,CAAA;IACd,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAAC,sBAA8B,EAAE,QAAuB;;QACpF,IAAI,UAAyC,CAAA;QAC7C,IAAI,CAAC;YACH,UAAU,GAAG,sBAAe,CAAC,QAAQ,CAAC,QAAQ,EAAE,oCAA6B,CAAC,CAAA;QAChF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,YAAY,CAAC,oBAAoB,sBAAsB,kCAAkC,KAAK,EAAE,CAAC,CAAA;QACzG,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,gBAAgB,CAAC,EAAE,UAAU,EAAE,CAAC,CAAA;YAC/E,IAAI,MAAM,CAAC,OAAO;gBAAE,OAAM;YAE1B,MAAM,YAAY,CAChB,2BAA2B,sBAAsB,iBAAiB,MAAA,MAAM,CAAC,KAAK,mCAAI,yBAAyB,EAAE,CAC9G,CAAA;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,YAAY,mBAAmB;gBAAE,MAAM,KAAK,CAAA;YAErD,MAAM,WAAW,CACf,mDAAmD,sBAAsB,MAAM,KAAK,EAAE,CACvF,CAAA;QACH,CAAC;IACH,CAAC;CACF;AAxQD,sDAwQC"}
@@ -1,8 +1,10 @@
1
1
  import { BaseLogger } from '@credo-ts/core';
2
2
  import { VeranaChainService } from './VeranaChainService';
3
+ import { VeranaIndexerService } from './VeranaIndexerService';
3
4
  import { CachedVsOperatorAuthorizationRecord } from './types';
4
5
  export interface AuthorizationServiceConfig {
5
6
  chain: VeranaChainService;
7
+ indexer: VeranaIndexerService;
6
8
  logger: BaseLogger;
7
9
  corporationId?: number;
8
10
  minRefreshIntervalMs?: number;
@@ -11,13 +13,15 @@ export interface AuthorizationServiceConfig {
11
13
  export declare class AuthorizationService {
12
14
  private vsoaByParticipant;
13
15
  private lastRefreshAt;
16
+ private lastRefreshAtBlock;
14
17
  private readonly chain;
18
+ private readonly indexer;
15
19
  private readonly logger;
16
20
  private readonly corporationId?;
17
21
  private readonly minRefreshIntervalMs;
18
22
  constructor(config: AuthorizationServiceConfig);
19
23
  private inScope;
20
- refreshForOperator(): Promise<void>;
24
+ refreshForOperator(minBlock?: number): Promise<void>;
21
25
  invalidateParticipant(participantId: number): void;
22
26
  canSign(participantId: number, msgType: string): boolean;
23
27
  getVsOperatorAuthorizationRecord(participantId: number): CachedVsOperatorAuthorizationRecord | undefined;
@@ -25,6 +29,4 @@ export declare class AuthorizationService {
25
29
  hasFeegrant(participantId: number): boolean;
26
30
  agentHoldsOperatorGrant(msgType: string): Promise<boolean>;
27
31
  callerHoldsOperatorGrant(account: string, msgType: string): Promise<boolean>;
28
- callerHoldsAnyVsOperatorGrant(account: string, msgType: string): Promise<boolean>;
29
- callerHoldsVsOperatorGrant(account: string, participantId: number, msgType: string): Promise<boolean>;
30
32
  }
@@ -7,19 +7,19 @@ function renews(period) {
7
7
  var _a;
8
8
  return period != null && (period.seconds > 0 || ((_a = period.nanos) !== null && _a !== void 0 ? _a : 0) > 0);
9
9
  }
10
- function isOperatorAuthorizationActive(expiration, period) {
10
+ // An unset expiration means the grant never expires (AUTHZ-CHECK-3 step 4, AUTHZ-CHECK-1 step 2).
11
+ function isAuthorizationActive(expiration, period) {
11
12
  return expiration === undefined || expiration.getTime() > Date.now() || renews(period);
12
13
  }
13
- function isVsoaRecordActive(expiration, period) {
14
- return expiration != null && (expiration.getTime() > Date.now() || renews(period));
15
- }
16
14
  /** VS operator authorization records cached for the admin API (https://github.com/verana-labs/vs-agent/issues/472); operator authorizations are queried on demand. */
17
15
  class AuthorizationService {
18
16
  constructor(config) {
19
17
  var _a;
20
18
  this.vsoaByParticipant = new Map();
21
19
  this.lastRefreshAt = 0;
20
+ this.lastRefreshAtBlock = 0;
22
21
  this.chain = config.chain;
22
+ this.indexer = config.indexer;
23
23
  this.logger = config.logger;
24
24
  this.corporationId = config.corporationId;
25
25
  this.minRefreshIntervalMs = (_a = config.minRefreshIntervalMs) !== null && _a !== void 0 ? _a : 2000;
@@ -27,12 +27,18 @@ class AuthorizationService {
27
27
  inScope(corporationId) {
28
28
  return this.corporationId === undefined || corporationId === this.corporationId;
29
29
  }
30
- async refreshForOperator() {
31
- // Catch-up replays hit the same current chain state, so back-to-back refreshes are skipped.
32
- if (Date.now() - this.lastRefreshAt < this.minRefreshIntervalMs)
30
+ // `minBlock` is the block of the indexer event that triggered the refresh. The delegation
31
+ // projection has its own checkpoint, so without it a read can still answer with pre-event state.
32
+ async refreshForOperator(minBlock) {
33
+ // Catch-up replays hit the same current chain state, so back-to-back refreshes are skipped,
34
+ // unless the caller needs a block this cache has not covered yet.
35
+ const staleForBlock = minBlock !== undefined && minBlock > this.lastRefreshAtBlock;
36
+ if (!staleForBlock && Date.now() - this.lastRefreshAt < this.minRefreshIntervalMs)
33
37
  return;
34
- const vsoas = await this.chain.listVsOperatorAuthorizations();
38
+ const vsoas = await this.indexer.listVsOperatorAuthorizations(this.chain.address, minBlock);
35
39
  this.lastRefreshAt = Date.now();
40
+ if (minBlock !== undefined)
41
+ this.lastRefreshAtBlock = minBlock;
36
42
  const rebuilt = new Map();
37
43
  for (const vsoa of vsoas) {
38
44
  if (!this.inScope(vsoa.corporationId))
@@ -51,7 +57,7 @@ class AuthorizationService {
51
57
  }
52
58
  canSign(participantId, msgType) {
53
59
  const record = this.vsoaByParticipant.get(participantId);
54
- return (!!record && record.msgTypes.includes(msgType) && isVsoaRecordActive(record.expiration, record.period));
60
+ return (!!record && record.msgTypes.includes(msgType) && isAuthorizationActive(record.expiration, record.period));
55
61
  }
56
62
  getVsOperatorAuthorizationRecord(participantId) {
57
63
  return this.vsoaByParticipant.get(participantId);
@@ -72,28 +78,10 @@ class AuthorizationService {
72
78
  async callerHoldsOperatorGrant(account, msgType) {
73
79
  if (!account.trim())
74
80
  return false;
75
- const auths = await this.chain.listOperatorAuthorizations(account);
81
+ const auths = await this.indexer.listOperatorAuthorizations(account);
76
82
  return auths.some(a => this.inScope(a.corporationId) &&
77
83
  a.msgTypes.includes(msgType) &&
78
- isOperatorAuthorizationActive(a.expiration, a.period));
79
- }
80
- async callerHoldsAnyVsOperatorGrant(account, msgType) {
81
- if (!account.trim())
82
- return false;
83
- const vsoas = await this.chain.listVsOperatorAuthorizations(account);
84
- return vsoas.some(vsoa => this.inScope(vsoa.corporationId) &&
85
- vsoa.records.some(r => this.vsoaByParticipant.has(r.participantId) &&
86
- r.msgTypes.includes(msgType) &&
87
- isVsoaRecordActive(r.expiration, r.period)));
88
- }
89
- async callerHoldsVsOperatorGrant(account, participantId, msgType) {
90
- if (!account.trim())
91
- return false;
92
- const vsoas = await this.chain.listVsOperatorAuthorizations(account);
93
- return vsoas.some(vsoa => this.inScope(vsoa.corporationId) &&
94
- vsoa.records.some(r => r.participantId === participantId &&
95
- r.msgTypes.includes(msgType) &&
96
- isVsoaRecordActive(r.expiration, r.period)));
84
+ isAuthorizationActive(a.expiration, a.period));
97
85
  }
98
86
  }
99
87
  exports.AuthorizationService = AuthorizationService;
@@ -1 +1 @@
1
- {"version":3,"file":"AuthorizationService.js","sourceRoot":"","sources":["../../src/blockchain/AuthorizationService.ts"],"names":[],"mappings":";;;AAKA,sFAAsF;AACtF,mFAAmF;AACnF,SAAS,MAAM,CAAC,MAAsB;;IACpC,OAAO,MAAM,IAAI,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,CAAC,IAAI,CAAC,MAAA,MAAM,CAAC,KAAK,mCAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAA;AAC1E,CAAC;AAED,SAAS,6BAA6B,CAAC,UAAiB,EAAE,MAAsB;IAC9E,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,MAAM,CAAC,MAAM,CAAC,CAAA;AACxF,CAAC;AAED,SAAS,kBAAkB,CAAC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AC,iBAAiB,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;QACxD,OAAO,CACL,CAAC,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,IAAI,MAAM,CAAC,UAAU,IAAI,IAAI,IAAI,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CACzG,CAAA;IACH,CAAC;IAED,KAAK,CAAC,uBAAuB,CAAC,OAAe;QAC3C,OAAO,IAAI,CAAC,wBAAwB,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IACnE,CAAC;IAED,uFAAuF;IACvF,KAAK,CAAC,wBAAwB,CAAC,OAAe,EAAE,OAAe;QAC7D,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;YAAE,OAAO,KAAK,CAAA;QACjC,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,0BAA0B,CAAC,OAAO,CAAC,CAAA;QACpE,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,CAAC,EAAE,CACF,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC;YAC7B,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC5B,qBAAqB,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC,CAChD,CAAA;IACH,CAAC;CACF;AA7FD,oDA6FC"}
@@ -7,6 +7,7 @@ export interface IndexerWebSocketServiceOptions {
7
7
  corporationId?: number;
8
8
  agentCorporationId?: number;
9
9
  }
10
+ export type IndexerSyncStatus = 'never-synced' | 'catching-up' | 'disconnected' | 'synced';
10
11
  export declare class IndexerWebSocketService {
11
12
  private readonly options;
12
13
  private ws;
@@ -15,18 +16,22 @@ export declare class IndexerWebSocketService {
15
16
  private watchdog;
16
17
  private stopped;
17
18
  private syncing;
19
+ private phase;
20
+ private everSynced;
18
21
  private generation;
19
22
  private chain;
20
23
  private syncBuffer;
21
- private subscribeSent;
24
+ private settleSubscribed;
22
25
  private readonly indexer;
23
26
  private readonly handlerRegistry;
24
27
  constructor(options: IndexerWebSocketServiceOptions);
25
28
  start(): Promise<void>;
29
+ get syncStatus(): IndexerSyncStatus;
26
30
  stop(): void;
27
31
  private get logger();
28
32
  private connect;
29
33
  private openWebSocket;
34
+ private resolveSubscribed;
30
35
  private handleMessage;
31
36
  private syncRest;
32
37
  private drainSyncBuffer;
@@ -34,6 +39,7 @@ export declare class IndexerWebSocketService {
34
39
  private runExclusive;
35
40
  private applyEvent;
36
41
  private applyChanges;
42
+ private emitNotification;
37
43
  private fetchActivity;
38
44
  private fetchEntity;
39
45
  private armWatchdog;
@@ -29,10 +29,12 @@ class IndexerWebSocketService {
29
29
  this.watchdog = null;
30
30
  this.stopped = false;
31
31
  this.syncing = false;
32
+ this.phase = 'connecting';
33
+ this.everSynced = false;
32
34
  this.generation = 0;
33
35
  this.chain = Promise.resolve();
34
36
  this.syncBuffer = [];
35
- this.subscribeSent = null;
37
+ this.settleSubscribed = null;
36
38
  this.indexer = new VeranaIndexerService_1.VeranaIndexerService({
37
39
  baseUrl: options.indexerUrl,
38
40
  logger: options.agent.config.logger,
@@ -43,6 +45,13 @@ class IndexerWebSocketService {
43
45
  this.stopped = false;
44
46
  await this.connect();
45
47
  }
48
+ get syncStatus() {
49
+ if (this.phase === 'catching-up')
50
+ return 'catching-up';
51
+ if (this.phase === 'synced')
52
+ return 'synced';
53
+ return this.everSynced ? 'disconnected' : 'never-synced';
54
+ }
46
55
  stop() {
47
56
  var _a;
48
57
  this.stopped = true;
@@ -62,14 +71,24 @@ class IndexerWebSocketService {
62
71
  return;
63
72
  const generation = ++this.generation;
64
73
  this.syncing = true;
74
+ this.phase = 'connecting';
65
75
  this.syncBuffer = [];
66
76
  const subscribed = new Promise(resolve => {
67
- this.subscribeSent = resolve;
77
+ this.settleSubscribed = resolve;
68
78
  });
69
79
  this.openWebSocket();
70
- await Promise.race([subscribed, delay(SUBSCRIBE_TIMEOUT_MS)]);
80
+ const outcome = await Promise.race([
81
+ subscribed,
82
+ delay(SUBSCRIBE_TIMEOUT_MS).then(() => 'timed-out'),
83
+ ]);
71
84
  if (this.stopped || generation !== this.generation)
72
85
  return;
86
+ if (outcome === 'disconnected')
87
+ return;
88
+ if (outcome === 'timed-out') {
89
+ this.logger.warn(`[IndexerWS] No 'subscribed' acknowledgement within ${SUBSCRIBE_TIMEOUT_MS}ms; starting the catch-up anyway. Events landing before the subscription becomes active may be missed.`);
90
+ }
91
+ this.phase = 'catching-up';
73
92
  try {
74
93
  await this.syncRest(generation);
75
94
  }
@@ -82,6 +101,8 @@ class IndexerWebSocketService {
82
101
  if (this.stopped || generation !== this.generation)
83
102
  return;
84
103
  this.syncing = false;
104
+ this.phase = 'synced';
105
+ this.everSynced = true;
85
106
  this.drainSyncBuffer(generation);
86
107
  }
87
108
  openWebSocket() {
@@ -98,13 +119,9 @@ class IndexerWebSocketService {
98
119
  if (ws === this.ws)
99
120
  this.logger.info(`[IndexerWS] Connected to indexer`);
100
121
  });
101
- const releaseSubscribeWait = () => {
102
- var _a;
103
- (_a = this.subscribeSent) === null || _a === void 0 ? void 0 : _a.call(this);
104
- this.subscribeSent = null;
105
- };
106
- ws.on('error', releaseSubscribeWait);
107
- ws.on('close', releaseSubscribeWait);
122
+ const abandonSubscribeWait = () => this.resolveSubscribed('disconnected');
123
+ ws.on('error', abandonSubscribeWait);
124
+ ws.on('close', abandonSubscribeWait);
108
125
  ws.on('ping', () => {
109
126
  if (ws === this.ws)
110
127
  this.armWatchdog();
@@ -119,6 +136,7 @@ class IndexerWebSocketService {
119
136
  if (ws !== this.ws)
120
137
  return;
121
138
  this.clearWatchdog();
139
+ this.phase = 'connecting';
122
140
  if (!this.stopped)
123
141
  this.scheduleReconnect();
124
142
  });
@@ -126,6 +144,11 @@ class IndexerWebSocketService {
126
144
  this.logger.error(`[IndexerWS] Error: ${error.message}`);
127
145
  });
128
146
  }
147
+ resolveSubscribed(outcome) {
148
+ var _a;
149
+ (_a = this.settleSubscribed) === null || _a === void 0 ? void 0 : _a.call(this, outcome);
150
+ this.settleSubscribed = null;
151
+ }
129
152
  handleMessage(ws, data) {
130
153
  let message;
131
154
  try {
@@ -140,11 +163,12 @@ class IndexerWebSocketService {
140
163
  const subscribe = this.options.corporationId != null
141
164
  ? { action: 'subscribe', corporationId: this.options.corporationId }
142
165
  : { action: 'subscribe', dids: this.options.agent.did ? [this.options.agent.did] : undefined };
143
- ws.send(JSON.stringify(subscribe), () => {
144
- var _a;
145
- (_a = this.subscribeSent) === null || _a === void 0 ? void 0 : _a.call(this);
146
- this.subscribeSent = null;
147
- });
166
+ ws.send(JSON.stringify(subscribe));
167
+ return;
168
+ }
169
+ if (message.type === 'subscribed') {
170
+ this.logger.debug(`[IndexerWS] Subscription active, delivery starts at block ${message.block}`);
171
+ this.resolveSubscribed('acknowledged');
148
172
  return;
149
173
  }
150
174
  if (message.type !== 'block')
@@ -222,8 +246,7 @@ class IndexerWebSocketService {
222
246
  const activity = await this.fetchActivity(event);
223
247
  if (this.stopped || generation !== this.generation)
224
248
  return;
225
- if (activity)
226
- await this.applyChanges(event, activity, state);
249
+ await this.applyChanges(event, activity, state);
227
250
  if (state.partialBlock === undefined || block > state.partialBlock) {
228
251
  state.partialBlock = block;
229
252
  state.partialKeys = [key];
@@ -238,30 +261,38 @@ class IndexerWebSocketService {
238
261
  async applyChanges(event, activity, state) {
239
262
  const syncState = state !== null && state !== void 0 ? state : (await (0, VeranaHelpers_1.loadSyncState)(this.options.agent));
240
263
  const block = event.block_height;
241
- (0, handlers_1.applyStateMutation)(syncState, activity);
242
- await this.handlerRegistry.dispatch(activity, {
243
- agent: this.options.agent,
244
- blockHeight: block,
245
- operatorAddress: event.payload.sender,
246
- agentCorporationId: this.options.agentCorporationId,
247
- state: syncState,
248
- txHash: event.tx_hash,
249
- });
264
+ if (activity) {
265
+ (0, handlers_1.applyStateMutation)(syncState, activity);
266
+ await this.handlerRegistry.dispatch(activity, {
267
+ agent: this.options.agent,
268
+ blockHeight: block,
269
+ operatorAddress: event.payload.sender,
270
+ agentCorporationId: this.options.agentCorporationId,
271
+ state: syncState,
272
+ txHash: event.tx_hash,
273
+ });
274
+ }
250
275
  if (!state) {
251
276
  syncState.lastBlockHeight = Math.max(syncState.lastBlockHeight, block);
252
277
  await (0, VeranaHelpers_1.saveSyncState)(this.options.agent, syncState);
253
278
  }
279
+ this.emitNotification(event, activity === null || activity === void 0 ? void 0 : activity.changes);
280
+ }
281
+ emitNotification(event, changes) {
282
+ const { payload } = event;
283
+ const resolved = changes && Object.keys(changes).length > 0;
254
284
  try {
255
- (0, events_1.emitVsAgentEvent)(this.options.agent, events_1.VsAgentEventTypes.IndexerNotification, new vs_agent_model_1.IndexerNotification({
256
- msg: activity.msg,
257
- entityType: String(activity.entity_type),
258
- entityId: String(activity.entity_id),
259
- changes: activity.changes,
260
- blockHeight: block,
261
- txHash: event.tx_hash,
262
- operatorAddress: event.payload.sender,
263
- timestamp: new Date(event.timestamp),
264
- }));
285
+ (0, events_1.emitVsAgentEvent)(this.options.agent, events_1.VsAgentEventTypes.IndexerNotification, new vs_agent_model_1.IndexerNotification(Object.assign({ eventType: event.event_type, did: event.did, blockHeight: event.block_height, txHash: event.tx_hash, timestamp: new Date(event.timestamp), payload: {
286
+ module: payload.module,
287
+ action: payload.action,
288
+ messageType: payload.message_type,
289
+ txIndex: payload.tx_index,
290
+ messageIndex: payload.message_index,
291
+ sender: payload.sender,
292
+ relatedDids: payload.related_dids,
293
+ entityType: payload.entity_type,
294
+ entityId: payload.entity_id,
295
+ } }, (resolved ? { changes } : {}))));
265
296
  }
266
297
  catch (err) {
267
298
  this.logger.error(`[IndexerWS] Failed to emit indexer notification: ${err.message}`);
@@ -314,6 +345,7 @@ class IndexerWebSocketService {
314
345
  if (this.stopped)
315
346
  return;
316
347
  this.logger.warn(`[IndexerWS] Forcing reconnect: ${reason}`);
348
+ this.phase = 'connecting';
317
349
  this.generation++; // stops queued work so it cannot move the height past the failed event
318
350
  this.clearWatchdog();
319
351
  const ws = this.ws;