-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathSettingCrypter.ts
More file actions
73 lines (59 loc) · 2.3 KB
/
SettingCrypter.ts
File metadata and controls
73 lines (59 loc) · 2.3 KB
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
import { CrypterInterface } from '../Encryption/CrypterInterface'
import { EncryptionVersion } from '../Encryption/EncryptionVersion'
import { UserRepositoryInterface } from '../User/UserRepositoryInterface'
import { Setting } from './Setting'
import { SettingCrypterInterface } from './SettingCrypterInterface'
import { Uuid } from '@standardnotes/domain-core'
import { SubscriptionSetting } from './SubscriptionSetting'
export class SettingCrypter implements SettingCrypterInterface {
constructor(
private userRepository: UserRepositoryInterface,
private crypter: CrypterInterface,
) {}
async encryptValue(value: string | null, userUuid: Uuid): Promise<string | null> {
if (value === null) {
return null
}
const user = await this.userRepository.findOneByUuid(userUuid)
if (user === null) {
throw new Error(`Could not find user with uuid: ${userUuid.value}`)
}
return this.crypter.encryptForUser(value, user)
}
async decryptSettingValue(setting: Setting, userUuidString: string): Promise<string | null> {
return this.decrypt(setting.props.value, setting.props.serverEncryptionVersion, userUuidString)
}
async decryptSubscriptionSettingValue(setting: SubscriptionSetting, userUuidString: string): Promise<string | null> {
return this.decrypt(setting.props.value, setting.props.serverEncryptionVersion, userUuidString)
}
private async decrypt(
value: string | null,
serverEncryptionVersion: number,
userUuidString: string,
): Promise<string | null> {
if (value !== null && serverEncryptionVersion === EncryptionVersion.Default) {
const userUuidOrError = Uuid.create(userUuidString)
if (userUuidOrError.isFailed()) {
throw new Error(userUuidOrError.getError())
}
const userUuid = userUuidOrError.getValue()
const user = await this.userRepository.findOneByUuid(userUuid)
if (user === null) {
throw new Error(`Could not find user with uuid: ${userUuid.value}`)
}
if (!this.isValidJSONSubjectForDecryption(value)) {
return value
}
return this.crypter.decryptForUser(value, user)
}
return value
}
private isValidJSONSubjectForDecryption(value: string): boolean {
try {
JSON.parse(value)
return true
} catch (error) {
return false
}
}
}