From b404a91ada509e19a287d026d55db0035ff6233b Mon Sep 17 00:00:00 2001 From: undergroundwires Date: Tue, 9 Jan 2024 20:44:06 +0100 Subject: [PATCH] Fix invisible script execution on Windows #264 This commit addresses an issue in the privacy.sexy desktop application where scripts executed as administrator on Windows were running in the background. This was observed in environments like Windows Pro VMs on Azure, where operations typically run with administrative privileges. Previously, the application used the `"$path"` shell command to execute scripts. This mechanism failed to activate the logic for requesting admin privileges if the app itself was running as an administrator. To resolve this, the script execution process has been modified to explicitly ask for administrator privileges using the `VerbAs` method. This ensures that the script always runs in a new `cmd.exe` window, enhancing visibility and user interaction. Other supporting changes: - Rename the generated script file from `run-{timestamp}-{extension}` er to `{timestamp}-privacy-script-{extension}` for clearer identification and better file sorting. - Refactor `ScriptFileCreator` to parameterize file extension and script name. - Rename `OsTimestampedFilenameGenerator` to `TimestampedFilenameGenerator` to better reflect its new and more scoped functionality after refactoring mentioned abvoe. - Remove `setAppName()` due to ineffective behavior in Windows. - Update `SECURITY.md` to highlight that the app doesn't require admin rights for standard operations. - Add `.editorconfig` settings for PowerShell scripts. - Add a integration test for script execution logic. Improve environment detection for more reliable test execution. - Disable application logging during unit/integration tests to keep test outputs clean and focused. --- .editorconfig | 13 +- SECURITY.md | 4 + .../{ => CodeRunner}/CodeRunner.ts | 1 + src/application/CodeRunner/ScriptFileName.ts | 1 + .../Creation/Filename/FilenameGenerator.ts | 4 +- .../OsTimestampedFilenameGenerator.ts | 47 ----- .../Filename/TimestampedFilenameGenerator.ts | 31 ++++ .../ScriptFileCreationOrchestrator.ts | 17 +- .../CodeRunner/Creation/ScriptFileCreator.ts | 10 +- .../VisibleTerminalScriptFileExecutor.ts | 110 ++++++++--- .../CodeRunner/ScriptFileCodeRunner.ts | 14 +- .../RuntimeEnvironmentFactory.ts | 21 ++- .../WindowVariables/WindowVariables.ts | 2 +- .../bootstrapping/ClientLoggerFactory.ts | 32 +++- .../Code/CodeButtons/CodeRunButton.vue | 5 +- .../Code/CodeButtons/Save/CodeSaveButton.vue | 7 +- .../electron/main/IpcRegistration.ts | 2 +- src/presentation/electron/main/index.ts | 12 -- .../IpcBridging/IpcChannelDefinitions.ts | 2 +- .../CodeRunner/ScriptFileCodeRunner.spec.ts | 89 +++++++++ tests/shared/Assertions/ExpectExists.ts | 8 +- .../OsTimestampedFilenameGenerator.spec.ts | 103 ----------- .../TimestampedFilenameGenerator.spec.ts | 124 +++++++++++++ .../ScriptFileCreationOrchestrator.spec.ts | 38 +++- .../VisibleTerminalScriptFileExecutor.spec.ts | 2 +- .../CodeRunner/ScriptFileCodeRunner.spec.ts | 55 +++++- .../RuntimeEnvironmentFactory.spec.ts | 56 +++++- .../bootstrapping/ClientLoggerFactory.spec.ts | 171 +++++++++++++----- tests/unit/shared/Stubs/CodeRunnerStub.ts | 2 +- .../shared/Stubs/FilenameGeneratorStub.ts | 12 +- .../shared/Stubs/ScriptFileCreatorStub.ts | 9 +- .../unit/shared/Stubs/WindowVariablesStub.ts | 2 +- 32 files changed, 716 insertions(+), 290 deletions(-) rename src/application/{ => CodeRunner}/CodeRunner.ts (75%) create mode 100644 src/application/CodeRunner/ScriptFileName.ts delete mode 100644 src/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.ts create mode 100644 src/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.ts create mode 100644 tests/integration/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts delete mode 100644 tests/unit/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.spec.ts create mode 100644 tests/unit/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.spec.ts diff --git a/.editorconfig b/.editorconfig index 2d899627..8428577b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,10 +1,11 @@ -# Top-most EditorConfig file -root = true +root = true # Top-most EditorConfig file + +[*] +end_of_line = lf [*.{js,jsx,ts,tsx,vue,sh}] indent_style = space indent_size = 2 -end_of_line = lf trim_trailing_whitespace = true insert_final_newline = true max_line_length = 100 @@ -17,3 +18,9 @@ indent_size = 4 indent_size = 4 # PEP 8 (the official Python style guide) recommends using 4 spaces per indentation level indent_style = space max_line_length = 100 + +[*.ps1] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/SECURITY.md b/SECURITY.md index 7d5abbe8..33132c60 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -37,6 +37,10 @@ privacy.sexy adopts a defense in depth strategy to protect users on multiple lay - **Auditing and Transparency:** The desktop application improves security and transparency by logging application activities and retaining files of executed scripts This facilitates detailed auditability and effective troubleshooting, contributing to the integrity and reliability of the application. +- **Privilege Management:** + The desktop application operates without persistent administrative or `sudo` privileges, reinforcing its security posture. It requests + elevation of privileges for system modifications with explicit user consent and logs every action taken with high privileges. This + approach actively minimizes potential security risks by limiting privileged operations and aligning with the principle of least privilege. ### Update Security and Integrity diff --git a/src/application/CodeRunner.ts b/src/application/CodeRunner/CodeRunner.ts similarity index 75% rename from src/application/CodeRunner.ts rename to src/application/CodeRunner/CodeRunner.ts index 5bbfacab..176eda1a 100644 --- a/src/application/CodeRunner.ts +++ b/src/application/CodeRunner/CodeRunner.ts @@ -1,5 +1,6 @@ export interface CodeRunner { runCode( code: string, + fileExtension: string, ): Promise; } diff --git a/src/application/CodeRunner/ScriptFileName.ts b/src/application/CodeRunner/ScriptFileName.ts new file mode 100644 index 00000000..b108db12 --- /dev/null +++ b/src/application/CodeRunner/ScriptFileName.ts @@ -0,0 +1 @@ +export const ScriptFileName = 'privacy-script' as const; diff --git a/src/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator.ts b/src/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator.ts index be5428f1..6c5615ca 100644 --- a/src/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator.ts +++ b/src/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator.ts @@ -1,3 +1,5 @@ +import { ScriptFileNameParts } from '../ScriptFileCreator'; + export interface FilenameGenerator { - generateFilename(): string; + generateFilename(scriptFileNameParts: ScriptFileNameParts): string; } diff --git a/src/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.ts b/src/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.ts deleted file mode 100644 index 66ee8d4b..00000000 --- a/src/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { OperatingSystem } from '@/domain/OperatingSystem'; -import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment'; -import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory'; -import { FilenameGenerator } from './FilenameGenerator'; - -/** - * Generates a timestamped filename specific to the given operating system. - * - * The filename includes: - * - A timestamp for uniqueness and easier auditability. - * - File extension based on the operating system. - */ -export class OsTimestampedFilenameGenerator implements FilenameGenerator { - private readonly currentOs?: OperatingSystem; - - constructor( - environment: RuntimeEnvironment = CurrentEnvironment, - ) { - this.currentOs = environment.os; - } - - public generateFilename( - date = new Date(), - ): string { - const baseFileName = `run-${createTimeStampForFile(date)}`; - const extension = this.currentOs === undefined ? undefined : FileExtensions[this.currentOs]; - return extension ? `${baseFileName}.${extension}` : baseFileName; - } -} - -const FileExtensions: Partial> = { - // '.bat' for Windows batch files; required for executability. - [OperatingSystem.Windows]: 'bat', - - // '.sh' for Unix-like systems; enhances recognition as a shell script - [OperatingSystem.macOS]: 'sh', - [OperatingSystem.Linux]: 'sh', -}; - -/** Generates a timestamp for the filename in 'YYYY-MM-DD_HH-MM-SS' format. */ -function createTimeStampForFile(date: Date): string { - return date - .toISOString() - .replace(/T/, '_') - .replace(/:/g, '-') - .replace(/\..+/, ''); -} diff --git a/src/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.ts b/src/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.ts new file mode 100644 index 00000000..81d3c237 --- /dev/null +++ b/src/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.ts @@ -0,0 +1,31 @@ +import { ScriptFileNameParts } from '../ScriptFileCreator'; +import { FilenameGenerator } from './FilenameGenerator'; + +export class TimestampedFilenameGenerator implements FilenameGenerator { + public generateFilename( + scriptFileNameParts: ScriptFileNameParts, + date = new Date(), + ): string { + validateScriptFileNameParts(scriptFileNameParts); + const baseFileName = `${createTimeStampForFile(date)}-${scriptFileNameParts.scriptName}`; + return scriptFileNameParts.scriptFileExtension ? `${baseFileName}.${scriptFileNameParts.scriptFileExtension}` : baseFileName; + } +} + +/** Generates a timestamp for the filename in 'YYYY-MM-DD_HH-MM-SS' format. */ +function createTimeStampForFile(date: Date): string { + return date + .toISOString() + .replace(/T/, '_') + .replace(/:/g, '-') + .replace(/\..+/, ''); +} + +function validateScriptFileNameParts(scriptFileNameParts: ScriptFileNameParts) { + if (!scriptFileNameParts.scriptName) { + throw new Error('Script name is required but not provided.'); + } + if (scriptFileNameParts.scriptFileExtension?.startsWith('.')) { + throw new Error('File extension should not start with a dot.'); + } +} diff --git a/src/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.ts b/src/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.ts index fc8725b5..8e485fa9 100644 --- a/src/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.ts +++ b/src/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.ts @@ -3,27 +3,30 @@ import { Logger } from '@/application/Common/Log/Logger'; import { SystemOperations } from '../System/SystemOperations'; import { NodeElectronSystemOperations } from '../System/NodeElectronSystemOperations'; import { FilenameGenerator } from './Filename/FilenameGenerator'; -import { ScriptFileCreator } from './ScriptFileCreator'; -import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator'; +import { ScriptFileNameParts, ScriptFileCreator } from './ScriptFileCreator'; +import { TimestampedFilenameGenerator } from './Filename/TimestampedFilenameGenerator'; import { ScriptDirectoryProvider } from './Directory/ScriptDirectoryProvider'; import { PersistentDirectoryProvider } from './Directory/PersistentDirectoryProvider'; export class ScriptFileCreationOrchestrator implements ScriptFileCreator { constructor( private readonly system: SystemOperations = new NodeElectronSystemOperations(), - private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(), + private readonly filenameGenerator: FilenameGenerator = new TimestampedFilenameGenerator(), private readonly directoryProvider: ScriptDirectoryProvider = new PersistentDirectoryProvider(), private readonly logger: Logger = ElectronLogger, ) { } - public async createScriptFile(contents: string): Promise { - const filePath = await this.provideFilePath(); + public async createScriptFile( + contents: string, + scriptFileNameParts: ScriptFileNameParts, + ): Promise { + const filePath = await this.provideFilePath(scriptFileNameParts); await this.createFile(filePath, contents); return filePath; } - private async provideFilePath(): Promise { - const filename = this.filenameGenerator.generateFilename(); + private async provideFilePath(scriptFileNameParts: ScriptFileNameParts): Promise { + const filename = this.filenameGenerator.generateFilename(scriptFileNameParts); const directoryPath = await this.directoryProvider.provideScriptDirectory(); const filePath = this.system.location.combinePaths(directoryPath, filename); return filePath; diff --git a/src/infrastructure/CodeRunner/Creation/ScriptFileCreator.ts b/src/infrastructure/CodeRunner/Creation/ScriptFileCreator.ts index f501c596..e4cd2493 100644 --- a/src/infrastructure/CodeRunner/Creation/ScriptFileCreator.ts +++ b/src/infrastructure/CodeRunner/Creation/ScriptFileCreator.ts @@ -1,3 +1,11 @@ export interface ScriptFileCreator { - createScriptFile(contents: string): Promise; + createScriptFile( + contents: string, + scriptFileNameParts: ScriptFileNameParts, + ): Promise; +} + +export interface ScriptFileNameParts { + readonly scriptName: string; + readonly scriptFileExtension: string | undefined; } diff --git a/src/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.ts b/src/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.ts index 68ad2971..f0867f67 100644 --- a/src/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.ts +++ b/src/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.ts @@ -24,6 +24,10 @@ export class VisibleTerminalScriptExecutor implements ScriptFileExecutor { } private async setFileExecutablePermissions(filePath: string): Promise { + /* + This is required on macOS and Linux otherwise the terminal emulators will refuse to + execute the script. It's not needed on Windows. + */ this.logger.info(`Setting execution permissions for file at ${filePath}`); await this.system.fileSystem.setFilePermissions(filePath, '755'); this.logger.info(`Execution permissions set successfully for ${filePath}`); @@ -53,43 +57,93 @@ interface TerminalExecutionContext { type TerminalRunner = (context: TerminalExecutionContext) => Promise; +export const LinuxTerminalEmulator = 'x-terminal-emulator'; + const TerminalRunners: Partial> = { [OperatingSystem.Windows]: async (context) => { + const command = [ + 'PowerShell', + 'Start-Process', + '-Verb RunAs', // Run as administrator with GUI sudo prompt + `-FilePath ${cmdShellPathArgumentEscape(context.scriptFilePath)}`, + ].join(' '); /* - Options: - "path": - ✅ Launches the script within `cmd.exe`. - ✅ Uses user-friendly GUI sudo prompt. + 📝 Options: + `child_process.execFile()` + "path", `cmd.exe /c "path"` + ❌ Script execution in the background without a visible terminal. + This occurs only when the user runs the application as administrator, as seen + in Windows Pro VMs on Azure. + `PowerShell Start -Verb RunAs "path"` + ✅ Visible terminal window + ✅ GUI sudo prompt (through `RunAs` option) + `PowerShell Start "path"` + `explorer.exe "path"` + `electron.shell.openPath` + `start cmd.exe /c "$path"` + ✅ Visible terminal window + ✅ GUI sudo prompt (through `RunAs` option) + 👍 Among all options `start` command is the most explicit one, being the most resilient + against the potential changes in Windows or Electron framework (e.g. https://github.com/electron/electron/issues/36765). + `%COMSPEC%` environment variable should be checked before defaulting to `cmd.exe. + Related docs: https://web.archive.org/web/20240106002357/https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows */ - const command = cmdShellPathArgumentEscape(context.scriptFilePath); await runCommand(command, context); }, [OperatingSystem.Linux]: async (context) => { - const command = `x-terminal-emulator -e ${posixShellPathArgumentEscape(context.scriptFilePath)}`; + const command = `${LinuxTerminalEmulator} -e ${posixShellPathArgumentEscape(context.scriptFilePath)}`; /* - Options: - `x-terminal-emulator -e`: - ✅ Launches the script within the default terminal emulator. - ❌ Requires terminal-based (not GUI) sudo prompt, which may not be very user friendly. + 🤔 Potential improvements: + Use user-friendly GUI sudo prompt (not terminal-based). + If `pkexec` exists, we could do `x-terminal-emulator -e pkexec 'path'`, which always + prompts with user-friendly GUI sudo prompt. + 📝 Options: + `x-terminal-emulator -e 'path'`: + ✅ Visible terminal window + ❌ Terminal-based (not GUI) sudo prompt. + `x-terminal-emulator -e pkexec 'path' + ✅ Visible terminal window + ✅ Always prompts with user-friendly GUI sudo prompt. + 🤔 Not using `pkexec` as it is not in all Linux distributions. It should have smarter + logic to handle if it does not exist. + `electron.shell.openPath`: + ❌ Opens the script in the default text editor, verified on + Debian/Ubuntu-based distributions. + `child_process.execFile()`: + ❌ Script execution in the background without a visible terminal. */ await runCommand(command, context); }, [OperatingSystem.macOS]: async (context) => { const command = `open -a Terminal.app ${posixShellPathArgumentEscape(context.scriptFilePath)}`; + // -a Specifies the application to use for opening the file + /* eslint-disable vue/max-len */ /* - Options: - `open -a Terminal.app`: - ✅ Launches the script within Terminal app, that exists natively in all modern macOS - versions. - ❌ Requires terminal-based (not GUI) sudo prompt, which may not be very user friendly. - ❌ Terminal app requires many privileges to execute the script, this would prompt user - to grant privileges to the Terminal app. - - `osascript -e "do shell script \\"${scriptPath}\\" with administrator privileges"`: - ✅ Uses user-friendly GUI sudo prompt. - ❌ Executes the script in the background, which does not provide the user with immediate - visual feedback or allow interaction with the script as it runs. + 🤔 Potential improvements: + Use user-friendly GUI sudo prompt for running the script. + 📝 Options: + `open -a Terminal.app 'path'` + ✅ Visible terminal window + ❌ Terminal-based (not GUI) sudo prompt. + ❌ Terminal app requires many privileges to execute the script, this prompts user + to grant privileges to the Terminal app. + `osascript -e 'do shell script "'/tmp/test.sh'" with administrator privileges'` + ✅ Script as root + ✅ GUI sudo prompt. + ❌ Script execution in the background without a visible terminal. + `osascript -e 'do shell script "open -a 'Terminal.app' '/tmp/test.sh'" with administrator privileges'` + ❌ Script as user, not root + ✅ GUI sudo prompt. + ✅ Visible terminal window + `osascript -e 'do shell script "/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal '/tmp/test.sh'" with administrator privileges'` + ✅ Script as root + ✅ GUI sudo prompt. + ✅ Visible terminal window + Useful resources about `do shell script .. with administrator privileges`: + - Change "osascript wants to make changes" prompt: https://web.archive.org/web/20240109191128/https://apple.stackexchange.com/questions/283353/how-to-rename-osascript-in-the-administrator-privileges-dialog + - More about `do shell script`: https://web.archive.org/web/20100906222226/http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html */ + /* eslint-enable vue/max-len */ await runCommand(command, context); }, } as const; @@ -101,11 +155,13 @@ async function runCommand(command: string, context: TerminalExecutionContext): P } function posixShellPathArgumentEscape(pathArgument: string): string { - // - Wraps the path in single quotes, which is a standard practice in POSIX shells - // (like bash and zsh) found on macOS/Linux to ensure that characters like spaces, '*', and - // '?' are treated as literals, not as special characters. - // - Escapes any single quotes within the path itself. This allows paths containing single - // quotes to be correctly interpreted in POSIX-compliant systems, such as Linux and macOS. + /* + - Wraps the path in single quotes, which is a standard practice in POSIX shells + (like bash and zsh) found on macOS/Linux to ensure that characters like spaces, '*', and + '?' are treated as literals, not as special characters. + - Escapes any single quotes within the path itself. This allows paths containing single + quotes to be correctly interpreted in POSIX-compliant systems, such as Linux and macOS. + */ return `'${pathArgument.replaceAll('\'', '\'\\\'\'')}'`; } diff --git a/src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts b/src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts index 2bff29fe..3b4ef39e 100644 --- a/src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts +++ b/src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts @@ -1,24 +1,30 @@ -import { CodeRunner } from '@/application/CodeRunner'; import { Logger } from '@/application/Common/Log/Logger'; +import { ScriptFileName } from '@/application/CodeRunner/ScriptFileName'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; import { ElectronLogger } from '../Log/ElectronLogger'; import { ScriptFileExecutor } from './Execution/ScriptFileExecutor'; -import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor'; import { ScriptFileCreator } from './Creation/ScriptFileCreator'; import { ScriptFileCreationOrchestrator } from './Creation/ScriptFileCreationOrchestrator'; +import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor'; export class ScriptFileCodeRunner implements CodeRunner { constructor( - private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(), + private readonly scriptFileExecutor + : ScriptFileExecutor = new VisibleTerminalScriptExecutor(), private readonly scriptFileCreator: ScriptFileCreator = new ScriptFileCreationOrchestrator(), private readonly logger: Logger = ElectronLogger, ) { } public async runCode( code: string, + fileExtension: string, ): Promise { this.logger.info('Initiating script running process.'); try { - const scriptFilePath = await this.scriptFileCreator.createScriptFile(code); + const scriptFilePath = await this.scriptFileCreator.createScriptFile(code, { + scriptName: ScriptFileName, + scriptFileExtension: fileExtension, + }); await this.scriptFileExecutor.executeScriptFile(scriptFilePath); this.logger.info(`Successfully ran script at ${scriptFilePath}`); } catch (error) { diff --git a/src/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.ts b/src/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.ts index 10df3ec9..b3328810 100644 --- a/src/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.ts +++ b/src/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.ts @@ -2,26 +2,33 @@ import { BrowserRuntimeEnvironment } from './Browser/BrowserRuntimeEnvironment'; import { NodeRuntimeEnvironment } from './Node/NodeRuntimeEnvironment'; import { RuntimeEnvironment } from './RuntimeEnvironment'; -export const CurrentEnvironment = determineAndCreateRuntimeEnvironment( - () => globalThis.window, -); +export const CurrentEnvironment = determineAndCreateRuntimeEnvironment({ + getGlobalWindow: () => globalThis.window, + getGlobalProcess: () => globalThis.process, +}); export function determineAndCreateRuntimeEnvironment( - windowAccessor: WindowAccessor, + globalAccessor: GlobalAccessor, browserEnvironmentFactory: BrowserRuntimeEnvironmentFactory = ( window, ) => new BrowserRuntimeEnvironment(window), nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory = () => new NodeRuntimeEnvironment(), ): RuntimeEnvironment { - const window = windowAccessor(); + if (globalAccessor.getGlobalProcess()) { + return nodeEnvironmentFactory(); + } + const window = globalAccessor.getGlobalWindow(); if (window) { return browserEnvironmentFactory(window); } - return nodeEnvironmentFactory(); + throw new Error('Unsupported runtime environment: The current context is neither a recognized browser nor a Node.js environment.'); } export type BrowserRuntimeEnvironmentFactory = (window: Window) => RuntimeEnvironment; export type NodeRuntimeEnvironmentFactory = () => NodeRuntimeEnvironment; -export type WindowAccessor = () => Window | undefined; +export interface GlobalAccessor { + getGlobalWindow(): Window | undefined; + getGlobalProcess(): NodeJS.Process | undefined; +} diff --git a/src/infrastructure/WindowVariables/WindowVariables.ts b/src/infrastructure/WindowVariables/WindowVariables.ts index aa61f9a2..74e4286b 100644 --- a/src/infrastructure/WindowVariables/WindowVariables.ts +++ b/src/infrastructure/WindowVariables/WindowVariables.ts @@ -1,6 +1,6 @@ import { OperatingSystem } from '@/domain/OperatingSystem'; import { Logger } from '@/application/Common/Log/Logger'; -import { CodeRunner } from '@/application/CodeRunner'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; /* Primary entry point for platform-specific injections */ export interface WindowVariables { diff --git a/src/presentation/bootstrapping/ClientLoggerFactory.ts b/src/presentation/bootstrapping/ClientLoggerFactory.ts index 56b246d6..26dfda13 100644 --- a/src/presentation/bootstrapping/ClientLoggerFactory.ts +++ b/src/presentation/bootstrapping/ClientLoggerFactory.ts @@ -13,15 +13,41 @@ export class ClientLoggerFactory implements LoggerFactory { protected constructor( environment: RuntimeEnvironment = CurrentEnvironment, + windowAccessor: WindowAccessor = () => globalThis.window, + noopLoggerFactory: LoggerCreationFunction = () => new NoopLogger(), + windowInjectedLoggerFactory: LoggerCreationFunction = () => new WindowInjectedLogger(), + consoleLoggerFactory: LoggerCreationFunction = () => new ConsoleLogger(), ) { + if (isUnitOrIntegrationTests(environment, windowAccessor)) { + this.logger = noopLoggerFactory(); // keep the test outputs clean + return; + } if (environment.isDesktop) { - this.logger = new WindowInjectedLogger(); + this.logger = windowInjectedLoggerFactory(); return; } if (environment.isNonProduction) { - this.logger = new ConsoleLogger(); + this.logger = consoleLoggerFactory(); return; } - this.logger = new NoopLogger(); + this.logger = noopLoggerFactory(); } } + +export type WindowAccessor = () => OptionalWindow; + +export type LoggerCreationFunction = () => Logger; + +type OptionalWindow = Window | undefined | null; + +function isUnitOrIntegrationTests( + environment: RuntimeEnvironment, + windowAccessor: WindowAccessor, +): boolean { + /* + In a desktop application context, Electron preloader process inject a logger into + the global window object. If we're in a desktop (Node) environment and the logger isn't + injected, it indicates a testing environment. + */ + return environment.isDesktop && !windowAccessor()?.log; +} diff --git a/src/presentation/components/Code/CodeButtons/CodeRunButton.vue b/src/presentation/components/Code/CodeButtons/CodeRunButton.vue index c8a38693..bb919373 100644 --- a/src/presentation/components/Code/CodeButtons/CodeRunButton.vue +++ b/src/presentation/components/Code/CodeButtons/CodeRunButton.vue @@ -26,7 +26,10 @@ export default defineComponent({ async function executeCode() { if (!codeRunner) { throw new Error('missing code runner'); } - await codeRunner.runCode(currentContext.state.code.current); + await codeRunner.runCode( + currentContext.state.code.current, + currentContext.state.collection.scripting.fileExtension, + ); } return { diff --git a/src/presentation/components/Code/CodeButtons/Save/CodeSaveButton.vue b/src/presentation/components/Code/CodeButtons/Save/CodeSaveButton.vue index 586cb77c..a9d6e183 100644 --- a/src/presentation/components/Code/CodeButtons/Save/CodeSaveButton.vue +++ b/src/presentation/components/Code/CodeButtons/Save/CodeSaveButton.vue @@ -21,6 +21,7 @@ import ModalDialog from '@/presentation/components/Shared/Modal/ModalDialog.vue' import { IReadOnlyCategoryCollectionState } from '@/application/Context/State/ICategoryCollectionState'; import { ScriptingLanguage } from '@/domain/ScriptingLanguage'; import { IScriptingDefinition } from '@/domain/IScriptingDefinition'; +import { ScriptFileName } from '@/application/CodeRunner/ScriptFileName'; import IconButton from '../IconButton.vue'; import InstructionList from './Instructions/InstructionList.vue'; import { IInstructionListData } from './Instructions/InstructionListData'; @@ -74,11 +75,11 @@ function getType(language: ScriptingLanguage) { throw new Error('unknown file type'); } } + function buildFileName(scripting: IScriptingDefinition) { - const fileName = 'privacy-script'; if (scripting.fileExtension) { - return `${fileName}.${scripting.fileExtension}`; + return `${ScriptFileName}.${scripting.fileExtension}`; } - return fileName; + return ScriptFileName; } diff --git a/src/presentation/electron/main/IpcRegistration.ts b/src/presentation/electron/main/IpcRegistration.ts index 0a2400ba..aa1243b9 100644 --- a/src/presentation/electron/main/IpcRegistration.ts +++ b/src/presentation/electron/main/IpcRegistration.ts @@ -1,5 +1,5 @@ import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner'; -import { CodeRunner } from '@/application/CodeRunner'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; import { registerIpcChannel } from '../shared/IpcBridging/IpcProxy'; import { IpcChannelDefinitions } from '../shared/IpcBridging/IpcChannelDefinitions'; diff --git a/src/presentation/electron/main/index.ts b/src/presentation/electron/main/index.ts index 971dc786..c8a9bdd7 100644 --- a/src/presentation/electron/main/index.ts +++ b/src/presentation/electron/main/index.ts @@ -8,7 +8,6 @@ import log from 'electron-log/main'; import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'; import { validateRuntimeSanity } from '@/infrastructure/RuntimeSanity/SanityChecks'; import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger'; -import { name } from '@/../package.json' assert { type: 'json' }; import { setupAutoUpdater } from './Update/UpdateInitializer'; import { APP_ICON_PATH, PRELOADER_SCRIPT_PATH, RENDERER_HTML_PATH, RENDERER_URL, @@ -62,7 +61,6 @@ function createWindow() { configureAppQuitBehavior(); registerAllIpcChannels(); -setAppName(); app.whenReady().then(async () => { if (isDevelopment) { @@ -167,13 +165,3 @@ function configureAppQuitBehavior() { }); } } - -function setAppName() { - /* - Set the app name in development mode to ensure correct userData path. - Without this, `app.getPath('userData')` defaults to 'Electron'. - */ - if (isDevelopment) { - app.setName(name); // Works only for Windows, unsolved for macOS. - } -} diff --git a/src/presentation/electron/shared/IpcBridging/IpcChannelDefinitions.ts b/src/presentation/electron/shared/IpcBridging/IpcChannelDefinitions.ts index 8ed63a0e..fed36f26 100644 --- a/src/presentation/electron/shared/IpcBridging/IpcChannelDefinitions.ts +++ b/src/presentation/electron/shared/IpcBridging/IpcChannelDefinitions.ts @@ -1,5 +1,5 @@ import { FunctionKeys } from '@/TypeHelpers'; -import { CodeRunner } from '@/application/CodeRunner'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; import { IpcChannel } from './IpcChannel'; export const IpcChannelDefinitions = { diff --git a/tests/integration/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts b/tests/integration/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts new file mode 100644 index 00000000..8ea0088e --- /dev/null +++ b/tests/integration/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts @@ -0,0 +1,89 @@ +import { mkdtemp } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { exec } from 'node:child_process'; +import { describe, it } from 'vitest'; +import { ScriptDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/ScriptDirectoryProvider'; +import { ScriptFileCreationOrchestrator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator'; +import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner'; +import { expectDoesNotThrowAsync } from '@tests/shared/Assertions/ExpectThrowsAsync'; +import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory'; +import { OperatingSystem } from '@/domain/OperatingSystem'; +import { LinuxTerminalEmulator } from '@/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor'; + +describe('ScriptFileCodeRunner', () => { + it('executes simple script correctly', async ({ skip }) => { + // arrange + const currentOperatingSystem = CurrentEnvironment.os; + if (await shouldSkipTest(currentOperatingSystem)) { + skip(); + } + const temporaryDirectoryProvider = createTemporaryDirectoryProvider(); + const codeRunner = createCodeRunner(temporaryDirectoryProvider); + const args = getPlatformSpecificArguments(currentOperatingSystem); + // act + const act = () => codeRunner.runCode(...args); + // assert + await expectDoesNotThrowAsync(act); + }); +}); + +function getPlatformSpecificArguments( + os: OperatingSystem | undefined, +): Parameters { + switch (os) { + case undefined: + throw new Error('Operating system detection failed: Unable to identify the current platform.'); + case OperatingSystem.Windows: + return [ + [ + '@echo off', + 'echo Hello, World!', + 'exit /b 0', + ].join('\n'), + 'bat', + ]; + case OperatingSystem.macOS: + case OperatingSystem.Linux: + return [ + [ + '#!/bin/bash', + 'echo "Hello, World!"', + 'exit 0', + ].join('\n'), + 'sh', + ]; + default: + throw new Error(`Platform not supported: The current operating system (${os}) is not compatible with this script execution.`); + } +} + +function shouldSkipTest( + os: OperatingSystem | undefined, +): Promise { + return new Promise((resolve) => { + if (os !== OperatingSystem.Linux) { + resolve(false); + } + exec(`which ${LinuxTerminalEmulator}`).on('close', (exitCode) => { + resolve(exitCode !== 0); + }); + }); +} + +function createCodeRunner(directoryProvider: ScriptDirectoryProvider): ScriptFileCodeRunner { + return new ScriptFileCodeRunner( + undefined, + new ScriptFileCreationOrchestrator(undefined, undefined, directoryProvider), + ); +} + +function createTemporaryDirectoryProvider(): ScriptDirectoryProvider { + return { + provideScriptDirectory: async () => { + const temporaryDirectoryPathPrefix = join(tmpdir(), 'privacy-sexy-tests-'); + const temporaryDirectoryFullPath = await mkdtemp(temporaryDirectoryPathPrefix); + return temporaryDirectoryFullPath; + }, + }; +} diff --git a/tests/shared/Assertions/ExpectExists.ts b/tests/shared/Assertions/ExpectExists.ts index ccbae95a..5e0c54ee 100644 --- a/tests/shared/Assertions/ExpectExists.ts +++ b/tests/shared/Assertions/ExpectExists.ts @@ -7,8 +7,12 @@ * non-nullable in the subsequent code. This can prevent potential type errors * and enhance code safety and clarity. */ -export function expectExists(value: T): asserts value is NonNullable { +export function expectExists(value: T, errorMessage?: string): asserts value is NonNullable { if (value === null || value === undefined) { - throw new Error('Expected value to exist'); + throw new Error([ + 'Assertion failed: expected value is either null or undefined.', + 'Expected a non-null and non-undefined value.', + ...(errorMessage ? [errorMessage] : []), + ].join('\n')); } } diff --git a/tests/unit/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.spec.ts b/tests/unit/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.spec.ts deleted file mode 100644 index b489c88a..00000000 --- a/tests/unit/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator.spec.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems'; -import { OperatingSystem } from '@/domain/OperatingSystem'; -import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage'; -import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub'; -import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator'; - -describe('OsTimestampedFilenameGenerator', () => { - describe('generateFilename', () => { - it('generates correct prefix', () => { - // arrange - const expectedPrefix = 'run'; - // act - const filename = generateFilenamePartsForTesting(); - // assert - expect(filename.prefix).to.equal(expectedPrefix); - }); - it('generates correct timestamp', () => { - // arrange - const currentDate = '2023-01-01T12:00:00.000Z'; - const expectedTimestamp = '2023-01-01_12-00-00'; - const date = new Date(currentDate); - // act - const filename = generateFilenamePartsForTesting({ date }); - // assert - expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[ - `Generated file name: ${filename.generatedFileName}` - ]); - }); - describe('generates correct extension', () => { - const testScenarios: Record = { - [OperatingSystem.Windows]: 'bat', - [OperatingSystem.Linux]: 'sh', - [OperatingSystem.macOS]: 'sh', - }; - AllSupportedOperatingSystems.forEach((operatingSystem) => { - it(`on ${OperatingSystem[operatingSystem]}`, () => { - // arrange - const expectedExtension = testScenarios[operatingSystem]; - // act - const filename = generateFilenamePartsForTesting({ operatingSystem }); - // assert - expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[ - `Generated file name: ${filename.generatedFileName}` - ]); - }); - }); - }); - describe('generates filename without extension for unknown OS', () => { - // arrange - const testScenarios: ReadonlyArray<{ - readonly description: string; - readonly unknownOs?: OperatingSystem; - }> = [ - { - description: 'unsupported OS', - unknownOs: 'Unsupported' as unknown as OperatingSystem, - }, - { - description: 'undefined OS', - unknownOs: undefined, - }, - ]; - testScenarios.forEach(({ description, unknownOs }) => { - it(description, () => { - // act - const filename = generateFilenamePartsForTesting({ operatingSystem: unknownOs }); - // assert - expect(filename.extension).toBeUndefined(); - }); - }); - }); - }); -}); - -interface TestFileNameComponents { - readonly prefix: string; - readonly timestamp: string; - readonly extension?: string; - readonly generatedFileName: string; -} - -function generateFilenamePartsForTesting(testScenario?: { - operatingSystem?: OperatingSystem, - date?: Date, -}): TestFileNameComponents { - const date = testScenario?.date ?? new Date(); - const sut = new OsTimestampedFilenameGenerator( - new RuntimeEnvironmentStub().withOs(testScenario?.operatingSystem), - ); - const filename = sut.generateFilename(date); - const pattern = /^(?[^-]+)-(?[^.]+)(?:\.(?[^.]+))?$/; // prefix-timestamp.extension - const match = filename.match(pattern); - if (!match?.groups?.prefix || !match?.groups?.timestamp) { - throw new Error(`Failed to parse prefix or timestamp: ${filename}`); - } - return { - generatedFileName: filename, - prefix: match.groups.prefix, - timestamp: match.groups.timestamp, - extension: match.groups.extension, - }; -} diff --git a/tests/unit/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.spec.ts b/tests/unit/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.spec.ts new file mode 100644 index 00000000..8ed362cc --- /dev/null +++ b/tests/unit/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator.spec.ts @@ -0,0 +1,124 @@ +import { describe, it, expect } from 'vitest'; +import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage'; +import { TimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/TimestampedFilenameGenerator'; +import { itEachAbsentStringValue } from '@tests/unit/shared/TestCases/AbsentTests'; + +describe('TimestampedFilenameGenerator', () => { + describe('generateFilename', () => { + describe('script name', () => { + it('uses correct script name', () => { + // arrange + const expectedScriptName = 'test-script'; + // act + const filename = generateFilenamePartsForTesting({ + scriptName: expectedScriptName, + }); + // assert + expect(filename.scriptName).to.equal(expectedScriptName); + }); + describe('error for missing script name', () => { + itEachAbsentStringValue((absentValue) => { + // arrange + const expectedError = 'Script name is required but not provided.'; + // act + const act = () => generateFilenamePartsForTesting({ + scriptName: absentValue, + }); + // assert + expect(act).to.throw(expectedError); + }, { excludeNull: true, excludeUndefined: true }); + }); + }); + it('generates expected timestamp', () => { + // arrange + const currentDate = '2023-01-01T12:00:00.000Z'; + const expectedTimestamp = '2023-01-01_12-00-00'; + const date = new Date(currentDate); + // act + const filename = generateFilenamePartsForTesting({ date }); + // assert + expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[ + `Generated file name: ${filename.generatedFilename}` + ]); + }); + describe('extension', () => { + it('uses correct extension', () => { + // arrange + const expectedExtension = 'sexy'; + // act + const filename = generateFilenamePartsForTesting({ extension: expectedExtension }); + // assert + expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[ + `Generated file name: ${filename.generatedFilename}` + ]); + }); + describe('handles absent extension', () => { + itEachAbsentStringValue((absentExtension) => { + // arrange + const expectedExtension = undefined; + // act + const filename = generateFilenamePartsForTesting({ extension: absentExtension }); + // assert + expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[ + `Generated file name: ${filename.generatedFilename}` + ]); + }, { excludeNull: true }); + }); + it('errors on dot-starting extension', () => { + // arrange + const invalidExtension = '.sexy'; + const expectedError = 'File extension should not start with a dot.'; + // act + const act = () => generateFilenamePartsForTesting({ extension: invalidExtension }); + // assert + expect(act).to.throw(expectedError); + }); + }); + }); +}); + +interface TestFileNameComponents { + readonly scriptName: string; + readonly timestamp: string; + readonly extension?: string; + readonly generatedFilename: string; +} + +function generateFilenamePartsForTesting(testScenario?: { + readonly date?: Date, + readonly extension?: string, + readonly scriptName?: string, +}): TestFileNameComponents { + const date = testScenario?.date ?? new Date(); + const sut = new TimestampedFilenameGenerator(); + const filename = sut.generateFilename( + { + scriptName: testScenario?.scriptName ?? 'privacy-script', + scriptFileExtension: testScenario?.extension, + }, + date, + ); + return parseFilename(filename); +} + +function parseFilename(generatedFilename: string): TestFileNameComponents { + const pattern = /^(?\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})-(?[^.]+?)(?:\.(?[^.]+))?$/;// timestamp-scriptName.extension + const match = generatedFilename.match(pattern); + function assertMatch(name: string, value: string | undefined): asserts value is string { + if (!value) { + throw new Error([ + `Missing "${name}" match in generated filename.`, + `Generated filename: ${generatedFilename}`, + `Match object: ${JSON.stringify(match)}`, + ].join('\n')); + } + } + assertMatch('script name', match?.groups?.scriptName); + assertMatch('timestamp', match?.groups?.timestamp); + return { + generatedFilename, + scriptName: match.groups.scriptName, + timestamp: match.groups.timestamp, + extension: match.groups.extension, + }; +} diff --git a/tests/unit/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.spec.ts b/tests/unit/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.spec.ts index 8c44dc87..fdf67a2e 100644 --- a/tests/unit/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.spec.ts +++ b/tests/unit/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator.spec.ts @@ -11,6 +11,8 @@ import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGenerato import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub'; import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations'; import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub'; +import { ScriptFileNameParts } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator'; +import { expectExists } from '@tests/shared/Assertions/ExpectExists'; describe('ScriptFileCreationOrchestrator', () => { describe('createScriptFile', () => { @@ -62,6 +64,28 @@ describe('ScriptFileCreationOrchestrator', () => { .pop(); expect(actualFileName).to.equal(expectedFilename); }); + it('generates file name using specified parts', async () => { + // arrange + const expectedParts: ScriptFileNameParts = { + scriptName: 'expected-script-name', + scriptFileExtension: 'expected-script-file-extension', + }; + const filenameGeneratorStub = new FilenameGeneratorStub(); + const context = new ScriptFileCreationOrchestratorTestSetup() + .withFileNameParts(expectedParts) + .withFilenameGenerator(filenameGeneratorStub); + + // act + await context.createScriptFile(); + + // assert + const fileNameGenerationCalls = filenameGeneratorStub.callHistory.filter((c) => c.methodName === 'generateFilename'); + expect(fileNameGenerationCalls).to.have.lengthOf(1); + const callArguments = fileNameGenerationCalls[0].args; + const [scriptNameFileParts] = callArguments; + expectExists(scriptNameFileParts, `Call arguments: ${JSON.stringify(callArguments)}`); + expect(scriptNameFileParts).to.equal(expectedParts); + }); it('generates complete file path', async () => { // arrange const expectedPath = 'expected-script-path'; @@ -84,7 +108,7 @@ describe('ScriptFileCreationOrchestrator', () => { expect(actualFilePath).to.equal(expectedPath); }); }); - describe('writing file to system', () => { + describe('file writing', () => { it('writes file to the generated path', async () => { // arrange const filesystem = new FileSystemOpsStub(); @@ -133,6 +157,11 @@ class ScriptFileCreationOrchestratorTestSetup { private fileContents = `[${ScriptFileCreationOrchestratorTestSetup.name}] script file contents`; + private fileNameParts: ScriptFileNameParts = { + scriptName: `[${ScriptFileCreationOrchestratorTestSetup.name}] script name`, + scriptFileExtension: `[${ScriptFileCreationOrchestratorTestSetup.name}] file extension`, + }; + public withFileContents(fileContents: string): this { this.fileContents = fileContents; return this; @@ -153,6 +182,11 @@ class ScriptFileCreationOrchestratorTestSetup { return this; } + public withFileNameParts(fileNameParts: ScriptFileNameParts): this { + this.fileNameParts = fileNameParts; + return this; + } + public createScriptFile(): ReturnType { const creator = new ScriptFileCreationOrchestrator( this.system, @@ -160,6 +194,6 @@ class ScriptFileCreationOrchestratorTestSetup { this.directoryProvider, this.logger, ); - return creator.createScriptFile(this.fileContents); + return creator.createScriptFile(this.fileContents, this.fileNameParts); } } diff --git a/tests/unit/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.spec.ts b/tests/unit/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.spec.ts index 0c7f2216..6daec82b 100644 --- a/tests/unit/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.spec.ts +++ b/tests/unit/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor.spec.ts @@ -55,7 +55,7 @@ describe('VisibleTerminalScriptFileExecutor', () => { { description: 'encloses path in quotes', filePath: 'file', - expectedCommand: '"file"', + expectedCommand: 'PowerShell Start-Process -Verb RunAs -FilePath "file"', }, ], [OperatingSystem.macOS]: [ diff --git a/tests/unit/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts b/tests/unit/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts index f574ef60..c230fba5 100644 --- a/tests/unit/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts +++ b/tests/unit/infrastructure/CodeRunner/ScriptFileCodeRunner.spec.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'; import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner'; import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub'; import { Logger } from '@/application/Common/Log/Logger'; +import { ScriptFileName } from '@/application/CodeRunner/ScriptFileName'; import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor'; import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub'; import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator'; @@ -11,7 +12,7 @@ import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync'; describe('ScriptFileCodeRunner', () => { describe('runCode', () => { - it('executes the script file as expected', async () => { + it('executes script file correctly', async () => { // arrange const expectedFilePath = 'expected script path'; const fileExecutor = new ScriptFileExecutorStub(); @@ -45,6 +46,41 @@ describe('ScriptFileCodeRunner', () => { const [actualCode] = createCalls[0].args; expect(actualCode).to.equal(expectedCode); }); + it('creates script file with provided extension', async () => { + // arrange + const expectedFileExtension = 'expected-file-extension'; + const fileCreator = new ScriptFileCreatorStub(); + const context = new CodeRunnerTestSetup() + .withFileCreator(fileCreator) + .withFileExtension(expectedFileExtension); + + // act + await context.runCode(); + + // assert + const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile'); + expect(createCalls.length).to.equal(1); + const [,scriptFileNameParts] = createCalls[0].args; + expectExists(scriptFileNameParts, JSON.stringify(`Call args: ${JSON.stringify(createCalls[0].args)}`)); + expect(scriptFileNameParts.scriptFileExtension).to.equal(expectedFileExtension); + }); + it('creates script file with provided name', async () => { + // arrange + const expectedScriptName = ScriptFileName; + const fileCreator = new ScriptFileCreatorStub(); + const context = new CodeRunnerTestSetup() + .withFileCreator(fileCreator); + + // act + await context.runCode(); + + // assert + const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile'); + expect(createCalls.length).to.equal(1); + const [,scriptFileNameParts] = createCalls[0].args; + expectExists(scriptFileNameParts, JSON.stringify(`Call args: ${JSON.stringify(createCalls[0].args)}`)); + expect(scriptFileNameParts.scriptName).to.equal(expectedScriptName); + }); describe('error handling', () => { const testScenarios: ReadonlyArray<{ readonly description: string; @@ -52,7 +88,7 @@ describe('ScriptFileCodeRunner', () => { readonly faultyContext: CodeRunnerTestSetup; }> = [ (() => { - const error = new Error('script file execution failed'); + const error = new Error('Test Error: Script file execution intentionally failed for testing purposes.'); const executor = new ScriptFileExecutorStub(); executor.executeScriptFile = () => { throw error; @@ -64,7 +100,7 @@ describe('ScriptFileCodeRunner', () => { }; })(), (() => { - const error = new Error('script file creation failed'); + const error = new Error('Test Error: Script file creation intentionally failed for testing purposes.'); const creator = new ScriptFileCreatorStub(); creator.createScriptFile = () => { throw error; @@ -76,7 +112,7 @@ describe('ScriptFileCodeRunner', () => { }; })(), ]; - describe('logs errors correctly', () => { + describe('logs errors', () => { testScenarios.forEach(({ description, faultyContext }) => { it(`logs error when ${description}`, async () => { // arrange @@ -94,7 +130,7 @@ describe('ScriptFileCodeRunner', () => { }); }); }); - describe('correctly rethrows errors', () => { + describe('rethrows errors', () => { testScenarios.forEach(({ description, injectedException, faultyContext }) => { it(`rethrows error when ${description}`, async () => { // act @@ -111,6 +147,8 @@ describe('ScriptFileCodeRunner', () => { class CodeRunnerTestSetup { private code = `[${CodeRunnerTestSetup.name}]code`; + private fileExtension = `[${CodeRunnerTestSetup.name}]file-extension`; + private fileCreator: ScriptFileCreator = new ScriptFileCreatorStub(); private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub(); @@ -123,7 +161,7 @@ class CodeRunnerTestSetup { this.fileCreator, this.logger, ); - await runner.runCode(this.code); + await runner.runCode(this.code, this.fileExtension); } public withFileExecutor(fileExecutor: ScriptFileExecutor): this { @@ -145,4 +183,9 @@ class CodeRunnerTestSetup { this.fileCreator = fileCreator; return this; } + + public withFileExtension(fileExtension: string): this { + this.fileExtension = fileExtension; + return this; + } } diff --git a/tests/unit/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.spec.ts b/tests/unit/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.spec.ts index 2dfa0a1c..6777df03 100644 --- a/tests/unit/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.spec.ts +++ b/tests/unit/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory.spec.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest'; import { BrowserRuntimeEnvironmentFactory, NodeRuntimeEnvironmentFactory, - WindowAccessor, determineAndCreateRuntimeEnvironment, + GlobalAccessor as GlobalPropertiesAccessor, determineAndCreateRuntimeEnvironment, } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory'; import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub'; @@ -11,7 +11,7 @@ describe('RuntimeEnvironmentFactory', () => { // arrange const expectedEnvironment = new RuntimeEnvironmentStub(); const context = new RuntimeEnvironmentFactoryTestSetup() - .withWindowAccessor(() => { return {} as Window; }) + .withWindowAccessor(() => createWindowStub()) .withBrowserEnvironmentFactory(() => expectedEnvironment); // act const actualEnvironment = context.buildEnvironment(); @@ -21,7 +21,7 @@ describe('RuntimeEnvironmentFactory', () => { it('passes correct window to browser environment', () => { // arrange - const expectedWindow = {} as Window; + const expectedWindow = createWindowStub(); let actualWindow: Window | undefined; const browserEnvironmentFactoryMock: BrowserRuntimeEnvironmentFactory = (providedWindow) => { actualWindow = providedWindow; @@ -41,18 +41,58 @@ describe('RuntimeEnvironmentFactory', () => { const expectedEnvironment = new RuntimeEnvironmentStub(); const context = new RuntimeEnvironmentFactoryTestSetup() .withWindowAccessor(() => undefined) + .withProcessAccessor(() => createProcessStub()) .withNodeEnvironmentFactory(() => expectedEnvironment); // act const actualEnvironment = context.buildEnvironment(); // assert expect(actualEnvironment).to.equal(expectedEnvironment); }); + + it('uses node environment when window is present too', () => { // This allows running integration tests + // arrange + const expectedEnvironment = new RuntimeEnvironmentStub(); + const context = new RuntimeEnvironmentFactoryTestSetup() + .withWindowAccessor(() => createWindowStub()) + .withProcessAccessor(() => createProcessStub()) + .withNodeEnvironmentFactory(() => expectedEnvironment); + // act + const actualEnvironment = context.buildEnvironment(); + // assert + expect(actualEnvironment).to.equal(expectedEnvironment); + }); + + it('throws if both node and window are missing', () => { + // arrange + const expectedError = 'Unsupported runtime environment: The current context is neither a recognized browser nor a Node.js environment.'; + const context = new RuntimeEnvironmentFactoryTestSetup() + .withWindowAccessor(() => undefined) + .withProcessAccessor(() => undefined); + // act + const act = () => context.buildEnvironment(); + // assert + expect(act).to.throw(expectedError); + }); }); }); +function createWindowStub(): Window { + return {} as Window; +} + +function createProcessStub(): NodeJS.Process { + return {} as NodeJS.Process; +} + +type WindowAccessor = GlobalPropertiesAccessor['getGlobalWindow']; + +type ProcessAccessor = GlobalPropertiesAccessor['getGlobalProcess']; + export class RuntimeEnvironmentFactoryTestSetup { private windowAccessor: WindowAccessor = () => undefined; + private processAccessor: ProcessAccessor = () => undefined; + private browserEnvironmentFactory : BrowserRuntimeEnvironmentFactory = () => new RuntimeEnvironmentStub(); @@ -64,6 +104,11 @@ export class RuntimeEnvironmentFactoryTestSetup { return this; } + public withProcessAccessor(processAccessor: ProcessAccessor): this { + this.processAccessor = processAccessor; + return this; + } + public withNodeEnvironmentFactory( nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory, ): this { @@ -80,7 +125,10 @@ export class RuntimeEnvironmentFactoryTestSetup { public buildEnvironment(): ReturnType { return determineAndCreateRuntimeEnvironment( - this.windowAccessor, + { + getGlobalProcess: this.processAccessor, + getGlobalWindow: this.windowAccessor, + }, this.browserEnvironmentFactory, this.nodeEnvironmentFactory, ); diff --git a/tests/unit/presentation/bootstrapping/ClientLoggerFactory.spec.ts b/tests/unit/presentation/bootstrapping/ClientLoggerFactory.spec.ts index d4096296..7b15c28f 100644 --- a/tests/unit/presentation/bootstrapping/ClientLoggerFactory.spec.ts +++ b/tests/unit/presentation/bootstrapping/ClientLoggerFactory.spec.ts @@ -1,80 +1,159 @@ -import { - describe, it, beforeEach, afterEach, -} from 'vitest'; +// eslint-disable-next-line max-classes-per-file +import { describe, it } from 'vitest'; import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment'; -import { ClientLoggerFactory } from '@/presentation/bootstrapping/ClientLoggerFactory'; +import { ClientLoggerFactory, LoggerCreationFunction, WindowAccessor } from '@/presentation/bootstrapping/ClientLoggerFactory'; import { Logger } from '@/application/Common/Log/Logger'; -import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger'; -import { ConsoleLogger } from '@/infrastructure/Log/ConsoleLogger'; -import { NoopLogger } from '@/infrastructure/Log/NoopLogger'; import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub'; -import { Constructible } from '@/TypeHelpers'; import { itIsSingleton } from '@tests/unit/shared/TestCases/SingletonTests'; import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub'; describe('ClientLoggerFactory', () => { describe('Current', () => { - itIsSingleton({ - getter: () => ClientLoggerFactory.Current, - expectedType: ClientLoggerFactory, + describe('singleton behavior', () => { + itIsSingleton({ + getter: () => ClientLoggerFactory.Current, + expectedType: ClientLoggerFactory, + }); }); }); describe('logger instantiation based on environment', () => { - const originalWindow = { ...window }; - beforeEach(() => { - Object.assign(window, { log: new LoggerStub() }); - }); - afterEach(() => { - Object.assign(window, originalWindow); - }); const testCases: Array<{ readonly description: string, - readonly expectedType: Constructible, - readonly environment: RuntimeEnvironment, + readonly build: ( + builder: ClientLoggerFactoryBuilder, + expectedLogger: Logger, + ) => ClientLoggerFactory, }> = [ { - description: 'desktop environment', - expectedType: WindowInjectedLogger, - environment: new RuntimeEnvironmentStub() - .withIsDesktop(true), + description: 'production desktop environment', + build: (b, expectedLogger) => b + .withWindowInjectedLoggerFactory(() => expectedLogger) + .withEnvironment(new RuntimeEnvironmentStub() + .withIsDesktop(true) + .withIsNonProduction(false)) + .withWindowAccessor(() => createWindowWithLogger()) + .build(), }, { - description: 'non-production and desktop environment', - expectedType: WindowInjectedLogger, - environment: new RuntimeEnvironmentStub() - .withIsDesktop(true) - .withIsNonProduction(true), + description: 'non-production desktop environment', + build: (b, expectedLogger) => b + .withWindowInjectedLoggerFactory(() => expectedLogger) + .withEnvironment(new RuntimeEnvironmentStub() + .withIsDesktop(true) + .withIsNonProduction(true)) + .withWindowAccessor(() => createWindowWithLogger()) + .build(), }, { - description: 'non-production without desktop', - expectedType: ConsoleLogger, - environment: new RuntimeEnvironmentStub() - .withIsDesktop(false) - .withIsNonProduction(true), + description: 'non-production web environment', + build: (b, expectedLogger) => b + .withConsoleLoggerFactory(() => expectedLogger) + .withEnvironment(new RuntimeEnvironmentStub() + .withIsDesktop(false) + .withIsNonProduction(true)) + .withWindowAccessor(() => createWindowWithLogger()) + .build(), }, { - description: 'production without desktop', - expectedType: NoopLogger, - environment: new RuntimeEnvironmentStub() - .withIsDesktop(false) - .withIsNonProduction(false), + description: 'production web environment', + build: (b, expectedLogger) => b + .withNoopLoggerFactory(() => expectedLogger) + .withEnvironment(new RuntimeEnvironmentStub() + .withIsDesktop(false) + .withIsNonProduction(false)) + .withWindowAccessor(() => createWindowWithLogger()) + .build(), + }, + { + description: 'unit/integration tests environment', + build: (b, expectedLogger) => b + .withNoopLoggerFactory(() => expectedLogger) + .withEnvironment(new RuntimeEnvironmentStub().withIsDesktop(true)) + .withWindowAccessor(() => createWindowWithLogger(null)) + .build(), }, ]; - testCases.forEach(({ description, expectedType, environment }) => { - it(`instantiates ${expectedType.name} for ${description}`, () => { + testCases.forEach(({ description, build }) => { + it(`creates correct logger for ${description}`, () => { // arrange - const factory = new TestableClientLoggerFactory(environment); + const expectedLogger = new LoggerStub(); + const factory = build(new ClientLoggerFactoryBuilder(), expectedLogger); // act const { logger } = factory; // assert - expect(logger).to.be.instanceOf(expectedType); + expect(logger).to.equal(expectedLogger); }); }); }); }); -class TestableClientLoggerFactory extends ClientLoggerFactory { - public constructor(environment: RuntimeEnvironment) { - super(environment); +function createWindowWithLogger(logger: Logger | null = new LoggerStub()): Window { + return { + log: logger, + } as unknown as Window; +} + +class ClientLoggerFactoryBuilder { + private environment: RuntimeEnvironment = new RuntimeEnvironmentStub(); + + private windowAccessor: WindowAccessor = () => ({} as Window); + + private noopLoggerFactory: LoggerCreationFunction = () => new LoggerStub(); + + private windowInjectedLoggerFactory: LoggerCreationFunction = () => new LoggerStub(); + + private consoleLoggerFactory: LoggerCreationFunction = () => new LoggerStub(); + + public withWindowAccessor(windowAccessor: WindowAccessor): this { + this.windowAccessor = windowAccessor; + return this; + } + + public withEnvironment(environment: RuntimeEnvironment): this { + this.environment = environment; + return this; + } + + public withNoopLoggerFactory(factory: LoggerCreationFunction): this { + this.noopLoggerFactory = factory; + return this; + } + + public withWindowInjectedLoggerFactory(factory: LoggerCreationFunction): this { + this.windowInjectedLoggerFactory = factory; + return this; + } + + public withConsoleLoggerFactory(factory: LoggerCreationFunction): this { + this.consoleLoggerFactory = factory; + return this; + } + + public build(): ClientLoggerFactory { + return new TestableClientLoggerFactory( + this.environment, + this.windowAccessor, + this.noopLoggerFactory, + this.windowInjectedLoggerFactory, + this.consoleLoggerFactory, + ); + } +} + +class TestableClientLoggerFactory extends ClientLoggerFactory { + public constructor( + environment: RuntimeEnvironment, + windowAccessor: WindowAccessor, + noopLoggerFactory: LoggerCreationFunction, + windowInjectedLoggerFactory: LoggerCreationFunction, + consoleLoggerFactory: LoggerCreationFunction, + ) { + super( + environment, + windowAccessor, + noopLoggerFactory, + windowInjectedLoggerFactory, + consoleLoggerFactory, + ); } } diff --git a/tests/unit/shared/Stubs/CodeRunnerStub.ts b/tests/unit/shared/Stubs/CodeRunnerStub.ts index cef0ceae..7353f867 100644 --- a/tests/unit/shared/Stubs/CodeRunnerStub.ts +++ b/tests/unit/shared/Stubs/CodeRunnerStub.ts @@ -1,4 +1,4 @@ -import { CodeRunner } from '@/application/CodeRunner'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; export class CodeRunnerStub implements CodeRunner { public runCode(): Promise { diff --git a/tests/unit/shared/Stubs/FilenameGeneratorStub.ts b/tests/unit/shared/Stubs/FilenameGeneratorStub.ts index c498ec90..d41b5e6a 100644 --- a/tests/unit/shared/Stubs/FilenameGeneratorStub.ts +++ b/tests/unit/shared/Stubs/FilenameGeneratorStub.ts @@ -1,9 +1,17 @@ import { FilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator'; +import { ScriptFileNameParts } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator'; +import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls'; -export class FilenameGeneratorStub implements FilenameGenerator { +export class FilenameGeneratorStub + extends StubWithObservableMethodCalls + implements FilenameGenerator { private filename = `[${FilenameGeneratorStub.name}]file-name-stub`; - public generateFilename(): string { + public generateFilename(scriptFileNameParts: ScriptFileNameParts): string { + this.registerMethodCall({ + methodName: 'generateFilename', + args: [scriptFileNameParts], + }); return this.filename; } diff --git a/tests/unit/shared/Stubs/ScriptFileCreatorStub.ts b/tests/unit/shared/Stubs/ScriptFileCreatorStub.ts index 3e1c0ce7..d2593762 100644 --- a/tests/unit/shared/Stubs/ScriptFileCreatorStub.ts +++ b/tests/unit/shared/Stubs/ScriptFileCreatorStub.ts @@ -1,4 +1,4 @@ -import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator'; +import { ScriptFileCreator, ScriptFileNameParts } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator'; import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls'; export class ScriptFileCreatorStub @@ -11,10 +11,13 @@ export class ScriptFileCreatorStub return this; } - public createScriptFile(contents: string): Promise { + public createScriptFile( + contents: string, + scriptFileNameParts: ScriptFileNameParts, + ): Promise { this.registerMethodCall({ methodName: 'createScriptFile', - args: [contents], + args: [contents, scriptFileNameParts], }); return Promise.resolve(this.createdFilePath); } diff --git a/tests/unit/shared/Stubs/WindowVariablesStub.ts b/tests/unit/shared/Stubs/WindowVariablesStub.ts index 88816beb..dfabb591 100644 --- a/tests/unit/shared/Stubs/WindowVariablesStub.ts +++ b/tests/unit/shared/Stubs/WindowVariablesStub.ts @@ -1,7 +1,7 @@ import { OperatingSystem } from '@/domain/OperatingSystem'; import { Logger } from '@/application/Common/Log/Logger'; import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables'; -import { CodeRunner } from '@/application/CodeRunner'; +import { CodeRunner } from '@/application/CodeRunner/CodeRunner'; import { LoggerStub } from './LoggerStub'; import { CodeRunnerStub } from './CodeRunnerStub';