diff options
| author | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
|---|---|---|
| committer | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
| commit | aceca8b5dfc8edd378ee9ff891bccb0f94c69f31 (patch) | |
| tree | 08401ce8d050afbbe77514f479601a8e9535f4ec /Sources/BubombCore | |
Diffstat (limited to 'Sources/BubombCore')
17 files changed, 1646 insertions, 0 deletions
diff --git a/Sources/BubombCore/Executors/ApplicationLauncher.swift b/Sources/BubombCore/Executors/ApplicationLauncher.swift new file mode 100644 index 0000000..27bfd1b --- /dev/null +++ b/Sources/BubombCore/Executors/ApplicationLauncher.swift @@ -0,0 +1,78 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Launches macOS applications safely using native APIs. +public final class ApplicationLauncher: Sendable { + public init() {} + + public func launch(appPath: String, arguments: [String] = []) async throws -> ExecutionResult { + let startTime = Date() + let validatedPath = try PathValidator.validateApplication(at: appPath).get() + let appURL = URL(fileURLWithPath: validatedPath) + + #if canImport(AppKit) + let config = NSWorkspace.OpenConfiguration() + if !arguments.isEmpty { + config.arguments = arguments + } + + do { + _ = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<NSRunningApplication, Error>) in + NSWorkspace.shared.openApplication(at: appURL, configuration: config) { app, error in + if let error = error { + continuation.resume(throwing: error) + } else if let app = app { + continuation.resume(returning: app) + } else { + continuation.resume(throwing: ExecutionError.applicationLaunchFailed("Application launch failed without error info.")) + } + } + } + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully launched application: \(appURL.lastPathComponent)", + stderr: "", + duration: duration + ) + } catch { + // If native NSWorkspace openApplication threw, try /usr/bin/open as fallback + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + #else + let runner = ProcessRunner() + var args = ["-a", validatedPath] + if !arguments.isEmpty { + args.append("--args") + args.append(contentsOf: arguments) + } + let res = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: args + ) + return ExecutionResult( + exitCode: res.exitCode, + stdout: "Launched via open tool: \(appURL.lastPathComponent)", + stderr: res.stderr, + duration: Date().timeIntervalSince(startTime) + ) + #endif + } +} diff --git a/Sources/BubombCore/Executors/ExecutionResult.swift b/Sources/BubombCore/Executors/ExecutionResult.swift new file mode 100644 index 0000000..2abfa60 --- /dev/null +++ b/Sources/BubombCore/Executors/ExecutionResult.swift @@ -0,0 +1,21 @@ +import Foundation + +/// Output result from any single executor. +public struct ExecutionResult: Sendable { + public var exitCode: Int? + public var stdout: String + public var stderr: String + public var duration: TimeInterval + + public init( + exitCode: Int? = 0, + stdout: String = "", + stderr: String = "", + duration: TimeInterval = 0 + ) { + self.exitCode = exitCode + self.stdout = stdout + self.stderr = stderr + self.duration = duration + } +} diff --git a/Sources/BubombCore/Executors/PayloadExecutor.swift b/Sources/BubombCore/Executors/PayloadExecutor.swift new file mode 100644 index 0000000..2142934 --- /dev/null +++ b/Sources/BubombCore/Executors/PayloadExecutor.swift @@ -0,0 +1,242 @@ +import Foundation +import Combine + +/// Lifecycle state during payload detonation. +public enum DetonationState: Equatable, Sendable { + case idle + case burning(payloadName: String, progressInfo: String?) + case exploded(record: ExecutionRecord) + case failed(record: ExecutionRecord) + + public var isRunning: Bool { + if case .burning = self { return true } + return false + } +} + +/// Central coordinator for executing payloads safely, preventing duplicates, +/// broadcasting state changes, and recording history. +@MainActor +public final class PayloadExecutor: ObservableObject { + public static let shared = PayloadExecutor() + + @Published public private(set) var currentState: DetonationState = .idle + + private let settingsStore: SettingsStore + private var currentShellExecutor: ShellCommandExecutor? + private var currentScriptExecutor: ScriptExecutor? + private var currentSequenceExecutor: SequenceExecutor? + + public init(settingsStore: SettingsStore = .shared) { + self.settingsStore = settingsStore + } + + /// Detonates a payload immediately. + /// - Parameters: + /// - payload: The payload to execute. If nil, uses the store's activePayload. + /// - ignoreSafetyConfirmation: Set to true only after the user explicitly confirmed a destructive action dialog. + /// - Returns: The resulting ExecutionRecord. + @discardableResult + public func detonate( + payload: Payload? = nil, + ignoreSafetyConfirmation: Bool = false + ) async throws -> ExecutionRecord { + let targetPayload: Payload + if let p = payload { + targetPayload = p + } else if let active = settingsStore.settings.activePayload { + targetPayload = active + } else { + let error = ExecutionError.noPayloadConfigured + let dummyRecord = ExecutionRecord( + payloadId: UUID(), + payloadName: "None", + payloadTypeDescription: "None", + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: error.localizedDescription + ) + self.currentState = .failed(record: dummyRecord) + throw error + } + + // Validate payload before launching + do { + try targetPayload.validate() + } catch let err as ExecutionError { + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: Date(), + finishedAt: Date(), + duration: 0, + status: .failed, + errorMessage: err.localizedDescription + ) + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + throw err + } + + // Safety check + if !ignoreSafetyConfirmation { + let alwaysConfirm = settingsStore.settings.confirmDestructiveActions + let (requiresConfirm, _) = SafetyPolicy.requiresConfirmation( + command: commandStringForPayload(targetPayload), + userSettingAlwaysConfirmDestructive: alwaysConfirm || targetPayload.requiresConfirmation + ) + if requiresConfirm { + throw ExecutionError.destructiveActionRejected + } + } + + // Check duplicate execution + if currentState.isRunning { + throw ExecutionError.duplicateExecution + } + self.currentState = .burning(payloadName: targetPayload.name, progressInfo: "Detonating...") + + let startTime = Date() + + do { + let result = try await executeInternal(payload: targetPayload) + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: .succeeded, + exitCode: result.exitCode, + standardOutput: result.stdout, + standardError: result.stderr, + errorMessage: nil + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .exploded(record: record) + + // Reset back to idle after short delay to let animations complete + scheduleIdleReset(delay: 1.2) + return record + + } catch { + let finishedAt = Date() + let duration = finishedAt.timeIntervalSince(startTime) + let errString = error.localizedDescription + let exitCode: Int? + + if case .nonZeroExitStatus(let code, _) = (error as? ExecutionError) { + exitCode = code + } else { + exitCode = nil + } + + let status: ExecutionStatus + if case .timeout = (error as? ExecutionError) { + status = .timedOut + } else if case .cancelled = (error as? ExecutionError) { + status = .cancelled + } else { + status = .failed + } + + let record = ExecutionRecord( + payloadId: targetPayload.id, + payloadName: targetPayload.name, + payloadTypeDescription: targetPayload.type.typeDisplayName, + startedAt: startTime, + finishedAt: finishedAt, + duration: duration, + status: status, + exitCode: exitCode, + standardOutput: "", + standardError: "", + errorMessage: errString + ) + + settingsStore.addExecutionRecord(record) + self.currentState = .failed(record: record) + + scheduleIdleReset(delay: 2.0) + throw error + } + } + + /// Cancels any currently running payload execution. + public func cancel() { + currentShellExecutor?.cancel() + currentScriptExecutor?.cancel() + currentSequenceExecutor?.cancel() + + self.currentState = .idle + } + + // MARK: - Private Helpers + + private func executeInternal(payload: Payload) async throws -> ExecutionResult { + switch payload.type { + case .shellCommand(let config): + let executor = ShellCommandExecutor() + self.currentShellExecutor = executor + defer { self.currentShellExecutor = nil } + return try await executor.execute(config: config) + + case .openApplication(let config): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: config.applicationPath, arguments: config.arguments) + + case .openURL(let config): + let launcher = URLLauncher() + return try await launcher.open(urlString: config.urlString) + + case .runScript(let config): + let executor = ScriptExecutor() + self.currentScriptExecutor = executor + defer { self.currentScriptExecutor = nil } + return try await executor.execute(config: config) + + case .sequence(let config): + let executor = SequenceExecutor() + self.currentSequenceExecutor = executor + defer { self.currentSequenceExecutor = nil } + return try await executor.execute(config: config) { [weak self] stepIndex, totalSteps, stepName in + Task { @MainActor [weak self] in + self?.currentState = .burning( + payloadName: payload.name, + progressInfo: "Step \(stepIndex)/\(totalSteps): \(stepName)" + ) + } + } + } + } + + private func commandStringForPayload(_ payload: Payload) -> String { + switch payload.type { + case .shellCommand(let config): + return config.command + case .runScript(let config): + return config.scriptPath + case .sequence(let config): + return config.steps.map { $0.summary }.joined(separator: " && ") + default: + return "" + } + } + + private func scheduleIdleReset(delay: TimeInterval) { + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self = self else { return } + if !self.currentState.isRunning { + self.currentState = .idle + } + } + } +} diff --git a/Sources/BubombCore/Executors/ProcessRunner.swift b/Sources/BubombCore/Executors/ProcessRunner.swift new file mode 100644 index 0000000..add19fa --- /dev/null +++ b/Sources/BubombCore/Executors/ProcessRunner.swift @@ -0,0 +1,219 @@ +import Foundation + +/// Safe, asynchronous wrapper around Foundation.Process with deadlock-free pipe reading via readabilityHandler, +/// timeout supervision, and cancellation support. +public final class ProcessRunner: @unchecked Sendable { + private let state = ProcessState() + + public init() {} + + /// Runs an executable process with arguments, environment, working directory, and timeout. + public func run( + executableURL: URL, + arguments: [String], + workingDirectory: String? = nil, + environment: [String: String] = [:], + timeoutSeconds: TimeInterval? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + + let proc = Process() + proc.executableURL = executableURL + proc.arguments = arguments + + if let workDir = workingDirectory, !workDir.isEmpty { + proc.currentDirectoryURL = URL(fileURLWithPath: (workDir as NSString).expandingTildeInPath) + } + + var env = ProcessInfo.processInfo.environment + for (k, v) in environment { + env[k] = v + } + proc.environment = env + + let outPipe = Pipe() + let errPipe = Pipe() + proc.standardOutput = outPipe + proc.standardError = errPipe + + let stdoutAccumulator = ThreadSafeAccumulator() + let stderrAccumulator = ThreadSafeAccumulator() + + outPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + outPipe.fileHandleForReading.readabilityHandler = nil + } else { + stdoutAccumulator.append(chunk) + } + } + + errPipe.fileHandleForReading.readabilityHandler = { handle in + let chunk = handle.availableData + if chunk.isEmpty { + errPipe.fileHandleForReading.readabilityHandler = nil + } else { + stderrAccumulator.append(chunk) + } + } + + try await state.setProcess(proc) + + do { + try proc.run() + } catch { + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + _ = await state.clearProcess() + throw ExecutionError.processLaunchFailed(error.localizedDescription) + } + + // Timeout supervisor + let timeoutRef = TimeoutRef() + var timeoutTimer: DispatchSourceTimer? + + if let timeout = timeoutSeconds, timeout > 0 { + let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global(qos: .userInteractive)) + timer.schedule(deadline: .now() + timeout) + timer.setEventHandler { [weak proc] in + timeoutRef.markTimedOut() + proc?.terminate() + + // Force kill if still unresponsive after 500ms + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if let pid = proc?.processIdentifier, proc?.isRunning == true { + kill(pid, SIGKILL) + } + } + } + timer.resume() + timeoutTimer = timer + } + + // Wait for process exit asynchronously on a global queue + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + proc.waitUntilExit() + continuation.resume() + } + } + + timeoutTimer?.cancel() + timeoutTimer = nil + + // Clean up readability handlers + outPipe.fileHandleForReading.readabilityHandler = nil + errPipe.fileHandleForReading.readabilityHandler = nil + + // Drain any remaining buffered data + let remainingOut = outPipe.fileHandleForReading.readDataToEndOfFile() + stdoutAccumulator.append(remainingOut) + + let remainingErr = errPipe.fileHandleForReading.readDataToEndOfFile() + stderrAccumulator.append(remainingErr) + + let duration = Date().timeIntervalSince(startTime) + let stdoutString = String(data: stdoutAccumulator.getData(), encoding: .utf8) ?? "" + let stderrString = String(data: stderrAccumulator.getData(), encoding: .utf8) ?? "" + + let wasCancelled = await state.clearProcess() + + if wasCancelled { + throw ExecutionError.cancelled + } + + if timeoutRef.isTimedOut { + throw ExecutionError.timeout(timeoutSeconds ?? 0) + } + + let exitCode = Int(proc.terminationStatus) + if exitCode != 0 { + let combined = stdoutString + (stderrString.isEmpty ? "" : "\n" + stderrString) + throw ExecutionError.nonZeroExitStatus(exitCode, output: combined) + } + + return ExecutionResult( + exitCode: exitCode, + stdout: stdoutString, + stderr: stderrString, + duration: duration + ) + } + + /// Cancels the running process immediately. + public func cancel() { + Task { + let proc = await state.cancel() + if let proc = proc, proc.isRunning { + proc.terminate() + DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) { + if proc.isRunning { + kill(proc.processIdentifier, SIGKILL) + } + } + } + } + } +} + +// MARK: - Helper Types + +private actor ProcessState { + private var process: Process? + private var isCancelled = false + + func setProcess(_ proc: Process) throws { + if isCancelled { + throw ExecutionError.cancelled + } + self.process = proc + } + + func cancel() -> Process? { + isCancelled = true + let proc = self.process + self.process = nil + return proc + } + + func clearProcess() -> Bool { + let wasCancelled = self.isCancelled + self.process = nil + return wasCancelled + } +} + +private final class ThreadSafeAccumulator: @unchecked Sendable { + private var data = Data() + private let lock = NSLock() + + func append(_ newChunk: Data) { + guard !newChunk.isEmpty else { return } + lock.lock() + data.append(newChunk) + lock.unlock() + } + + func getData() -> Data { + lock.lock() + defer { lock.unlock() } + return data + } +} + +private final class TimeoutRef: @unchecked Sendable { + private var timedOut = false + private let lock = NSLock() + + var isTimedOut: Bool { + lock.lock() + defer { lock.unlock() } + return timedOut + } + + func markTimedOut() { + lock.lock() + timedOut = true + lock.unlock() + } +} diff --git a/Sources/BubombCore/Executors/ScriptExecutor.swift b/Sources/BubombCore/Executors/ScriptExecutor.swift new file mode 100644 index 0000000..55be037 --- /dev/null +++ b/Sources/BubombCore/Executors/ScriptExecutor.swift @@ -0,0 +1,77 @@ +import Foundation + +/// Executes local scripts safely without mutating file permissions or user scripts. +public final class ScriptExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ScriptConfig) async throws -> ExecutionResult { + let validPath = try PathValidator.validateScript(at: config.scriptPath).get() + + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let isExecutable = FileManager.default.isExecutableFile(atPath: validPath) + let (interpreterURL, leadingArgs) = resolveInterpreter(forScriptAt: validPath, isExecutable: isExecutable) + + var finalArgs = leadingArgs + finalArgs.append(validPath) + finalArgs.append(contentsOf: config.arguments) + + return try await runner.run( + executableURL: interpreterURL, + arguments: finalArgs, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } + + /// Determines the appropriate interpreter for a script based on its shebang or file extension. + private func resolveInterpreter(forScriptAt path: String, isExecutable: Bool) -> (interpreterURL: URL, leadingArgs: [String]) { + // First check shebang + if let fileHandle = FileHandle(forReadingAtPath: path) { + defer { try? fileHandle.close() } + let headerData = fileHandle.readData(ofLength: 256) + if let headerString = String(data: headerData, encoding: .utf8), headerString.hasPrefix("#!") { + let firstLine = headerString.components(separatedBy: .newlines).first ?? "" + let shebangBody = firstLine.dropFirst(2).trimmingCharacters(in: .whitespaces) + let tokens = shebangBody.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + if let interpreter = tokens.first { + if interpreter == "/usr/bin/env" && tokens.count > 1 { + let actualBin = tokens[1] + return (URL(fileURLWithPath: "/usr/bin/env"), [actualBin]) + } else if FileManager.default.isExecutableFile(atPath: interpreter) { + return (URL(fileURLWithPath: interpreter), Array(tokens.dropFirst())) + } + } + } + } + + // If file is directly marked executable and no shebang, run directly + if isExecutable { + return (URL(fileURLWithPath: path), []) + } + + // Fallback by extension + let ext = (path as NSString).pathExtension.lowercased() + switch ext { + case "sh", "zsh", "bash": + return (URL(fileURLWithPath: "/bin/zsh"), []) + case "py": + return (URL(fileURLWithPath: "/usr/bin/python3"), []) + case "rb": + return (URL(fileURLWithPath: "/usr/bin/ruby"), []) + case "pl": + return (URL(fileURLWithPath: "/usr/bin/perl"), []) + default: + return (URL(fileURLWithPath: "/bin/sh"), []) + } + } +} diff --git a/Sources/BubombCore/Executors/SequenceExecutor.swift b/Sources/BubombCore/Executors/SequenceExecutor.swift new file mode 100644 index 0000000..29a0331 --- /dev/null +++ b/Sources/BubombCore/Executors/SequenceExecutor.swift @@ -0,0 +1,131 @@ +import Foundation + +/// Executes a sequence of payload steps in defined order with progress updates and failure policies. +public final class SequenceExecutor: @unchecked Sendable { + public typealias ProgressHandler = @Sendable (Int, Int, String) -> Void + + private let state = SequenceState() + + public init() {} + + public func execute( + config: SequenceConfig, + progress: ProgressHandler? = nil + ) async throws -> ExecutionResult { + let startTime = Date() + let totalSteps = config.steps.count + guard totalSteps > 0 else { + throw ExecutionError.invalidConfiguration("Sequence has no steps configured.") + } + + var fullStdout = "" + var fullStderr = "" + + for (index, step) in config.steps.enumerated() { + if await state.checkCancelled() { + throw ExecutionError.cancelled + } + + progress?(index + 1, totalSteps, step.name) + + let stepHeader = "--- [Step \(index + 1)/\(totalSteps): \(step.name)] ---\n" + fullStdout += stepHeader + + do { + let result = try await executeStep(step) + if !result.stdout.isEmpty { + fullStdout += result.stdout + (result.stdout.hasSuffix("\n") ? "" : "\n") + } + if !result.stderr.isEmpty { + fullStderr += "[\(step.name) stderr]: " + result.stderr + (result.stderr.hasSuffix("\n") ? "" : "\n") + } + } catch { + let errString = error.localizedDescription + let failureLog = "❌ Step \(index + 1) failed: \(errString)\n" + fullStderr += failureLog + + if config.stopOnError { + throw ExecutionError.stepFailed(stepIndex: index, stepName: step.name, reason: errString) + } + } + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: fullStdout, + stderr: fullStderr, + duration: duration + ) + } + + private func executeStep(_ step: SequenceStep) async throws -> ExecutionResult { + switch step.action { + case .openApplication(let appPath): + let launcher = ApplicationLauncher() + return try await launcher.launch(appPath: appPath) + + case .openURL(let urlString): + let launcher = URLLauncher() + return try await launcher.open(urlString: urlString) + + case .runCommand(let cmd, let workDir, let timeout): + let executor = ShellCommandExecutor() + await state.setShell(executor) + defer { + Task { await self.state.setShell(nil) } + } + let shellConfig = ShellConfig( + command: cmd, + shellPath: "/bin/zsh", + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: shellConfig) + + case .runScript(let scriptPath, let args, let workDir, let timeout): + let executor = ScriptExecutor() + await state.setScript(executor) + defer { + Task { await self.state.setScript(nil) } + } + let scriptConfig = ScriptConfig( + scriptPath: scriptPath, + arguments: args, + workingDirectory: workDir, + timeoutSeconds: timeout + ) + return try await executor.execute(config: scriptConfig) + } + } + + public func cancel() { + Task { + await state.cancel() + } + } +} + +private actor SequenceState { + private var isCancelled = false + private var shellExecutor: ShellCommandExecutor? + private var scriptExecutor: ScriptExecutor? + + func setShell(_ executor: ShellCommandExecutor?) { + self.shellExecutor = executor + } + + func setScript(_ executor: ScriptExecutor?) { + self.scriptExecutor = executor + } + + func cancel() { + self.isCancelled = true + shellExecutor?.cancel() + scriptExecutor?.cancel() + } + + func checkCancelled() -> Bool { + return isCancelled + } +} diff --git a/Sources/BubombCore/Executors/ShellCommandExecutor.swift b/Sources/BubombCore/Executors/ShellCommandExecutor.swift new file mode 100644 index 0000000..36c606b --- /dev/null +++ b/Sources/BubombCore/Executors/ShellCommandExecutor.swift @@ -0,0 +1,63 @@ +import Foundation + +/// Executes shell commands using an explicit shell or direct binary invocation. +public final class ShellCommandExecutor: @unchecked Sendable { + private let runner = ProcessRunner() + + public init() {} + + public func execute(config: ShellConfig) async throws -> ExecutionResult { + // Validate working directory if specified + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + let trimmedCommand = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedCommand.isEmpty else { + throw ExecutionError.invalidConfiguration("Command cannot be empty.") + } + + let executableURL: URL + let arguments: [String] + + let shell = config.shellPath.trimmingCharacters(in: .whitespacesAndNewlines) + if !shell.isEmpty { + // Validate shell executable exists + let validShell = try PathValidator.validateExecutable(at: shell).get() + executableURL = URL(fileURLWithPath: validShell) + + var fullCommand = trimmedCommand + if !config.arguments.isEmpty { + let appended = config.arguments.map { arg -> String in + if arg.contains(" ") || arg.contains("\"") { + return "\"\(arg.replacingOccurrences(of: "\"", with: "\\\""))\"" + } + return arg + }.joined(separator: " ") + fullCommand += " " + appended + } + arguments = ["-c", fullCommand] + } else { + // Direct binary invocation + let components = trimmedCommand.components(separatedBy: .whitespaces).filter { !$0.isEmpty } + guard let binaryName = components.first else { + throw ExecutionError.invalidConfiguration("No binary specified.") + } + let validBinary = try PathValidator.validateExecutable(at: binaryName).get() + executableURL = URL(fileURLWithPath: validBinary) + arguments = Array(components.dropFirst()) + config.arguments + } + + return try await runner.run( + executableURL: executableURL, + arguments: arguments, + workingDirectory: config.workingDirectory, + environment: config.environmentVariables, + timeoutSeconds: config.timeoutSeconds + ) + } + + public func cancel() { + runner.cancel() + } +} diff --git a/Sources/BubombCore/Executors/URLLauncher.swift b/Sources/BubombCore/Executors/URLLauncher.swift new file mode 100644 index 0000000..c56e121 --- /dev/null +++ b/Sources/BubombCore/Executors/URLLauncher.swift @@ -0,0 +1,45 @@ +import Foundation +#if canImport(AppKit) +import AppKit +#endif + +/// Validates and opens URLs in the user's default web browser. +public final class URLLauncher: Sendable { + public init() {} + + public func open(urlString: String) async throws -> ExecutionResult { + let startTime = Date() + let validatedURL = try PathValidator.validateURL(urlString).get() + + var success = false + + #if canImport(AppKit) + success = await MainActor.run { + NSWorkspace.shared.open(validatedURL) + } + #endif + + if !success { + // Fallback to /usr/bin/open if NSWorkspace is not available or failed + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/usr/bin/open"), + arguments: [validatedURL.absoluteString] + ) + return ExecutionResult( + exitCode: result.exitCode, + stdout: "Opened \(validatedURL.absoluteString) via open tool", + stderr: result.stderr, + duration: Date().timeIntervalSince(startTime) + ) + } + + let duration = Date().timeIntervalSince(startTime) + return ExecutionResult( + exitCode: 0, + stdout: "Successfully opened URL: \(validatedURL.absoluteString)", + stderr: "", + duration: duration + ) + } +} diff --git a/Sources/BubombCore/Models/AppSettings.swift b/Sources/BubombCore/Models/AppSettings.swift new file mode 100644 index 0000000..949ae75 --- /dev/null +++ b/Sources/BubombCore/Models/AppSettings.swift @@ -0,0 +1,55 @@ +import Foundation + +public enum AnimationPreference: String, Codable, CaseIterable, Equatable, Sendable { + case full = "Full (Sparks & Smoke)" + case subtle = "Subtle (Sparks Only)" + case none = "None (Reduced Motion)" +} + +/// Persistent user configuration for Bubomb. +public struct AppSettings: Codable, Equatable, Sendable { + public var activePayload: Payload? + public var savedPayloads: [Payload] + public var launchAtLogin: Bool + public var startSilentlyInMenuBar: Bool + public var animationPreference: AnimationPreference + public var confirmDestructiveActions: Bool + public var playCompletionFeedback: Bool + public var recentExecutions: [ExecutionRecord] + + public static let currentVersion = "1.0.0" + public static let buildNumber = "1" + + public init( + activePayload: Payload? = nil, + savedPayloads: [Payload] = [], + launchAtLogin: Bool = false, + startSilentlyInMenuBar: Bool = true, + animationPreference: AnimationPreference = .full, + confirmDestructiveActions: Bool = true, + playCompletionFeedback: Bool = true, + recentExecutions: [ExecutionRecord] = [] + ) { + self.activePayload = activePayload + self.savedPayloads = savedPayloads + self.launchAtLogin = launchAtLogin + self.startSilentlyInMenuBar = startSilentlyInMenuBar + self.animationPreference = animationPreference + self.confirmDestructiveActions = confirmDestructiveActions + self.playCompletionFeedback = playCompletionFeedback + self.recentExecutions = recentExecutions + } + + public static var defaultSettings: AppSettings { + AppSettings( + activePayload: nil, + savedPayloads: [], + launchAtLogin: false, + startSilentlyInMenuBar: true, + animationPreference: .full, + confirmDestructiveActions: true, + playCompletionFeedback: true, + recentExecutions: [] + ) + } +} diff --git a/Sources/BubombCore/Models/ExecutionRecord.swift b/Sources/BubombCore/Models/ExecutionRecord.swift new file mode 100644 index 0000000..760f87e --- /dev/null +++ b/Sources/BubombCore/Models/ExecutionRecord.swift @@ -0,0 +1,83 @@ +import Foundation + +public enum ExecutionStatus: String, Codable, Equatable, Hashable, Sendable { + case succeeded = "Succeeded" + case failed = "Failed" + case cancelled = "Cancelled" + case timedOut = "Timed Out" + + public var badgeColorName: String { + switch self { + case .succeeded: return "green" + case .failed: return "red" + case .cancelled: return "orange" + case .timedOut: return "purple" + } + } +} + +/// Metadata and logs from a payload detonation. +public struct ExecutionRecord: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var payloadId: UUID + public var payloadName: String + public var payloadTypeDescription: String + public var startedAt: Date + public var finishedAt: Date + public var duration: TimeInterval + public var status: ExecutionStatus + public var exitCode: Int? + public var standardOutput: String + public var standardError: String + public var errorMessage: String? + + public init( + id: UUID = UUID(), + payloadId: UUID, + payloadName: String, + payloadTypeDescription: String, + startedAt: Date, + finishedAt: Date = Date(), + duration: TimeInterval = 0, + status: ExecutionStatus, + exitCode: Int? = nil, + standardOutput: String = "", + standardError: String = "", + errorMessage: String? = nil + ) { + self.id = id + self.payloadId = payloadId + self.payloadName = payloadName + self.payloadTypeDescription = payloadTypeDescription + self.startedAt = startedAt + self.finishedAt = finishedAt + self.duration = duration + self.status = status + self.exitCode = exitCode + self.standardOutput = standardOutput + self.standardError = standardError + self.errorMessage = errorMessage + } + + public var formattedDuration: String { + if duration < 1.0 { + return String(format: "%.0f ms", duration * 1000) + } else { + return String(format: "%.2f s", duration) + } + } + + public var combinedOutput: String { + var out = "" + if !standardOutput.isEmpty { + out += standardOutput + } + if !standardError.isEmpty { + if !out.isEmpty && !out.hasSuffix("\n") { + out += "\n" + } + out += standardError + } + return out + } +} diff --git a/Sources/BubombCore/Models/Payload.swift b/Sources/BubombCore/Models/Payload.swift new file mode 100644 index 0000000..2a14aae --- /dev/null +++ b/Sources/BubombCore/Models/Payload.swift @@ -0,0 +1,129 @@ +import Foundation + +/// A complete configured payload in Bubomb. +public struct Payload: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var name: String + public var type: PayloadType + public var requiresConfirmation: Bool + public var createdAt: Date + public var updatedAt: Date + + public init( + id: UUID = UUID(), + name: String = "My Action", + type: PayloadType = .shellCommand(ShellConfig()), + requiresConfirmation: Bool = false, + createdAt: Date = Date(), + updatedAt: Date = Date() + ) { + self.id = id + self.name = name + self.type = type + self.requiresConfirmation = requiresConfirmation + self.createdAt = createdAt + self.updatedAt = updatedAt + } + + /// Validates this payload against system requirements and filesystem paths. + public func validate() throws { + let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedName.isEmpty { + throw ExecutionError.invalidConfiguration("Payload name cannot be empty.") + } + + switch type { + case .shellCommand(let config): + let trimmedCmd = config.command.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedCmd.isEmpty { + throw ExecutionError.invalidConfiguration("Command cannot be empty.") + } + if !config.shellPath.isEmpty { + _ = try PathValidator.validateExecutable(at: config.shellPath).get() + } + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + case .openApplication(let config): + let trimmedApp = config.applicationPath.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedApp.isEmpty { + throw ExecutionError.invalidConfiguration("Application path cannot be empty.") + } + _ = try PathValidator.validateApplication(at: trimmedApp).get() + + case .openURL(let config): + _ = try PathValidator.validateURL(config.urlString).get() + + case .runScript(let config): + let trimmedScript = config.scriptPath.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmedScript.isEmpty { + throw ExecutionError.invalidConfiguration("Script path cannot be empty.") + } + _ = try PathValidator.validateScript(at: trimmedScript).get() + if let workDir = config.workingDirectory { + _ = try PathValidator.validateWorkingDirectory(workDir).get() + } + + case .sequence(let config): + if config.steps.isEmpty { + throw ExecutionError.invalidConfiguration("Multi-step sequence must have at least one step.") + } + for (index, step) in config.steps.enumerated() { + switch step.action { + case .openApplication(let path): + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Application path is empty.") + } + _ = try PathValidator.validateApplication(at: trimmed).get() + case .openURL(let url): + _ = try PathValidator.validateURL(url).get() + case .runCommand(let cmd, let workDir, _): + let trimmed = cmd.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Command is empty.") + } + if let dir = workDir { + _ = try PathValidator.validateWorkingDirectory(dir).get() + } + case .runScript(let path, _, let workDir, _): + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + throw ExecutionError.invalidConfiguration("Step \(index + 1): Script path is empty.") + } + _ = try PathValidator.validateScript(at: trimmed).get() + if let dir = workDir { + _ = try PathValidator.validateWorkingDirectory(dir).get() + } + } + } + } + } + + /// Evaluates if safety policy flags this payload as destructive. + public var safetyRisk: SafetyPolicy.RiskLevel { + switch type { + case .shellCommand(let config): + return SafetyPolicy.evaluate(command: config.command) + case .runScript(let config): + return SafetyPolicy.evaluate(command: config.scriptPath) + case .sequence(let config): + for step in config.steps { + switch step.action { + case .runCommand(let cmd, _, _): + let risk = SafetyPolicy.evaluate(command: cmd) + if risk.isDestructive { return risk } + case .runScript(let script, _, _, _): + let risk = SafetyPolicy.evaluate(command: script) + if risk.isDestructive { return risk } + default: + break + } + } + return .safe + default: + return .safe + } + } +} diff --git a/Sources/BubombCore/Models/PayloadType.swift b/Sources/BubombCore/Models/PayloadType.swift new file mode 100644 index 0000000..e65beee --- /dev/null +++ b/Sources/BubombCore/Models/PayloadType.swift @@ -0,0 +1,105 @@ +import Foundation + +public struct ShellConfig: Codable, Equatable, Hashable, Sendable { + public var command: String + public var shellPath: String + public var arguments: [String] + public var workingDirectory: String? + public var environmentVariables: [String: String] + public var timeoutSeconds: TimeInterval? + + public init( + command: String = "", + shellPath: String = "/bin/zsh", + arguments: [String] = [], + workingDirectory: String? = nil, + environmentVariables: [String: String] = [:], + timeoutSeconds: TimeInterval? = 30 + ) { + self.command = command + self.shellPath = shellPath + self.arguments = arguments + self.workingDirectory = workingDirectory + self.environmentVariables = environmentVariables + self.timeoutSeconds = timeoutSeconds + } +} + +public struct AppConfig: Codable, Equatable, Hashable, Sendable { + public var applicationPath: String + public var arguments: [String] + + public init(applicationPath: String = "", arguments: [String] = []) { + self.applicationPath = applicationPath + self.arguments = arguments + } +} + +public struct URLConfig: Codable, Equatable, Hashable, Sendable { + public var urlString: String + + public init(urlString: String = "https://") { + self.urlString = urlString + } +} + +public struct ScriptConfig: Codable, Equatable, Hashable, Sendable { + public var scriptPath: String + public var arguments: [String] + public var workingDirectory: String? + public var environmentVariables: [String: String] + public var timeoutSeconds: TimeInterval? + + public init( + scriptPath: String = "", + arguments: [String] = [], + workingDirectory: String? = nil, + environmentVariables: [String: String] = [:], + timeoutSeconds: TimeInterval? = 60 + ) { + self.scriptPath = scriptPath + self.arguments = arguments + self.workingDirectory = workingDirectory + self.environmentVariables = environmentVariables + self.timeoutSeconds = timeoutSeconds + } +} + +public struct SequenceConfig: Codable, Equatable, Hashable, Sendable { + public var steps: [SequenceStep] + public var stopOnError: Bool + + public init(steps: [SequenceStep] = [], stopOnError: Bool = true) { + self.steps = steps + self.stopOnError = stopOnError + } +} + +/// The specific payload types supported by Bubomb. +public enum PayloadType: Codable, Equatable, Hashable, Sendable { + case shellCommand(ShellConfig) + case openApplication(AppConfig) + case openURL(URLConfig) + case runScript(ScriptConfig) + case sequence(SequenceConfig) + + public var typeDisplayName: String { + switch self { + case .shellCommand: return "Shell Command" + case .openApplication: return "Open Application" + case .openURL: return "Open URL" + case .runScript: return "Run Script" + case .sequence: return "Multi-step Sequence" + } + } + + public var iconName: String { + switch self { + case .shellCommand: return "terminal.fill" + case .openApplication: return "app.badge.fill" + case .openURL: return "link" + case .runScript: return "doc.text.fill" + case .sequence: return "list.bullet.rectangle.fill" + } + } +} diff --git a/Sources/BubombCore/Models/SafetyPolicy.swift b/Sources/BubombCore/Models/SafetyPolicy.swift new file mode 100644 index 0000000..84bcf37 --- /dev/null +++ b/Sources/BubombCore/Models/SafetyPolicy.swift @@ -0,0 +1,88 @@ +import Foundation + +/// Safety evaluation for configured commands and payloads. +public struct SafetyPolicy: Sendable { + public enum RiskLevel: Equatable, Sendable { + case safe + case suspicious(reason: String) + case destructive(reason: String) + + public var isDestructive: Bool { + if case .destructive = self { return true } + return false + } + + public var warningMessage: String? { + switch self { + case .safe: + return nil + case .suspicious(let reason): + return reason + case .destructive(let reason): + return reason + } + } + } + + /// Evaluates a command string for known destructive or dangerous patterns. + public static func evaluate(command: String) -> RiskLevel { + let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { return .safe } + + // Destructive patterns: root/home recursive deletion, disk formatting, raw block devices, fork bombs + let destructivePatterns: [(pattern: String, reason: String)] = [ + (#"\brm\s+-[a-zA-Z]*[rR][a-zA-Z]*[fF][a-zA-Z]*\s+(/|~|\$HOME|\.\./|\*)(?:\s|$|[;&|])"#, "Recursive force removal of system or root/home directory"), + (#"\brm\s+-[a-zA-Z]*[fF][a-zA-Z]*[rR][a-zA-Z]*\s+(/|~|\$HOME|\.\./|\*)(?:\s|$|[;&|])"#, "Recursive force removal of system or root/home directory"), + (#"\bmkfs\b"#, "Filesystem formatting command detected"), + (#"\bdd\s+if=.*of=/dev/(r?disk|sd)"#, "Raw disk overwrite command (dd) detected"), + (#">\s*/dev/(r?disk|sd)"#, "Direct write redirection to raw disk device"), + (#"\bchmod\s+-[a-zA-Z]*R[a-zA-Z]*\s+777\s+/"#, "Dangerous root directory permission change"), + (#":\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:"#, "Fork bomb pattern detected"), + (#"\bdiskutil\s+(eraseDisk|partitionDisk|unmountDisk)\b"#, "Disk erasure or partition command detected") + ] + + for (pattern, reason) in destructivePatterns { + if let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: trimmed.utf16.count) + if regex.firstMatch(in: trimmed, options: [], range: range) != nil { + return .destructive(reason: reason) + } + } + } + + // Suspicious patterns: sudo, disabling gatekeeper/SIP, curl-pipe-to-sh + let suspiciousPatterns: [(pattern: String, reason: String)] = [ + (#"\bsudo\b"#, "Command requests superuser privileges (sudo)"), + (#"\bspctl\s+--master-disable\b"#, "Attempt to disable macOS Gatekeeper"), + (#"\bcsrutil\s+disable\b"#, "Attempt to disable macOS System Integrity Protection (SIP)"), + (#"(curl|wget)\s+.*\|\s*(sh|bash|zsh)"#, "Piping remote network script directly into shell") + ] + + for (pattern, reason) in suspiciousPatterns { + if let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: trimmed.utf16.count) + if regex.firstMatch(in: trimmed, options: [], range: range) != nil { + return .suspicious(reason: reason) + } + } + } + + return .safe + } + + /// Determines if an execution must require explicit user confirmation. + public static func requiresConfirmation(command: String, userSettingAlwaysConfirmDestructive: Bool) -> (required: Bool, reason: String?) { + let risk = evaluate(command: command) + switch risk { + case .destructive(let reason): + return (true, "⚠️ Potentially destructive operation detected: \(reason)") + case .suspicious(let reason): + if userSettingAlwaysConfirmDestructive { + return (true, "Notice: \(reason)") + } + return (false, reason) + case .safe: + return (false, nil) + } + } +} diff --git a/Sources/BubombCore/Models/SequenceStep.swift b/Sources/BubombCore/Models/SequenceStep.swift new file mode 100644 index 0000000..f1d075d --- /dev/null +++ b/Sources/BubombCore/Models/SequenceStep.swift @@ -0,0 +1,43 @@ +import Foundation + +/// Individual step within a Multi-step Sequence payload. +public struct SequenceStep: Identifiable, Codable, Equatable, Hashable, Sendable { + public var id: UUID + public var name: String + public var action: StepAction + + public init(id: UUID = UUID(), name: String, action: StepAction) { + self.id = id + self.name = name + self.action = action + } + + public enum StepAction: Codable, Equatable, Hashable, Sendable { + case openApplication(applicationPath: String) + case openURL(urlString: String) + case runCommand(command: String, workingDirectory: String?, timeoutSeconds: TimeInterval?) + case runScript(scriptPath: String, arguments: [String], workingDirectory: String?, timeoutSeconds: TimeInterval?) + } + + public var actionTypeTitle: String { + switch action { + case .openApplication: return "Open App" + case .openURL: return "Open URL" + case .runCommand: return "Shell Command" + case .runScript: return "Run Script" + } + } + + public var summary: String { + switch action { + case .openApplication(let path): + return (path as NSString).lastPathComponent + case .openURL(let url): + return url + case .runCommand(let cmd, _, _): + return cmd + case .runScript(let path, _, _, _): + return (path as NSString).lastPathComponent + } + } +} diff --git a/Sources/BubombCore/Persistence/SettingsStore.swift b/Sources/BubombCore/Persistence/SettingsStore.swift new file mode 100644 index 0000000..ff3ae8a --- /dev/null +++ b/Sources/BubombCore/Persistence/SettingsStore.swift @@ -0,0 +1,134 @@ +import Foundation +import Combine + +/// Manages persistence and state observation for Bubomb settings. +public final class SettingsStore: ObservableObject, @unchecked Sendable { + public static let shared = SettingsStore() + + private let userDefaults: UserDefaults + private let storageKey = "com.bubomb.settings.v1" + private let fileManager = FileManager.default + private let lock = NSLock() + + @Published public private(set) var settings: AppSettings + + public init(userDefaults: UserDefaults = .standard) { + self.userDefaults = userDefaults + + // Load initial settings + if let data = userDefaults.data(forKey: storageKey), + let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) { + self.settings = decoded + } else if let diskSettings = Self.loadFromDisk() { + self.settings = diskSettings + } else { + self.settings = AppSettings.defaultSettings + } + } + + /// Update full settings object. + public func update(_ newSettings: AppSettings) { + lock.lock() + defer { lock.unlock() } + + self.settings = newSettings + persist(newSettings) + } + + /// Sets or updates the active payload. + public func setActivePayload(_ payload: Payload?) { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + updated.activePayload = payload + + // Also ensure it is in savedPayloads list if non-nil + if let payload = payload { + if let index = updated.savedPayloads.firstIndex(where: { $0.id == payload.id }) { + updated.savedPayloads[index] = payload + } else { + updated.savedPayloads.append(payload) + } + } + + self.settings = updated + persist(updated) + } + + /// Appends a new execution record (caps at 30 entries). + public func addExecutionRecord(_ record: ExecutionRecord) { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + var history = updated.recentExecutions + history.insert(record, at: 0) + if history.count > 30 { + history = Array(history.prefix(30)) + } + updated.recentExecutions = history + + self.settings = updated + persist(updated) + } + + /// Clears execution history. + public func clearHistory() { + lock.lock() + defer { lock.unlock() } + + var updated = self.settings + updated.recentExecutions = [] + self.settings = updated + persist(updated) + } + + /// Resets all settings to defaults. + public func resetToDefaults() { + lock.lock() + defer { lock.unlock() } + + let defaults = AppSettings.defaultSettings + self.settings = defaults + persist(defaults) + } + + // MARK: - Internal Persistence + + private func persist(_ settingsToSave: AppSettings) { + guard let data = try? JSONEncoder().encode(settingsToSave) else { return } + userDefaults.set(data, forKey: storageKey) + Self.saveToDisk(data: data) + + // Notify observers on main queue + DispatchQueue.main.async { [weak self] in + self?.objectWillChange.send() + } + } + + private static var diskURL: URL? { + guard let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { + return nil + } + let bubombDir = appSupport.appendingPathComponent("Bubomb", isDirectory: true) + if !FileManager.default.fileExists(atPath: bubombDir.path) { + try? FileManager.default.createDirectory(at: bubombDir, withIntermediateDirectories: true) + } + return bubombDir.appendingPathComponent("settings.json") + } + + private static func saveToDisk(data: Data) { + guard let url = diskURL else { return } + try? data.write(to: url, options: .atomic) + } + + private static func loadFromDisk() -> AppSettings? { + guard let url = diskURL, + let data = try? Data(contentsOf: url), + let decoded = try? JSONDecoder().decode(AppSettings.self, from: data) else { + return nil + } + return decoded + } +} diff --git a/Sources/BubombCore/Utilities/ExecutionError.swift b/Sources/BubombCore/Utilities/ExecutionError.swift new file mode 100644 index 0000000..ea2fd5f --- /dev/null +++ b/Sources/BubombCore/Utilities/ExecutionError.swift @@ -0,0 +1,64 @@ +import Foundation + +/// Errors that can occur during Bubomb payload validation, execution, and persistence. +public enum ExecutionError: LocalizedError, Equatable, Sendable { + case noPayloadConfigured + case invalidConfiguration(String) + case executableNotFound(String) + case scriptNotFound(String) + case workingDirectoryNotFound(String) + case invalidURL(String) + case permissionDenied(String) + case nonZeroExitStatus(Int, output: String) + case timeout(TimeInterval) + case cancelled + case processLaunchFailed(String) + case duplicateExecution + case destructiveActionRejected + case stepFailed(stepIndex: Int, stepName: String, reason: String) + case applicationNotFound(String) + case applicationLaunchFailed(String) + + public var errorDescription: String? { + switch self { + case .noPayloadConfigured: + return "No payload configured. Open Settings to set up an action." + case .invalidConfiguration(let details): + return "Invalid configuration: \(details)" + case .executableNotFound(let path): + return "Executable not found at path: \(path)" + case .scriptNotFound(let path): + return "Script file not found at path: \(path)" + case .workingDirectoryNotFound(let path): + return "Working directory does not exist: \(path)" + case .invalidURL(let url): + return "Invalid URL: \(url). Only valid http:// and https:// URLs are supported." + case .permissionDenied(let path): + return "Permission denied accessing: \(path)" + case .nonZeroExitStatus(let code, let output): + let trimmed = output.trimmingCharacters(in: .whitespacesAndNewlines) + if trimmed.isEmpty { + return "Command failed with exit status \(code)." + } else { + let firstLine = trimmed.components(separatedBy: .newlines).first ?? "" + return "Command failed with exit status \(code): \(firstLine)" + } + case .timeout(let duration): + return "Execution timed out after \(String(format: "%.1f", duration)) seconds." + case .cancelled: + return "Execution was cancelled by the user." + case .processLaunchFailed(let details): + return "Failed to launch process: \(details)" + case .duplicateExecution: + return "A payload is already running. Wait for it to finish or cancel it." + case .destructiveActionRejected: + return "Destructive action was rejected by the user." + case .stepFailed(let index, let name, let reason): + return "Step \(index + 1) ('\(name)') failed: \(reason)" + case .applicationNotFound(let path): + return "Application not found at path: \(path)" + case .applicationLaunchFailed(let details): + return "Failed to open application: \(details)" + } + } +} diff --git a/Sources/BubombCore/Utilities/PathValidator.swift b/Sources/BubombCore/Utilities/PathValidator.swift new file mode 100644 index 0000000..af8c14c --- /dev/null +++ b/Sources/BubombCore/Utilities/PathValidator.swift @@ -0,0 +1,69 @@ +import Foundation + +/// Utilities for validating filesystem paths and URLs. +public enum PathValidator { + /// Checks whether an executable exists at the given path and is executable. + public static func validateExecutable(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.executableNotFound(expanded)) + } + guard fileManager.isExecutableFile(atPath: expanded) else { + return .failure(.permissionDenied("File is not executable: \(expanded)")) + } + return .success(expanded) + } + + /// Checks whether a script file exists at the given path. + public static func validateScript(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.scriptNotFound(expanded)) + } + guard fileManager.isReadableFile(atPath: expanded) else { + return .failure(.permissionDenied("Script file is not readable: \(expanded)")) + } + return .success(expanded) + } + + /// Checks whether a working directory exists and is a directory. + public static func validateWorkingDirectory(_ path: String?) -> Result<String?, ExecutionError> { + guard let path = path, !path.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return .success(nil) + } + let expanded = NSString(string: path).expandingTildeInPath + var isDir: ObjCBool = false + if FileManager.default.fileExists(atPath: expanded, isDirectory: &isDir), isDir.boolValue { + return .success(expanded) + } + return .failure(.workingDirectoryNotFound(expanded)) + } + + /// Validates an HTTP or HTTPS URL. + public static func validateURL(_ urlString: String) -> Result<URL, ExecutionError> { + let trimmed = urlString.trimmingCharacters(in: .whitespacesAndNewlines) + guard let url = URL(string: trimmed), + let scheme = url.scheme?.lowercased(), + (scheme == "http" || scheme == "https"), + url.host != nil, + !(url.host?.isEmpty ?? true) else { + return .failure(.invalidURL(urlString)) + } + return .success(url) + } + + /// Checks if an application bundle exists. + public static func validateApplication(at path: String) -> Result<String, ExecutionError> { + let expanded = NSString(string: path).expandingTildeInPath + let fileManager = FileManager.default + + guard fileManager.fileExists(atPath: expanded) else { + return .failure(.applicationNotFound(expanded)) + } + return .success(expanded) + } +} |
