@twin.org/immutable-proof-service 0.0.1-next.8 → 0.0.1

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.
@@ -1,15 +1,81 @@
1
- import { Guards, ComponentFactory, StringHelper, Validation, Converter, RandomHelper, ObjectHelper, Urn, GeneralError, Is, NotFoundError, JsonHelper } from '@twin.org/core';
2
- import { ImmutableProofTypes, ImmutableProofFailure } from '@twin.org/immutable-proof-models';
3
- import { DidContexts, DidTypes, DidCryptoSuites } from '@twin.org/standards-w3c-did';
1
+ import { property, SortDirection, entity, EntitySchemaFactory, EntitySchemaHelper } from '@twin.org/entity';
2
+ import { Guards, ComponentFactory, StringHelper, Is, Validation, Converter, RandomHelper, ObjectHelper, Urn, GeneralError, NotFoundError, JsonHelper } from '@twin.org/core';
3
+ import { ImmutableProofTypes, ImmutableProofContexts, ImmutableProofFailure, ImmutableProofTopics } from '@twin.org/immutable-proof-models';
4
+ import { DidCryptoSuites, ProofTypes, DidContexts } from '@twin.org/standards-w3c-did';
4
5
  import { HttpStatusCode, HeaderTypes, MimeTypes } from '@twin.org/web';
5
- import { BackgroundTaskConnectorFactory } from '@twin.org/background-task-models';
6
- import { Blake2b, Sha256 } from '@twin.org/crypto';
6
+ import { BackgroundTaskConnectorFactory, TaskStatus } from '@twin.org/background-task-models';
7
+ import { Sha256 } from '@twin.org/crypto';
7
8
  import { JsonLdHelper, JsonLdProcessor } from '@twin.org/data-json-ld';
8
9
  import { EntityStorageConnectorFactory } from '@twin.org/entity-storage-models';
9
10
  import { IdentityConnectorFactory } from '@twin.org/identity-models';
10
- import { ImmutableStorageConnectorFactory, ImmutableStorageTypes } from '@twin.org/immutable-storage-models';
11
- import { VaultConnectorFactory } from '@twin.org/vault-models';
12
- import { property, SortDirection, entity, EntitySchemaFactory, EntitySchemaHelper } from '@twin.org/entity';
11
+ import { VerifiableStorageConnectorFactory } from '@twin.org/verifiable-storage-models';
12
+
13
+ // Copyright 2024 IOTA Stiftung.
14
+ // SPDX-License-Identifier: Apache-2.0.
15
+ /**
16
+ * Class describing the immutable proof.
17
+ */
18
+ let ImmutableProof = class ImmutableProof {
19
+ /**
20
+ * The id of the proof.
21
+ */
22
+ id;
23
+ /**
24
+ * The identity of the node which controls the proof.
25
+ */
26
+ nodeIdentity;
27
+ /**
28
+ * The identity of the user which created the proof.
29
+ */
30
+ userIdentity;
31
+ /**
32
+ * The date/time of when the proof was created.
33
+ */
34
+ dateCreated;
35
+ /**
36
+ * The associated id for the item.
37
+ */
38
+ proofObjectId;
39
+ /**
40
+ * The associated hash for the item.
41
+ */
42
+ proofObjectHash;
43
+ /**
44
+ * The verifiable storage id.
45
+ */
46
+ verifiableStorageId;
47
+ };
48
+ __decorate([
49
+ property({ type: "string", isPrimary: true }),
50
+ __metadata("design:type", String)
51
+ ], ImmutableProof.prototype, "id", void 0);
52
+ __decorate([
53
+ property({ type: "string" }),
54
+ __metadata("design:type", String)
55
+ ], ImmutableProof.prototype, "nodeIdentity", void 0);
56
+ __decorate([
57
+ property({ type: "string" }),
58
+ __metadata("design:type", String)
59
+ ], ImmutableProof.prototype, "userIdentity", void 0);
60
+ __decorate([
61
+ property({ type: "string", format: "date-time", sortDirection: SortDirection.Descending }),
62
+ __metadata("design:type", String)
63
+ ], ImmutableProof.prototype, "dateCreated", void 0);
64
+ __decorate([
65
+ property({ type: "string", optional: true }),
66
+ __metadata("design:type", String)
67
+ ], ImmutableProof.prototype, "proofObjectId", void 0);
68
+ __decorate([
69
+ property({ type: "string" }),
70
+ __metadata("design:type", String)
71
+ ], ImmutableProof.prototype, "proofObjectHash", void 0);
72
+ __decorate([
73
+ property({ type: "string", optional: true }),
74
+ __metadata("design:type", String)
75
+ ], ImmutableProof.prototype, "verifiableStorageId", void 0);
76
+ ImmutableProof = __decorate([
77
+ entity()
78
+ ], ImmutableProof);
13
79
 
