Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / docs-core / lib / UseCase / VerifyMessages.ts
blob33242596949fbcbd67cd019ed7c549f7146b3ae3
1 import { VERIFICATION_STATUS } from '@proton/crypto'
2 import type { UseCaseInterface } from '../Domain/UseCase/UseCaseInterface'
3 import { Result } from '@proton/docs-shared'
4 import type { EncryptionService } from '../Services/Encryption/EncryptionService'
5 import type { EncryptionContext } from '../Services/Encryption/EncryptionContext'
6 import type { DecryptedMessage } from '@proton/docs-shared'
7 import type { VerificationUsecaseResult, SingleMessageVerificationResult } from './VerifyUpdatesResult'
9 export class VerifyMessages implements UseCaseInterface<VerificationUsecaseResult> {
10   constructor(private encryption: EncryptionService<EncryptionContext.RealtimeMessage>) {}
12   async execute(dto: { messages: DecryptedMessage[] }): Promise<Result<VerificationUsecaseResult>> {
13     const results: SingleMessageVerificationResult[] = []
14     let hasFailure = false
16     for (const message of dto.messages) {
17       const verificationKey = await this.encryption.getVerificationKey(message.authorAddress)
19       if (verificationKey.isFailed()) {
20         hasFailure = true
21         results.push({
22           verified: false,
23           message: message,
24         })
25       }
27       const verifyResult = await this.encryption.verifyData(
28         message.content,
29         message.signature,
30         message.aad,
31         verificationKey.getValue(),
32       )
34       if (verifyResult.isFailed()) {
35         hasFailure = true
36         results.push({
37           verified: false,
38           message: message,
39         })
40       }
42       const verifyValue = verifyResult.getValue()
43       if (verifyValue !== VERIFICATION_STATUS.SIGNED_AND_VALID) {
44         hasFailure = true
45         results.push({
46           verified: false,
47           message: message,
48         })
49       }
51       results.push({
52         verified: true,
53         message: message,
54       })
55     }
57     return Result.ok({
58       allVerified: !hasFailure,
59       messages: results,
60     })
61   }