-
Notifications
You must be signed in to change notification settings - Fork 7
/
claims.service.ts
503 lines (446 loc) · 17 KB
/
claims.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
97
98
99
100
101
102
103
104
105
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import { utils, Wallet } from "ethers";
import jsonwebtoken from "jsonwebtoken";
import { v4 } from "uuid";
import { IRoleDefinition, PreconditionType } from "@energyweb/iam-contracts";
import { Methods } from "@ew-did-registry/did";
import { Algorithms } from "@ew-did-registry/jwt";
import { addressOf } from "@ew-did-registry/did-ethr-resolver";
import { hashes, IPublicClaim } from "@ew-did-registry/claims";
import { DIDAttribute } from "@ew-did-registry/did-resolver-interface";
import { ClaimManager__factory } from "../../../ethers/factories/ClaimManager__factory";
import { ERROR_MESSAGES } from "../../errors";
import { emptyAddress } from "../../utils/constants";
import { canonizeSig } from "../../utils/enrollment";
import { CacheClient } from "../cacheClient/cacheClient.service";
import { DomainsService } from "../domains/domains.service";
import { NamespaceType } from "../domains/domains.types";
import { SignerService } from "../signer/signer.service";
import { chainConfigs } from "../../config/chain.config";
import {
IClaimIssuance,
IClaimRejection,
IClaimRequest,
RegistrationTypes,
defaultClaimExpiry,
erc712_type_hash,
proof_type_hash,
typedMsgPrefix,
} from "./claims.types";
import { DidRegistry } from "../didRegistry/didRegistry.service";
import { ClaimData } from "../didRegistry/did.types";
import { isValidDID } from "../../utils/did";
import { JWT } from "@ew-did-registry/jwt";
import { privToPem, KeyType } from "@ew-did-registry/keys";
const { id, keccak256, defaultAbiCoder, solidityKeccak256, namehash, arrayify } = utils;
export class ClaimsService {
private _claimManager: string;
private _claimManagerInterface = ClaimManager__factory.createInterface();
constructor(
private _signerService: SignerService,
private _domainsService: DomainsService,
private _cacheClient: CacheClient,
private _didRegistry: DidRegistry,
) {
this._signerService.onInit(this.init.bind(this));
}
static async create(
signerService: SignerService,
domainsService: DomainsService,
cacheClient: CacheClient,
didRegistry: DidRegistry,
) {
const service = new ClaimsService(signerService, domainsService, cacheClient, didRegistry);
await service.init();
return service;
}
async init() {
const chainId = this._signerService.chainId;
this._claimManager = chainConfigs()[chainId].claimManagerAddress;
}
async getClaimsBySubjects(subjects: string[]) {
return this._cacheClient.getClaimsBySubjects(subjects);
}
/**
* @description - Returns claims for given requester. Allows filtering by status and parent namespace
*/
async getClaimsByRequester({
did,
isAccepted,
namespace,
}: {
did: string;
isAccepted?: boolean;
namespace?: string;
}) {
return this._cacheClient.getClaimsByRequester(did, { isAccepted, namespace });
}
/**
* @description - Returns claims for given issuer. Allows filtering by status and parent namespace
*/
async getClaimsByIssuer({ did, isAccepted, namespace }: { did: string; isAccepted?: boolean; namespace?: string }) {
return this._cacheClient.getClaimsByIssuer(did, { isAccepted, namespace });
}
/**
* @description - Returns claims for given subject. Allows filtering by status and parent namespace
*/
async getClaimsBySubject({
did,
isAccepted,
namespace,
}: {
did: string;
isAccepted?: boolean;
namespace?: string;
}) {
return this._cacheClient.getClaimsBySubject(did, { isAccepted, namespace });
}
/**
* @description - Returns claim with the given Id or null if claim does not exist
*/
async getClaimById(claimId: string) {
return this._cacheClient.getClaimById(claimId);
}
/**
* @description allows subject to request for credential
*/
async createClaimRequest({
claim,
subject = this._signerService.did,
registrationTypes = [RegistrationTypes.OffChain],
}: {
claim: {
claimType: string;
claimTypeVersion: number;
fields: { key: string; value: string | number }[];
issuerFields?: { key: string; value: string | number }[];
};
subject?: string;
registrationTypes?: RegistrationTypes[];
}) {
const { claimType: role, claimTypeVersion: version } = claim;
const token = await this._didRegistry.createPublicClaim({ data: claim, subject });
await this.verifyEnrolmentPrerequisites({ subject, role });
// temporarily, until claimIssuer is not removed from Claim entity
const issuer = [`did:${Methods.Erc1056}:${emptyAddress}`];
const message: IClaimRequest = {
id: v4(),
token,
claimIssuer: issuer,
requester: this._signerService.did,
registrationTypes,
};
if (registrationTypes.includes(RegistrationTypes.OnChain)) {
if (!version) {
throw new Error(ERROR_MESSAGES.ONCHAIN_ROLE_VERSION_NOT_SPECIFIED);
}
message.subjectAgreement = await this.approveRolePublishing({ subject, role, version });
}
await this._cacheClient.requestClaim(subject, message);
}
async issueClaimRequest({
requester,
token,
id,
subjectAgreement,
registrationTypes,
issuerFields,
}: {
requester: string;
token: string;
id: string;
subjectAgreement: string;
registrationTypes: RegistrationTypes[];
issuerFields?: { key: string; value: string | number }[];
}) {
const { claimData, sub } = this._didRegistry.jwt.decode(token) as {
claimData: { claimType: string; claimTypeVersion: number; expiry: number };
sub: string;
};
await this.verifyEnrolmentPrerequisites({ subject: sub, role: claimData.claimType });
const message: IClaimIssuance = {
id,
requester,
claimIssuer: [this._signerService.did],
acceptedBy: this._signerService.did,
};
const strippedClaimData = this.stripClaimData(claimData);
if (registrationTypes.includes(RegistrationTypes.OffChain)) {
const publicClaim: IPublicClaim = {
did: sub,
signer: this._signerService.did,
claimData: { ...strippedClaimData, ...(issuerFields && { issuerFields }) },
};
message.issuedToken = await this._didRegistry.issuePublicClaim({
publicClaim,
});
}
if (registrationTypes.includes(RegistrationTypes.OnChain)) {
const { claimType: role, claimTypeVersion: version } = claimData;
const expiry = claimData.expiry === undefined ? defaultClaimExpiry : claimData.expiry;
const onChainProof = await this.createOnChainProof(role, version, expiry, sub);
const data = this._claimManagerInterface.encodeFunctionData("register", [
addressOf(sub),
namehash(role),
version,
expiry,
addressOf(this._signerService.did),
subjectAgreement,
onChainProof,
]);
await this._signerService.send({
to: this._claimManager,
data,
});
message.onChainProof = onChainProof;
}
return this._cacheClient.issueClaim(this._signerService.did, message);
}
async rejectClaimRequest({ id, requesterDID }: { id: string; requesterDID: string }) {
const message: IClaimRejection = {
id,
requester: requesterDID,
claimIssuer: [this._signerService.did],
isRejected: true,
};
return this._cacheClient.rejectClaim(this._signerService.did, message);
}
async deleteClaim({ id }: { id: string }) {
await this._cacheClient.deleteClaim(id);
}
async issueClaim({
claim,
subject,
}: {
claim: {
claimType: string;
claimTypeVersion: number;
issuerFields: { key: string; value: string | number }[];
};
subject: string;
}) {
await this.verifyEnrolmentPrerequisites({ subject, role: claim.claimType });
const message: IClaimIssuance = {
id: v4(),
requester: subject,
claimIssuer: [this._signerService.did],
acceptedBy: this._signerService.did,
};
const publicClaim: IPublicClaim = {
did: subject,
signer: this._signerService.did,
claimData: claim,
};
message.issuedToken = await this._didRegistry.issuePublicClaim({
publicClaim,
});
await this._cacheClient.issueClaim(this._signerService.did, message);
return message.issuedToken;
}
async getClaimId({ claimData }: { claimData: ClaimData }) {
const { service = [] } = await this._didRegistry.getDidDocument();
const { id, claimTypeVersion } =
service.find(
({ profile, claimType, claimTypeVersion }) =>
Boolean(profile) ||
(claimType === claimData.claimType && claimTypeVersion === claimData.claimTypeVersion),
) || {};
if (claimData.profile && id) {
return id;
}
if (claimData.claimType && id && claimData.claimTypeVersion === claimTypeVersion) {
return id;
}
return v4();
}
/**
* publishPublicClaim
*
* @description store claim data in ipfs and save url to DID document services
* @returns ulr to ipfs
*
*/
async publishPublicClaim({ token }: { token: string }) {
const payload = (await this._didRegistry.decodeJWTToken({ token })) as {
iss: string;
sub: string;
claimData: ClaimData;
};
const { iss, claimData } = payload;
let sub = payload.sub;
// Initialy subject was ignored because it was requester
if (!sub || sub.length === 0 || !isValidDID(sub)) {
sub = this._signerService.did;
}
if (!(await this._didRegistry.verifyPublicClaim(token, iss))) {
throw new Error("Incorrect signature");
}
const url = await this._didRegistry.ipfsStore.save(token);
const data = {
type: DIDAttribute.ServicePoint,
value: {
id: await this.getClaimId({ claimData }),
serviceEndpoint: url,
hash: hashes.SHA256(token),
hashAlg: "SHA256",
},
};
await this._didRegistry.updateDocument({ didAttribute: DIDAttribute.ServicePoint, data, did: sub });
return url;
}
/**
* createSelfSignedClaim
*
* @description creates self signed claim and upload the data to ipfs
*
*/
async createSelfSignedClaim({ data, subject }: { data: ClaimData; subject?: string }) {
const token = await this._didRegistry.createPublicClaim({ data, subject });
return this.publishPublicClaim({ token });
}
/**
* getUserClaims
*
* @description get user claims
*
*/
async getUserClaims({ did = this._signerService.did }: { did?: string } | undefined = {}) {
const { service } = (await this._didRegistry.getDidDocument({ did })) || {};
return service;
}
private async verifyEnrolmentPrerequisites({ subject, role }: { subject: string; role: string }) {
const roleDefinition = await this._domainsService.getDefinition({
type: NamespaceType.Role,
namespace: role,
});
if (!roleDefinition) {
throw new Error(ERROR_MESSAGES.ROLE_NOT_EXISTS);
}
const { enrolmentPreconditions } = roleDefinition as IRoleDefinition;
if (!enrolmentPreconditions || enrolmentPreconditions.length === 0) return;
const enroledRoles = new Set(
(await this.getClaimsBySubject({ did: subject, isAccepted: true })).map(({ claimType }) => claimType),
);
const requiredRoles = new Set(
enrolmentPreconditions
.filter(({ type }) => type === PreconditionType.Role)
.map(({ conditions }) => conditions)
.reduce((all, cur) => all.concat(cur), []),
);
if (Array.from(requiredRoles).some((role) => !enroledRoles.has(role))) {
throw new Error(ERROR_MESSAGES.ROLE_PREREQUISITES_NOT_MET);
}
}
private async createOnChainProof(role: string, version: number, expiry: number, subject: string): Promise<string> {
const messageId = Buffer.from(typedMsgPrefix, "hex");
const chainId = await this._signerService.chainId;
const domainSeparator = utils.keccak256(
defaultAbiCoder.encode(
["bytes32", "bytes32", "bytes32", "uint256", "address"],
[erc712_type_hash, utils.id("Claim Manager"), utils.id("1.0"), chainId, this._claimManager],
),
);
const proofHash = solidityKeccak256(
["bytes", "bytes32", "bytes32"],
[
messageId,
domainSeparator,
utils.keccak256(
defaultAbiCoder.encode(
["bytes32", "address", "bytes32", "uint", "uint", "address"],
[
proof_type_hash,
addressOf(subject),
namehash(role),
version,
expiry,
this._signerService.address,
],
),
),
],
);
return canonizeSig(await this._signerService.signMessage(arrayify(proofHash)));
}
private async approveRolePublishing({
subject,
role,
version,
}: {
subject: string;
role: string;
version: number;
}) {
const erc712_type_hash = id(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)",
);
const agreement_type_hash = id("Agreement(address subject,bytes32 role,uint256 version)");
const chainId = await this._signerService.chainId;
const domainSeparator = keccak256(
defaultAbiCoder.encode(
["bytes32", "bytes32", "bytes32", "uint256", "address"],
[erc712_type_hash, id("Claim Manager"), id("1.0"), chainId, this._claimManager],
),
);
const messageId = Buffer.from(typedMsgPrefix, "hex");
const agreementHash = solidityKeccak256(
["bytes", "bytes32", "bytes32"],
[
messageId,
domainSeparator,
keccak256(
defaultAbiCoder.encode(
["bytes32", "address", "bytes32", "uint256"],
[agreement_type_hash, addressOf(subject), namehash(role), version],
),
),
],
);
return canonizeSig(await this._signerService.signMessage(arrayify(agreementHash)));
}
/**
* @description create a public claim to prove identity
* @returns JWT token of created identity
*/
async createIdentityProof() {
const blockNumber = await this._signerService.provider.getBlockNumber();
return this._didRegistry.createPublicClaim({
data: {
blockNumber,
},
});
}
/**
* @description create a proof of identity delegate
* @param delegateKey private key of the delegate in hexadecimal format
* @param rpcUrl the url of the blockchain provider
* @param identity Did of the delegate
* @returns token of delegate
*/
async createDelegateProof(
delegateKey: string,
identity: string,
algorithm: Algorithms = Algorithms.EIP191,
): Promise<string> {
const provider = this._signerService.provider;
const blockNumber = (await provider.getBlockNumber()).toString();
const payload = {
iss: identity,
claimData: {
blockNumber,
},
};
if (algorithm === Algorithms.EIP191) {
return new JWT(new Wallet(delegateKey)).sign(payload, { issuer: identity });
} else if (algorithm === Algorithms.ES256) {
/** @todo move to @ew-did-registry/jwt */
return jsonwebtoken.sign(payload, privToPem(delegateKey, KeyType.Secp256r1), { issuer: identity });
} else {
throw new Error(ERROR_MESSAGES.JWT_ALGORITHM_NOT_SUPPORTED);
}
}
private stripClaimData(data: ClaimData): ClaimData {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { fields, ...claimData } = data;
return claimData;
}
}