14
80
  /**
15
81
  * The source used when communicating about these routes.
@@ -45,8 +111,8 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
45
111
  id: "immutableProofCreateRequestExample",
46
112
  request: {
47
113
  body: {
48
- proofObject: {
49
- "@context": "http://schema.org",
114
+ document: {
115
+ "@context": "https://schema.org",
50
116
  type: "Person",
51
117
  name: "John Smith"
52
118
  }
@@ -106,15 +172,19 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
106
172
  id: "immutableProofGetResponseExample",
107
173
  response: {
108
174
  body: {
109
- "@context": ImmutableProofTypes.ContextRoot,
175
+ "@context": [
176
+ ImmutableProofContexts.ContextRoot,
177
+ ImmutableProofContexts.ContextRootCommon
178
+ ],
110
179
  type: ImmutableProofTypes.ImmutableProof,
111
180
  id: "ais:1234567890",
181
+ nodeIdentity: "node-1",
112
182
  userIdentity: "user-1",
113
183
  proofObjectId: "test:1234567890",
114
184
  proofObjectHash: "EAOKyDN0mYQbBh91eMdVeroxQx1H4GfnRbmt6n/2L/Y=",
115
185
  proof: {
116
- "@context": DidContexts.ContextVCDataIntegrity,
117
- type: DidTypes.DataIntegrityProof,
186
+ "@context": DidContexts.ContextDataIntegrity,
187
+ type: ProofTypes.DataIntegrityProof,
118
188
  cryptosuite: DidCryptoSuites.EdDSAJcs2022,
119
189
  created: "2024-08-22T11:56:56.272Z",
120
190
  proofPurpose: "assertionMethod",
@@ -136,15 +206,19 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
136
206
  [HeaderTypes.ContentType]: MimeTypes.JsonLd
137
207
  },
138
208
  body: {
139
- "@context": ImmutableProofTypes.ContextRoot,
209
+ "@context": [
210
+ ImmutableProofContexts.ContextRoot,
211
+ ImmutableProofContexts.ContextRootCommon
212
+ ],
140
213
  type: ImmutableProofTypes.ImmutableProof,
141
214
  id: "ais:1234567890",
215
+ nodeIdentity: "node-1",
142
216
  userIdentity: "user-1",
143
217
  proofObjectId: "test:1234567890",
144
218
  proofObjectHash: "EAOKyDN0mYQbBh91eMdVeroxQx1H4GfnRbmt6n/2L/Y=",
145
219
  proof: {
146
- "@context": DidContexts.ContextVCDataIntegrity,
147
- type: DidTypes.DataIntegrityProof,
220
+ "@context": DidContexts.ContextDataIntegrity,
221
+ type: ProofTypes.DataIntegrityProof,
148
222
  cryptosuite: DidCryptoSuites.EdDSAJcs2022,
149
223
  created: "2024-08-22T11:56:56.272Z",
150
224
  proofPurpose: "assertionMethod",
@@ -164,8 +238,8 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
164
238
  operationId: "immutableProofVerify",
165
239
  summary: "Verify a proof",
166
240
  tag: tagsImmutableProof[0].name,
167
- method: "POST",
168
- path: `${baseRouteName}/:id`,
241
+ method: "GET",
242
+ path: `${baseRouteName}/:id/verify`,
169
243
  handler: async (httpRequestContext, request) => immutableProofVerify(httpRequestContext, componentName, request),
170
244
  requestType: {
171
245
  type: "IImmutableProofVerifyRequest",
@@ -175,13 +249,6 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
175
249
  request: {
176
250
  pathParams: {
177
251
  id: "ais:1234567890"
178
- },
179
- body: {
180
- proofObject: {
181
- "@context": "http://schema.org",
182
- type: "Person",
183
- name: "John Smith"
184
- }
185
252
  }
186
253
  }
187
254
  }
@@ -195,7 +262,7 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
195
262
  id: "immutableProofVerifyResponseExample",
196
263
  response: {
197
264
  body: {
198
- "@context": ImmutableProofTypes.ContextRoot,
265
+ "@context": ImmutableProofContexts.ContextRoot,
199
266
  type: ImmutableProofTypes.ImmutableProofVerification,
200
267
  verified: true
201
268
  }
@@ -210,7 +277,7 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
210
277
  id: "immutableProofVerifyResponseFailExample",
211
278
  response: {
212
279
  body: {
213
- "@context": ImmutableProofTypes.ContextRoot,
280
+ "@context": ImmutableProofContexts.ContextRoot,
214
281
  type: ImmutableProofTypes.ImmutableProofVerification,
215
282
  verified: false,
216
283
  failure: ImmutableProofFailure.ProofTypeMismatch
@@ -235,9 +302,9 @@ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
235
302
  */
