Cotton code
320 lines · 13.8 KB · SwiftRaw
// The share channel — the third App Group channel, and the only thing the share// extension and the app say to each other.//// **There was no Cotton-authored share extension to port.** A plugin generated// the whole target at build time, so what Cotton actually owned was the four// activation rules (now `project.yml:340-344`) and the DRAIN. The channel// between the two halves was the plugin's, and all three pieces of it retired// with the previous runtime: ONE overwritten `UserDefaults` slot, cleared when// the app backgrounds, reached through a `<scheme>://dataUrl=<key>?nonce=<uuid>`// redirect that a native-intent hook rewrote back to `/`.//// **The single slot was a bug and the port stops reproducing it.** One slot means// the second of two quick shares overwrites the first, and "cleared when the app// backgrounds" means a share that arrived while the app was foregrounded-then-// backgrounded is thrown away before anything drained it. This channel is an// APPEND-ONLY ARRAY instead, drained and removed whole on next foreground: it// is the only shape an extension can write without a second design.//// ── The one rule that makes the append safe ──────────────────────────────────//// The append is a read-modify-write over raw `[Any]` through `JSONSerialization`,// never a decode-and-re-encode: an entry this binary does not fully understand// still belongs to the app that will drain it, and re-encoding a decoded struct// would silently drop a newer build's fields.// The two processes are never interactively visible at once, so writer overlap is// theoretical; it is documented rather than defended with locks.//// The app group is `CottonDefaults.appGroup(bundleIdentifier:)`'s and is never// derived a second time here — there is one app, one group, and no dev variant.import Foundation/// The channel's names: the mailbox key, and where the bytes it points at live.public enum ShareChannel {    /// The App Group `UserDefaults` key the extension appends to and the app    /// drains. A `kind:` or a key string is wire protocol: change one and a    /// share the extension already wrote becomes unreadable.    public static let mailboxKey = "cotton.share.mailbox.v1"    /// Where the extension copies the bytes it was handed.    ///    /// A directory of its own under the container root, beside — never inside —    /// the layout Rust builds there (`cotton-client/src/layout.rs` owns `client`,    /// `media`, `identity`, `files`, `cache`, `backup`, `tls` and the four    /// top-level files). Nothing below the boundary knows this name.    public static let inboxDirectoryName = "share-inbox"    /// The app group's container, or `nil` when the entitlement is not in force    /// — which is a library test with no container, never a shipping build.    public static func container(bundleIdentifier: String? = Bundle.main.bundleIdentifier)        -> URL?    {        FileManager.default.containerURL(            forSecurityApplicationGroupIdentifier: CottonDefaults.appGroup(                bundleIdentifier: bundleIdentifier            )        )    }    /// Where a shared file is copied to. Created by the writer, not by this.    public static func inboxDirectory(bundleIdentifier: String? = Bundle.main.bundleIdentifier)        -> URL?    {        container(bundleIdentifier: bundleIdentifier)?            .appendingPathComponent(inboxDirectoryName, isDirectory: true)    }}// MARK: - One entry/// One share, as the extension wrote it down — with this struct's own encoder,/// so the drain decodes it plainly. ``shareKind`` names the three kinds.public struct ShareEntry: Codable, Equatable, Sendable {    /// This share's own id. The drain clears by it, so two shares that arrived    /// together are two entries and neither can clear the other.    public var id: String    /// When the extension wrote it, ISO-8601. Recorded, never gated on: an old    /// entry is a share nobody drained, which is a share to honour.    public var at: String    /// `"url"` · `"text"` · `"file"`.    public var kind: String    /// The web URL a link or a page share carried.    public var url: String?    /// The prose a text share carried. May carry several URLs — extraction is    /// the crate's rule, never a second regex up here.    public var text: String?    /// What the sharing app called the page. Carried because the channel has a    /// place for it; see ``ShareIntake`` for why the drain does not send it.    public var title: String?    /// Where the COPIED bytes are, inside the app group's container.    public var path: String?    /// The name the sharing app gave the file, when it gave one.    public var fileName: String?    /// The declared type — a MIME type, or the UTI iOS handed over when it had    /// no MIME for it. Both are read by the classification rules.    public var mimeType: String?    /// How many times a drain has already tried this share and failed.    ///    /// **Zero for everything the extension writes**, and the app is the only    /// writer of anything else: a branch that keeps its bytes on a failure    /// re-offers the entry ONCE (``ShareMailbox/reoffer(_:)``), and the second    /// failure reports and discards. That is the bound on "keep it and try    /// again" — without one, kept bytes are bytes nobody will ever look for    /// again, which is the leak the meetings branch had.    public var attempt: Int    public init(        id: String = UUID().uuidString,        at: String,        kind: String,        url: String? = nil,        text: String? = nil,        title: String? = nil,        path: String? = nil,        fileName: String? = nil,        mimeType: String? = nil,        attempt: Int = 0    ) {        self.id = id        self.at = at        self.kind = kind        self.url = url        self.text = text        self.title = title        self.path = path        self.fileName = fileName        self.mimeType = mimeType        self.attempt = attempt    }    private enum CodingKeys: String, CodingKey {        case id, at, kind, url, text, title, path, fileName, mimeType, attempt    }    /// The same entry, naming where its bytes are NOW.    ///    /// A branch may rename a staged copy before it hands it over — the    /// recordings branch does, because the crate reads the container off the    /// path — so an entry put back for another try has to name the file that is    /// actually on disk. Putting back the name the extension wrote would be    /// re-offering a path with nothing behind it.    public init(_ entry: ShareEntry, movedTo path: String) {        self = entry        self.path = path    }    /// The three kinds this build writes, or `nil` for a word it does not know.    public var shareKind: ShareKind? { ShareKind(rawValue: kind) }}/// What the extension was handed.public enum ShareKind: String, Sendable, CaseIterable {    /// A web URL — a link, or a page shared out of a browser.    case url    /// Selected prose. May contain URLs; may contain none.    case text    /// One file, already copied into the app group's container.    case file}// MARK: - Storage/// Where the mailbox is kept.////// A protocol with two members so a test touches no real defaults — the same/// seam ``PendingLinkStore`` is, for the same reason. It is TEXT rather than/// `Data` because the entries are JSON written with `JSONSerialization`.public protocol ShareMailboxStorage: Sendable {    func text(_ key: String) -> String?    func set(_ key: String, _ value: String?)}/// The shipping storage: one `UserDefaults` suite, the app group's.////// `@unchecked Sendable` because `UserDefaults` is thread-safe by contract and/// carries no annotation saying so; the struct holds nothing else.public struct DefaultsShareMailboxStorage: ShareMailboxStorage, @unchecked Sendable {    private let defaults: UserDefaults    public init(defaults: UserDefaults = CottonDefaults.suite()) {        self.defaults = defaults    }    public init?(bundleIdentifier: String?) {        guard            let defaults = UserDefaults(                suiteName: CottonDefaults.appGroup(bundleIdentifier: bundleIdentifier)            )        else { return nil }        self.defaults = defaults    }    public func text(_ key: String) -> String? { defaults.string(forKey: key) }    public func set(_ key: String, _ value: String?) {        guard let value else {            defaults.removeObject(forKey: key)            return        }        defaults.set(value, forKey: key)    }}// MARK: - The mailbox/// The append-only list of shares waiting to be drained.////// A `struct` rather than an actor because both writers are already serialised/// by the platform — the extension writes once, from its own short-lived/// process, before it closes the sheet; the app drains once per foreground —/// and an actor would make the extension's one write an `await` inside a/// completion handler for nothing.public struct ShareMailbox: Sendable {    private let storage: any ShareMailboxStorage    /// The `UserDefaults` key this mailbox is: the share channel's, or the    /// passkey channel's (`PasskeyMailbox`) — one spelling, two kinds.    private let key: String    public init(storage: any ShareMailboxStorage = DefaultsShareMailboxStorage(), key: String = ShareChannel.mailboxKey) {        self.storage = storage        self.key = key    }    /// Append one share, read-modify-write.    ///    /// Existing entries are carried across as RAW JSON rather than re-encoded    /// structs: an entry this binary does not fully understand still belongs to the app    /// that will drain it. Without the App Group the write silently does    /// nothing, which is the platform's answer rather than a failure to handle.    public func append<Entry: Encodable>(_ entry: Entry) {        var items: [Any] = []        if let raw = storage.text(key),            let parsed = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [Any]        {            items = parsed        }        guard            let encoded = try? JSONEncoder().encode(entry),            let object = try? JSONSerialization.jsonObject(with: encoded)        else { return }        items.append(object)        guard            let out = try? JSONSerialization.data(withJSONObject: items),            let string = String(data: out, encoding: .utf8)        else { return }        storage.set(key, string)    }    /// Put one share BACK, for one more try on the next foreground.    ///    /// The drain removes the whole list before any branch runs, which is the    /// rule that stops an intent re-firing for ever. This is the one exception    /// and it is bounded by ``ShareEntry/attempt``: a branch that keeps its    /// bytes on a failure — because the sharing app has let go of them and    /// nobody else is holding them — re-offers ONCE, and the second failure    /// reports and discards. "Keep it" must not mean "leak for ever": before    /// this, a `.opus` whose import was refused sat in the app group's    /// `share-inbox/` with nothing left that knew it was there (the walk of    /// 15 Sep 2026).    ///    /// A share that has already been re-offered is NOT put back again: the    /// count is the whole of the bound, so a caller that asks twice gets one.    @discardableResult    public func reoffer(_ entry: ShareEntry) -> Bool {        guard entry.attempt < 1 else { return false }        var again = entry        again.attempt = entry.attempt + 1        append(again)        return true    }    /// Take everything waiting, and REMOVE THE WHOLE LIST.    ///    /// Removing before anything is processed is the port of `useReaderIntake`'s    /// `finally { resetShareIntent() }` (`:80-83, 100-102, 144-146, 176-178,    /// 207-209, 214`), and it is the same rule stated structurally rather than    /// as a clause every branch has to remember: **an intent must never survive    /// to re-fire this effect for ever.** A share whose branch then fails is a    /// share the person is told about and lands the screen for — it is not a    /// share that is offered again on every foreground until the app is deleted.    ///    /// An entry that will not decode is DROPPED rather than taking the list with    /// it: a mailbox is not worth losing because one entry in it is corrupt.    public func drain() -> [ShareEntry] { drain(ShareEntry.self) }    /// ``drain()`` for a mailbox of another kind of entry.    public func drain<Entry: Decodable>(_: Entry.Type) -> [Entry] {        guard let raw = storage.text(key) else { return [] }        storage.set(key, nil)        return decoded(raw)    }    /// What is waiting, left where it is.    public func peek<Entry: Decodable>(_: Entry.Type) -> [Entry] {        guard let raw = storage.text(key) else { return [] }        return decoded(raw)    }    private func decoded<Entry: Decodable>(_ raw: String) -> [Entry] {        guard            let items = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [Any]        else { return [] }        return items.compactMap { item in            guard                // `isValidJSONObject` FIRST, and it is not belt-and-braces:                // `data(withJSONObject:)` raises an Obj-C exception — not a                // Swift error — for a top-level value that is not a dictionary                // or array, so `try?` catches nothing and a mailbox holding one                // stray string would take the whole app down on the next                // launch.                JSONSerialization.isValidJSONObject(item),                let data = try? JSONSerialization.data(withJSONObject: item),                let entry = try? JSONDecoder().decode(Entry.self, from: data)            else { return nil }            return entry        }    }}