// A link's page and picture, fetched by this phone and no one else (FEEDBACK-4 B4, chat CONTRACT.md "Link // previews"): an ephemeral session (no cookies, no cache, no credentials), the page's first 256 KB within 6 s and // `text/html` only, its picture 2 MB at most, made a JPEG under 2,800 base64 characters, 160 px on its long side. // Never an address on this phone or its network: the core refuses those before the phone asks, and this file checks // the first hop and every redirect after it again, by every address the name has. The core chooses the link, reads // the page and says what goes; the card stands above the writing box (`ChatLinkCardStrip`). #if os(iOS) import Foundation import ImageIO import SwiftUI import UniformTypeIdentifiers enum ChatLinkFetch { static let pageMost = 256 * 1024 static let pictureMost = 2 * 1024 * 1024 static let thumbMost = 2_800 static let thumbSide = 160 static let wait: TimeInterval = 6 static let hops = 4 /// The page at `url` as text, or nil (not a web page, too slow, too far, on his network). static func page(_ url: String) async -> String? { guard let (data, response) = await fetch(url, accept: "text/html", most: pageMost, whole: false, of: { $0 == "text/html" }) else { return nil } let encoding = response.textEncodingName .map { CFStringConvertIANACharSetNameToEncoding($0 as CFString) } .flatMap { $0 == kCFStringEncodingInvalidId ? nil : String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding($0)) } return String(data: data, encoding: encoding ?? .utf8) ?? String(decoding: data, as: UTF8.self) } /// The picture at `url` made the card's thumb, or nil. static func thumb(_ url: String) async -> String? { guard let (data, _) = await fetch(url, accept: "image/*", most: pictureMost, whole: true, of: { $0.hasPrefix("image/") }) else { return nil } return thumbOf(data) } /// `data` (a picture) as a JPEG under `thumbMost` base64 characters, `thumbSide` on its long side: quality first, /// then size. static func thumbOf(_ data: Data) -> String? { guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil } var side = thumbSide while side >= 40 { let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side] guard let small = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } for quality in [0.7, 0.55, 0.4, 0.25] { let out = NSMutableData() guard let jpeg = CGImageDestinationCreateWithData(out as CFMutableData, UTType.jpeg.identifier as CFString, 1, nil) else { return nil } CGImageDestinationAddImage(jpeg, small, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) guard CGImageDestinationFinalize(jpeg) else { return nil } let text = (out as Data).base64EncodedString() if text.count <= thumbMost { return text } } side = side * 3 / 4 } return nil } // MARK: the fetch /// The session: ephemeral, no cookies, no cache, no credentials, 6 s for the whole of it. private static let session: URLSession = { let c = URLSessionConfiguration.ephemeral c.httpCookieAcceptPolicy = .never c.httpShouldSetCookies = false c.httpCookieStorage = nil c.urlCache = nil c.urlCredentialStorage = nil c.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData c.timeoutIntervalForRequest = wait c.timeoutIntervalForResource = wait c.httpMaximumConnectionsPerHost = 2 #if COTTON_DEV // Chat Dev's seed serves its invented pages and picture on this phone: a UI test never reaches the internet. if ChatWarmSeed.asked { c.protocolClasses = [ChatWarmLinkServer.self] } #endif return URLSession(configuration: c) }() /// Up to `most` bytes of `url` (with `whole`, nil when there is more: a picture cut short is no picture), every hop /// checked before it is asked; nil unless the last answer is a 200 of a type `of` takes (read before the body). private static func fetch(_ url: String, accept: String, most: Int, whole: Bool, of type: (String) -> Bool) async -> (Data, URLResponse)? { guard let start = URL(string: url), ChatLinkAddress.mayAsk(start) else { return nil } var ask = URLRequest(url: start) ask.setValue(accept, forHTTPHeaderField: "Accept") ask.httpShouldHandleCookies = false let hops = Hops() do { let (bytes, response) = try await session.bytes(for: ask, delegate: hops) guard (response as? HTTPURLResponse)?.statusCode == 200, type(response.mimeType?.lowercased() ?? "") else { bytes.task.cancel() return nil } if response.expectedContentLength > Int64(most), whole { bytes.task.cancel(); return nil } var data = Data() data.reserveCapacity(min(most, max(0, Int(response.expectedContentLength)))) for try await byte in bytes { if data.count == most { bytes.task.cancel() return whole ? nil : (data, response) } data.append(byte) } return (data, response) } catch { return nil } } /// Each redirect asked only to a public address, at most `hops` of them; no credential is ever offered. private final class Hops: NSObject, URLSessionTaskDelegate, @unchecked Sendable { private let lock = NSLock() private var count = 0 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { let n = lock.withLock { count += 1; return count } guard n <= ChatLinkFetch.hops, ChatLinkAddress.mayAsk(request.url) else { return nil } return request } func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) async -> (URLSession.AuthChallengeDisposition, URLCredential?) { challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust ? (.performDefaultHandling, nil) : (.cancelAuthenticationChallenge, nil) } } } #if COTTON_DEV /// Chat Dev's seed: the invented pages, the move to his own network and the invented picture, served on this phone /// from `ChatWarmLinks` (Fixtures/chat-warm.json's `linkPreview`), registered only on `ChatLinkFetch`'s own session. final class ChatWarmLinkServer: URLProtocol, @unchecked Sendable { override class func canInit(with request: URLRequest) -> Bool { true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } override func startLoading() { guard let url = request.url, let client else { return } ChatWarmLinks.asked(url.absoluteString) let served = ChatWarmLinks.served(url.absoluteString) var headers = ["Content-Type": served.type] if let to = served.moved { headers["Location"] = to } let response = HTTPURLResponse(url: url, statusCode: served.status, httpVersion: "HTTP/1.1", headerFields: headers)! if let to = served.moved.flatMap(URL.init(string:)) { client.urlProtocol(self, wasRedirectedTo: URLRequest(url: to), redirectResponse: response) } // A move refused stands as the last answer. client.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) client.urlProtocol(self, didLoad: served.body) client.urlProtocolDidFinishLoading(self) } override func stopLoading() {} } #endif /// The card fetched for the link in what is written (FEEDBACK-4 B4), standing above the writing box: its picture, /// site and title, and the close mark, after which that link offers none again in this message. struct ChatLinkCardStrip: View { let card: ChatLinkCard let close: () -> Void @Environment(\.chatLook) private var look @State private var picture: UIImage? var body: some View { HStack(spacing: 10) { if let picture { Image(uiImage: picture).resizable().scaledToFill() .frame(width: 44, height: 44) .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) .accessibilityHidden(true) .accessibilityIdentifier("chat-preview-picture") } VStack(alignment: .leading, spacing: 1) { if let site = card.site { Text(verbatim: site).font(look.font(12.5)).foregroundStyle(look.colours.dim).lineLimit(1) } Text(verbatim: card.title ?? "").font(look.font(15, .semibold)).foregroundStyle(look.colours.text).lineLimit(2) .fixedSize(horizontal: false, vertical: true) } .frame(maxWidth: .infinity, alignment: .leading) .accessibilityElement(children: .combine) Button(action: close) { Image(systemName: "xmark").font(.system(size: 14, weight: .semibold)).foregroundStyle(look.colours.dim) .frame(width: 36, height: 36) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: ShellLines.line("chat", "app.compose.preview_close"))) .accessibilityIdentifier("chat-preview-close") } .padding(.leading, 8) .padding(.vertical, 8) .padding(.trailing, 2) .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(look.colours.pill)) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-preview") .task(id: card.thumb) { picture = ChatLinkThumb.image(card.thumb) } } } /// A card's `thumb` (a base64 JPEG the sender's phone made) as a picture. enum ChatLinkThumb { static func image(_ thumb: String?) -> UIImage? { guard let thumb, let data = Data(base64Encoded: thumb), data.count > 2, data[0] == 0xFF, data[1] == 0xD8 else { return nil } return UIImage(data: data) } } #endif