summaryrefslogtreecommitdiff
path: root/Sources/BubombCore/Models
diff options
context:
space:
mode:
Diffstat (limited to 'Sources/BubombCore/Models')
-rw-r--r--Sources/BubombCore/Models/AppSettings.swift55
-rw-r--r--Sources/BubombCore/Models/ExecutionRecord.swift83
-rw-r--r--Sources/BubombCore/Models/Payload.swift129
-rw-r--r--Sources/BubombCore/Models/PayloadType.swift105
-rw-r--r--Sources/BubombCore/Models/SafetyPolicy.swift88
-rw-r--r--Sources/BubombCore/Models/SequenceStep.swift43
6 files changed, 503 insertions, 0 deletions
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
+ }
+ }
+}