|
| 1 | +import { writeFile, access, readFile } from 'node:fs/promises'; |
| 2 | +import { constants } from 'node:fs'; |
| 3 | +import { Logger } from '@/application/Common/Log/Logger'; |
| 4 | +import { ElectronLogger } from '../Log/ElectronLogger'; |
| 5 | +import { |
| 6 | + FailedFileWrite, ReadbackFileWriter, FileWriteErrorType, |
| 7 | + FileWriteOutcome, SuccessfulFileWrite, |
| 8 | +} from './ReadbackFileWriter'; |
| 9 | + |
| 10 | +const FILE_ENCODING: NodeJS.BufferEncoding = 'utf-8'; |
| 11 | + |
| 12 | +export class NodeReadbackFileWriter implements ReadbackFileWriter { |
| 13 | + constructor( |
| 14 | + private readonly logger: Logger = ElectronLogger, |
| 15 | + private readonly fileSystem: FileReadWriteOperations = { |
| 16 | + writeFile, |
| 17 | + readFile: (path, encoding) => readFile(path, encoding), |
| 18 | + access, |
| 19 | + }, |
| 20 | + ) { } |
| 21 | + |
| 22 | + public async writeAndVerifyFile( |
| 23 | + filePath: string, |
| 24 | + fileContents: string, |
| 25 | + ): Promise<FileWriteOutcome> { |
| 26 | + this.logger.info(`Starting file write and verification process for: ${filePath}`); |
| 27 | + const fileWritePipelineActions: ReadonlyArray<() => Promise<FileWriteOutcome>> = [ |
| 28 | + () => this.createOrOverwriteFile(filePath, fileContents), |
| 29 | + () => this.verifyFileExistsWithoutReading(filePath), |
| 30 | + /* |
| 31 | + Reading the file contents back, we can detect if the file has been altered or |
| 32 | + removed post-creation. Removal of scripts when reading back is seen by some antivirus |
| 33 | + software when it falsely identifies a script as harmful. |
| 34 | + */ |
| 35 | + () => this.verifyFileContentsByReading(filePath, fileContents), |
| 36 | + ]; |
| 37 | + for (const action of fileWritePipelineActions) { |
| 38 | + const actionOutcome = await action(); // eslint-disable-line no-await-in-loop |
| 39 | + if (!actionOutcome.success) { |
| 40 | + return actionOutcome; |
| 41 | + } |
| 42 | + } |
| 43 | + return this.reportSuccess(`File successfully written and verified: ${filePath}`); |
| 44 | + } |
| 45 | + |
| 46 | + private async createOrOverwriteFile( |
| 47 | + filePath: string, |
| 48 | + fileContents: string, |
| 49 | + ): Promise<FileWriteOutcome> { |
| 50 | + try { |
| 51 | + this.logger.info(`Creating file at ${filePath}, size: ${fileContents.length} characters`); |
| 52 | + await this.fileSystem.writeFile(filePath, fileContents, FILE_ENCODING); |
| 53 | + return this.reportSuccess('Created file.'); |
| 54 | + } catch (error) { |
| 55 | + return this.reportFailure('WriteOperationFailed', error); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + private async verifyFileExistsWithoutReading( |
| 60 | + filePath: string, |
| 61 | + ): Promise<FileWriteOutcome> { |
| 62 | + try { |
| 63 | + await this.fileSystem.access(filePath, constants.F_OK); |
| 64 | + return this.reportSuccess('Verified file existence without reading.'); |
| 65 | + } catch (error) { |
| 66 | + return this.reportFailure('FileExistenceVerificationFailed', error); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private async verifyFileContentsByReading( |
| 71 | + filePath: string, |
| 72 | + expectedFileContents: string, |
| 73 | + ): Promise<FileWriteOutcome> { |
| 74 | + try { |
| 75 | + const actualFileContents = await this.fileSystem.readFile(filePath, FILE_ENCODING); |
| 76 | + if (actualFileContents !== expectedFileContents) { |
| 77 | + return this.reportFailure( |
| 78 | + 'ContentVerificationFailed', |
| 79 | + [ |
| 80 | + 'The contents of the written file do not match the expected contents.', |
| 81 | + 'Written file contents do not match the expected file contents', |
| 82 | + `File path: ${filePath}`, |
| 83 | + `Expected total characters: ${actualFileContents.length}`, |
| 84 | + `Actual total characters: ${expectedFileContents.length}`, |
| 85 | + ].join('\n'), |
| 86 | + ); |
| 87 | + } |
| 88 | + return this.reportSuccess('Verified file content by reading.'); |
| 89 | + } catch (error) { |
| 90 | + return this.reportFailure('ReadVerificationFailed', error); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + private reportFailure( |
| 95 | + errorType: FileWriteErrorType, |
| 96 | + error: Error | string, |
| 97 | + ): FailedFileWrite { |
| 98 | + this.logger.error('Error saving file', errorType, error); |
| 99 | + return { |
| 100 | + success: false, |
| 101 | + error: { |
| 102 | + type: errorType, |
| 103 | + message: typeof error === 'string' ? error : error.message, |
| 104 | + }, |
| 105 | + }; |
| 106 | + } |
| 107 | + |
| 108 | + private reportSuccess(successAction: string): SuccessfulFileWrite { |
| 109 | + this.logger.info(`Successful file save: ${successAction}`); |
| 110 | + return { |
| 111 | + success: true, |
| 112 | + }; |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +export interface FileReadWriteOperations { |
| 117 | + readonly writeFile: typeof writeFile; |
| 118 | + readonly access: typeof access; |
| 119 | + readFile: (filePath: string, encoding: NodeJS.BufferEncoding) => Promise<string>; |
| 120 | +} |
0 commit comments