Newer
Older
Berend Sliedrecht
committed
import type { TenantAgent } from '../agent.service.js';
import type {
CredentialExchangeRecord,
CredentialStateChangedEvent,
} from '@credo-ts/core';
Konstantin Tsabolov
committed
EventAnonCredsCredentialOfferGetAll,
EventAnonCredsCredentialOfferGetAllInput,
EventAnonCredsCredentialOfferGetById,
EventAnonCredsCredentialOfferGetByIdInput,
Konstantin Tsabolov
committed
EventAnonCredsCredentialRequestGetAll,
EventAnonCredsCredentialRequestGetAllInput,
Konstantin Tsabolov
committed
EventAnonCredsCredentialRequestGetById,
EventAnonCredsCredentialRequestGetByIdInput,
EventAnonCredsCredentialsDeleteById,
EventAnonCredsCredentialsDeleteByIdInput,
EventAnonCredsCredentialsGetAllInput,
EventAnonCredsCredentialsGetByIdInput,
EventDidcommAnonCredsCredentialsOffer,
EventDidcommAnonCredsCredentialsOfferInput,
EventDidcommAnonCredsCredentialsOfferToSelf,
EventDidcommAnonCredsCredentialsOfferToSelfInput,
import {
AutoAcceptCredential,
CredentialState,
CredentialEventTypes,
} from '@credo-ts/core';
Berend Sliedrecht
committed
import { GenericRecord } from '@credo-ts/core/build/modules/generic-records/repository/GenericRecord.js';
import { Injectable } from '@nestjs/common';
import { logger } from '@ocm/shared';
Berend Sliedrecht
committed
import { GenericRecordTokens, MetadataTokens } from '../../common/constants.js';
import { AgentService } from '../agent.service.js';
import { WithTenantService } from '../withTenantService.js';
@Injectable()
export class AnonCredsCredentialsService {
public constructor(
private withTenantService: WithTenantService,
private agentService: AgentService,
) {}
}: EventAnonCredsCredentialsGetAllInput): Promise<
Array<CredentialExchangeRecord>
> {
return this.withTenantService.invoke(tenantId, (t) =>
t.credentials.getAll(),
);
}
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public async getAllOffers({
tenantId,
}: EventAnonCredsCredentialOfferGetAllInput): Promise<
EventAnonCredsCredentialOfferGetAll['data']
> {
return this.withTenantService.invoke(tenantId, (t) =>
t.credentials.findAllByQuery({
$or: [
{ state: CredentialState.OfferSent },
{ state: CredentialState.OfferReceived },
],
}),
);
}
public async getAllRequests({
tenantId,
}: EventAnonCredsCredentialRequestGetAllInput): Promise<
EventAnonCredsCredentialRequestGetAll['data']
> {
return this.withTenantService.invoke(tenantId, (t) =>
t.credentials.findAllByQuery({
$or: [
{ state: CredentialState.RequestSent },
{ state: CredentialState.RequestReceived },
],
}),
);
}
public async deleteById({
tenantId,
credentialRecordId,
}: EventAnonCredsCredentialsDeleteByIdInput): Promise<
EventAnonCredsCredentialsDeleteById['data']
> {
return this.withTenantService.invoke(tenantId, async (t) => {
await t.credentials.deleteById(credentialRecordId);
return {};
});
}
public async getById({
tenantId,
credentialRecordId,
}: EventAnonCredsCredentialsGetByIdInput): Promise<CredentialExchangeRecord | null> {
return this.withTenantService.invoke(tenantId, (t) =>
t.credentials.findById(credentialRecordId),
);
}
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
public async getOfferById({
tenantId,
credentialOfferId,
}: EventAnonCredsCredentialOfferGetByIdInput): Promise<
EventAnonCredsCredentialOfferGetById['data']
> {
return this.withTenantService.invoke(tenantId, async (t) => {
const credential = await t.credentials.findById(credentialOfferId);
if (
credential &&
credential.state !== CredentialState.OfferSent &&
credential.state !== CredentialState.OfferReceived
) {
logger.warn(
`Credential '${credentialOfferId}' does exist, but is not in offer state. Actual state: ${credential.state}`,
);
}
return credential;
});
}
public async getRequestById({
tenantId,
credentialRequestId,
}: EventAnonCredsCredentialRequestGetByIdInput): Promise<
EventAnonCredsCredentialRequestGetById['data']
> {
return this.withTenantService.invoke(tenantId, async (t) => {
const credential = await t.credentials.findById(credentialRequestId);
if (
credential &&
credential.state !== CredentialState.RequestSent &&
credential.state !== CredentialState.RequestReceived
) {
logger.warn(
`Credential '${credentialRequestId}' does exist, but is not in a request state. Actual state: ${credential.state}`,
);
}
return credential;
});
}
public async offer({
tenantId,
connectionId,
credentialDefinitionId,
attributes,
}: EventDidcommAnonCredsCredentialsOfferInput): Promise<
EventDidcommAnonCredsCredentialsOffer['data']
> {
Berend Sliedrecht
committed
return this.withTenantService.invoke(tenantId, async (t) => {
const revocationRegistryIndex = await this.getNextRevocationIdx(t);
return t.credentials.offerCredential({
protocolVersion: 'v2',
connectionId,
credentialFormats: {
anoncreds: {
credentialDefinitionId,
attributes,
revocationRegistryDefinitionId,
revocationRegistryIndex,
},
Berend Sliedrecht
committed
});
});
}
public async offerToSelf({
tenantId,
credentialDefinitionId,
attributes,
}: EventDidcommAnonCredsCredentialsOfferToSelfInput): Promise<
EventDidcommAnonCredsCredentialsOfferToSelf['data']
> {
return this.withTenantService.invoke(tenantId, async (t) => {
const connections = await t.connections.getAll();
const connection = connections.find((c) => {
const metadata = c.metadata.get<{ withSelf: boolean }>(
Berend Sliedrecht
committed
MetadataTokens.CONNECTION_METADATA_KEY,
);
return metadata && metadata.withSelf === true;
});
if (!connection) {
throw new Error(
'Cannot offer a credential to yourself as there is no connection',
);
}
if (!connection.isReady) {
throw new Error('Connection with yourself is not ready, yet');
}
Berend Sliedrecht
committed
const revocationRegistryIndex = await this.getNextRevocationIdx(t);
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
const acceptOfferListener = new Promise((resolve) => {
this.agentService.agent.events.on<CredentialStateChangedEvent>(
CredentialEventTypes.CredentialStateChanged,
async ({ payload: { credentialRecord } }) => {
const { connectionId } = credentialRecord;
if (
!connectionId ||
credentialRecord.state !== CredentialState.OfferReceived
) {
return;
}
const connectionRecord = await t.connections.getById(connectionId);
const metadata = connectionRecord.metadata.get<{
withSelf: boolean;
}>(MetadataTokens.CONNECTION_METADATA_KEY);
if (!metadata || metadata.withSelf === false) return;
await t.credentials.acceptOffer({
credentialRecordId: credentialRecord.id,
autoAcceptCredential: AutoAcceptCredential.Always,
});
resolve(connectionRecord);
},
);
});
const waitUntilDone = new Promise<CredentialExchangeRecord>((resolve) =>
this.agentService.agent.events.on<CredentialStateChangedEvent>(
CredentialEventTypes.CredentialStateChanged,
({ payload: { credentialRecord } }) => {
if (
credentialRecord.state === CredentialState.Done ||
credentialRecord.state === CredentialState.CredentialIssued
)
resolve(credentialRecord);
},
),
);
void t.credentials.offerCredential({
protocolVersion: 'v2',
autoAcceptCredential: AutoAcceptCredential.Always,
connectionId: connection.id,
credentialFormats: {
anoncreds: {
credentialDefinitionId,
attributes,
revocationRegistryDefinitionId,
revocationRegistryIndex,
},
await acceptOfferListener;
return waitUntilDone;
Berend Sliedrecht
committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// TODO: this is mainly focussed on one revocation status list per issuer. But this is normally not the case. The credential should store the record id in metadata to support multiple generic records. One per revocation status list
private async getNextRevocationIdx(
tenantAgent: TenantAgent,
): Promise<number> {
let recordExists = true;
let genericRecord = await tenantAgent.genericRecords.findById(
GenericRecordTokens.REVOCATION,
);
if (!genericRecord) {
recordExists = false;
genericRecord = new GenericRecord({
id: GenericRecordTokens.REVOCATION,
content: {
revocationIndices: [],
},
});
}
if (
!genericRecord.content.revocationIndices ||
!Array.isArray(genericRecord.content.revocationIndices)
) {
throw new Error(
`Revocation record '${GenericRecordTokens.REVOCATION}' does not have the required revocationIndices in the content. Invalid state has been reached`,
);
}
const highestIdx =
genericRecord.content.revocationIndices.length > 0
? Math.max(...genericRecord.content.revocationIndices)
: 0;
const credentialIdx = highestIdx + 1;
genericRecord.content.revocationIndices.push(credentialIdx);
recordExists
? await tenantAgent.genericRecords.update(genericRecord)
: await tenantAgent.genericRecords.save(genericRecord);
return credentialIdx;
}