@twin.org/immutable-proof-service 0.0.1-next.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.
@@ -0,0 +1,713 @@
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';
4
+ import { HttpStatusCode, HeaderTypes, MimeTypes } from '@twin.org/web';
5
+ import { Blake2b, Sha256 } from '@twin.org/crypto';
6
+ import { JsonLdHelper, JsonLdProcessor } from '@twin.org/data-json-ld';
7
+ import { SchemaOrgDataTypes, SchemaOrgTypes } from '@twin.org/data-schema-org';
8
+ import { ComparisonOperator, SortDirection, property, entity, EntitySchemaFactory, EntitySchemaHelper } from '@twin.org/entity';
9
+ import { EntityStorageConnectorFactory } from '@twin.org/entity-storage-models';
10
+ import { IdentityConnectorFactory } from '@twin.org/identity-models';
11
+ import { ImmutableStorageConnectorFactory } from '@twin.org/immutable-storage-models';
12
+ import { VaultConnectorFactory } from '@twin.org/vault-models';
13
+
14
+ /**
15
+ * The source used when communicating about these routes.
16
+ */
17
+ const ROUTES_SOURCE = "immutableProofRoutes";
18
+ /**
19
+ * The tag to associate with the routes.
20
+ */
21
+ const tagsImmutableProof = [
22
+ {
23
+ name: "Immutable Proof",
24
+ description: "Endpoints which are modelled to access an immutable proof contract."
25
+ }
26
+ ];
27
+ /**
28
+ * The REST routes for immutable proof.
29
+ * @param baseRouteName Prefix to prepend to the paths.
30
+ * @param componentName The name of the component to use in the routes stored in the ComponentFactory.
31
+ * @returns The generated routes.
32
+ */
33
+ function generateRestRoutesImmutableProof(baseRouteName, componentName) {
34
+ const createRoute = {
35
+ operationId: "immutableProofCreate",
36
+ summary: "Create a proof",
37
+ tag: tagsImmutableProof[0].name,
38
+ method: "POST",
39
+ path: `${baseRouteName}/`,
40
+ handler: async (httpRequestContext, request) => immutableProofCreate(httpRequestContext, componentName, request),
41
+ requestType: {
42
+ type: "IImmutableProofCreateRequest",
43
+ examples: [
44
+ {
45
+ id: "immutableProofCreateRequestExample",
46
+ request: {
47
+ body: {
48
+ proofObject: {
49
+ "@context": "http://schema.org",
50
+ type: "Person",
51
+ name: "John Smith"
52
+ }
53
+ }
54
+ }
55
+ }
56
+ ]
57
+ },
58
+ responseType: [
59
+ {
60
+ type: "ICreatedResponse",
61
+ examples: [
62
+ {
63
+ id: "immutableProofCreateResponseExample",
64
+ response: {
65
+ statusCode: HttpStatusCode.created,
66
+ headers: {
67
+ [HeaderTypes.Location]: "test:1234567890"
68
+ }
69
+ }
70
+ }
71
+ ]
72
+ },
73
+ {
74
+ type: "INotFoundResponse"
75
+ }
76
+ ]
77
+ };
78
+ const getRoute = {
79
+ operationId: "immutableProofGet",
80
+ summary: "Get a proof",
81
+ tag: tagsImmutableProof[0].name,
82
+ method: "GET",
83
+ path: `${baseRouteName}/:id`,
84
+ handler: async (httpRequestContext, request) => immutableProofGet(httpRequestContext, componentName, request),
85
+ requestType: {
86
+ type: "IImmutableProofGetRequest",
87
+ examples: [
88
+ {
89
+ id: "immutableProofGetRequestExample",
90
+ request: {
91
+ headers: {
92
+ [HeaderTypes.Accept]: MimeTypes.Json
93
+ },
94
+ pathParams: {
95
+ id: "ais:1234567890"
96
+ }
97
+ }
98
+ }
99
+ ]
100
+ },
101
+ responseType: [
102
+ {
103
+ type: "IImmutableProofGetResponse",
104
+ examples: [
105
+ {
106
+ id: "immutableProofGetResponseExample",
107
+ response: {
108
+ body: {
109
+ "@context": ImmutableProofTypes.ContextRoot,
110
+ type: ImmutableProofTypes.ImmutableProof,
111
+ id: "ais:1234567890",
112
+ userIdentity: "user-1",
113
+ proofObjectId: "test:1234567890",
114
+ proofObjectHash: "EAOKyDN0mYQbBh91eMdVeroxQx1H4GfnRbmt6n/2L/Y=",
115
+ proof: {
116
+ "@context": DidContexts.ContextVCDataIntegrity,
117
+ type: DidTypes.DataIntegrityProof,
118
+ cryptosuite: DidCryptoSuites.EdDSAJcs2022,
119
+ created: "2024-08-22T11:56:56.272Z",
120
+ proofPurpose: "assertionMethod",
121
+ proofValue: "7DdiPPYtxLjCD3wA1po2rv..."
122
+ }
123
+ }
124
+ }
125
+ }
126
+ ]
127
+ },
128
+ {
129
+ type: "IImmutableProofGetResponse",
130
+ mimeType: MimeTypes.JsonLd,
131
+ examples: [
132
+ {
133
+ id: "immutableProofJsonLdGetResponseExample",
134
+ response: {
135
+ headers: {
136
+ [HeaderTypes.ContentType]: MimeTypes.JsonLd
137
+ },
138
+ body: {
139
+ "@context": ImmutableProofTypes.ContextRoot,
140
+ type: ImmutableProofTypes.ImmutableProof,
141
+ id: "ais:1234567890",
142
+ userIdentity: "user-1",
143
+ proofObjectId: "test:1234567890",
144
+ proofObjectHash: "EAOKyDN0mYQbBh91eMdVeroxQx1H4GfnRbmt6n/2L/Y=",
145
+ proof: {
146
+ "@context": DidContexts.ContextVCDataIntegrity,
147
+ type: DidTypes.DataIntegrityProof,
148
+ cryptosuite: DidCryptoSuites.EdDSAJcs2022,
149
+ created: "2024-08-22T11:56:56.272Z",
150
+ proofPurpose: "assertionMethod",
151
+ proofValue: "7DdiPPYtxLjCD3wA1po2rv..."
152
+ }
153
+ }
154
+ }
155
+ }
156
+ ]
157
+ },
158
+ {
159
+ type: "INotFoundResponse"
160
+ }
161
+ ]
162
+ };
163
+ const verifyRoute = {
164
+ operationId: "immutableProofVerify",
165
+ summary: "Verify a proof",
166
+ tag: tagsImmutableProof[0].name,
167
+ method: "POST",
168
+ path: `${baseRouteName}/:id`,
169
+ handler: async (httpRequestContext, request) => immutableProofVerify(httpRequestContext, componentName, request),
170
+ requestType: {
171
+ type: "IImmutableProofVerifyRequest",
172
+ examples: [
173
+ {
174
+ id: "immutableProofVerifyRequestExample",
175
+ request: {
176
+ pathParams: {
177
+ id: "ais:1234567890"
178
+ },
179
+ body: {
180
+ proofObject: {
181
+ "@context": "http://schema.org",
182
+ type: "Person",
183
+ name: "John Smith"
184
+ }
185
+ }
186
+ }
187
+ }
188
+ ]
189
+ },
190
+ responseType: [
191
+ {
192
+ type: "IImmutableProofVerifyResponse",
193
+ examples: [
194
+ {
195
+ id: "immutableProofVerifyResponseExample",
196
+ response: {
197
+ body: {
198
+ verified: true
199
+ }
200
+ }
201
+ }
202
+ ]
203
+ },
204
+ {
205
+ type: "IImmutableProofVerifyResponse",
206
+ examples: [
207
+ {
208
+ id: "immutableProofVerifyResponseFailExample",
209
+ response: {
210
+ body: {
211
+ verified: false,
212
+ failure: ImmutableProofFailure.ProofTypeMismatch
213
+ }
214
+ }
215
+ }
216
+ ]
217
+ },
218
+ {
219
+ type: "INotFoundResponse"
220
+ }
221
+ ]
222
+ };
223
+ return [createRoute, getRoute, verifyRoute];
224
+ }
225
+ /**
226
+ * Create a proof.
227
+ * @param httpRequestContext The request context for the API.
228
+ * @param componentName The name of the component to use in the routes.
229
+ * @param request The request.
230
+ * @returns The response object with additional http response properties.
231
+ */
232
+ async function immutableProofCreate(httpRequestContext, componentName, request) {
233
+ Guards.object(ROUTES_SOURCE, "request", request);
234
+ Guards.object(ROUTES_SOURCE, "request.body.proofObject", request.body.proofObject);
235
+ const component = ComponentFactory.get(componentName);
236
+ const result = await component.create(request.body.proofObject);
237
+ return {
238
+ statusCode: HttpStatusCode.created,
239
+ headers: {
240
+ [HeaderTypes.Location]: result
241
+ }
242
+ };
243
+ }
244
+ /**
245
+ * Get the proof.
246
+ * @param httpRequestContext The request context for the API.
247
+ * @param componentName The name of the component to use in the routes.
248
+ * @param request The request.
249
+ * @returns The response object with additional http response properties.
250
+ */
251
+ async function immutableProofGet(httpRequestContext, componentName, request) {
252
+ Guards.object(ROUTES_SOURCE, "request", request);
253
+ Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
254
+ Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
255
+ const mimeType = request.headers?.[HeaderTypes.Accept] === MimeTypes.JsonLd ? "jsonld" : "json";
256
+ const component = ComponentFactory.get(componentName);
257
+ const result = await component.get(request.pathParams.id);
258
+ return {
259
+ headers: {
260
+ [HeaderTypes.ContentType]: mimeType === "json" ? MimeTypes.Json : MimeTypes.JsonLd
261
+ },
262
+ body: result
263
+ };
264
+ }
265
+ /**
266
+ * Verify the proof.
267
+ * @param httpRequestContext The request context for the API.
268
+ * @param componentName The name of the component to use in the routes.
269
+ * @param request The request.
270
+ * @returns The response object with additional http response properties.
271
+ */
272
+ async function immutableProofVerify(httpRequestContext, componentName, request) {
273
+ Guards.object(ROUTES_SOURCE, "request", request);
274
+ Guards.object(ROUTES_SOURCE, "request.pathParams", request.pathParams);
275
+ Guards.stringValue(ROUTES_SOURCE, "request.pathParams.id", request.pathParams.id);
276
+ Guards.object(ROUTES_SOURCE, "request.body.proofObject", request.body.proofObject);
277
+ const component = ComponentFactory.get(componentName);
278
+ const result = await component.verify(request.pathParams.id, request.body.proofObject);
279
+ return {
280
+ body: result
281
+ };
282
+ }
283
+
284
+ // Copyright 2024 IOTA Stiftung.
285
+ // SPDX-License-Identifier: Apache-2.0.
286
+ /**
287
+ * Class for performing immutable proof operations.
288
+ */
289
+ class ImmutableProofService {
290
+ /**
291
+ * The namespace for the service.
292
+ */
293
+ static NAMESPACE = "immutable-proof";
294
+ /**
295
+ * Runtime name for the class.
296
+ */
297
+ CLASS_NAME = "ImmutableProofService";
298
+ /**
299
+ * The configuration for the connector.
300
+ * @internal
301
+ */
302
+ _config;
303
+ /**
304
+ * The vault connector.
305
+ * @internal
306
+ */
307
+ _vaultConnector;
308
+ /**
309
+ * The identity connector.
310
+ * @internal
311
+ */
312
+ _identityConnector;
313
+ /**
314
+ * The entity storage for proofs.
315
+ * @internal
316
+ */
317
+ _proofStorage;
318
+ /**
319
+ * The immutable storage for the credentials.
320
+ * @internal
321
+ */
322
+ _immutableStorage;
323
+ /**
324
+ * The assertion method id to use for the proofs.
325
+ * @internal
326
+ */
327
+ _assertionMethodId;
328
+ /**
329
+ * The proof config key id to use for the proofs.
330
+ * @internal
331
+ */
332
+ _proofConfigKeyId;
333
+ /**
334
+ * Are we currently processing proofs.
335
+ * @internal
336
+ */
337
+ _processing;
338
+ /**
339
+ * Create a new instance of ImmutableProofService.
340
+ * @param options The dependencies for the immutable proof connector.
341
+ * @param options.config The configuration for the connector.
342
+ * @param options.vaultConnectorType The vault connector type, defaults to "vault".
343
+ * @param options.immutableProofEntityStorageType The entity storage for proofs, defaults to "immutable-proof".
344
+ * @param options.immutableStorageType The immutable storage, defaults to "immutable-proof".
345
+ * @param options.identityConnectorType The identity connector type, defaults to "identity".
346
+ */
347
+ constructor(options) {
348
+ this._vaultConnector = VaultConnectorFactory.get(options?.vaultConnectorType ?? "vault");
349
+ this._proofStorage = EntityStorageConnectorFactory.get(options?.immutableProofEntityStorageType ?? StringHelper.kebabCase("ImmutableProof"));
350
+ this._immutableStorage = ImmutableStorageConnectorFactory.get(options?.immutableStorageType ?? "immutable-proof");
351
+ this._identityConnector = IdentityConnectorFactory.get(options?.identityConnectorType ?? "identity");
352
+ this._config = options?.config ?? {};
353
+ this._assertionMethodId = this._config.assertionMethodId ?? "immutable-proof";
354
+ this._proofConfigKeyId = this._config.proofConfigKeyId ?? "immutable-proof";
355
+ SchemaOrgDataTypes.registerRedirects();
356
+ this._processing = false;
357
+ }
358
+ /**
359
+ * Create a new authentication proof.
360
+ * @param proofObject The object for the proof as JSON-LD.
361
+ * @param userIdentity The identity to create the immutable proof operation with.
362
+ * @param nodeIdentity The node identity to use for vault operations.
363
+ * @returns The id of the new authentication proof.
364
+ */
365
+ async create(proofObject, userIdentity, nodeIdentity) {
366
+ Guards.object(this.CLASS_NAME, "proofObject", proofObject);
367
+ Guards.stringValue(this.CLASS_NAME, "userIdentity", userIdentity);
368
+ Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
369
+ try {
370
+ const validationFailures = [];
371
+ await JsonLdHelper.validate(proofObject, validationFailures);
372
+ Validation.asValidationError(this.CLASS_NAME, "proofObject", validationFailures);
373
+ const id = Converter.bytesToHex(RandomHelper.generate(32), false);
374
+ const dateCreated = new Date(Date.now()).toISOString();
375
+ const proofObjectId = ObjectHelper.extractProperty(proofObject, ["@id", "id"], false);
376
+ const hash = this.calculateHash(id, dateCreated, nodeIdentity, userIdentity, proofObject);
377
+ const proofEntity = {
378
+ id,
379
+ nodeIdentity,
380
+ userIdentity,
381
+ dateCreated,
382
+ proofObjectId,
383
+ proofObjectHash: Converter.bytesToBase64(hash)
384
+ };
385
+ await this._proofStorage.set(proofEntity);
386
+ this.startProcessingProofs();
387
+ return new Urn(ImmutableProofService.NAMESPACE, id).toString();
388
+ }
389
+ catch (error) {
390
+ throw new GeneralError(this.CLASS_NAME, "createFailed", undefined, error);
391
+ }
392
+ }
393
+ /**
394
+ * Get an authentication proof.
395
+ * @param id The id of the proof to get.
396
+ * @returns The proof.
397
+ * @throws NotFoundError if the proof is not found.
398
+ */
399
+ async get(id) {
400
+ Guards.stringValue(this.CLASS_NAME, "id", id);
401
+ const urnParsed = Urn.fromValidString(id);
402
+ if (urnParsed.namespaceIdentifier() !== ImmutableProofService.NAMESPACE) {
403
+ throw new GeneralError(this.CLASS_NAME, "namespaceMismatch", {
404
+ namespace: ImmutableProofService.NAMESPACE,
405
+ id
406
+ });
407
+ }
408
+ try {
409
+ const { immutableProof } = await this.internalGet(id);
410
+ const compacted = await JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
411
+ return compacted;
412
+ }
413
+ catch (error) {
414
+ throw new GeneralError(this.CLASS_NAME, "getFailed", undefined, error);
415
+ }
416
+ }
417
+ /**
418
+ * Verify an authentication proof.
419
+ * @param id The id of the proof to verify.
420
+ * @param proofObject The object to verify as JSON-LD.
421
+ * @returns The result of the verification and any failures.
422
+ * @throws NotFoundError if the proof is not found.
423
+ */
424
+ async verify(id, proofObject) {
425
+ Guards.stringValue(this.CLASS_NAME, "id", id);
426
+ const urnParsed = Urn.fromValidString(id);
427
+ if (urnParsed.namespaceIdentifier() !== ImmutableProofService.NAMESPACE) {
428
+ throw new GeneralError(this.CLASS_NAME, "namespaceMismatch", {
429
+ namespace: ImmutableProofService.NAMESPACE,
430
+ id
431
+ });
432
+ }
433
+ try {
434
+ const { verified, failure } = await this.internalGet(id, proofObject);
435
+ return {
436
+ verified,
437
+ failure
438
+ };
439
+ }
440
+ catch (error) {
441
+ throw new GeneralError(this.CLASS_NAME, "verifyFailed", undefined, error);
442
+ }
443
+ }
444
+ /**
445
+ * Remove the immutable storage for the proof.
446
+ * @param id The id of the proof to remove the storage from.
447
+ * @param nodeIdentity The node identity to use for vault operations.
448
+ * @returns Nothing.
449
+ * @throws NotFoundError if the proof is not found.
450
+ */
451
+ async removeImmutable(id, nodeIdentity) {
452
+ Guards.stringValue(this.CLASS_NAME, "id", id);
453
+ Guards.stringValue(this.CLASS_NAME, "nodeIdentity", nodeIdentity);
454
+ const urnParsed = Urn.fromValidString(id);
455
+ if (urnParsed.namespaceIdentifier() !== ImmutableProofService.NAMESPACE) {
456
+ throw new GeneralError(this.CLASS_NAME, "namespaceMismatch", {
457
+ namespace: ImmutableProofService.NAMESPACE,
458
+ id
459
+ });
460
+ }
461
+ try {
462
+ const streamId = urnParsed.namespaceSpecific(0);
463
+ const streamEntity = await this._proofStorage.get(streamId);
464
+ if (Is.empty(streamEntity)) {
465
+ throw new NotFoundError(this.CLASS_NAME, "proofNotFound", id);
466
+ }
467
+ if (Is.stringValue(streamEntity.immutableStorageId)) {
468
+ await this._immutableStorage.remove(nodeIdentity, streamEntity.immutableStorageId);
469
+ delete streamEntity.immutableStorageId;
470
+ await this._proofStorage.set(streamEntity);
471
+ }
472
+ }
473
+ catch (error) {
474
+ throw new GeneralError(this.CLASS_NAME, "removeImmutableFailed", undefined, error);
475
+ }
476
+ }
477
+ /**
478
+ * Calculate the object hash.
479
+ * @param object The entry to calculate the hash for.
480
+ * @returns The hash.
481
+ * @internal
482
+ */
483
+ calculateHash(id, dateCreated, nodeIdentity, userIdentity, proofObject) {
484
+ const b2b = new Blake2b(Blake2b.SIZE_256);
485
+ b2b.update(Converter.utf8ToBytes(id));
486
+ b2b.update(Converter.utf8ToBytes(dateCreated));
487
+ b2b.update(Converter.utf8ToBytes(nodeIdentity));
488
+ b2b.update(Converter.utf8ToBytes(userIdentity));
489
+ b2b.update(ObjectHelper.toBytes(proofObject));
490
+ return b2b.digest();
491
+ }
492
+ /**
493
+ * Map the stream entity to a model.
494
+ * @param proofEntity The stream entity.
495
+ * @returns The model.
496
+ * @internal
497
+ */
498
+ proofEntityToModel(proofEntity) {
499
+ const model = {
500
+ "@context": [
501
+ ImmutableProofTypes.ContextRoot,
502
+ SchemaOrgTypes.ContextRoot,
503
+ DidContexts.ContextVCDataIntegrity
504
+ ],
505
+ type: ImmutableProofTypes.ImmutableProof,
506
+ id: proofEntity.id,
507
+ userIdentity: proofEntity.userIdentity,
508
+ proofObjectId: proofEntity.proofObjectId,
509
+ proofObjectHash: proofEntity.proofObjectHash
510
+ };
511
+ return model;
512
+ }
513
+ /**
514
+ * Start processing proofs.
515
+ * @returns Nothing.
516
+ * @internal
517
+ */
518
+ startProcessingProofs() {
519
+ if (!this._processing) {
520
+ setTimeout(async () => {
521
+ await this.processProofs();
522
+ }, 0);
523
+ }
524
+ }
525
+ /**
526
+ * Process the proofs.
527
+ * @internal
528
+ */
529
+ async processProofs() {
530
+ // Get the oldest pending proof, plus one more, we can then determine whether to
531
+ // trigger another process after this one
532
+ const pendingProofs = await this._proofStorage.query({
533
+ property: "immutableStorageId",
534
+ comparison: ComparisonOperator.Equals,
535
+ value: undefined
536
+ }, [
537
+ {
538
+ property: "dateCreated",
539
+ sortDirection: SortDirection.Ascending
540
+ }
541
+ ], undefined, undefined, 2);
542
+ if (pendingProofs.entities.length > 0) {
543
+ const proofEntity = pendingProofs.entities[0];
544
+ const immutableProof = this.proofEntityToModel(proofEntity);
545
+ const hashData = await this.generateHashData(proofEntity.nodeIdentity, immutableProof);
546
+ immutableProof.proof = await this._identityConnector.createProof(proofEntity.nodeIdentity, `${proofEntity.nodeIdentity}#${this._assertionMethodId}`, hashData);
547
+ proofEntity.dateCreated = immutableProof.proof.created ?? new Date(Date.now()).toISOString();
548
+ const compacted = await JsonLdProcessor.compact(immutableProof, immutableProof["@context"]);
549
+ proofEntity.immutableStorageId = await this._immutableStorage.store(proofEntity.nodeIdentity, ObjectHelper.toBytes(compacted));
550
+ await this._proofStorage.set(proofEntity);
551
+ }
552
+ // If there are still remaining proofs, start the timer again
553
+ this._processing = false;
554
+ if (pendingProofs.entities.length > 1) {
555
+ this.startProcessingProofs();
556
+ }
557
+ }
558
+ /**
559
+ * Verify an authentication proof.
560
+ * @param id The id of the proof to verify.
561
+ * @param proofObject The object to verify as JSON-LD.
562
+ * @returns The result of the verification and any failures.
563
+ * @throws NotFoundError if the proof is not found.
564
+ * @internal
565
+ */
566
+ async internalGet(id, proofObject) {
567
+ const urnParsed = Urn.fromValidString(id);
568
+ const proofId = urnParsed.namespaceSpecific(0);
569
+ const proofEntity = await this._proofStorage.get(proofId);
570
+ if (Is.empty(proofEntity)) {
571
+ throw new NotFoundError(this.CLASS_NAME, "proofNotFound", id);
572
+ }
573
+ let proofModel = await this.proofEntityToModel(proofEntity);
574
+ let verified = false;
575
+ let failure = ImmutableProofFailure.NotIssued;
576
+ if (Is.stringValue(proofEntity.immutableStorageId)) {
577
+ failure = ImmutableProofFailure.ProofMissing;
578
+ const immutableData = await this._immutableStorage.get(proofEntity.immutableStorageId);
579
+ if (Is.uint8Array(immutableData)) {
580
+ proofModel = ObjectHelper.fromBytes(immutableData);
581
+ if (Is.object(proofModel.proof) && Is.object(proofObject)) {
582
+ if (proofModel.proof.cryptosuite !== DidCryptoSuites.EdDSAJcs2022) {
583
+ failure = ImmutableProofFailure.CryptoSuiteMismatch;
584
+ }
585
+ else if (proofModel.proof.type !== DidTypes.DataIntegrityProof) {
586
+ failure = ImmutableProofFailure.ProofTypeMismatch;
587
+ }
588
+ else {
589
+ const hashData = await this.generateHashData(proofEntity.nodeIdentity, proofModel);
590
+ const isVerified = await this._identityConnector.verifyProof(hashData, proofModel.proof);
591
+ if (isVerified) {
592
+ verified = true;
593
+ failure = undefined;
594
+ }
595
+ else {
596
+ failure = ImmutableProofFailure.SignatureMismatch;
597
+ }
598
+ }
599
+ }
600
+ }
601
+ }
602
+ return {
603
+ immutableProof: proofModel,
604
+ verified,
605
+ failure
606
+ };
607
+ }
608
+ /**
609
+ * Generate the hash data for the proof.
610
+ * Conforms to https://www.w3.org/TR/vc-di-eddsa/#create-proof-eddsa-jcs-2022
611
+ * @param nodeIdentity The node identity to use for vault operations.
612
+ * @param immutableProof The immutable proof to generate the hash data for.
613
+ * @returns The hash data.
614
+ * @internal
615
+ */
616
+ async generateHashData(nodeIdentity, immutableProof) {
617
+ const canonicalDocument = JsonHelper.canonicalize(ObjectHelper.omit(immutableProof, ["proof"]));
618
+ const proofConfigKey = await this._vaultConnector.getKey(`${nodeIdentity}/${this._proofConfigKeyId}`);
619
+ const proofConfigHash = Sha256.sum256(proofConfigKey.privateKey);
620
+ const transformedDocumentHash = Sha256.sum256(Converter.utf8ToBytes(canonicalDocument));
621
+ const hashData = new Uint8Array(proofConfigHash.length + transformedDocumentHash.length);
622
+ hashData.set(proofConfigHash);
623
+ hashData.set(transformedDocumentHash, proofConfigHash.length);
624
+ return hashData;
625
+ }
626
+ }
627
+
628
+ // Copyright 2024 IOTA Stiftung.
629
+ // SPDX-License-Identifier: Apache-2.0.
630
+ /**
631
+ * Class describing the immutable proof.
632
+ */
633
+ let ImmutableProof = class ImmutableProof {
634
+ /**
635
+ * The id of the proof.
636
+ */
637
+ id;
638
+ /**
639
+ * The identity of the node which controls the proof.
640
+ */
641
+ nodeIdentity;
642
+ /**
643
+ * The identity of the user which created the proof.
644
+ */
645
+ userIdentity;
646
+ /**
647
+ * The date/time of when the proof was created.
648
+ */
649
+ dateCreated;
650
+ /**
651
+ * The associated id for the item.
652
+ */
653
+ proofObjectId;
654
+ /**
655
+ * The associated hash for the item.
656
+ */
657
+ proofObjectHash;
658
+ /**
659
+ * The immutable storage id.
660
+ */
661
+ immutableStorageId;
662
+ };
663
+ __decorate([
664
+ property({ type: "string", isPrimary: true }),
665
+ __metadata("design:type", String)
666
+ ], ImmutableProof.prototype, "id", void 0);
667
+ __decorate([
668
+ property({ type: "string" }),
669
+ __metadata("design:type", String)
670
+ ], ImmutableProof.prototype, "nodeIdentity", void 0);
671
+ __decorate([
672
+ property({ type: "string" }),
673
+ __metadata("design:type", String)
674
+ ], ImmutableProof.prototype, "userIdentity", void 0);
675
+ __decorate([
676
+ property({ type: "string", format: "date-time", sortDirection: SortDirection.Descending }),
677
+ __metadata("design:type", String)
678
+ ], ImmutableProof.prototype, "dateCreated", void 0);
679
+ __decorate([
680
+ property({ type: "string" }),
681
+ __metadata("design:type", String)
682
+ ], ImmutableProof.prototype, "proofObjectId", void 0);
683
+ __decorate([
684
+ property({ type: "string" }),
685
+ __metadata("design:type", String)
686
+ ], ImmutableProof.prototype, "proofObjectHash", void 0);
687
+ __decorate([
688
+ property({ type: "string" }),
689
+ __metadata("design:type", String)
690
+ ], ImmutableProof.prototype, "immutableStorageId", void 0);
691
+ ImmutableProof = __decorate([
692
+ entity()
693
+ ], ImmutableProof);
694
+
695
+ const restEntryPoints = [
696
+ {
697
+ name: "immutable-proof",
698
+ defaultBaseRoute: "immutable-proof",
699
+ tags: tagsImmutableProof,
700
+ generateRoutes: generateRestRoutesImmutableProof
701
+ }
702
+ ];
703
+
704
+ // Copyright 2024 IOTA Stiftung.
705
+ // SPDX-License-Identifier: Apache-2.0.
706
+ /**
707
+ * Initialize the schema for the immutable proof entity storage connector.
708
+ */
709
+ function initSchema() {
710
+ EntitySchemaFactory.register("ImmutableProof", () => EntitySchemaHelper.getSchema(ImmutableProof));
711
+ }
712
+
713
+ export { ImmutableProof, ImmutableProofService, generateRestRoutesImmutableProof, immutableProofCreate, immutableProofGet, immutableProofVerify, initSchema, restEntryPoints, tagsImmutableProof };