// 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)importFoundationimportImageIOimportSwiftUIimportUniformTypeIdentifiersenumChatLinkFetch {staticlet pageMost = 256 * 1024staticlet pictureMost = 2 * 1024 * 1024staticlet thumbMost = 2_800staticlet thumbSide = 160staticlet wait: TimeInterval = 6staticlet hops = 4/// The page at `url` as text, or nil (not a web page, too slow, too far, on his network).staticfunc page(_ url: String) async -> String? {guardlet (data, response) = await fetch(url, accept: "text/html", most: pageMost, whole: false, of: { $0 == "text/html" }) else { returnnil }let encoding = response.textEncodingName .map { CFStringConvertIANACharSetNameToEncoding($0 as CFString) } .flatMap { $0 == kCFStringEncodingInvalidId ? nil : String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding($0)) }returnString(data: data, encoding: encoding ?? .utf8) ?? String(decoding: data, as: UTF8.self) }/// The picture at `url` made the card's thumb, or nil.staticfunc thumb(_ url: String) async -> String? {guardlet (data, _) = await fetch(url, accept: "image/*", most: pictureMost, whole: true, of: { $0.hasPrefix("image/") }) else { returnnil }return thumbOf(data) }/// `data` (a picture) as a JPEG under `thumbMost` base64 characters, `thumbSide` on its long side: quality first,/// then size.staticfunc thumbOf(_ data: Data) -> String? {guardlet source = CGImageSourceCreateWithData(data as CFData, nil) else { returnnil }var side = thumbSidewhile side >= 40 {let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: side]guardlet small = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { returnnil }for quality in [0.7, 0.55, 0.4, 0.25] {let out = NSMutableData()guardlet jpeg = CGImageDestinationCreateWithData(out as CFMutableData, UTType.jpeg.identifier as CFString, 1, nil) else { returnnil } CGImageDestinationAddImage(jpeg, small, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)guard CGImageDestinationFinalize(jpeg) else { returnnil }let text = (out asData).base64EncodedString()if text.count <= thumbMost { return text } } side = side * 3 / 4 }returnnil }// MARK: the fetch/// The session: ephemeral, no cookies, no cache, no credentials, 6 s for the whole of it.privatestaticlet 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.ifChatWarmSeed.asked { c.protocolClasses = [ChatWarmLinkServer.self] } #endifreturn 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).privatestaticfunc fetch(_ url: String, accept: String, most: Int, whole: Bool, of type: (String) -> Bool) async -> (Data, URLResponse)? {guardlet start = URL(string: url), ChatLinkAddress.mayAsk(start) else { returnnil }var ask = URLRequest(url: start) ask.setValue(accept, forHTTPHeaderField: "Accept") ask.httpShouldHandleCookies = falselet hops = Hops()do {let (bytes, response) = tryawait session.bytes(for: ask, delegate: hops)guard (response as? HTTPURLResponse)?.statusCode == 200, type(response.mimeType?.lowercased() ?? "") else { bytes.task.cancel()returnnil }if response.expectedContentLength > Int64(most), whole { bytes.task.cancel(); returnnil }var data = Data() data.reserveCapacity(min(most, max(0, Int(response.expectedContentLength))))fortryawait byte in bytes {if data.count == most { bytes.task.cancel()return whole ? nil : (data, response) } data.append(byte) }return (data, response) } catch {returnnil } }/// Each redirect asked only to a public address, at most `hops` of them; no credential is ever offered.privatefinalclassHops: NSObject, URLSessionTaskDelegate, @unchecked Sendable {privatelet lock = NSLock()privatevar count = 0func 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 { returnnil }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.finalclassChatWarmLinkServer: URLProtocol, @unchecked Sendable {overrideclassfunc canInit(with request: URLRequest) -> Bool { true }overrideclassfunc canonicalRequest(for request: URLRequest) -> URLRequest { request }overridefunc startLoading() {guardlet url = request.url, let client else { return }ChatWarmLinks.asked(url.absoluteString)let served = ChatWarmLinks.served(url.absoluteString)var headers = ["Content-Type": served.type]iflet to = served.moved { headers["Location"] = to }let response = HTTPURLResponse(url: url, statusCode: served.status, httpVersion: "HTTP/1.1", headerFields: headers)!iflet 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) }overridefunc 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.structChatLinkCardStrip: View {let card: ChatLinkCardlet close: () -> Void @Environment(\.chatLook) privatevar look @State privatevar picture: UIImage?var body: someView { HStack(spacing: 10) {iflet 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) {iflet 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.enumChatLinkThumb {staticfunc image(_ thumb: String?) -> UIImage? {guardlet thumb, let data = Data(base64Encoded: thumb), data.count > 2, data[0] == 0xFF, data[1] == 0xD8else { returnnil }return UIImage(data: data) }}#endif