-
Notifications
You must be signed in to change notification settings - Fork 7
/
did-registry.service.ts
474 lines (440 loc) · 12.2 KB
/
did-registry.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
import { Wallet, providers } from 'ethers';
import { KeyType } from '@ew-did-registry/keys';
import { JWT } from '@ew-did-registry/jwt';
import { ProxyOperator } from '@ew-did-registry/proxyidentity';
import {
addressOf,
EwSigner,
Operator,
} from '@ew-did-registry/did-ethr-resolver';
import {
DIDAttribute,
Encoding,
IPublicKey,
IServiceEndpoint,
IUpdateData,
KeyTags,
ProviderTypes,
PubKeyType,
} from '@ew-did-registry/did-resolver-interface';
import {
DIDDocumentFull,
IDIDDocumentFull,
} from '@ew-did-registry/did-document';
import { DidStore } from '@ew-did-registry/did-ipfs-store';
import { Methods } from '@ew-did-registry/did';
import {
ClaimsIssuer,
ClaimsUser,
IPublicClaim,
ProofVerifier,
} from '@ew-did-registry/claims';
import { SignerService } from '../signer/signer.service';
import { ERROR_MESSAGES } from '../../errors';
import { CacheClient } from '../cache-client/cache-client.service';
import { ClaimData } from './did.types';
import { chainConfigs } from '../../config/chain.config';
import { AssetsService } from '../assets/assets.service';
import {
UpdateServicePoint,
UpdateDelegate,
UpdatePublicKey,
} from './did-registry.validation';
import { getLogger } from '../../config/logger.config';
const { JsonRpcProvider } = providers;
export class DidRegistry {
private _identityOwner: EwSigner;
private _operator: Operator;
private _did: string;
private _document: IDIDDocumentFull;
private _ipfsStore: DidStore;
private _jwt: JWT;
private _userClaims: ClaimsUser;
private _issuerClaims: ClaimsIssuer;
constructor(
private _signerService: SignerService,
private _cacheClient: CacheClient,
private _assetsService: AssetsService,
private _ipfsUrl = 'https://ipfs.infura.io:5001/api/v0/'
) {
this._signerService.onInit(this.init.bind(this));
}
static async connect(
signerService: SignerService,
cacheClient: CacheClient,
assetsService: AssetsService,
ipfsUrl?: string
) {
const registry = new DidRegistry(
signerService,
cacheClient,
assetsService,
ipfsUrl
);
await registry.init();
return registry;
}
get jwt() {
return this._jwt;
}
// temporarily, to allow claim service to save claim
get ipfsStore() {
return this._ipfsStore;
}
async init() {
this._ipfsStore = new DidStore(this._ipfsUrl);
await this._setOperator();
this.setJWT();
await this._setDocument();
this._setClaims();
}
async getDidDocument({
did = this._did,
includeClaims = true,
}: { did?: string; includeClaims?: boolean } | undefined = {}) {
if (this._cacheClient) {
try {
const didDoc = await this._cacheClient.getDidDocument(
did,
includeClaims
);
return {
...didDoc,
service: didDoc.service as (IServiceEndpoint & ClaimData)[],
};
} catch (err) {
getLogger().info(err);
throw err;
}
}
const document = await this._operator.read(did);
return {
...document,
service: includeClaims
? await this.downloadClaims({
services:
document.service && document.service.length > 0
? document.service
: [],
})
: [],
};
}
/**
* @description gets list of services endpoints from User's DID document
* @returns list of claims
*/
async getServices({
did = this._signerService.did,
}: { did?: string } | undefined = {}) {
const { service } = (await this.getDidDocument({ did })) || {};
return service;
}
/**
* @description get public keys from User's DID document
* @returns list of public keys
*/
async getDidPublicKeys({
did = this._signerService.did,
}): Promise<IPublicKey[]> {
return (await this.getDidDocument({ did: did, includeClaims: false }))
.publicKey;
}
/**
* @description get public keys from DID's document
* @returns list of DID's delegates
*/
async getDidDelegates({ did = this._did }): Promise<string[] | undefined> {
return (await this.getDidDocument({ did: did, includeClaims: true }))
.delegates;
}
/**
* @description create a public claim based on data provided
* @returns JWT token of created claim
*/
async createPublicClaim({
data,
subject,
}: {
data: ClaimData;
subject?: string;
}) {
if (subject) {
return this._userClaims.createPublicClaim(data, { subject, issuer: '' });
}
return this._userClaims.createPublicClaim(data);
}
/**
* @description issue a public claim
* @returns return issued token
*/
async issuePublicClaim({
token,
publicClaim,
}: {
token?: string;
publicClaim?: IPublicClaim;
}) {
if (publicClaim) {
return this._issuerClaims.issuePublicClaim(publicClaim);
}
if (token) {
return this._issuerClaims.issuePublicClaim(token);
}
throw new Error('unable to issue Public Claim');
}
/**
* @description verifies issued token of claim
* @returns public claim data
*/
async verifyPublicClaim(token: string, iss: string) {
const issuerDoc = await this.getDidDocument({
did: iss,
includeClaims: true,
});
const verifier = new ProofVerifier(issuerDoc);
return verifier.verifyAssertionProof(token);
}
/**
* @param options Options to connect with blockchain
*
* @param options.didAttribute Type of document to be updated
*
* @param options.data New attribute value
* @param options.did Asset did to be updated
* @param options.validity Time (s) for the attribute to expire
*
* @description updates did document based on data provided
* @returns true if document is updated successfuly
*
*/
async updateDocument({
didAttribute,
data,
validity,
did = this._signerService.did,
}: {
didAttribute: DIDAttribute;
data: IUpdateData;
did?: string;
validity?: number;
}): Promise<boolean> {
this.validDateUpdateDocumentRequest({
didAttribute,
data,
did,
});
const didDocument = await this.getDIDDocFull(did);
const updateData: IUpdateData = {
algo: KeyType.Secp256k1,
encoding: Encoding.HEX,
...data,
};
const update = await didDocument.update(didAttribute, updateData, validity);
return Boolean(update);
}
/**
* @description Adds public key to the document of controlled `did`
* @returns true if document is updated successfuly
*/
async updateSignedDidPublicKey({
did = this._signerService.did,
publicKey,
validity,
algo = KeyType.Secp256k1,
type = PubKeyType.SignatureAuthentication2018,
tag = '',
}: {
did: string;
publicKey: string;
algo: KeyType;
type: PubKeyType;
tag: string;
validity?: number;
}): Promise<boolean> {
if (!publicKey)
throw new Error(
ERROR_MESSAGES.CAN_NOT_UPDATE_DOCUMENT_PROPERTIES_INVALID_OR_MISSING +
'publicKey'
);
const didDocument = await this.getDIDDocFull(did);
const isDIdDocUpdated = await didDocument.updatePublicKey({
publicKey,
did: this._signerService.did,
algo,
type,
tag,
validity,
});
return Boolean(isDIdDocUpdated);
}
/**
* @description updates delegate of the document of controlled `did`
* @returns true if document is updated successfuly
*/
async updateSignedDidDelegate({
did = this._signerService.did,
delegatePublicKey,
validity,
algo = KeyType.Secp256k1,
type = PubKeyType.SignatureAuthentication2018,
}: {
did: string;
delegatePublicKey: string;
algo: KeyType;
type: PubKeyType;
validity?: number;
}): Promise<boolean> {
if (!delegatePublicKey)
throw new Error(
ERROR_MESSAGES.CAN_NOT_UPDATE_DOCUMENT_PROPERTIES_INVALID_OR_MISSING +
'delegatePublicKey'
);
const didDocument = await this.getDIDDocFull(did);
const isDIdDocUpdated = await didDocument.updateDelegate({
delegatePublicKey,
algo,
type,
validity,
});
return Boolean(isDIdDocUpdated);
}
/**
* @description create did document if not exists
* @returns true if document is created successfully
*/
async createDocument(): Promise<boolean> {
if (this._cacheClient) {
const cachedDoc = await this._cacheClient.getDidDocument(this._did);
const pubKey = cachedDoc.publicKey.find((pk) =>
pk.id.endsWith(KeyTags.OWNER)
);
if (!pubKey) {
return this._document.create();
}
return true;
}
return this._document.create();
}
/**
* @description revokes did document
* @returns information (true/false) if the DID document was revoked
*/
async revokeDidDocument(): Promise<boolean> {
await this._document.deactivate();
return true;
}
async decodeJWTToken({ token }: { token: string }) {
return this._jwt.decode(token);
}
private async getDIDDocFull(did) {
if (did === this._signerService.did) {
return this._document;
} else {
const assetDID = (await this._assetsService.getOwnedAssets()).find(
(a) => a.document.id === did
)?.id;
if (!assetDID) {
throw new Error(ERROR_MESSAGES.CAN_NOT_UPDATE_NOT_CONTROLLED_DOCUMENT);
}
const { didRegistryAddress: didContractAddress } =
chainConfigs()[this._signerService.chainId];
const operator = new ProxyOperator(
this._identityOwner,
{ address: didContractAddress },
addressOf(assetDID)
);
return new DIDDocumentFull(did, operator);
}
}
private async _setOperator() {
const signer = this._signerService.signer;
const provider = signer.provider;
const publicKey = await this._signerService.publicKey();
if (signer instanceof Wallet && provider instanceof JsonRpcProvider) {
this._identityOwner = EwSigner.fromPrivateKey(signer.privateKey, {
type: ProviderTypes.HTTP,
uriOrInfo: provider.connection.url,
});
} else if (provider instanceof JsonRpcProvider) {
this._identityOwner = EwSigner.fromEthersSigner(signer, publicKey);
} else {
/** @todo from EIP1193Provider */
throw new Error(ERROR_MESSAGES.UNKNOWN_PROVIDER);
}
this._did = `did:${
Methods.Erc1056
}:${this._signerService.chainName()}:${await signer.getAddress()}`;
const address =
chainConfigs()[this._signerService.chainId].didRegistryAddress;
this._operator = new Operator(this._identityOwner, { address });
}
private setJWT() {
this._jwt = new JWT(this._identityOwner);
}
private async _setDocument() {
this._document = new DIDDocumentFull(this._did, this._operator);
}
private _setClaims() {
this._userClaims = new ClaimsUser(
this._identityOwner,
this._document,
this._ipfsStore
);
this._issuerClaims = new ClaimsIssuer(
this._identityOwner,
this._document,
this._ipfsStore
);
}
private async downloadClaims({ services }: { services: IServiceEndpoint[] }) {
return Promise.all(
services.map(async ({ serviceEndpoint, ...rest }) => {
const data = await this._ipfsStore.get(serviceEndpoint);
const { claimData, ...claimRest } = this._jwt?.decode(data) as {
claimData: ClaimData;
};
return {
serviceEndpoint,
...rest,
...claimData,
...claimRest,
} as IServiceEndpoint & ClaimData;
})
);
}
/**
* validates update document request
*/
private validDateUpdateDocumentRequest({
didAttribute,
data,
did,
}: {
didAttribute: DIDAttribute;
data: IUpdateData;
did: string;
}) {
const rq = { didAttribute, data, did };
try {
switch (didAttribute) {
case DIDAttribute.ServicePoint:
UpdateServicePoint.check(rq);
break;
case DIDAttribute.Authenticate:
UpdateDelegate.check(rq);
break;
case DIDAttribute.PublicKey:
UpdatePublicKey.check(rq);
break;
default:
throw new Error('didAttribute invalida or missing');
}
} catch (e) {
throw new Error(
ERROR_MESSAGES.CAN_NOT_UPDATE_DOCUMENT_PROPERTIES_INVALID_OR_MISSING +
(e as Error).message
);
}
}
}