refactor: import/export use cases (#2397)
This commit is contained in:
@@ -12,13 +12,14 @@ import {
|
||||
StatusServiceInterface,
|
||||
MfaServiceInterface,
|
||||
GenerateUuid,
|
||||
CreateDecryptedBackupFile,
|
||||
} from '@standardnotes/services'
|
||||
import { VaultLockServiceInterface } from './../VaultLock/VaultLockServiceInterface'
|
||||
import { HistoryServiceInterface } from './../History/HistoryServiceInterface'
|
||||
import { InternalEventBusInterface } from './../Internal/InternalEventBusInterface'
|
||||
import { PreferenceServiceInterface } from './../Preferences/PreferenceServiceInterface'
|
||||
import { AsymmetricMessageServiceInterface } from './../AsymmetricMessage/AsymmetricMessageServiceInterface'
|
||||
import { ImportDataReturnType } from './../Mutator/ImportDataUseCase'
|
||||
import { ImportDataResult } from '../Import/ImportDataResult'
|
||||
import { ChallengeServiceInterface } from './../Challenge/ChallengeServiceInterface'
|
||||
import { VaultServiceInterface } from '../Vault/VaultServiceInterface'
|
||||
import { ApplicationIdentifier } from '@standardnotes/common'
|
||||
@@ -42,6 +43,8 @@ import { UserServiceInterface } from '../User/UserServiceInterface'
|
||||
import { SessionsClientInterface } from '../Session/SessionsClientInterface'
|
||||
import { HomeServerServiceInterface } from '../HomeServer/HomeServerServiceInterface'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
import { Result } from '@standardnotes/domain-core'
|
||||
import { CreateEncryptedBackupFile } from '../Import/CreateEncryptedBackupFile'
|
||||
|
||||
export interface ApplicationInterface {
|
||||
deinit(mode: DeinitMode, source: DeinitSource): void
|
||||
@@ -51,9 +54,6 @@ export interface ApplicationInterface {
|
||||
addEventObserver(callback: ApplicationEventCallback, singleEvent?: ApplicationEvent): () => void
|
||||
addSingleEventObserver(event: ApplicationEvent, callback: ApplicationEventCallback): () => void
|
||||
hasProtectionSources(): boolean
|
||||
createEncryptedBackupFileForAutomatedDesktopBackups(): Promise<BackupFile | undefined>
|
||||
createEncryptedBackupFile(): Promise<BackupFile | undefined>
|
||||
createDecryptedBackupFile(): Promise<BackupFile | undefined>
|
||||
hasPasscode(): boolean
|
||||
lock(): Promise<void>
|
||||
setValue(key: string, value: unknown, mode?: StorageValueModes): void
|
||||
@@ -68,12 +68,17 @@ export interface ApplicationInterface {
|
||||
setCustomHost(host: string): Promise<void>
|
||||
isUsingHomeServer(): Promise<boolean>
|
||||
|
||||
importData(data: BackupFile, awaitSync?: boolean): Promise<ImportDataReturnType>
|
||||
importData(data: BackupFile, awaitSync?: boolean): Promise<Result<ImportDataResult>>
|
||||
|
||||
// Use cases
|
||||
get changeAndSaveItem(): ChangeAndSaveItem
|
||||
get createDecryptedBackupFile(): CreateDecryptedBackupFile
|
||||
get createEncryptedBackupFile(): CreateEncryptedBackupFile
|
||||
get generateUuid(): GenerateUuid
|
||||
get getHost(): GetHost
|
||||
get setHost(): SetHost
|
||||
|
||||
// Services
|
||||
get alerts(): AlertService
|
||||
get asymmetric(): AsymmetricMessageServiceInterface
|
||||
get challenges(): ChallengeServiceInterface
|
||||
@@ -85,7 +90,6 @@ export interface ApplicationInterface {
|
||||
get files(): FilesClientInterface
|
||||
get history(): HistoryServiceInterface
|
||||
get homeServer(): HomeServerServiceInterface | undefined
|
||||
get generateUuid(): GenerateUuid
|
||||
get items(): ItemManagerInterface
|
||||
get legacyApi(): LegacyApiServiceInterface
|
||||
get mfa(): MfaServiceInterface
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
} from '@standardnotes/encryption'
|
||||
import { KeyParamsOrigination, ProtocolVersion } from '@standardnotes/common'
|
||||
import {
|
||||
BackupFile,
|
||||
DecryptedPayloadInterface,
|
||||
EncryptedPayloadInterface,
|
||||
ItemContent,
|
||||
@@ -54,9 +53,6 @@ export interface EncryptionProviderInterface {
|
||||
getEncryptionDisplayName(): Promise<string>
|
||||
upgradeAvailable(): Promise<boolean>
|
||||
|
||||
createEncryptedBackupFile(): Promise<BackupFile>
|
||||
createDecryptedBackupFile(): BackupFile
|
||||
|
||||
getUserVersion(): ProtocolVersion | undefined
|
||||
hasAccount(): boolean
|
||||
hasPasscode(): boolean
|
||||
@@ -75,6 +71,11 @@ export interface EncryptionProviderInterface {
|
||||
|
||||
deleteWorkspaceSpecificKeyStateFromDevice(): Promise<void>
|
||||
|
||||
itemsKeyForEncryptedPayload(
|
||||
payload: EncryptedPayloadInterface,
|
||||
): ItemsKeyInterface | KeySystemItemsKeyInterface | undefined
|
||||
defaultItemsKeyForItemVersion(version: ProtocolVersion, fromKeys?: ItemsKeyInterface[]): ItemsKeyInterface | undefined
|
||||
|
||||
unwrapRootKey(wrappingKey: RootKeyInterface): Promise<void>
|
||||
computeRootKey(password: string, keyParams: SNRootKeyParams): Promise<RootKeyInterface>
|
||||
computeWrappingKey(passcode: string): Promise<RootKeyInterface>
|
||||
|
||||
@@ -5,7 +5,6 @@ import { InternalEventHandlerInterface } from './../Internal/InternalEventHandle
|
||||
import { MutatorClientInterface } from './../Mutator/MutatorClientInterface'
|
||||
import {
|
||||
CreateAnyKeyParams,
|
||||
CreateEncryptionSplitWithKeyLookup,
|
||||
encryptedInputParametersFromPayload,
|
||||
ErrorDecryptingParameters,
|
||||
FindPayloadInDecryptionSplit,
|
||||
@@ -16,7 +15,6 @@ import {
|
||||
KeyedEncryptionSplit,
|
||||
LegacyAttachedData,
|
||||
RootKeyEncryptedAuthenticatedData,
|
||||
SplitPayloadsByEncryptionType,
|
||||
V001Algorithm,
|
||||
V002Algorithm,
|
||||
EncryptedOutputParameters,
|
||||
@@ -25,15 +23,10 @@ import {
|
||||
EncryptionOperatorsInterface,
|
||||
} from '@standardnotes/encryption'
|
||||
import {
|
||||
BackupFile,
|
||||
CreateDecryptedBackupFileContextPayload,
|
||||
CreateEncryptedBackupFileContextPayload,
|
||||
DecryptedPayload,
|
||||
DecryptedPayloadInterface,
|
||||
EncryptedPayload,
|
||||
EncryptedPayloadInterface,
|
||||
isDecryptedPayload,
|
||||
isEncryptedPayload,
|
||||
ItemContent,
|
||||
ItemsKeyInterface,
|
||||
RootKeyInterface,
|
||||
@@ -47,7 +40,6 @@ import {
|
||||
import { PureCryptoInterface } from '@standardnotes/sncrypto-common'
|
||||
import {
|
||||
extendArray,
|
||||
isNotUndefined,
|
||||
isNullOrUndefined,
|
||||
isReactNativeEnvironment,
|
||||
isWebCryptoAvailable,
|
||||
@@ -81,7 +73,6 @@ import { EncryptTypeAPayloadWithKeyLookup } from './UseCase/TypeA/EncryptPayload
|
||||
import { EncryptTypeAPayload } from './UseCase/TypeA/EncryptPayload'
|
||||
import { ValidateAccountPasswordResult } from '../RootKeyManager/ValidateAccountPasswordResult'
|
||||
import { ValidatePasscodeResult } from '../RootKeyManager/ValidatePasscodeResult'
|
||||
import { ContentType } from '@standardnotes/domain-core'
|
||||
import { EncryptionProviderInterface } from './EncryptionProviderInterface'
|
||||
import { KeyMode } from '../RootKeyManager/KeyMode'
|
||||
|
||||
@@ -578,47 +569,6 @@ export class EncryptionService
|
||||
return CreateAnyKeyParams(keyParams)
|
||||
}
|
||||
|
||||
public async createEncryptedBackupFile(): Promise<BackupFile> {
|
||||
const payloads = this.items.items.map((item) => item.payload)
|
||||
|
||||
const split = SplitPayloadsByEncryptionType(payloads)
|
||||
|
||||
const keyLookupSplit = CreateEncryptionSplitWithKeyLookup(split)
|
||||
|
||||
const result = await this.encryptSplit(keyLookupSplit)
|
||||
|
||||
const ejected = result.map((payload) => CreateEncryptedBackupFileContextPayload(payload))
|
||||
|
||||
const data: BackupFile = {
|
||||
version: ProtocolVersionLatest,
|
||||
items: ejected,
|
||||
}
|
||||
|
||||
const keyParams = this.getRootKeyParams()
|
||||
data.keyParams = keyParams?.getPortableValue()
|
||||
return data
|
||||
}
|
||||
|
||||
public createDecryptedBackupFile(): BackupFile {
|
||||
const payloads = this.payloads.nonDeletedItems.filter((item) => item.content_type !== ContentType.TYPES.ItemsKey)
|
||||
|
||||
const data: BackupFile = {
|
||||
version: ProtocolVersionLatest,
|
||||
items: payloads
|
||||
.map((payload) => {
|
||||
if (isDecryptedPayload(payload)) {
|
||||
return CreateDecryptedBackupFileContextPayload(payload)
|
||||
} else if (isEncryptedPayload(payload)) {
|
||||
return CreateEncryptedBackupFileContextPayload(payload)
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
.filter(isNotUndefined),
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
public hasPasscode(): boolean {
|
||||
return this.rootKeyManager.hasPasscode()
|
||||
}
|
||||
|
||||
@@ -1,285 +0,0 @@
|
||||
import {
|
||||
AnyKeyParamsContent,
|
||||
compareVersions,
|
||||
leftVersionGreaterThanOrEqualToRight,
|
||||
ProtocolVersion,
|
||||
} from '@standardnotes/common'
|
||||
import {
|
||||
BackupFileType,
|
||||
CreateAnyKeyParams,
|
||||
isItemsKey,
|
||||
isKeySystemItemsKey,
|
||||
SNItemsKey,
|
||||
SplitPayloadsByEncryptionType,
|
||||
} from '@standardnotes/encryption'
|
||||
import {
|
||||
ContentTypeUsesKeySystemRootKeyEncryption,
|
||||
ContentTypeUsesRootKeyEncryption,
|
||||
BackupFile,
|
||||
CreateDecryptedItemFromPayload,
|
||||
CreatePayloadSplit,
|
||||
DecryptedPayload,
|
||||
DecryptedPayloadInterface,
|
||||
EncryptedPayload,
|
||||
EncryptedPayloadInterface,
|
||||
isDecryptedPayload,
|
||||
isDecryptedTransferPayload,
|
||||
isEncryptedPayload,
|
||||
isEncryptedTransferPayload,
|
||||
ItemsKeyContent,
|
||||
ItemsKeyInterface,
|
||||
PayloadInterface,
|
||||
KeySystemItemsKeyInterface,
|
||||
RootKeyInterface,
|
||||
KeySystemRootKeyInterface,
|
||||
isKeySystemRootKey,
|
||||
RootKeyParamsInterface,
|
||||
} from '@standardnotes/models'
|
||||
import { ClientDisplayableError } from '@standardnotes/responses'
|
||||
import { extendArray, LoggerInterface } from '@standardnotes/utils'
|
||||
import { EncryptionService } from '../EncryptionService'
|
||||
import { ContentType } from '@standardnotes/domain-core'
|
||||
|
||||
export class DecryptBackupFile {
|
||||
constructor(
|
||||
private encryption: EncryptionService,
|
||||
private logger: LoggerInterface,
|
||||
) {}
|
||||
|
||||
async execute(
|
||||
file: BackupFile,
|
||||
password?: string,
|
||||
): Promise<ClientDisplayableError | (EncryptedPayloadInterface | DecryptedPayloadInterface)[]> {
|
||||
const payloads: (EncryptedPayloadInterface | DecryptedPayloadInterface)[] = file.items.map((item) => {
|
||||
if (isEncryptedTransferPayload(item)) {
|
||||
return new EncryptedPayload(item)
|
||||
} else if (isDecryptedTransferPayload(item)) {
|
||||
return new DecryptedPayload(item)
|
||||
} else {
|
||||
throw Error('Unhandled case in DecryptBackupFile')
|
||||
}
|
||||
})
|
||||
|
||||
const { encrypted, decrypted } = CreatePayloadSplit(payloads)
|
||||
|
||||
const type = this.getBackupFileType(file, payloads)
|
||||
|
||||
switch (type) {
|
||||
case BackupFileType.Corrupt:
|
||||
return new ClientDisplayableError('Invalid backup file.')
|
||||
case BackupFileType.Encrypted: {
|
||||
if (!password) {
|
||||
throw Error('Attempting to decrypt encrypted file with no password')
|
||||
}
|
||||
|
||||
const keyParamsData = (file.keyParams || file.auth_params) as AnyKeyParamsContent
|
||||
|
||||
const rootKey = await this.encryption.computeRootKey(password, CreateAnyKeyParams(keyParamsData))
|
||||
|
||||
const results = await this.decryptEncrypted({
|
||||
password,
|
||||
payloads: encrypted,
|
||||
rootKey,
|
||||
keyParams: CreateAnyKeyParams(keyParamsData),
|
||||
})
|
||||
|
||||
return [...decrypted, ...results]
|
||||
}
|
||||
case BackupFileType.EncryptedWithNonEncryptedItemsKey:
|
||||
return [...decrypted, ...(await this.decryptEncryptedWithNonEncryptedItemsKey(payloads))]
|
||||
case BackupFileType.FullyDecrypted:
|
||||
return [...decrypted, ...encrypted]
|
||||
}
|
||||
}
|
||||
|
||||
private getBackupFileType(file: BackupFile, payloads: PayloadInterface[]): BackupFileType {
|
||||
if (file.keyParams || file.auth_params) {
|
||||
return BackupFileType.Encrypted
|
||||
} else {
|
||||
const hasEncryptedItem = payloads.find(isEncryptedPayload)
|
||||
const hasDecryptedItemsKey = payloads.find(
|
||||
(payload) => payload.content_type === ContentType.TYPES.ItemsKey && isDecryptedPayload(payload),
|
||||
)
|
||||
|
||||
if (hasEncryptedItem && hasDecryptedItemsKey) {
|
||||
return BackupFileType.EncryptedWithNonEncryptedItemsKey
|
||||
} else if (!hasEncryptedItem) {
|
||||
return BackupFileType.FullyDecrypted
|
||||
} else {
|
||||
return BackupFileType.Corrupt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async decryptEncrypted(dto: {
|
||||
password: string
|
||||
keyParams: RootKeyParamsInterface
|
||||
payloads: EncryptedPayloadInterface[]
|
||||
rootKey: RootKeyInterface
|
||||
}): Promise<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]> {
|
||||
const results: (EncryptedPayloadInterface | DecryptedPayloadInterface)[] = []
|
||||
|
||||
const { rootKeyEncryption, itemsKeyEncryption } = SplitPayloadsByEncryptionType(dto.payloads)
|
||||
|
||||
const rootKeyBasedDecryptionResults = await this.encryption.decryptSplit({
|
||||
usesRootKey: {
|
||||
items: rootKeyEncryption || [],
|
||||
key: dto.rootKey,
|
||||
},
|
||||
})
|
||||
|
||||
extendArray(results, rootKeyBasedDecryptionResults)
|
||||
|
||||
const decryptedPayloads = await this.decrypt({
|
||||
payloads: itemsKeyEncryption || [],
|
||||
availableItemsKeys: rootKeyBasedDecryptionResults
|
||||
.filter(isItemsKey)
|
||||
.filter(isDecryptedPayload)
|
||||
.map((p) => CreateDecryptedItemFromPayload(p)),
|
||||
keyParams: dto.keyParams,
|
||||
rootKey: dto.rootKey,
|
||||
})
|
||||
|
||||
extendArray(results, decryptedPayloads)
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
private async decryptEncryptedWithNonEncryptedItemsKey(
|
||||
payloads: (EncryptedPayloadInterface | DecryptedPayloadInterface)[],
|
||||
): Promise<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]> {
|
||||
const decryptedItemsKeys: DecryptedPayloadInterface<ItemsKeyContent>[] = []
|
||||
const encryptedPayloads: EncryptedPayloadInterface[] = []
|
||||
|
||||
payloads.forEach((payload) => {
|
||||
if (payload.content_type === ContentType.TYPES.ItemsKey && isDecryptedPayload(payload)) {
|
||||
decryptedItemsKeys.push(payload as DecryptedPayloadInterface<ItemsKeyContent>)
|
||||
} else if (isEncryptedPayload(payload)) {
|
||||
encryptedPayloads.push(payload)
|
||||
}
|
||||
})
|
||||
|
||||
const itemsKeys = decryptedItemsKeys.map((p) => CreateDecryptedItemFromPayload<ItemsKeyContent, SNItemsKey>(p))
|
||||
|
||||
return this.decrypt({ payloads: encryptedPayloads, availableItemsKeys: itemsKeys, rootKey: undefined })
|
||||
}
|
||||
|
||||
private findKeyToUseForPayload(dto: {
|
||||
payload: EncryptedPayloadInterface
|
||||
availableKeys: ItemsKeyInterface[]
|
||||
keyParams?: RootKeyParamsInterface
|
||||
rootKey?: RootKeyInterface
|
||||
}): ItemsKeyInterface | RootKeyInterface | KeySystemRootKeyInterface | KeySystemItemsKeyInterface | undefined {
|
||||
if (ContentTypeUsesRootKeyEncryption(dto.payload.content_type)) {
|
||||
if (!dto.rootKey) {
|
||||
throw new Error('Attempting to decrypt root key encrypted payload with no root key')
|
||||
}
|
||||
return dto.rootKey
|
||||
}
|
||||
|
||||
if (ContentTypeUsesKeySystemRootKeyEncryption(dto.payload.content_type)) {
|
||||
throw new Error('Backup file key system root key encryption is not supported')
|
||||
}
|
||||
|
||||
let itemsKey: ItemsKeyInterface | RootKeyInterface | KeySystemItemsKeyInterface | undefined
|
||||
|
||||
if (dto.payload.items_key_id) {
|
||||
itemsKey = this.encryption.itemsKeyForEncryptedPayload(dto.payload)
|
||||
if (itemsKey) {
|
||||
return itemsKey
|
||||
}
|
||||
}
|
||||
|
||||
itemsKey = dto.availableKeys.find((itemsKeyPayload) => {
|
||||
return dto.payload.items_key_id === itemsKeyPayload.uuid
|
||||
})
|
||||
|
||||
if (itemsKey) {
|
||||
return itemsKey
|
||||
}
|
||||
|
||||
if (!dto.keyParams) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadVersion = dto.payload.version as ProtocolVersion
|
||||
|
||||
/**
|
||||
* Payloads with versions <= 003 use root key directly for encryption.
|
||||
* However, if the incoming key params are >= 004, this means we should
|
||||
* have an items key based off the 003 root key. We can't use the 004
|
||||
* root key directly because it's missing dataAuthenticationKey.
|
||||
*/
|
||||
if (leftVersionGreaterThanOrEqualToRight(dto.keyParams.version, ProtocolVersion.V004)) {
|
||||
itemsKey = this.encryption.defaultItemsKeyForItemVersion(payloadVersion, dto.availableKeys)
|
||||
} else if (compareVersions(payloadVersion, ProtocolVersion.V003) <= 0) {
|
||||
itemsKey = dto.rootKey
|
||||
}
|
||||
|
||||
return itemsKey
|
||||
}
|
||||
|
||||
private async decrypt(dto: {
|
||||
payloads: EncryptedPayloadInterface[]
|
||||
availableItemsKeys: ItemsKeyInterface[]
|
||||
rootKey: RootKeyInterface | undefined
|
||||
keyParams?: RootKeyParamsInterface
|
||||
}): Promise<(DecryptedPayloadInterface | EncryptedPayloadInterface)[]> {
|
||||
const results: (DecryptedPayloadInterface | EncryptedPayloadInterface)[] = []
|
||||
|
||||
for (const encryptedPayload of dto.payloads) {
|
||||
try {
|
||||
const key = this.findKeyToUseForPayload({
|
||||
payload: encryptedPayload,
|
||||
availableKeys: dto.availableItemsKeys,
|
||||
keyParams: dto.keyParams,
|
||||
rootKey: dto.rootKey,
|
||||
})
|
||||
|
||||
if (!key) {
|
||||
results.push(
|
||||
encryptedPayload.copy({
|
||||
errorDecrypting: true,
|
||||
}),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if (isItemsKey(key) || isKeySystemItemsKey(key)) {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesItemsKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
} else if (isKeySystemRootKey(key)) {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesKeySystemRootKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
} else {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesRootKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
}
|
||||
} catch (e) {
|
||||
results.push(
|
||||
encryptedPayload.copy({
|
||||
errorDecrypting: true,
|
||||
}),
|
||||
)
|
||||
this.logger.error('Error decrypting payload', encryptedPayload, e)
|
||||
}
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ProtectionsClientInterface } from './../Protection/ProtectionClientInterface'
|
||||
import { ContentType, Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import {
|
||||
BackupFile,
|
||||
CreateDecryptedBackupFileContextPayload,
|
||||
CreateEncryptedBackupFileContextPayload,
|
||||
isDecryptedPayload,
|
||||
isEncryptedPayload,
|
||||
} from '@standardnotes/models'
|
||||
import { PayloadManagerInterface } from '../Payloads/PayloadManagerInterface'
|
||||
import { ProtocolVersionLatest } from '@standardnotes/common'
|
||||
import { isNotUndefined } from '@standardnotes/utils'
|
||||
|
||||
export class CreateDecryptedBackupFile implements UseCaseInterface<BackupFile> {
|
||||
constructor(
|
||||
private payloads: PayloadManagerInterface,
|
||||
private protections: ProtectionsClientInterface,
|
||||
) {}
|
||||
|
||||
async execute(): Promise<Result<BackupFile>> {
|
||||
if (!(await this.protections.authorizeBackupCreation())) {
|
||||
return Result.fail('Failed to authorize backup creation')
|
||||
}
|
||||
|
||||
const payloads = this.payloads.nonDeletedItems.filter((item) => item.content_type !== ContentType.TYPES.ItemsKey)
|
||||
|
||||
const data: BackupFile = {
|
||||
version: ProtocolVersionLatest,
|
||||
items: payloads
|
||||
.map((payload) => {
|
||||
if (isDecryptedPayload(payload)) {
|
||||
return CreateDecryptedBackupFileContextPayload(payload)
|
||||
} else if (isEncryptedPayload(payload)) {
|
||||
return CreateEncryptedBackupFileContextPayload(payload)
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
.filter(isNotUndefined),
|
||||
}
|
||||
|
||||
return Result.ok(data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ItemManagerInterface } from './../Item/ItemManagerInterface'
|
||||
import { ProtectionsClientInterface } from './../Protection/ProtectionClientInterface'
|
||||
import { Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import { BackupFile, CreateEncryptedBackupFileContextPayload } from '@standardnotes/models'
|
||||
import { ProtocolVersionLatest } from '@standardnotes/common'
|
||||
import { CreateEncryptionSplitWithKeyLookup, SplitPayloadsByEncryptionType } from '@standardnotes/encryption'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
|
||||
export class CreateEncryptedBackupFile implements UseCaseInterface<BackupFile> {
|
||||
constructor(
|
||||
private items: ItemManagerInterface,
|
||||
private protections: ProtectionsClientInterface,
|
||||
private encryption: EncryptionProviderInterface,
|
||||
) {}
|
||||
|
||||
async execute(params: { skipAuthorization: boolean } = { skipAuthorization: false }): Promise<Result<BackupFile>> {
|
||||
if (!params.skipAuthorization && !(await this.protections.authorizeBackupCreation())) {
|
||||
return Result.fail('Failed to authorize backup creation')
|
||||
}
|
||||
|
||||
const payloads = this.items.items.map((item) => item.payload)
|
||||
|
||||
const split = SplitPayloadsByEncryptionType(payloads)
|
||||
|
||||
const keyLookupSplit = CreateEncryptionSplitWithKeyLookup(split)
|
||||
|
||||
const result = await this.encryption.encryptSplit(keyLookupSplit)
|
||||
|
||||
const ejected = result.map((payload) => CreateEncryptedBackupFileContextPayload(payload))
|
||||
|
||||
const data: BackupFile = {
|
||||
version: ProtocolVersionLatest,
|
||||
items: ejected,
|
||||
}
|
||||
|
||||
const keyParams = this.encryption.getRootKeyParams()
|
||||
data.keyParams = keyParams?.getPortableValue()
|
||||
return Result.ok(data)
|
||||
}
|
||||
}
|
||||
215
packages/services/src/Domain/Import/DecryptBackupFile.ts
Normal file
215
packages/services/src/Domain/Import/DecryptBackupFile.ts
Normal file
@@ -0,0 +1,215 @@
|
||||
import { EncryptionProviderInterface } from './../Encryption/EncryptionProviderInterface'
|
||||
import { AnyKeyParamsContent } from '@standardnotes/common'
|
||||
import {
|
||||
BackupFileType,
|
||||
CreateAnyKeyParams,
|
||||
isItemsKey,
|
||||
isKeySystemItemsKey,
|
||||
SNItemsKey,
|
||||
SplitPayloadsByEncryptionType,
|
||||
} from '@standardnotes/encryption'
|
||||
import {
|
||||
BackupFile,
|
||||
CreateDecryptedItemFromPayload,
|
||||
CreatePayloadSplit,
|
||||
DecryptedPayload,
|
||||
DecryptedPayloadInterface,
|
||||
EncryptedPayload,
|
||||
EncryptedPayloadInterface,
|
||||
isDecryptedPayload,
|
||||
isDecryptedTransferPayload,
|
||||
isEncryptedPayload,
|
||||
isEncryptedTransferPayload,
|
||||
isKeySystemRootKey,
|
||||
ItemsKeyContent,
|
||||
ItemsKeyInterface,
|
||||
KeySystemItemsKeyInterface,
|
||||
KeySystemRootKeyInterface,
|
||||
} from '@standardnotes/models'
|
||||
import { extendArray } from '@standardnotes/utils'
|
||||
import { ContentType, Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import { GetBackupFileType } from './GetBackupFileType'
|
||||
import { DecryptBackupPayloads } from './DecryptBackupPayloads'
|
||||
import { KeySystemKeyManagerInterface } from '../KeySystem/KeySystemKeyManagerInterface'
|
||||
|
||||
export class DecryptBackupFile implements UseCaseInterface<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]> {
|
||||
constructor(
|
||||
private encryption: EncryptionProviderInterface,
|
||||
private keys: KeySystemKeyManagerInterface,
|
||||
private _getBackupFileType: GetBackupFileType,
|
||||
private _decryptBackupPayloads: DecryptBackupPayloads,
|
||||
) {}
|
||||
|
||||
async execute(
|
||||
file: BackupFile,
|
||||
password?: string,
|
||||
): Promise<Result<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]>> {
|
||||
const payloads = this.convertToPayloads(file)
|
||||
|
||||
const type = this._getBackupFileType.execute(file, payloads).getValue()
|
||||
|
||||
if (type === BackupFileType.Corrupt) {
|
||||
return Result.fail('Invalid backup file.')
|
||||
}
|
||||
|
||||
const { encrypted, decrypted } = CreatePayloadSplit(payloads)
|
||||
|
||||
if (type === BackupFileType.FullyDecrypted) {
|
||||
return Result.ok([...decrypted, ...encrypted])
|
||||
}
|
||||
|
||||
if (type === BackupFileType.EncryptedWithNonEncryptedItemsKey) {
|
||||
const result = await this.handleEncryptedWithNonEncryptedItemsKeyFileType(payloads)
|
||||
if (result.isFailed()) {
|
||||
return Result.fail(result.getError())
|
||||
}
|
||||
return Result.ok([...decrypted, ...result.getValue()])
|
||||
}
|
||||
|
||||
if (!password) {
|
||||
throw Error('Attempting to decrypt encrypted file with no password')
|
||||
}
|
||||
|
||||
const results = await this.handleEncryptedFileType({
|
||||
payloads: encrypted,
|
||||
file,
|
||||
password,
|
||||
})
|
||||
|
||||
if (results.isFailed()) {
|
||||
return Result.fail(results.getError())
|
||||
}
|
||||
|
||||
return Result.ok([...decrypted, ...results.getValue()])
|
||||
}
|
||||
|
||||
/** This is a backup file made from a session which had an encryption source, such as an account or a passcode. */
|
||||
private async handleEncryptedFileType(dto: {
|
||||
file: BackupFile
|
||||
password: string
|
||||
payloads: EncryptedPayloadInterface[]
|
||||
}): Promise<Result<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]>> {
|
||||
const keyParams = CreateAnyKeyParams((dto.file.keyParams || dto.file.auth_params) as AnyKeyParamsContent)
|
||||
const rootKey = await this.encryption.computeRootKey(dto.password, keyParams)
|
||||
|
||||
const results: (EncryptedPayloadInterface | DecryptedPayloadInterface)[] = []
|
||||
|
||||
const { rootKeyEncryption, itemsKeyEncryption, keySystemRootKeyEncryption } = SplitPayloadsByEncryptionType(
|
||||
dto.payloads,
|
||||
)
|
||||
|
||||
/** Decrypts items encrypted with a user root key, such as contacts, synced vault root keys, and items keys */
|
||||
const rootKeyBasedDecryptionResults = await this.encryption.decryptSplit({
|
||||
usesRootKey: {
|
||||
items: rootKeyEncryption || [],
|
||||
key: rootKey,
|
||||
},
|
||||
})
|
||||
|
||||
/** Extract items keys and synced vault root keys from root key decryption results */
|
||||
const recentlyDecryptedKeys: (ItemsKeyInterface | KeySystemItemsKeyInterface | KeySystemRootKeyInterface)[] =
|
||||
rootKeyBasedDecryptionResults
|
||||
.filter((x) => isItemsKey(x) || isKeySystemRootKey(x))
|
||||
.filter(isDecryptedPayload)
|
||||
.map((p) => CreateDecryptedItemFromPayload(p))
|
||||
|
||||
/**
|
||||
* Now handle encrypted keySystemRootKeyEncryption items (vault items keys). For every encrypted vault items key
|
||||
* find the respective vault root key, either from recently decrypted above, or from the key manager. Decrypt the
|
||||
* vault items key, and if successful, add it to recentlyDecryptedKeys so that it can be used to decrypt subsequent items
|
||||
*/
|
||||
for (const payload of keySystemRootKeyEncryption ?? []) {
|
||||
if (!payload.key_system_identifier) {
|
||||
throw new Error('Attempting to decrypt key system root key encrypted payload with no key system identifier')
|
||||
}
|
||||
|
||||
const keys = rootKeyBasedDecryptionResults
|
||||
.filter(isDecryptedPayload)
|
||||
.filter(isKeySystemRootKey)
|
||||
.map((p) => CreateDecryptedItemFromPayload(p)) as unknown as KeySystemRootKeyInterface[]
|
||||
|
||||
const key =
|
||||
keys.find((k) => k.systemIdentifier === payload.key_system_identifier) ??
|
||||
this.keys.getPrimaryKeySystemRootKey(payload.key_system_identifier)
|
||||
|
||||
if (!key) {
|
||||
results.push(
|
||||
payload.copy({
|
||||
errorDecrypting: true,
|
||||
}),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const result = await this.encryption.decryptSplitSingle({
|
||||
usesKeySystemRootKey: {
|
||||
items: [payload],
|
||||
key,
|
||||
},
|
||||
})
|
||||
|
||||
if (isDecryptedPayload(result) && isKeySystemItemsKey(result)) {
|
||||
recentlyDecryptedKeys.push(CreateDecryptedItemFromPayload(result))
|
||||
}
|
||||
|
||||
results.push(result)
|
||||
}
|
||||
|
||||
extendArray(results, rootKeyBasedDecryptionResults)
|
||||
|
||||
const payloadsToDecrypt = [...(itemsKeyEncryption ?? [])]
|
||||
|
||||
const decryptedPayloads = await this._decryptBackupPayloads.execute({
|
||||
payloads: payloadsToDecrypt,
|
||||
recentlyDecryptedKeys: recentlyDecryptedKeys,
|
||||
keyParams: keyParams,
|
||||
rootKey: rootKey,
|
||||
})
|
||||
if (decryptedPayloads.isFailed()) {
|
||||
return Result.fail(decryptedPayloads.getError())
|
||||
}
|
||||
|
||||
extendArray(results, decryptedPayloads.getValue())
|
||||
|
||||
return Result.ok(results)
|
||||
}
|
||||
|
||||
/**
|
||||
* These are backup files made when not signed into an account and without an encryption source such as a passcode.
|
||||
* In this case the items key exists in the backup in plaintext, but the items are encrypted with this items key.
|
||||
*/
|
||||
private async handleEncryptedWithNonEncryptedItemsKeyFileType(
|
||||
payloads: (EncryptedPayloadInterface | DecryptedPayloadInterface)[],
|
||||
): Promise<Result<(EncryptedPayloadInterface | DecryptedPayloadInterface)[]>> {
|
||||
const decryptedItemsKeys: DecryptedPayloadInterface<ItemsKeyContent>[] = []
|
||||
const encryptedPayloads: EncryptedPayloadInterface[] = []
|
||||
|
||||
payloads.forEach((payload) => {
|
||||
if (payload.content_type === ContentType.TYPES.ItemsKey && isDecryptedPayload(payload)) {
|
||||
decryptedItemsKeys.push(payload as DecryptedPayloadInterface<ItemsKeyContent>)
|
||||
} else if (isEncryptedPayload(payload)) {
|
||||
encryptedPayloads.push(payload)
|
||||
}
|
||||
})
|
||||
|
||||
const itemsKeys = decryptedItemsKeys.map((p) => CreateDecryptedItemFromPayload<ItemsKeyContent, SNItemsKey>(p))
|
||||
|
||||
return this._decryptBackupPayloads.execute({
|
||||
payloads: encryptedPayloads,
|
||||
recentlyDecryptedKeys: itemsKeys,
|
||||
rootKey: undefined,
|
||||
})
|
||||
}
|
||||
|
||||
private convertToPayloads(file: BackupFile): (EncryptedPayloadInterface | DecryptedPayloadInterface)[] {
|
||||
return file.items.map((item) => {
|
||||
if (isEncryptedTransferPayload(item)) {
|
||||
return new EncryptedPayload(item)
|
||||
} else if (isDecryptedTransferPayload(item)) {
|
||||
return new DecryptedPayload(item)
|
||||
} else {
|
||||
throw Error('Unhandled case in DecryptBackupFile')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
91
packages/services/src/Domain/Import/DecryptBackupPayloads.ts
Normal file
91
packages/services/src/Domain/Import/DecryptBackupPayloads.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import {
|
||||
EncryptedPayloadInterface,
|
||||
ItemsKeyInterface,
|
||||
RootKeyInterface,
|
||||
RootKeyParamsInterface,
|
||||
DecryptedPayloadInterface,
|
||||
isKeySystemRootKey,
|
||||
KeySystemRootKeyInterface,
|
||||
KeySystemItemsKeyInterface,
|
||||
} from '@standardnotes/models'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
import { DetermineKeyToUse } from './DetermineKeyToUse'
|
||||
import { isItemsKey, isKeySystemItemsKey } from '@standardnotes/encryption'
|
||||
import { LoggerInterface } from '@standardnotes/utils'
|
||||
|
||||
type EncryptedOrDecrypted = (DecryptedPayloadInterface | EncryptedPayloadInterface)[]
|
||||
|
||||
export class DecryptBackupPayloads implements UseCaseInterface<EncryptedOrDecrypted> {
|
||||
constructor(
|
||||
private encryption: EncryptionProviderInterface,
|
||||
private _determineKeyToUse: DetermineKeyToUse,
|
||||
private logger: LoggerInterface,
|
||||
) {}
|
||||
|
||||
async execute(dto: {
|
||||
payloads: EncryptedPayloadInterface[]
|
||||
recentlyDecryptedKeys: (ItemsKeyInterface | KeySystemItemsKeyInterface | KeySystemRootKeyInterface)[]
|
||||
rootKey: RootKeyInterface | undefined
|
||||
keyParams?: RootKeyParamsInterface
|
||||
}): Promise<Result<EncryptedOrDecrypted>> {
|
||||
const results: (DecryptedPayloadInterface | EncryptedPayloadInterface)[] = []
|
||||
|
||||
for (const encryptedPayload of dto.payloads) {
|
||||
try {
|
||||
const key = this._determineKeyToUse
|
||||
.execute({
|
||||
payload: encryptedPayload,
|
||||
recentlyDecryptedKeys: dto.recentlyDecryptedKeys,
|
||||
keyParams: dto.keyParams,
|
||||
rootKey: dto.rootKey,
|
||||
})
|
||||
.getValue()
|
||||
|
||||
if (!key) {
|
||||
results.push(
|
||||
encryptedPayload.copy({
|
||||
errorDecrypting: true,
|
||||
}),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if (isItemsKey(key) || isKeySystemItemsKey(key)) {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesItemsKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
} else if (isKeySystemRootKey(key)) {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesKeySystemRootKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
} else {
|
||||
const decryptedPayload = await this.encryption.decryptSplitSingle({
|
||||
usesRootKey: {
|
||||
items: [encryptedPayload],
|
||||
key: key,
|
||||
},
|
||||
})
|
||||
results.push(decryptedPayload)
|
||||
}
|
||||
} catch (e) {
|
||||
results.push(
|
||||
encryptedPayload.copy({
|
||||
errorDecrypting: true,
|
||||
}),
|
||||
)
|
||||
this.logger.error('Error decrypting payload', encryptedPayload, e)
|
||||
}
|
||||
}
|
||||
|
||||
return Result.ok(results)
|
||||
}
|
||||
}
|
||||
108
packages/services/src/Domain/Import/DetermineKeyToUse.ts
Normal file
108
packages/services/src/Domain/Import/DetermineKeyToUse.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { Result, SyncUseCaseInterface } from '@standardnotes/domain-core'
|
||||
import { compareVersions, leftVersionGreaterThanOrEqualToRight, ProtocolVersion } from '@standardnotes/common'
|
||||
import {
|
||||
ContentTypeUsesKeySystemRootKeyEncryption,
|
||||
ContentTypeUsesRootKeyEncryption,
|
||||
EncryptedPayloadInterface,
|
||||
ItemsKeyInterface,
|
||||
KeySystemItemsKeyInterface,
|
||||
RootKeyInterface,
|
||||
KeySystemRootKeyInterface,
|
||||
RootKeyParamsInterface,
|
||||
isKeySystemRootKey,
|
||||
} from '@standardnotes/models'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
import { KeySystemKeyManagerInterface } from '../KeySystem/KeySystemKeyManagerInterface'
|
||||
import { isItemsKey } from '@standardnotes/encryption'
|
||||
|
||||
type AnyKey = ItemsKeyInterface | RootKeyInterface | KeySystemRootKeyInterface | KeySystemItemsKeyInterface
|
||||
|
||||
export class DetermineKeyToUse implements SyncUseCaseInterface<AnyKey | undefined> {
|
||||
constructor(
|
||||
private encryption: EncryptionProviderInterface,
|
||||
private keys: KeySystemKeyManagerInterface,
|
||||
) {}
|
||||
|
||||
execute(dto: {
|
||||
payload: EncryptedPayloadInterface
|
||||
recentlyDecryptedKeys: (ItemsKeyInterface | KeySystemItemsKeyInterface | KeySystemRootKeyInterface)[]
|
||||
keyParams?: RootKeyParamsInterface
|
||||
rootKey?: RootKeyInterface
|
||||
}): Result<AnyKey | undefined> {
|
||||
if (ContentTypeUsesRootKeyEncryption(dto.payload.content_type)) {
|
||||
if (!dto.rootKey) {
|
||||
throw new Error('Attempting to decrypt root key encrypted payload with no root key')
|
||||
}
|
||||
return Result.ok(dto.rootKey)
|
||||
}
|
||||
|
||||
if (ContentTypeUsesKeySystemRootKeyEncryption(dto.payload.content_type)) {
|
||||
if (!dto.payload.key_system_identifier) {
|
||||
throw new Error('Attempting to decrypt key system root key encrypted payload with no key system identifier')
|
||||
}
|
||||
try {
|
||||
const recentlyDecrypted = dto.recentlyDecryptedKeys.filter(isKeySystemRootKey)
|
||||
let keySystemRootKey = recentlyDecrypted.find(
|
||||
(key) => key.systemIdentifier === dto.payload.key_system_identifier,
|
||||
)
|
||||
if (!keySystemRootKey) {
|
||||
keySystemRootKey = this.keys.getPrimaryKeySystemRootKey(dto.payload.key_system_identifier)
|
||||
}
|
||||
|
||||
return Result.ok(keySystemRootKey)
|
||||
} catch (error) {
|
||||
return Result.fail(JSON.stringify(error))
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.payload.key_system_identifier) {
|
||||
const keySystemItemsKey: KeySystemItemsKeyInterface | undefined = dto.recentlyDecryptedKeys.find(
|
||||
(key) => key.key_system_identifier === dto.payload.key_system_identifier,
|
||||
) as KeySystemItemsKeyInterface | undefined
|
||||
|
||||
if (keySystemItemsKey) {
|
||||
return Result.ok(keySystemItemsKey)
|
||||
}
|
||||
}
|
||||
|
||||
let itemsKey: ItemsKeyInterface | RootKeyInterface | KeySystemItemsKeyInterface | undefined
|
||||
|
||||
if (dto.payload.items_key_id) {
|
||||
itemsKey = this.encryption.itemsKeyForEncryptedPayload(dto.payload)
|
||||
if (itemsKey) {
|
||||
return Result.ok(itemsKey)
|
||||
}
|
||||
}
|
||||
|
||||
itemsKey = dto.recentlyDecryptedKeys.filter(isItemsKey).find((itemsKeyPayload) => {
|
||||
return Result.ok(dto.payload.items_key_id === itemsKeyPayload.uuid)
|
||||
})
|
||||
|
||||
if (itemsKey) {
|
||||
return Result.ok(itemsKey)
|
||||
}
|
||||
|
||||
if (!dto.keyParams) {
|
||||
return Result.ok(undefined)
|
||||
}
|
||||
|
||||
const payloadVersion = dto.payload.version as ProtocolVersion
|
||||
|
||||
/**
|
||||
* Payloads with versions <= 003 use root key directly for encryption.
|
||||
* However, if the incoming key params are >= 004, this means we should
|
||||
* have an items key based off the 003 root key. We can't use the 004
|
||||
* root key directly because it's missing dataAuthenticationKey.
|
||||
*/
|
||||
if (leftVersionGreaterThanOrEqualToRight(dto.keyParams.version, ProtocolVersion.V004)) {
|
||||
itemsKey = this.encryption.defaultItemsKeyForItemVersion(
|
||||
payloadVersion,
|
||||
dto.recentlyDecryptedKeys.filter(isItemsKey),
|
||||
)
|
||||
} else if (compareVersions(payloadVersion, ProtocolVersion.V003) <= 0) {
|
||||
itemsKey = dto.rootKey
|
||||
}
|
||||
|
||||
return Result.ok(itemsKey)
|
||||
}
|
||||
}
|
||||
24
packages/services/src/Domain/Import/GetBackupFileType.ts
Normal file
24
packages/services/src/Domain/Import/GetBackupFileType.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { ContentType, Result, SyncUseCaseInterface } from '@standardnotes/domain-core'
|
||||
import { BackupFileType } from '@standardnotes/encryption'
|
||||
import { BackupFile, PayloadInterface, isDecryptedPayload, isEncryptedPayload } from '@standardnotes/models'
|
||||
|
||||
export class GetBackupFileType implements SyncUseCaseInterface<BackupFileType> {
|
||||
execute(file: BackupFile, payloads: PayloadInterface[]): Result<BackupFileType> {
|
||||
if (file.keyParams || file.auth_params) {
|
||||
return Result.ok(BackupFileType.Encrypted)
|
||||
}
|
||||
|
||||
const hasEncryptedItem = payloads.find(isEncryptedPayload)
|
||||
const hasDecryptedItemsKey = payloads.find(
|
||||
(payload) => payload.content_type === ContentType.TYPES.ItemsKey && isDecryptedPayload(payload),
|
||||
)
|
||||
|
||||
if (hasEncryptedItem && hasDecryptedItemsKey) {
|
||||
return Result.ok(BackupFileType.EncryptedWithNonEncryptedItemsKey)
|
||||
} else if (!hasEncryptedItem) {
|
||||
return Result.ok(BackupFileType.FullyDecrypted)
|
||||
} else {
|
||||
return Result.ok(BackupFileType.Corrupt)
|
||||
}
|
||||
}
|
||||
}
|
||||
29
packages/services/src/Domain/Import/GetFilePassword.ts
Normal file
29
packages/services/src/Domain/Import/GetFilePassword.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import {
|
||||
Challenge,
|
||||
ChallengePrompt,
|
||||
ChallengeReason,
|
||||
ChallengeServiceInterface,
|
||||
ChallengeValidation,
|
||||
} from '../Challenge'
|
||||
import { Strings } from './Strings'
|
||||
|
||||
export class GetFilePassword implements UseCaseInterface<string> {
|
||||
constructor(private challenges: ChallengeServiceInterface) {}
|
||||
|
||||
async execute(): Promise<Result<string>> {
|
||||
const challenge = new Challenge(
|
||||
[new ChallengePrompt(ChallengeValidation.None, Strings.FileAccountPassword, undefined, true)],
|
||||
ChallengeReason.DecryptEncryptedFile,
|
||||
true,
|
||||
)
|
||||
|
||||
const passwordResponse = await this.challenges.promptForChallengeResponse(challenge)
|
||||
if (passwordResponse == undefined) {
|
||||
return Result.fail('Import aborted due to canceled password prompt')
|
||||
}
|
||||
|
||||
this.challenges.completeChallenge(challenge)
|
||||
return Result.ok(passwordResponse?.values[0].value as string)
|
||||
}
|
||||
}
|
||||
145
packages/services/src/Domain/Import/ImportData.ts
Normal file
145
packages/services/src/Domain/Import/ImportData.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { DecryptBackupFile } from './DecryptBackupFile'
|
||||
import { HistoryServiceInterface } from '../History/HistoryServiceInterface'
|
||||
import { PayloadManagerInterface } from '../Payloads/PayloadManagerInterface'
|
||||
import { ProtectionsClientInterface } from '../Protection/ProtectionClientInterface'
|
||||
import { SyncServiceInterface } from '../Sync/SyncServiceInterface'
|
||||
import { ItemManagerInterface } from '../Item/ItemManagerInterface'
|
||||
import { ProtocolVersion, compareVersions } from '@standardnotes/common'
|
||||
import {
|
||||
BackupFile,
|
||||
BackupFileDecryptedContextualPayload,
|
||||
CreateDecryptedBackupFileContextPayload,
|
||||
CreateEncryptedBackupFileContextPayload,
|
||||
DecryptedItemInterface,
|
||||
DecryptedPayloadInterface,
|
||||
EncryptedPayloadInterface,
|
||||
isDecryptedPayload,
|
||||
isEncryptedPayload,
|
||||
isEncryptedTransferPayload,
|
||||
} from '@standardnotes/models'
|
||||
import { Result, UseCaseInterface } from '@standardnotes/domain-core'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
import { Strings } from './Strings'
|
||||
import { ImportDataResult } from './ImportDataResult'
|
||||
import { GetFilePassword } from './GetFilePassword'
|
||||
|
||||
export class ImportData implements UseCaseInterface<ImportDataResult> {
|
||||
constructor(
|
||||
private items: ItemManagerInterface,
|
||||
private sync: SyncServiceInterface,
|
||||
private protections: ProtectionsClientInterface,
|
||||
private encryption: EncryptionProviderInterface,
|
||||
private payloads: PayloadManagerInterface,
|
||||
private history: HistoryServiceInterface,
|
||||
private _decryptBackFile: DecryptBackupFile,
|
||||
private _getFilePassword: GetFilePassword,
|
||||
) {}
|
||||
|
||||
async execute(data: BackupFile, awaitSync = false): Promise<Result<ImportDataResult>> {
|
||||
const versionValidation = this.validateFileVersion(data)
|
||||
if (versionValidation.isFailed()) {
|
||||
return Result.fail(versionValidation.getError())
|
||||
}
|
||||
|
||||
const decryptedPayloadsOrError = await this.decryptData(data)
|
||||
if (decryptedPayloadsOrError.isFailed()) {
|
||||
return Result.fail(decryptedPayloadsOrError.getError())
|
||||
}
|
||||
|
||||
const valid = this.getValidPayloadsToImportFromDecryptedResult(decryptedPayloadsOrError.getValue())
|
||||
|
||||
if (!(await this.protections.authorizeFileImport())) {
|
||||
return Result.fail('Import aborted')
|
||||
}
|
||||
|
||||
const affectedUuids = await this.payloads.importPayloads(valid, this.history.getHistoryMapCopy())
|
||||
|
||||
const promise = this.sync.sync()
|
||||
if (awaitSync) {
|
||||
await promise
|
||||
}
|
||||
|
||||
const affectedItems = this.items.findItems(affectedUuids) as DecryptedItemInterface[]
|
||||
|
||||
return Result.ok({
|
||||
affectedItems: affectedItems,
|
||||
errorCount: decryptedPayloadsOrError.getValue().length - valid.length,
|
||||
})
|
||||
}
|
||||
|
||||
private validateFileVersion(data: BackupFile): Result<void> {
|
||||
if (data.version) {
|
||||
const result = this.validateVersion(data.version)
|
||||
if (result.isFailed()) {
|
||||
return Result.fail(result.getError())
|
||||
}
|
||||
}
|
||||
return Result.ok()
|
||||
}
|
||||
|
||||
private async decryptData(
|
||||
data: BackupFile,
|
||||
): Promise<Result<(DecryptedPayloadInterface | EncryptedPayloadInterface)[]>> {
|
||||
let password: string | undefined
|
||||
|
||||
if (data.auth_params || data.keyParams) {
|
||||
const passwordResult = await this._getFilePassword.execute()
|
||||
if (passwordResult.isFailed()) {
|
||||
return Result.fail(passwordResult.getError())
|
||||
}
|
||||
password = passwordResult.getValue()
|
||||
}
|
||||
|
||||
this.cleanImportData(data)
|
||||
|
||||
const decryptedPayloadsOrError = await this._decryptBackFile.execute(data, password)
|
||||
if (decryptedPayloadsOrError.isFailed()) {
|
||||
return Result.fail(decryptedPayloadsOrError.getError())
|
||||
}
|
||||
|
||||
return Result.ok(decryptedPayloadsOrError.getValue())
|
||||
}
|
||||
|
||||
private getValidPayloadsToImportFromDecryptedResult(
|
||||
results: (DecryptedPayloadInterface | EncryptedPayloadInterface)[],
|
||||
): (EncryptedPayloadInterface | DecryptedPayloadInterface)[] {
|
||||
const decrypted = results.filter(isDecryptedPayload)
|
||||
const encrypted = results.filter(isEncryptedPayload)
|
||||
const vaulted = encrypted.filter((payload) => {
|
||||
return payload.key_system_identifier !== undefined
|
||||
})
|
||||
|
||||
const valid = [...decrypted, ...vaulted]
|
||||
return valid
|
||||
}
|
||||
|
||||
private cleanImportData(data: BackupFile): void {
|
||||
data.items = data.items.map((item) => {
|
||||
if (isEncryptedTransferPayload(item)) {
|
||||
return CreateEncryptedBackupFileContextPayload(item)
|
||||
} else {
|
||||
return CreateDecryptedBackupFileContextPayload(item as BackupFileDecryptedContextualPayload)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Prior to 003 backup files did not have a version field so we cannot
|
||||
* stop importing if there is no backup file version, only if there is
|
||||
* an unsupported version.
|
||||
*/
|
||||
private validateVersion(version: ProtocolVersion): Result<void> {
|
||||
const supportedVersions = this.encryption.supportedVersions()
|
||||
if (!supportedVersions.includes(version)) {
|
||||
return Result.fail(Strings.UnsupportedBackupFileVersion)
|
||||
}
|
||||
|
||||
const userVersion = this.encryption.getUserVersion()
|
||||
if (userVersion && compareVersions(version, userVersion) === 1) {
|
||||
/** File was made with a greater version than the user's account */
|
||||
return Result.fail(Strings.BackupFileMoreRecentThanAccount)
|
||||
}
|
||||
|
||||
return Result.ok()
|
||||
}
|
||||
}
|
||||
9
packages/services/src/Domain/Import/ImportDataResult.ts
Normal file
9
packages/services/src/Domain/Import/ImportDataResult.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { DecryptedItemInterface } from '@standardnotes/models'
|
||||
|
||||
export type ImportDataResult = {
|
||||
// Items that were either created or dirtied by this import
|
||||
affectedItems: DecryptedItemInterface[]
|
||||
|
||||
// The number of items that were not imported due to failure to decrypt.
|
||||
errorCount: number
|
||||
}
|
||||
7
packages/services/src/Domain/Import/Strings.ts
Normal file
7
packages/services/src/Domain/Import/Strings.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export const Strings = {
|
||||
UnsupportedBackupFileVersion:
|
||||
'This backup file was created using a newer version of the application and cannot be imported here. Please update your application and try again.',
|
||||
BackupFileMoreRecentThanAccount:
|
||||
"This backup file was created using a newer encryption version than your account's. Please run the available encryption upgrade and try again.",
|
||||
FileAccountPassword: 'File account password',
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
import { DecryptBackupFile } from '../Encryption/UseCase/DecryptBackupFile'
|
||||
import { HistoryServiceInterface } from '../History/HistoryServiceInterface'
|
||||
import { ChallengeServiceInterface } from '../Challenge/ChallengeServiceInterface'
|
||||
import { PayloadManagerInterface } from '../Payloads/PayloadManagerInterface'
|
||||
import { ProtectionsClientInterface } from '../Protection/ProtectionClientInterface'
|
||||
import { SyncServiceInterface } from '../Sync/SyncServiceInterface'
|
||||
import { ItemManagerInterface } from '../Item/ItemManagerInterface'
|
||||
import { ProtocolVersion, compareVersions } from '@standardnotes/common'
|
||||
import {
|
||||
BackupFile,
|
||||
BackupFileDecryptedContextualPayload,
|
||||
CreateDecryptedBackupFileContextPayload,
|
||||
CreateEncryptedBackupFileContextPayload,
|
||||
DecryptedItemInterface,
|
||||
isDecryptedPayload,
|
||||
isEncryptedPayload,
|
||||
isEncryptedTransferPayload,
|
||||
} from '@standardnotes/models'
|
||||
import { ClientDisplayableError } from '@standardnotes/responses'
|
||||
import { Challenge, ChallengePrompt, ChallengeReason, ChallengeValidation } from '../Challenge'
|
||||
import { Result } from '@standardnotes/domain-core'
|
||||
import { EncryptionProviderInterface } from '../Encryption/EncryptionProviderInterface'
|
||||
|
||||
const Strings = {
|
||||
UnsupportedBackupFileVersion:
|
||||
'This backup file was created using a newer version of the application and cannot be imported here. Please update your application and try again.',
|
||||
BackupFileMoreRecentThanAccount:
|
||||
"This backup file was created using a newer encryption version than your account's. Please run the available encryption upgrade and try again.",
|
||||
FileAccountPassword: 'File account password',
|
||||
}
|
||||
|
||||
export type ImportDataReturnType =
|
||||
| {
|
||||
affectedItems: DecryptedItemInterface[]
|
||||
errorCount: number
|
||||
}
|
||||
| {
|
||||
error: ClientDisplayableError
|
||||
}
|
||||
|
||||
export class ImportDataUseCase {
|
||||
constructor(
|
||||
private itemManager: ItemManagerInterface,
|
||||
private sync: SyncServiceInterface,
|
||||
private protectionService: ProtectionsClientInterface,
|
||||
private encryption: EncryptionProviderInterface,
|
||||
private payloadManager: PayloadManagerInterface,
|
||||
private challengeService: ChallengeServiceInterface,
|
||||
private historyService: HistoryServiceInterface,
|
||||
private _decryptBackFile: DecryptBackupFile,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @returns
|
||||
* .affectedItems: Items that were either created or dirtied by this import
|
||||
* .errorCount: The number of items that were not imported due to failure to decrypt.
|
||||
*/
|
||||
async execute(data: BackupFile, awaitSync = false): Promise<ImportDataReturnType> {
|
||||
if (data.version) {
|
||||
const result = this.validateVersion(data.version)
|
||||
if (result.isFailed()) {
|
||||
return { error: new ClientDisplayableError(result.getError()) }
|
||||
}
|
||||
}
|
||||
|
||||
let password: string | undefined
|
||||
|
||||
if (data.auth_params || data.keyParams) {
|
||||
const passwordResult = await this.getFilePassword()
|
||||
if (passwordResult.isFailed()) {
|
||||
return { error: new ClientDisplayableError(passwordResult.getError()) }
|
||||
}
|
||||
password = passwordResult.getValue()
|
||||
}
|
||||
|
||||
if (!(await this.protectionService.authorizeFileImport())) {
|
||||
return { error: new ClientDisplayableError('Import aborted') }
|
||||
}
|
||||
|
||||
data.items = data.items.map((item) => {
|
||||
if (isEncryptedTransferPayload(item)) {
|
||||
return CreateEncryptedBackupFileContextPayload(item)
|
||||
} else {
|
||||
return CreateDecryptedBackupFileContextPayload(item as BackupFileDecryptedContextualPayload)
|
||||
}
|
||||
})
|
||||
|
||||
const decryptedPayloadsOrError = await this._decryptBackFile.execute(data, password)
|
||||
if (decryptedPayloadsOrError instanceof ClientDisplayableError) {
|
||||
return { error: decryptedPayloadsOrError }
|
||||
}
|
||||
|
||||
const decryptedPayloads = decryptedPayloadsOrError.filter(isDecryptedPayload)
|
||||
const encryptedPayloads = decryptedPayloadsOrError.filter(isEncryptedPayload)
|
||||
const acceptableEncryptedPayloads = encryptedPayloads.filter((payload) => {
|
||||
return payload.key_system_identifier !== undefined
|
||||
})
|
||||
const importablePayloads = [...decryptedPayloads, ...acceptableEncryptedPayloads]
|
||||
|
||||
const affectedUuids = await this.payloadManager.importPayloads(
|
||||
importablePayloads,
|
||||
this.historyService.getHistoryMapCopy(),
|
||||
)
|
||||
|
||||
const promise = this.sync.sync()
|
||||
if (awaitSync) {
|
||||
await promise
|
||||
}
|
||||
|
||||
const affectedItems = this.itemManager.findItems(affectedUuids) as DecryptedItemInterface[]
|
||||
|
||||
return {
|
||||
affectedItems: affectedItems,
|
||||
errorCount: decryptedPayloadsOrError.length - importablePayloads.length,
|
||||
}
|
||||
}
|
||||
|
||||
private async getFilePassword(): Promise<Result<string>> {
|
||||
const challenge = new Challenge(
|
||||
[new ChallengePrompt(ChallengeValidation.None, Strings.FileAccountPassword, undefined, true)],
|
||||
ChallengeReason.DecryptEncryptedFile,
|
||||
true,
|
||||
)
|
||||
const passwordResponse = await this.challengeService.promptForChallengeResponse(challenge)
|
||||
if (passwordResponse == undefined) {
|
||||
/** Challenge was canceled */
|
||||
return Result.fail('Import aborted')
|
||||
}
|
||||
this.challengeService.completeChallenge(challenge)
|
||||
return Result.ok(passwordResponse?.values[0].value as string)
|
||||
}
|
||||
|
||||
/**
|
||||
* Prior to 003 backup files did not have a version field so we cannot
|
||||
* stop importing if there is no backup file version, only if there is
|
||||
* an unsupported version.
|
||||
*/
|
||||
private validateVersion(version: ProtocolVersion): Result<void> {
|
||||
const supportedVersions = this.encryption.supportedVersions()
|
||||
if (!supportedVersions.includes(version)) {
|
||||
return Result.fail(Strings.UnsupportedBackupFileVersion)
|
||||
}
|
||||
|
||||
const userVersion = this.encryption.getUserVersion()
|
||||
if (userVersion && compareVersions(version, userVersion) === 1) {
|
||||
/** File was made with a greater version than the user's account */
|
||||
return Result.fail(Strings.BackupFileMoreRecentThanAccount)
|
||||
}
|
||||
|
||||
return Result.ok()
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,6 @@ export * from './Encryption/UseCase/Asymmetric/DecryptMessage'
|
||||
export * from './Encryption/UseCase/Asymmetric/DecryptOwnMessage'
|
||||
export * from './Encryption/UseCase/Asymmetric/EncryptMessage'
|
||||
export * from './Encryption/UseCase/Asymmetric/GetMessageAdditionalData'
|
||||
export * from './Encryption/UseCase/DecryptBackupFile'
|
||||
export * from './Encryption/UseCase/DecryptErroredPayloads'
|
||||
export * from './Encryption/UseCase/GetKeyPairs'
|
||||
export * from './Encryption/UseCase/ItemsKey/CreateNewDefaultItemsKey'
|
||||
@@ -101,6 +100,15 @@ export * from './HomeServer/HomeServerManagerInterface'
|
||||
export * from './HomeServer/HomeServerService'
|
||||
export * from './HomeServer/HomeServerServiceInterface'
|
||||
export * from './HomeServer/HomeServerStatus'
|
||||
export * from './Import/DecryptBackupFile'
|
||||
export * from './Import/DecryptBackupPayloads'
|
||||
export * from './Import/DetermineKeyToUse'
|
||||
export * from './Import/GetBackupFileType'
|
||||
export * from './Import/GetFilePassword'
|
||||
export * from './Import/ImportData'
|
||||
export * from './Import/ImportDataResult'
|
||||
export * from './Import/CreateDecryptedBackupFile'
|
||||
export * from './Import/CreateEncryptedBackupFile'
|
||||
export * from './Integrity/IntegrityApiInterface'
|
||||
export * from './Integrity/IntegrityEvent'
|
||||
export * from './Integrity/IntegrityEventPayload'
|
||||
@@ -122,7 +130,6 @@ export * from './ItemsEncryption/ItemsEncryption'
|
||||
export * from './ItemsEncryption/ItemsEncryption'
|
||||
export * from './KeySystem/KeySystemKeyManager'
|
||||
export * from './Mfa/MfaServiceInterface'
|
||||
export * from './Mutator/ImportDataUseCase'
|
||||
export * from './Mutator/MutatorClientInterface'
|
||||
export * from './Payloads/PayloadManagerInterface'
|
||||
export * from './Preferences/PreferenceServiceInterface'
|
||||
|
||||
Reference in New Issue
Block a user