SPB Git

Repository Public

PasteGuard.swift 5.6 KB 119 lines swift

1import Foundation2import SettingsModel34/// What is risky about a piece of text about to be pasted into a terminal.5public struct PasteAssessment: Sendable, Equatable {6    public var lineCount: Int7    public var byteCount: Int8    /// More than one line: a shell would start executing before the user sees the whole text.9    public var isMultiline: Bool10    /// ESC or other C0/C1 control characters that could drive the terminal or the application.11    public var containsControlCharacters: Bool12    /// The text contains the "end of bracketed paste" marker, a known trick to escape the13    /// paste bracket and get the rest executed as typed input.14    public var containsBracketEscape: Bool15    /// The text ends with a newline: the last line would run immediately.16    public var endsWithNewline: Bool17    /// The text contains `sudo`, which deserves a second look when it comes from the clipboard.18    public var mentionsSudo: Bool1920    public var isSuspicious: Bool { containsControlCharacters || containsBracketEscape }21}2223public enum PasteDecision: Sendable, Equatable {24    /// Paste straight away.25    case allow26    /// Show the text and the assessment and ask.27    case confirm28}2930public enum PasteGuard {31    static let bracketEnd = "\u{1b}[201~"3233    public static func assess(_ text: String) -> PasteAssessment {34        let normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")35        let trimmed = normalized.hasSuffix("\n") ? String(normalized.dropLast()) : normalized36        let lines = trimmed.isEmpty ? 0 : trimmed.components(separatedBy: "\n").count37        let control = text.unicodeScalars.contains { scalar in38            let v = scalar.value39            return (v < 0x20 && v != 0x09 && v != 0x0a && v != 0x0d) || v == 0x7f || (0x80...0x9f).contains(v)40        }41        let words = normalized.split(whereSeparator: { !$0.isLetter && !$0.isNumber && $0 != "_" })42        return PasteAssessment(lineCount: lines, byteCount: text.utf8.count, isMultiline: lines > 1,43                               containsControlCharacters: control,44                               containsBracketEscape: text.contains(bracketEnd) || text.contains("\u{9b}201~"),45                               endsWithNewline: normalized.hasSuffix("\n"),46                               mentionsSudo: words.contains("sudo"))47    }4849    /// Suspicious content always asks, whatever the preference: the preference only governs50    /// ordinary multi-line text.51    public static func decide(_ assessment: PasteAssessment, policy: PasteConfirmation) -> PasteDecision {52        if assessment.isSuspicious { return .confirm }53        switch policy {54        case .never: return .allow55        case .multiline: return assessment.isMultiline || (assessment.endsWithNewline && assessment.lineCount > 0) ? .confirm : .allow56        case .always: return assessment.byteCount > 0 ? .confirm : .allow57        }58    }5960    /// Text made safe to paste: control characters (except tab and newline) removed, line endings61    /// normalized. This is what the confirmation sheet offers as "Paste sanitized".62    public static func sanitize(_ text: String, stripTrailingNewline: Bool = true) -> String {63        var normalized = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")64        // Remove the visible remains of escape sequences too ("[201~" would be left behind).65        normalized = normalized.replacingOccurrences(of: bracketEnd, with: "").replacingOccurrences(of: "\u{1b}[200~", with: "")66        var scalars = String.UnicodeScalarView()67        for scalar in normalized.unicodeScalars {68            let v = scalar.value69            if (v < 0x20 && v != 0x09 && v != 0x0a) || v == 0x7f || (0x80...0x9f).contains(v) { continue }70            scalars.append(scalar)71        }72        var result = String(scalars)73        if stripTrailingNewline { while result.hasSuffix("\n") { result.removeLast() } }74        return result75    }76}7778/// Guard for "broadcast input": decides whether a line typed once may be sent to several sessions.79public enum BroadcastGuard {80    /// Accumulates typed bytes per broadcast group and yields the completed line when Return is81    /// pressed, so the line can be checked *before* the newline reaches the other sessions.82    public struct LineTracker: Sendable {83        private var buffer: [UInt8] = []84        public init() {}8586        public enum Event: Sendable, Equatable {87            /// Ordinary bytes; forward them.88            case passthrough89            /// Return was pressed; this is the line about to run.90            case line(String)91        }9293        public mutating func consume(_ bytes: some Sequence<UInt8>) -> Event {94            var completed: String?95            for byte in bytes {96                switch byte {97                case 0x0d, 0x0a:98                    completed = String(decoding: buffer, as: UTF8.self)99                    buffer.removeAll()100                case 0x7f, 0x08:101                    if !buffer.isEmpty { buffer.removeLast() }102                case 0x15, 0x03:103                    buffer.removeAll()104                case 0x17:105                    while let last = buffer.last, last == 0x20 { buffer.removeLast() }106                    while let last = buffer.last, last != 0x20 { buffer.removeLast() }107                default:108                    if byte >= 0x20 { buffer.append(byte) }109                }110            }111            if let completed { return .line(completed) }112            return .passthrough113        }114115        public mutating func reset() { buffer.removeAll() }116        public var pending: String { String(decoding: buffer, as: UTF8.self) }117    }118}119
Files main
Menu

Theme