236
303
  async function immutableProofCreate(httpRequestContext, componentName, request) {
237
304
  Guards.object(ROUTES_SOURCE, "request", request);
238
- Guards.object(ROUTES_SOURCE, "request.body.proofObject", request.body.proofObject);
305
+ Guards.object(ROUTES_SOURCE, "request.body.document", request.body.document);
239
306
  const component = ComponentFactory.get(componentName);
240
- const result = await component.create(request.body.proofObject);
307
+ const result = await component.create(request.body.document, httpRequestContext.userIdentity, httpRequestContext.nodeIdentity);
241
308
  return {
242
309
  statusCode: HttpStatusCode.created,
243
310
  headers: {
@@ -277,10 +344,9 @@ async function immutableProofVerify(httpRequestContext, componentName, request)
277
344
  Guards.object(ROUTES_SOURCE, "request", request);
278
345
  Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
279
346
  Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
280
- Guards.object(ROUTES_SOURCE, "request.body.proofObject", request.body.proofObject);
281
347
  const mimeType = request.headers?.[HeaderTypes.Accept] === MimeTypes.JsonLd ? "jsonld" : "json";
282
348
  const component = ComponentFactory.get(componentName);
283
- const result = await component.verify(request.pathParams.id, request.body.proofObject);
349
+ const result = await component.verify(request.pathParams.id);
284
350
  return {
285
351
  headers: {
286
352
  [HeaderTypes.ContentType]: mimeType === "json" ? MimeTypes.Json : MimeTypes.JsonLd
@@ -308,11 +374,6 @@ class ImmutableProofService {
308
374
  * @internal
309
375
  */
310
376
  _config;
311
- /**
312
- * The vault connector.
313
- * @internal
314
- */
315
- _vaultConnector;
316
377
  /**
317
378
  * The identity connector.
318
379
  * @internal
@@ -324,75 +385,89 @@ class ImmutableProofService {
324
385
  */
325
386
  _proofStorage;
326
387
  /**
327
- * The immutable storage for the credentials.
388
+ * The verifiable storage for the credentials.
328
389
  * @internal
329
390
  */
330
- _immutableStorage;
391
+ _verifiableStorage;
331
392
  /**
332
393
  * The background task connector.
333
394
  * @internal
334
395
  */
335
396
  _backgroundTaskConnector;
336
397
  /**
337
- * The assertion method id to use for the proofs.
398
+ * The event bus component.
399
+ * @internal
400
+ */
401
+ _eventBusComponent;
402
+ /**
403
+ * The verification method id to use for the proofs.
338
404
  * @internal
339
405
  */
340
- _assertionMethodId;
406
+ _verificationMethodId;
341
407
  /**
342
- * The proof hash key id to use for the proofs.
408
+ * The identity connector type.
343
409
  * @internal
344
410
  */
345
- _proofHashKeyId;
411
+ _identityConnectorType;
346
412
  /**
347
413
  * Create a new instance of ImmutableProofService.
348
414
  * @param options The dependencies for the immutable proof connector.
349
- * @param options.config The configuration for the connector.
350
- * @param options.vaultConnectorType The vault connector type, defaults to "vault".
351
- * @param options.immutableProofEntityStorageType The entity storage for proofs, defaults to "immutable-proof".
352
- * @param options.immutableStorageType The immutable storage, defaults to "immutable-storage".
353
- * @param options.identityConnectorType The identity connector type, defaults to "identity".
354
- * @param options.backgroundTaskConnectorType The background task connector type, defaults to "background-task".
355
415
  */
356
416
  constructor(options) {
357
- this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
358
417
  this._proofStorage = EntityStorageConnectorFactory.get(options?.immutableProofEntityStorageType ?? StringHelper.kebabCase("ImmutableProof"));
359
- this._immutableStorage = ImmutableStorageConnectorFactory.get(options?.immutableStorageType ?? "immutable-storage");
360
- this._identityConnector = IdentityConnectorFactory.get(options?.identityConnectorType ?? "identity");
418
+ this._verifiableStorage = VerifiableStorageConnectorFactory.get(options?.verifiableStorageType ?? "verifiable-storage");
419
+ this._identityConnectorType = options?.identityConnectorType ?? "identity";
420
+ this._identityConnector = IdentityConnectorFactory.get(this._identityConnectorType);
361
421
  this._backgroundTaskConnector = BackgroundTaskConnectorFactory.get(options?.backgroundTaskConnectorType ?? "background-task");
422
+ if (Is.stringValue(options?.eventBusComponentType)) {
423
+ this._eventBusComponent = ComponentFactory.get(options.eventBusComponentType);
424
+ }
362
425
  this._config = options?.config ?? {};
363
- this._assertionMethodId = this._config.assertionMethodId ?? "immutable-proof-assertion";
364
- this._proofHashKeyId = this._config.proofHashKeyId ?? "immutable-proof-hash";
365
- this._backgroundTaskConnector.registerHandler("immutable-proof", async (proof) => this.processProof(proof));
426
+ this._verificationMethodId = this._config.verificationMethodId ?? "immutable-proof-assertion";
427
+ this._backgroundTaskConnector.registerHandler("immutable-proof", "@twin.org/immutable-proof-task", "processProofTask", async (task) => {
428
+ await this.finaliseTask(task);
429
+ });
366
430
  }
367
431
  /**
368
- * Create a new authentication proof.
369
- * @param proofObject The object for the proof as JSON-LD.
432
+ * Create a new proof.
433
+ * @param document The document to create the proof for.
370
434
  * @param userIdentity The identity to create the immutable proof operation with.
371
435
  * @param nodeIdentity The node identity to use for vault operations.
372
- * @returns The id of the new authentication proof.
436
+ * @returns The id of the new proof.
373
437
  */
374
- async create(proofObject, userIdentity, nodeIdentity) {
375
- Guards.object(this.CLASS_NAME, "proofObject", proofObject);
438
+ async create(document, userIdentity, nodeIdentity) {
439
+ Guards.object(this.CLASS_NAME, "document", document);
376
440
  Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
377
441
  Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
378
442
  try {
379
443
  const validationFailures = [];
380
- await JsonLdHelper.validate(proofObject, validationFailures);
381
- Validation.asValidationError(this.CLASS_NAME, "proofObject", validationFailures);
444
+ await JsonLdHelper.validate(document, validationFailures);
445
+ Validation.asValidationError(this.CLASS_NAME, "document", validationFailures);
382
446
  const id = Converter.bytesToHex(RandomHelper.generate(32), false);
383
447
  const dateCreated = new Date(Date.now()).toISOString();
384
- const proofObjectId = ObjectHelper.extractProperty(proofObject, ["@id", "id"], false);
385
- const hash = this.calculateHash(id, dateCreated, nodeIdentity, userIdentity, proofObject);
448
+ const proofObjectId = ObjectHelper.extractProperty(document, ["@id", "id"], false);
449
+ // We don't want to store the whole document in the immutable proof, as this could be large
450
+ // and also reveal information that should not be stored in the proof so we hash the document
451
+ // and store the hash
452
+ const proofObjectHash = this.calculateDocumentHash(document);
386
453
  const proofEntity = {
387
454
  id,
388
455
  nodeIdentity,
389
456
  userIdentity,
390
457
  dateCreated,
391
458
  proofObjectId,
392
- proofObjectHash: Converter.bytesToBase64(hash)
459
+ proofObjectHash
393
460
  };
394
461
  await this._proofStorage.set(proofEntity);
395
- await this._backgroundTaskConnector.create("immutable-proof", proofEntity);
462
+ const immutableProof = this.proofEntityToJsonLd(proofEntity);
463
+ const proofTaskPayload = {
464
+ proofId: id,
465
+ nodeIdentity,
466
+ identityConnectorType: this._identityConnectorType,
467
+ verificationMethodId: this._verificationMethodId,
468
+ document: immutableProof
469
+ };
470
+ await this._backgroundTaskConnector.create("immutable-proof", proofTaskPayload);
396
471
  return new Urn(ImmutableProofService.NAMESPACE, id).toString();
397
472
  }
398
473
  catch (error) {
@@ -400,7 +475,7 @@ class ImmutableProofService {
400
475
  }
401
476
  }
402
477
  /**
403
- * Get an authentication proof.
478
+ * Get a proof.
404
479
  * @param id The id of the proof to get.
405
480
  * @returns The proof.
406
481
  * @throws NotFoundError if the proof is not found.
@@ -415,22 +490,20 @@ class ImmutableProofService {
415
490
  });
416
491
  }
417
492
  try {
418
- const { immutableProof } = await this.internalGet(id);
419
- const compacted = await JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
420
- return compacted;
493
+ const { immutableProof } = await this.internalGet(id, false);
494
+ return JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
421
495
  }
422
496
  catch (error) {
423
497
  throw new GeneralError(this.CLASS_NAME, "getFailed", undefined, error);
424
498
  }
425
499
  }
426
500
  /**
427
- * Verify an authentication proof.
501
+ * Verify a proof.
428
502
  * @param id The id of the proof to verify.
429
- * @param proofObject The object to verify as JSON-LD.
430
503
  * @returns The result of the verification and any failures.
431
504
  * @throws NotFoundError if the proof is not found.
432
505
  */
433
- async verify(id, proofObject) {
506
+ async verify(id) {
434
507
  Guards.stringValue(this.CLASS_NAME, "id", id);
435
508
  const urnParsed = Urn.fromValidString(id);
436
509
  if (urnParsed.namespaceIdentifier() !== ImmutableProofService.NAMESPACE) {
@@ -440,9 +513,9 @@ class ImmutableProofService {
440
513
  });
441
514
  }
442
515
  try {
443
- const { verified, failure } = await this.internalGet(id, proofObject);
516
+ const { verified, failure } = await this.internalGet(id, true);
444
517
  return {
445
- "@context": ImmutableProofTypes.ContextRoot,
518
+ "@context": ImmutableProofContexts.ContextRoot,
446
519
  type: ImmutableProofTypes.ImmutableProofVerification,
447
520
  verified,
448
521
  failure
@@ -453,13 +526,13 @@ class ImmutableProofService {
453
526
  }
454
527
  }
455
528
  /**
456
- * Remove the immutable storage for the proof.
529
+ * Remove the verifiable storage for the proof.
457
530
  * @param id The id of the proof to remove the storage from.
458
531
  * @param nodeIdentity The node identity to use for vault operations.
459
532
  * @returns Nothing.
460
533
  * @throws NotFoundError if the proof is not found.
461
534
  */
462
- async removeImmutable(id, nodeIdentity) {
535
+ async removeVerifiable(id, nodeIdentity) {
463
536
  Guards.stringValue(this.CLASS_NAME, "id", id);
464
537
  Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
465
538
  const urnParsed = Urn.fromValidString(id);
@@ -475,14 +548,14 @@ class ImmutableProofService {
475
548
  if (Is.empty(streamEntity)) {
476
549
  throw new NotFoundError(this.CLASS_NAME, "proofNotFound", id);
477
550
  }
478
- if (Is.stringValue(streamEntity.immutableStorageId)) {
479
- await this._immutableStorage.remove(nodeIdentity, streamEntity.immutableStorageId);
480
- delete streamEntity.immutableStorageId;
551
+ if (Is.stringValue(streamEntity.verifiableStorageId)) {
552
+ await this._verifiableStorage.remove(nodeIdentity, streamEntity.verifiableStorageId);
553
+ delete streamEntity.verifiableStorageId;
481
554
  await this._proofStorage.set(streamEntity);
482
555
  }
483
556
  }
484
557
  catch (error) {
485
- throw new GeneralError(this.CLASS_NAME, "removeImmutableFailed", undefined, error);
558
+ throw new GeneralError(this.CLASS_NAME, "removeVerifiableFailed", undefined, error);
486
559
  }
487
560
  }
488
561
  /**
@@ -491,14 +564,8 @@ class ImmutableProofService {
491
564
  * @returns The hash.
492
565
  * @internal
493
566
  */
494
- calculateHash(id, dateCreated, nodeIdentity, userIdentity, proofObject) {
495
- const b2b = new Blake2b(Blake2b.SIZE_256);
496
- b2b.update(Converter.utf8ToBytes(id));
497
- b2b.update(Converter.utf8ToBytes(dateCreated));
498
- b2b.update(Converter.utf8ToBytes(nodeIdentity));
499
- b2b.update(Converter.utf8ToBytes(userIdentity));
500
- b2b.update(ObjectHelper.toBytes(proofObject));
501
- return b2b.digest();
567
+ calculateDocumentHash(nodeObject) {
568
+ return `sha256:${Converter.bytesToBase64(Sha256.sum256(ObjectHelper.toBytes(JsonHelper.canonicalize(nodeObject))))}`;
502
569
  }
503
570
  /**
504
571
  * Map the stream entity to a model.
@@ -507,76 +574,83 @@ class ImmutableProofService {
507
574
  * @internal
508
575
  */
509
576
  proofEntityToJsonLd(proofEntity) {
510
- const model = {
511
- "@context": ImmutableProofTypes.ContextRoot,
577
+ const jsonLd = {
578
+ "@context": [ImmutableProofContexts.ContextRoot, ImmutableProofContexts.ContextRootCommon],
512
579
  type: ImmutableProofTypes.ImmutableProof,
513
580
  id: proofEntity.id,
581
+ nodeIdentity: proofEntity.nodeIdentity,
514
582
  userIdentity: proofEntity.userIdentity,
515
583
  proofObjectId: proofEntity.proofObjectId,
516
- proofObjectHash: proofEntity.proofObjectHash
584
+ proofObjectHash: proofEntity.proofObjectHash,
585
+ verifiableStorageId: proofEntity.verifiableStorageId
517
586
  };
518
- return model;
587
+ return jsonLd;
519
588
  }
520
589
  /**
521
590
  * Process a proof.
522
591
  * @param proofEntity The proof entity to process.
523
592
  * @internal
524
593
  */
525
- async processProof(proofEntity) {
526
- const immutableProof = this.proofEntityToJsonLd(proofEntity);
527
- const hashData = await this.generateHashData(proofEntity.nodeIdentity, immutableProof);
528
- // As we are adding the proof to the data we update its context
529
- immutableProof["@context"] = [
530
- ImmutableProofTypes.ContextRoot,
531
- DidContexts.ContextVCDataIntegrity
532
- ];
533
- immutableProof.proof = await this._identityConnector.createProof(proofEntity.nodeIdentity, `${proofEntity.nodeIdentity}#${this._assertionMethodId}`, hashData);
534
- if (Is.stringValue(immutableProof.proof.created)) {
535
- proofEntity.dateCreated = immutableProof.proof.created;
594
+ async finaliseTask(task) {
595
+ if (task.status === TaskStatus.Success && Is.object(task.payload) && Is.object(task.result)) {
596
+ const proofEntity = await this._proofStorage.get(task.payload.proofId);
597
+ if (Is.object(proofEntity)) {
598
+ const immutableProof = this.proofEntityToJsonLd(proofEntity);
599
+ // As we are adding the proof to the data we update its context
600
+ immutableProof["@context"] = JsonLdProcessor.combineContexts([ImmutableProofContexts.ContextRoot, ImmutableProofContexts.ContextRootCommon], task.result.proof["@context"]);
601
+ immutableProof.proof = task.result.proof;
602
+ ObjectHelper.propertyDelete(immutableProof.proof, "@context");
603
+ if (Is.stringValue(immutableProof.proof.created)) {
604
+ proofEntity.dateCreated = immutableProof.proof.created;
605
+ }
606
+ const compacted = await JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
607
+ const verifiableCreateResult = await this._verifiableStorage.create(proofEntity.nodeIdentity, ObjectHelper.toBytes(compacted));
608
+ proofEntity.verifiableStorageId = verifiableCreateResult.id;
609
+ await this._proofStorage.set(proofEntity);
610
+ await this._eventBusComponent?.publish(ImmutableProofTopics.ProofCreated, { id: new Urn(ImmutableProofService.NAMESPACE, task.payload.proofId).toString() });
611
+ }
536
612
  }
537
- const compacted = await JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
538
- const immutableStoreResult = await this._immutableStorage.store(proofEntity.nodeIdentity, ObjectHelper.toBytes(compacted));
539
- proofEntity.immutableStorageId = immutableStoreResult.id;
540
- await this._proofStorage.set(proofEntity);
541
613
  }
542
614
  /**
543
- * Verify an authentication proof.
615
+ * Verify a proof.
544
616
  * @param id The id of the proof to verify.
545
- * @param proofObject The object to verify as JSON-LD.
617
+ * @param verify Validate the proof.
546
618
  * @returns The result of the verification and any failures.
547
619
  * @throws NotFoundError if the proof is not found.
548
620
  * @internal
549
621
  */
550
- async internalGet(id, proofObject) {
622
+ async internalGet(id, verify) {
551
623
  const urnParsed = Urn.fromValidString(id);
552
624
  const proofId = urnParsed.namespaceSpecific(0);
553
625
  const proofEntity = await this._proofStorage.get(proofId);
554
626
  if (Is.empty(proofEntity)) {
555
627
  throw new NotFoundError(this.CLASS_NAME, "proofNotFound", id);
556
628
  }
557
- let proofModel = await this.proofEntityToJsonLd(proofEntity);
629
+ let proofJsonLd = this.proofEntityToJsonLd(proofEntity);
558
630
  let verified = false;
559
631
  let failure = ImmutableProofFailure.NotIssued;
560
- if (Is.stringValue(proofEntity.immutableStorageId)) {
632
+ if (Is.stringValue(proofEntity.verifiableStorageId)) {
561
633
  failure = ImmutableProofFailure.ProofMissing;
562
- const immutableResult = await this._immutableStorage.get(proofEntity.immutableStorageId);
634
+ const immutableResult = await this._verifiableStorage.get(proofEntity.verifiableStorageId);
563
635
  if (Is.uint8Array(immutableResult.data)) {
564
- proofModel = ObjectHelper.fromBytes(immutableResult.data);
565
- proofModel.immutableReceipt = immutableResult.receipt;
566
- // As we are adding the receipt to the data we update its context
567
- if (Is.array(proofModel["@context"])) {
568
- proofModel["@context"].push(ImmutableStorageTypes.ContextRoot);
636
+ proofJsonLd = ObjectHelper.fromBytes(immutableResult.data);
637
+ const unsecureDocument = ObjectHelper.clone(proofJsonLd);
638
+ proofJsonLd.immutableReceipt = immutableResult.receipt;
639
+ proofJsonLd.verifiableStorageId = proofEntity.verifiableStorageId;
640
+ // As we are adding the receipt to the data we update the JSON-LD context
641
+ const receiptContext = immutableResult.receipt["@context"];
642
+ if (!Is.empty(receiptContext)) {
643
+ proofJsonLd["@context"] = JsonLdProcessor.combineContexts(proofJsonLd["@context"], receiptContext);
569
644
  }
570
- if (Is.object(proofModel.proof) && Is.object(proofObject)) {
571
- if (proofModel.proof.cryptosuite !== DidCryptoSuites.EdDSAJcs2022) {
645
+ if (verify && Is.object(proofJsonLd.proof)) {
646
+ if (proofJsonLd.proof.cryptosuite !== DidCryptoSuites.EdDSAJcs2022) {
572
647
  failure = ImmutableProofFailure.CryptoSuiteMismatch;
573
648
  }
574
- else if (proofModel.proof.type !== DidTypes.DataIntegrityProof) {
649
+ else if (proofJsonLd.proof.type !== ProofTypes.DataIntegrityProof) {
575
650
  failure = ImmutableProofFailure.ProofTypeMismatch;
576
651
  }
577
652
  else {
578
- const hashData = await this.generateHashData(proofEntity.nodeIdentity, proofModel);
579
- const isVerified = await this._identityConnector.verifyProof(hashData, proofModel.proof);
653
+ const isVerified = await this._identityConnector.verifyProof(unsecureDocument, proofJsonLd.proof);
580
654
  if (isVerified) {
581
655
  verified = true;
582
656
  failure = undefined;
@@ -589,102 +663,13 @@ class ImmutableProofService {
589
663
  }
590
664
  }
591
665
  return {
592
- immutableProof: proofModel,
666
+ immutableProof: proofJsonLd,
593
667
  verified,
594
668
  failure
595
669
  };
596
670
  }
597
- /**
598
- * Generate the hash data for the proof.
599
- * Conforms to https://www.w3.org/TR/vc-di-eddsa/#create-proof-eddsa-jcs-2022
600
- * @param nodeIdentity The node identity to use for vault operations.
601
- * @param immutableProof The immutable proof to generate the hash data for.
602
- * @returns The hash data.
603
- * @internal
604
- */
605
- async generateHashData(nodeIdentity, immutableProof) {
606
- // We hash the data for the proof without the the proof or immutable receipt for the proof
607
- // without these objects we can simplify the context
608
- const object = ObjectHelper.omit(immutableProof, ["proof", "immutableReceipt"]);
609
- object["@context"] = ImmutableProofTypes.ContextRoot;
610
- const canonicalDocument = JsonHelper.canonicalize(object);
611
- const proofKey = await this._vaultConnector.getKey(`${nodeIdentity}/${this._proofHashKeyId}`);
612
- const proofHash = Sha256.sum256(proofKey.privateKey);
613
- const transformedDocumentHash = Sha256.sum256(Converter.utf8ToBytes(canonicalDocument));
614
- const hashData = new Uint8Array(proofHash.length + transformedDocumentHash.length);
615
- hashData.set(proofHash);
616
- hashData.set(transformedDocumentHash, proofHash.length);
617
- return hashData;
618
- }
619
671
  }
620
672
 
621
- // Copyright 2024 IOTA Stiftung.
622
- // SPDX-License-Identifier: Apache-2.0.
623
- /**
624
- * Class describing the immutable proof.
625
- */
626
- let ImmutableProof = class ImmutableProof {
627
- /**
628
- * The id of the proof.
629
- */
630
- id;
631
- /**
632
- * The identity of the node which controls the proof.
633
- */
634
- nodeIdentity;
635
- /**
636
- * The identity of the user which created the proof.
637
- */
638
- userIdentity;
639
- /**
640
- * The date/time of when the proof was created.
641
- */
642
- dateCreated;
643
- /**
644
- * The associated id for the item.
645
- */
646
- proofObjectId;
647
- /**
648
- * The associated hash for the item.
649
- */
650
- proofObjectHash;
651
- /**
652
- * The immutable storage id.
653
- */
654
- immutableStorageId;
655
- };
656
- __decorate([
657
- property({ type: "string", isPrimary: true }),
658
- __metadata("design:type", String)
659
- ], ImmutableProof.prototype, "id", void 0);
660
- __decorate([
661
- property({ type: "string" }),
662
- __metadata("design:type", String)
663
- ], ImmutableProof.prototype, "nodeIdentity", void 0);
664
- __decorate([
665
- property({ type: "string" }),
666
- __metadata("design:type", String)
667
- ], ImmutableProof.prototype, "userIdentity", void 0);
668
- __decorate([
669
- property({ type: "string", format: "date-time", sortDirection: SortDirection.Descending }),
670
- __metadata("design:type", String)
671
- ], ImmutableProof.prototype, "dateCreated", void 0);
672
- __decorate([
673
- property({ type: "string" }),
674
- __metadata("design:type", String)
675
- ], ImmutableProof.prototype, "proofObjectId", void 0);
676
- __decorate([
677
- property({ type: "string" }),
678
- __metadata("design:type", String)
679
- ], ImmutableProof.prototype, "proofObjectHash", void 0);
680
- __decorate([
681
- property({ type: "string" }),
682
- __metadata("design:type", String)
683
- ], ImmutableProof.prototype, "immutableStorageId", void 0);
684
- ImmutableProof = __decorate([
685
- entity()
686
- ], ImmutableProof);
687
-
688
673
  const restEntryPoints = [
689
674
  {
690
675
  name: "immutable-proof",