Cotton code
157 lines · 6.2 KB · SwiftRaw
// The shared clipboard seam for every secret column and transient reveal.// Copying a secret WITHOUT showing it.//// A seam rather than two `#if os` lines at the call site, for two reasons that// are both about this being a credential:////   * **the expiry is a platform capability, not a promise.** iOS can be told//     to drop a pasteboard entry after its seconds whether Cotton runs or not;//     macOS forgets it only while Cotton runs, and the screen says which it//     got rather than claiming the safer one everywhere.//   * **a secret is marked concealed.** Clipboard managers, Universal//     Clipboard and Cotton's own Clips honour the nspasteboard.org marks, so a//     password copied here never becomes a clip anywhere.//   * a test must be able to assert what was copied without a pasteboard. A//     simulator's pasteboard is shared between runs, so a test that wrote to//     the real one is a test that passes once and then lies.//// The value never reaches the SCREEN on this path. That is what makes Copy the// gesture to use in a room with other people in it, and why it is offered// beside every sealed field rather than only after a reveal.//// Every copy an act asks for goes through here too (`RecordActionOutcomes`),// a plain one (an address) with no expiry and a sealed one with its// `SecretClipboard.seconds` — so no surface writes to a pasteboard of its own.import Foundation#if canImport(UIKit)    import UIKit    import UniformTypeIdentifiers#elseif canImport(AppKit)    import AppKit#endif/// How long Cotton's own copy of a secret stays on the clipboard, on every/// platform: two minutes (owner, 14 Oct 2026; was sixty seconds). A column's/// reveal policy may ask for less, never more.enum SecretClipboard {    static let seconds: TimeInterval = 120    /// The expiry a copy with this policy gets: the policy's own, capped.    static func seconds(policy: TimeInterval?) -> TimeInterval {        guard let policy, policy > 0 else { return seconds }        return min(policy, seconds)    }}/// The pasteboard marks of nspasteboard.org that every well-behaved clipboard/// reader honours: a concealed item is a secret, a transient one is a/// program's scratch. Cotton writes the first on every secret it copies and/// its Clips watcher never keeps an item carrying either.public enum PasteboardMark {    public static let concealed = "org.nspasteboard.ConcealedType"    public static let transient = "org.nspasteboard.TransientType"    /// Both, as the type identifiers a reader checks an item's types against.    public static let skipped: Set<String> = [concealed, transient]}/// Where a copied value goes.protocol Clipboard: Sendable {    /// Put a value on the clipboard, asking the platform to forget it after    /// `seconds`. Answers whether the EXPIRY was honoured — the copy itself    /// always happens.    @discardableResult func put(_ value: String, expiringAfter seconds: TimeInterval) -> Bool    /// Put a value that is not a secret on the clipboard, kept until the    /// next copy — an address, a clone command.    func put(_ value: String)}/// The real one.struct SystemClipboard: Clipboard, @unchecked Sendable {    #if canImport(UIKit)    private let pasteboard: UIPasteboard    init(pasteboard: UIPasteboard = .general) { self.pasteboard = pasteboard }    #elseif canImport(AppKit)    private let pasteboard: NSPasteboard    init(pasteboard: NSPasteboard = .general) { self.pasteboard = pasteboard }    #endif    @discardableResult    func put(_ value: String, expiringAfter seconds: TimeInterval) -> Bool {        #if canImport(UIKit)            // `expirationDate` is the system's own promise: the entry is            // removed at that instant whether the app is running or not, which            // a timer in this process could not manage.            // `localOnly` keeps a secret off Universal Clipboard; the            // concealed mark keeps it out of every clip reader on this one.            pasteboard.setItems(                [[UTType.plainText.identifier: value, PasteboardMark.concealed: Data()]],                options: [.expirationDate: Date().addingTimeInterval(seconds), .localOnly: true]            )            return true        #elseif canImport(AppKit)            let concealed = NSPasteboard.PasteboardType(PasteboardMark.concealed)            pasteboard.declareTypes([.string, concealed], owner: nil)            guard pasteboard.setString(value, forType: .string),                  pasteboard.setData(Data(), forType: concealed) else { return false }            let change = pasteboard.changeCount            let board = pasteboard            // A newer copy belongs to someone else, including another app.            DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {                if board.changeCount == change { board.clearContents() }            }            return true        #else            return false        #endif    }    func put(_ value: String) {        #if canImport(UIKit)            UIPasteboard.general.string = value        #elseif canImport(AppKit)            NSPasteboard.general.clearContents()            NSPasteboard.general.setString(value, forType: .string)        #endif    }}/// What the tests drive, and the only way to assert a copy without a/// pasteboard.final class RecordingClipboard: Clipboard, @unchecked Sendable {    private let lock = NSLock()    private var copied: [(value: String, seconds: TimeInterval)] = []    private var plainCopies: [String] = []    private let expires: Bool    init(expires: Bool = true) {        self.expires = expires    }    @discardableResult    func put(_ value: String, expiringAfter seconds: TimeInterval) -> Bool {        lock.lock()        defer { lock.unlock() }        copied.append((value, seconds))        return expires    }    func put(_ value: String) {        lock.lock()        defer { lock.unlock() }        plainCopies.append(value)    }    /// The values copied with no expiry, in order.    var plain: [String] {        lock.lock()        defer { lock.unlock() }        return plainCopies    }    var entries: [(value: String, seconds: TimeInterval)] {        lock.lock()        defer { lock.unlock() }        return copied    }}