SPB Git

Repository Public

ConsentGate.swift 5.3 KB 122 lines swift

1import Foundation23/// A command suggested by the assistant (or typed for broadcast). It is inert:4/// the app must not execute it. Its risk is computed at creation and cannot be altered.5public struct ProposedCommand: Sendable, Equatable, Identifiable {6    public let id: UUID7    /// Command line, exactly as it would be sent to the shell.8    public let text: String9    /// Working directory in which it would run.10    public let workingDirectory: String?11    /// Target host.12    public let host: String?13    /// `true` when the command targets several hosts at once.14    public let isMultiHost: Bool15    /// Risk assessment computed from `text` and `isMultiHost`.16    public let risk: RiskAssessment1718    public init(text: String, workingDirectory: String? = nil, host: String? = nil, isMultiHost: Bool = false,19                analyzer: CommandRiskAnalyzer = CommandRiskAnalyzer()) {20        self.id = UUID()21        self.text = text22        self.workingDirectory = workingDirectory23        self.host = host24        self.isMultiHost = isMultiHost25        self.risk = analyzer.assess(text, isMultiHost: isMultiHost)26    }27}2829/// Explicit act of the user, collected by the UI.30public enum UserConfirmation: Sendable, Equatable {31    /// The user clicked "Run" on the confirmation sheet.32    case standard33    /// The user typed the confirmation phrase returned by ``ConsentGate/confirmationPhrase(for:)``.34    case reinforced(typedPhrase: String)35}3637/// Strength of confirmation demanded for a proposal.38public enum ConsentRequirement: Sendable, Equatable {39    case standard40    case reinforced41}4243/// Why a proposal was not approved.44public enum ConsentError: Error, Sendable, Equatable {45    /// The command is empty.46    case emptyCommand47    /// A standard confirmation was given where a typed phrase is required.48    case reinforcedConfirmationRequired(phrase: String)49    /// The typed phrase does not match.50    case confirmationPhraseMismatch(expected: String)51}5253/// The only command type the app may execute. It cannot be constructed outside this54/// module: obtain one from ``ConsentGate/approve(_:with:)``.55public struct ApprovedCommand: Sendable, Equatable {56    /// Command line to execute, identical to the proposal that was shown.57    public let text: String58    public let workingDirectory: String?59    public let host: String?60    public let isMultiHost: Bool61    /// Risk that was displayed when the user confirmed.62    public let risk: RiskAssessment63    /// Strength of the confirmation that was given.64    public let confirmation: ConsentRequirement65    public let approvedAt: Date66    /// Identifier of the originating ``ProposedCommand``.67    public let proposalID: UUID6869    init(proposal: ProposedCommand, confirmation: ConsentRequirement, approvedAt: Date) {70        self.text = proposal.text71        self.workingDirectory = proposal.workingDirectory72        self.host = proposal.host73        self.isMultiHost = proposal.isMultiHost74        self.risk = proposal.risk75        self.confirmation = confirmation76        self.approvedAt = approvedAt77        self.proposalID = proposal.id78    }79}8081/// Turns proposals into approvals. Stateless; holds the consent rules.82public struct ConsentGate: Sendable {83    public init() {}8485    /// `.reinforced` for destructive, privilege-escalating, network-transfer and multi-host proposals.86    public func requirement(for proposal: ProposedCommand) -> ConsentRequirement {87        proposal.isMultiHost || proposal.risk.requiresReinforcedConfirmation ? .reinforced : .standard88    }8990    /// Phrase the user must type for a reinforced confirmation (compared case-insensitively, trimmed).91    public func confirmationPhrase(for proposal: ProposedCommand) -> String {92        let reasons = proposal.risk.reasons93        if proposal.risk.level == .destructive { return "run destructive command" }94        if proposal.isMultiHost || reasons.contains(.multiHost) { return "run on all hosts" }95        if reasons.contains(.privilegeEscalation) { return "run as administrator" }96        return "send data"97    }9899    /// Approves a command for execution.100    /// - Throws: ``ConsentError`` when the confirmation is insufficient.101    public func approve(_ proposal: ProposedCommand, with confirmation: UserConfirmation, now: Date = Date()) throws -> ApprovedCommand {102        guard !proposal.text.allSatisfy(\.isWhitespace) else { throw ConsentError.emptyCommand }103        switch (requirement(for: proposal), confirmation) {104        case (.standard, _):105            return ApprovedCommand(proposal: proposal, confirmation: .standard, approvedAt: now)106        case (.reinforced, .standard):107            throw ConsentError.reinforcedConfirmationRequired(phrase: confirmationPhrase(for: proposal))108        case (.reinforced, .reinforced(let typed)):109            let expected = confirmationPhrase(for: proposal)110            guard typed.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() == expected else {111                throw ConsentError.confirmationPhraseMismatch(expected: expected)112            }113            return ApprovedCommand(proposal: proposal, confirmation: .reinforced, approvedAt: now)114        }115    }116117    /// Records that the user reviewed `preview` and agreed to send it.118    public func approve(_ preview: ContextPreview, now: Date = Date()) -> ApprovedPreview {119        ApprovedPreview(preview: preview, approvedAt: now)120    }121}122
Files main
Menu

Theme