// COTTON SITES' CALLS (assets/design/sites/CONTRACT.md "The core calls each screen needs"): every word and every // decision is the core's; the phone draws them and keeps each site's sign-in in WebKit's store named by the site's // `store_uuid`. The list is sealed in the core's book on this phone under the app's own key (`SitesAppKey`), sent // with every call and kept nowhere else. #if os(iOS) import CottonKit import Foundation import Security /// A site as the list, the switcher and the chooser draw it (`sites_app.rs` `row`). struct SitesRow: Decodable, Equatable, Sendable, Identifiable, Hashable { var id: String var letter: String var label: String /// Its address without `www.`. var site: String /// "mail.example · Inbox (4)", "club.example · forgets when closed", or "Sign in once". var line: String /// Where it opens: its last page, else its home. var open: String var stay: Bool var pinned: Bool var hidden: Bool var trackers: Bool var signInOnce: Bool var store: String var storeUUID: String var login: String? enum CodingKeys: String, CodingKey { case id, letter, label, site, line, open, stay, pinned, hidden, trackers, store, login case signInOnce = "sign_in_once" case storeUUID = "store_uuid" } /// Sites' row, or the shorter one `sites.add` and `sites.edit` still answer for Comms (no letter, pin or /// trackers): read either; the list is read again after every change. init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) label = try c.decode(String.self, forKey: .label) letter = try c.decodeIfPresent(String.self, forKey: .letter) ?? label.first(where: { $0.isLetter || $0.isNumber }).map { String($0).uppercased() } ?? "·" site = try c.decodeIfPresent(String.self, forKey: .site) ?? "" line = try c.decodeIfPresent(String.self, forKey: .line) ?? site open = try c.decodeIfPresent(String.self, forKey: .open) ?? "" stay = try c.decodeIfPresent(Bool.self, forKey: .stay) ?? true pinned = try c.decodeIfPresent(Bool.self, forKey: .pinned) ?? false hidden = try c.decodeIfPresent(Bool.self, forKey: .hidden) ?? false trackers = try c.decodeIfPresent(Bool.self, forKey: .trackers) ?? true signInOnce = try c.decodeIfPresent(Bool.self, forKey: .signInOnce) ?? false store = try c.decodeIfPresent(String.self, forKey: .store) ?? "site-\(id)" storeUUID = try c.decode(String.self, forKey: .storeUUID) login = try c.decodeIfPresent(String.self, forKey: .login) } } struct SitesLabelled: Decodable, Equatable, Sendable { var label: String var line: String? } /// `sites.home`: the list. struct SitesHome: Decodable, Equatable, Sendable { struct Search: Decodable, Equatable, Sendable { var line: String } struct Hidden: Decodable, Equatable, Sendable { var label: String var line: String var locked: Bool var hide: String? var rows: [SitesRow]? /// Twins among hidden sites, only while they show. var twins: [Twins]? } struct First: Decodable, Equatable, Sendable { var line: String; var add: String; var quick: String } var title: String var search: Search /// Absent while a signed-in copy is still loading and holds nothing to show: no Add alone then. var add: String? var you: String var rows: [SitesRow] var quick: SitesLabelled var hidden: Hidden var first: First? /// The same name at the same address more than once, among the shown sites only. var twins: [Twins]? /// A signed-in copy still loading: "Loading your list…", and the sites it last held that have not come yet. var loading: Loading? var waitingRows: [Waiting]? /// The earlier Sites' list did not open on this phone: what to do, and Leave them. var bookStuck: BookStuck? /// Sign-ins on this phone for sites no longer in the list (drawn in You). var orphans: Orphans? struct Loading: Decodable, Equatable, Sendable { var line: String } /// A site the copy held before, not here yet: drawn greyed, never opened. struct Waiting: Decodable, Equatable, Sendable, Identifiable { var id: String var label: String var site: String var letter: String /// A hidden site: the core names one only while the hidden sites show, and it is drawn among them. var hidden: Bool = false enum CodingKeys: String, CodingKey { case id, label, site, letter, hidden } init(id: String, label: String, site: String, letter: String, hidden: Bool = false) { self.id = id; self.label = label; self.site = site; self.letter = letter; self.hidden = hidden } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) label = try c.decode(String.self, forKey: .label) site = try c.decode(String.self, forKey: .site) letter = try c.decode(String.self, forKey: .letter) hidden = try c.decodeIfPresent(Bool.self, forKey: .hidden) ?? false } } struct BookStuck: Decodable, Equatable, Sendable { var line: String; var leave: String } /// Each one named (the core's `sites`, by id); Remove takes one at a time, asked first. struct Orphans: Decodable, Equatable, Sendable { var line: String var remove: String var sites: [Orphan] } struct Orphan: Decodable, Equatable, Sendable, Identifiable, Hashable { var id: String; var label: String } enum CodingKeys: String, CodingKey { case title, search, add, you, rows, quick, hidden, first, twins, loading, orphans case waitingRows = "waiting_rows" case bookStuck = "book_stuck" } struct Twins: Decodable, Equatable, Sendable, Identifiable, Hashable { var line: String var keep: String var ids: [String] var id: String { ids.joined(separator: "+") } } } /// Undo for a removal, while the core holds it (`sites.delete`, `sites.keep_one`). struct SitesUndo: Decodable, Equatable, Sendable { var label: String var seconds: Double } /// A website store the core says is owed removal (`sites.stores.gone`). struct SitesGoneStore: Decodable, Equatable, Sendable { var store: String var storeUUID: String enum CodingKeys: String, CodingKey { case store case storeUUID = "store_uuid" } } /// `sites.search`: what he typed, read on the phone. struct SitesFound: Decodable, Equatable, Sendable { struct First: Decodable, Equatable, Sendable { var kind: String var label: String var line: String? var url: String? } var first: First var inYours: String var matches: [SitesRow] var none: String? enum CodingKeys: String, CodingKey { case first, matches, none case inYours = "in_yours" } } /// `sites.choose`: where a link opens. Nothing loads until he picks. struct SitesChoice: Decodable, Equatable, Sendable { struct Group: Decodable, Equatable, Sendable { var label: String; var rows: [SitesRow] } struct Hidden: Decodable, Equatable, Sendable { var label: String; var line: String; var locked: Bool; var rows: [SitesRow]? } var title: String var url: String var shown: String var once: String? var atSite: Group var others: Group var hidden: Hidden var quick: SitesLabelled var newSite: SitesLabelled var nothingYet: String enum CodingKeys: String, CodingKey { case title, url, shown, once, others, hidden, quick case atSite = "at_site" case newSite = "new_site" case nothingYet = "nothing_yet" } } /// `sites.open`: what a page loads, in which store, and the words it arrives with. struct SitesOpened: Decodable, Equatable, Sendable { struct Quick: Decodable, Equatable, Sendable { var strip: String var name: String var nameLine: String var close: String enum CodingKeys: String, CodingKey { case strip, name, close case nameLine = "name_line" } } struct Arrived: Decodable, Equatable, Sendable { var line: String; var wrong: String } var url: String var stay: Bool var title: String var store: String var storeUUID: String? var quick: Quick? var arrived: Arrived? /// The saved `interactionState`, base64, for a page the phone let go. var state: String? var trackers: Bool? enum CodingKeys: String, CodingKey { case url, stay, title, store, quick, arrived, state, trackers case storeUUID = "store_uuid" } } struct SitesAsk: Decodable, Equatable, Sendable { var line: String; var yes: String; var no: String } /// `sites.forget` / `sites.close`: closed, or the ask a site that forgets puts first. struct SitesClosing: Decodable, Equatable, Sendable { var said: String? var ask: SitesAsk? var first: String? } /// `sites.exit`: the web's own page, or a hand-off to the phone, asked first. struct SitesExit: Decodable, Equatable, Sendable { var inside: Bool? var kind: String? var line: String? var go: String? var stay: String? } /// `sites.panel`: the head a page's own words are drawn under, so a page never passes itself off as Sites. struct SitesPanel: Decodable, Equatable, Sendable { var head: String var line: String? var ok: String? var cancel: String? var photo: String? var camera: String? var file: String? } /// `sites.failed`: a page that can't load, in Sites' own paper. struct SitesFailed: Decodable, Equatable, Sendable { var title: String var line: String var again: String var whenBack: String? var offline: Bool? enum CodingKeys: String, CodingKey { case title, line, again, offline case whenBack = "when_back" } } /// `sites.add.plan`: the address written whole, the name suggested, and a line when the address is used already. struct SitesPlan: Decodable, Equatable, Sendable { var home: String; var label: String; var line: String? } /// `sites.settings`: You. struct SitesSettings: Decodable, Equatable, Sendable { struct Choice: Decodable, Equatable, Sendable, Identifiable { var id: String; var label: String; var chosen: Bool?; var line: String? } struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String var label: String var line: String? var choices: [Choice]? var text: String? var on: Bool? enum CodingKeys: String, CodingKey { case id, label, line, choices, value } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) id = try c.decode(String.self, forKey: .id) label = try c.decode(String.self, forKey: .label) line = try c.decodeIfPresent(String.self, forKey: .line) choices = try c.decodeIfPresent([Choice].self, forKey: .choices) text = try? c.decodeIfPresent(String.self, forKey: .value) on = try? c.decodeIfPresent(Bool.self, forKey: .value) } } struct Card: Decodable, Equatable, Sendable { var count: String } var title: String var card: Card var rows: [Row] var shared: [Row] } /// `sites.storage`: what each site keeps on this phone, largest first. struct SitesStorage: Decodable, Equatable, Sendable { struct Row: Decodable, Equatable, Sendable, Identifiable { var id: String; var letter: String; var label: String; var size: String } var title: String var rows: [Row] var all: String var allAsk: String enum CodingKeys: String, CodingKey { case title, rows, all case allAsk = "all_ask" } } /// The core's refusal, already in words. struct SitesRefusal: Error, Equatable { let words: String } /// Every call Sites makes, each with this phone's key. struct SitesCalls: Sendable { let core: any CottonCalling /// This phone's key for the book (the Keychain's; a test hands in its own). var key: @Sendable () throws -> String = { try SitesAppKey.held() } private func call(_ method: String, _ fields: [String: SitesValue] = [:], as: A.Type) async throws -> A { var body = fields body["key"] = .text(try key()) do { return try await core.call(method, body, as: A.self) } catch { throw Self.words(error) } } private func send(_ method: String, _ fields: [String: SitesValue] = [:]) async throws { var body = fields body["key"] = .text(try key()) do { _ = try await core.callJSON(method, body) } catch { throw Self.words(error) } } /// A refusal's words (the core's `message`), else the error as it came. static func words(_ error: Error) -> Error { if let refused = error as? SitesRefusal { return refused } if let message = (error as? CottonCallError)?.message, !message.isEmpty { return SitesRefusal(words: message) } return error } func home(unlocked: Bool) async throws -> SitesHome { try await call("sites.home", ["unlocked": .flag(unlocked)], as: SitesHome.self) } func plan(_ home: String) async throws -> SitesPlan { try await call("sites.add.plan", ["home": .text(home)], as: SitesPlan.self) } private struct Changed: Decodable, Sendable { var row: SitesRow; var said: String? } func add(label: String, home: String, stay: Bool, hidden: Bool, pinned: Bool = false) async throws -> (SitesRow, String?) { let answer = try await call("sites.add", ["label": .text(label), "home": .text(home), "stay": .flag(stay), "hidden": .flag(hidden), "pinned": .flag(pinned)], as: Changed.self) return (answer.row, answer.said) } func edit(_ id: String, _ fields: [String: SitesValue]) async throws -> (SitesRow, String?) { var all = fields all["id"] = .text(id) let answer = try await call("sites.edit", all, as: Changed.self) return (answer.row, answer.said) } struct Deleted: Decodable, Sendable { var said: String?; var undo: SitesUndo? } /// The site leaves the list at once; the core holds it for Undo and erases it when the time is up. func delete(_ id: String) async throws -> Deleted { try await call("sites.delete", ["id": .text(id)], as: Deleted.self) } private struct Undone: Decodable, Sendable { var undone: String } func undo(_ id: String) async throws { _ = try await call("sites.undo", ["id": .text(id)], as: Undone.self) } struct Kept: Decodable, Sendable { var kept: String; var undo: SitesUndo? } func keepOne(keep: String, drop: String) async throws -> Kept { try await call("sites.keep_one", ["keep": .text(keep), "drop": .text(drop)], as: Kept.self) } private struct OrphanRemoved: Decodable, Sendable { var removed: Int } /// One site's sign-in no longer in the list, removed (the core checks it again; its store is then owed). func orphanRemove(_ id: String) async throws -> Int { try await call("sites.orphans.remove", ["id": .text(id)], as: OrphanRemoved.self).removed } private struct Gone: Decodable, Sendable { var stores: [SitesGoneStore]; var kept: Bool? } func storesGone() async throws -> [SitesGoneStore] { try await call("sites.stores.gone", as: Gone.self).stores } /// The owed stores, and whether he already said Keep for now to every one of them (the core keeps that across launches). func storesOwed() async throws -> (stores: [SitesGoneStore], kept: Bool) { let gone = try await call("sites.stores.gone", as: Gone.self) return (gone.stores, gone.kept ?? false) } private struct StoresKept: Decodable, Sendable { var kept: Int } /// Keep for now: not asked again until a store not among these is owed. func storesKeep(_ stores: [String]) async throws { _ = try await call("sites.stores.keep", ["stores": .list(stores)], as: StoresKept.self) } private struct BookLeft: Decodable, Sendable { var left: Bool } /// The earlier Sites' list that will not open here, left (set aside on this phone, never sent). func bookLeave() async throws { _ = try await call("sites.book.leave", as: BookLeft.self) } private struct StoresLeft: Decodable, Sendable { var left: Int } func storesRemoved(_ stores: [String]) async throws { _ = try await call("sites.stores.removed", ["stores": .list(stores)], as: StoresLeft.self) } private struct Arranged: Decodable, Sendable { var said: String } func arrange(order: [String], pinned: [String]) async throws -> String { try await call("sites.arrange", ["order": .list(order), "pinned": .list(pinned)], as: Arranged.self).said } func search(_ q: String, unlocked: Bool) async throws -> SitesFound { try await call("sites.search", ["q": .text(q), "unlocked": .flag(unlocked)], as: SitesFound.self) } func choose(_ url: String, from: String? = nil, moving: Bool = false, unlocked: Bool) async throws -> SitesChoice { var fields: [String: SitesValue] = ["url": .text(url), "moving": .flag(moving), "unlocked": .flag(unlocked)] if let from { fields["from"] = .text(from) } return try await call("sites.choose", fields, as: SitesChoice.self) } /// A site's page (at its last page, or at `url`), or a quick visit or a search's throwaway place (no `id`). func open(id: String?, url: String?, quick: Bool = false, search: Bool = false, from: String? = nil) async throws -> SitesOpened { var fields: [String: SitesValue] = [:] if let id { fields["id"] = .text(id) } if let url { fields["url"] = .text(url) } if quick { fields["quick"] = .flag(true) } if search { fields["search"] = .flag(true) } if let from { fields["from"] = .text(from) } return try await call("sites.open", fields, as: SitesOpened.self) } /// The tracker rules WebKit compiles and the site's own switch (CONTRACT Trackers: asked as a site opens). func trackers(_ id: String) async throws -> SitesTrackersAnswer { try await call("sites.trackers", ["id": .text(id)], as: SitesTrackersAnswer.self) } /// Where a site's page is now and its title, for the list's second line; `nil` on Sign out. func left(_ id: String, url: String?, title: String?) async throws { var fields: [String: SitesValue] = ["id": .text(id), "url": url.map(SitesValue.text) ?? .none] if let title { fields["title"] = .text(title) } try await send("sites.left", fields) } struct Live: Decodable, Sendable { var keep: [String]; var letGo: [String] enum CodingKeys: String, CodingKey { case keep; case letGo = "let_go" } } func live(_ id: String?, budget: Int) async throws -> Live { var fields: [String: SitesValue] = ["budget": .number(budget)] if let id { fields["id"] = .text(id) } return try await call("sites.live", fields, as: Live.self) } func keepState(_ id: String, _ blob: String) async throws { try await send("sites.state", ["id": .text(id), "blob": .text(blob)]) } func close(_ id: String) async throws -> SitesClosing { try await call("sites.close", ["id": .text(id)], as: SitesClosing.self) } func forget(_ id: String) async throws -> SitesClosing { try await call("sites.forget", ["id": .text(id)], as: SitesClosing.self) } func exit(_ url: String) async throws -> SitesExit { try await call("sites.exit", ["url": .text(url)], as: SitesExit.self) } func panel(_ kind: String, url: String) async throws -> SitesPanel { try await call("sites.panel", ["kind": .text(kind), "url": .text(url)], as: SitesPanel.self) } func failed(id: String?, url: String, offline: Bool) async throws -> SitesFailed { var fields: [String: SitesValue] = ["url": .text(url), "offline": .flag(offline)] if let id { fields["id"] = .text(id) } return try await call("sites.failed", fields, as: SitesFailed.self) } func settings() async throws -> SitesSettings { try await call("sites.settings", as: SitesSettings.self) } func set(_ name: String, _ value: SitesValue) async throws -> SitesSettings { try await call("sites.set", ["name": .text(name), "value": value], as: SitesSettings.self) } func storage(_ sizes: [String: Int]) async throws -> SitesStorage { try await call("sites.storage", ["sizes": .sizes(sizes)], as: SitesStorage.self) } } /// A field of a call, as JSON. enum SitesValue: Encodable, Sendable { case text(String), flag(Bool), number(Int), list([String]), sizes([String: Int]), none func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() switch self { case .text(let s): try c.encode(s) case .flag(let b): try c.encode(b) case .number(let n): try c.encode(n) case .list(let l): try c.encode(l) case .sizes(let m): try c.encode(m) case .none: try c.encodeNil() } } } /// The key Sites' list is sealed under: 32 random bytes made on first use, in this phone's keychain, readable only /// while it is unlocked, on this device only (never synced, never in a backup that leaves it). The core takes it with /// every call and keeps it nowhere. enum SitesAppKey { private static let service = "cotton.sites" private static let account = "key" struct Refused: Error { let status: OSStatus } static func held() throws -> String { if let found = read() { return found } var bytes = [UInt8](repeating: 0, count: 32) let made = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) guard made == errSecSuccess else { throw Refused(status: made) } let key = Data(bytes).base64EncodedString() .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") var item = base() item[kSecValueData as String] = Data(key.utf8) item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly let status = SecItemAdd(item as CFDictionary, nil) guard status == errSecSuccess else { throw Refused(status: status) } return key } #if COTTON_DEV /// Sites Dev's `-sites-fresh`: the key forgotten, so the list it sealed is never read again. static func forget() { SecItemDelete(base() as CFDictionary) } #endif private static func base() -> [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account] } private static func read() -> String? { var query = base() query[kSecReturnData as String] = true query[kSecMatchLimit as String] = kSecMatchLimitOne var found: CFTypeRef? guard SecItemCopyMatching(query as CFDictionary, &found) == errSecSuccess, let data = found as? Data else { return nil } return String(decoding: data, as: UTF8.self) } } #endif