Repository Public License
1import Foundation23public enum ExfiltrationVerdict: Sendable, Hashable {4 case allow5 /// The user must see the exact data and approve.6 case confirm([String])7 case refuse([String])89 public var reasons: [String] {10 switch self {11 case .allow: []12 case .confirm(let reasons), .refuse(let reasons): reasons13 }14 }15}1617/// Checks what the model wants to send out (a URL, a search query, typed text) against what it has seen.18///19/// The threat: a page tells the model to put the conversation, or the content of another page, into an address20/// (`https://allowed.example/c?d=<everything you know>`). The guard remembers a fingerprint of every text the21/// model was given and every address it was offered, and inspects each part of an outgoing URL the model can22/// fill with data: query names and values, the fragment, path segments and host labels.23///24/// It is a heuristic. Data shorter than `shingleLength` normalised characters, paraphrased data and data split over25/// many small requests below `hostBudget` are not detected.26public struct ExfiltrationGuard: Sendable {27 /// Characters of normalised text that must match before an overlap counts.28 public static let shingleLength = 2029 /// Overlap needed in a search query (quoting a title in a search is ordinary research).30 public static let searchOverlapThreshold = 6031 /// Overlap needed in typed text.32 public static let typedOverlapThreshold = 4033 /// A URL part longer than this that the model composed itself needs confirmation.34 public static let longSlotLength = 20035 /// Characters of model-composed URL parts one host may receive in a run before the user is asked.36 public static let hostBudget = 60037 static let maxShingles = 1_500_0003839 private var shingles = Set<UInt64>()40 private var knownURLs = Set<String>()41 private var composedByHost: [String: Int] = [:]4243 public init() {}4445 // MARK: Observation4647 /// Remembers text the model was given (page content, the user's goal). Addresses written in it become known.48 public mutating func observe(text: String) {49 let slice = String(text.prefix(400_000))50 for url in Self.urls(in: slice) { knownURLs.insert(Self.key(url)) }51 let bytes = Self.normalise(slice)52 guard bytes.count >= Self.shingleLength, shingles.count < Self.maxShingles else { return }53 for start in 0...(bytes.count - Self.shingleLength) {54 shingles.insert(Self.hash(bytes[start..<(start + Self.shingleLength)]))55 }56 }5758 /// Remembers an address a page offered (a link, a form action) or a page the agent is on.59 public mutating func observe(url: URL) { knownURLs.insert(Self.key(url.absoluteString)) }6061 public func isKnown(_ url: URL) -> Bool { knownURLs.contains(Self.key(url.absoluteString)) }6263 // MARK: Checks6465 /// Longest run of `text` (in normalised characters) that also appears in observed text; 0 below `shingleLength`.66 public func overlap(of text: String) -> Int {67 let bytes = Self.normalise(text)68 guard bytes.count >= Self.shingleLength else { return 0 }69 var best = 0, run = 070 for start in 0...(bytes.count - Self.shingleLength) {71 if shingles.contains(Self.hash(bytes[start..<(start + Self.shingleLength)])) {72 run += 1; best = max(best, run + Self.shingleLength - 1)73 } else { run = 0 }74 }75 return best76 }7778 /// Judges a URL the model wants to open, fetch or download. Records what it composed, so call it once per attempt.79 public mutating func evaluate(url: URL) -> ExfiltrationVerdict {80 if isKnown(url) { return .allow }81 let text = url.absoluteString82 if text.count > 2_000 { return .refuse(["the address is \(text.count) characters long"]) }83 var confirm: [String] = [], refuse: [String] = []84 var composed = 085 for slot in Self.slots(of: url) {86 let value = slot.value87 guard value.count >= 8 else { continue }88 composed += value.count89 if let decoded = Self.decodeBlob(value) {90 if overlap(of: decoded) >= Self.shingleLength {91 refuse.append("\(slot.name) is encoded text copied from a page or from the conversation")92 } else {93 confirm.append("\(slot.name) is an opaque encoded value of \(value.count) characters")94 }95 continue96 }97 let shared = overlap(of: value)98 if shared >= Self.shingleLength {99 confirm.append("\(slot.name) contains \(shared) characters copied from a page or from the conversation")100 } else if value.count >= Self.longSlotLength {101 confirm.append("\(slot.name) is \(value.count) characters long")102 }103 }104 if !refuse.isEmpty { return .refuse(refuse + confirm) }105 let host = DomainPolicy.normalisedHost(of: url) ?? ""106 let total = composedByHost[host, default: 0] + composed107 composedByHost[host] = total108 if confirm.isEmpty, total > Self.hostBudget, composed > 0 {109 confirm.append("\(total) characters of composed address data have gone to \(host) in this run")110 }111 return confirm.isEmpty ? .allow : .confirm(confirm)112 }113114 /// Judges free text leaving the device outside a URL (a search query, text typed into a page).115 public func evaluate(outboundText text: String, threshold: Int) -> ExfiltrationVerdict {116 if let decoded = Self.decodeBlob(text.trimmingCharacters(in: .whitespacesAndNewlines)) {117 return overlap(of: decoded) >= Self.shingleLength118 ? .refuse(["the text is encoded content copied from a page or from the conversation"])119 : .confirm(["the text is an opaque encoded value"])120 }121 let shared = overlap(of: text)122 return shared >= max(threshold, Self.shingleLength)123 ? .confirm(["the text contains \(shared) characters copied from a page or from the conversation"]) : .allow124 }125126 // MARK: Internals127128 struct Slot: Hashable { var name: String; var value: String }129130 /// Every part of an address a model can fill with data, percent-decoded.131 static func slots(of url: URL) -> [Slot] {132 var slots: [Slot] = []133 let components = URLComponents(url: url, resolvingAgainstBaseURL: false)134 func decode(_ text: String) -> String {135 (text.replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? text)136 }137 for item in components?.percentEncodedQueryItems ?? [] {138 slots.append(Slot(name: "query parameter name", value: decode(item.name)))139 if let value = item.value {140 slots.append(Slot(name: "query parameter “\(AgentText.singleLine(decode(item.name), limit: 24))”", value: decode(value)))141 }142 }143 if let fragment = components?.percentEncodedFragment, !fragment.isEmpty { slots.append(Slot(name: "the fragment", value: decode(fragment))) }144 for (index, segment) in (components?.percentEncodedPath ?? "").split(separator: "/").enumerated() {145 slots.append(Slot(name: "path segment \(index + 1)", value: decode(String(segment))))146 }147 for label in (url.host(percentEncoded: false) ?? "").split(separator: ".") {148 slots.append(Slot(name: "a host label", value: String(label)))149 }150 return slots151 }152153 /// The text hidden in a base64 / base64url / hex value, or `nil` when `value` does not look like an encoded blob.154 /// A blob that does not decode to text yields an empty string (still a blob, nothing to compare).155 static func decodeBlob(_ value: String) -> String? {156 guard value.count >= 32, value.count <= 8_192 else { return nil }157 let scalars = Array(value.unicodeScalars)158 guard scalars.allSatisfy({ $0.isASCII }) else { return nil }159 let isHex = scalars.count >= 40 && scalars.allSatisfy { ("0"..."9").contains($0) || ("a"..."f").contains($0) || ("A"..."F").contains($0) }160 if isHex {161 var bytes: [UInt8] = []162 var index = 0163 while index + 1 < scalars.count {164 if let byte = UInt8(String(String.UnicodeScalarView(scalars[index...(index + 1)])), radix: 16) { bytes.append(byte) }165 index += 2166 }167 return String(bytes: bytes, encoding: .utf8).map(printable) ?? ""168 }169 let alphabet = scalars.allSatisfy { ("0"..."9").contains($0) || ("a"..."z").contains($0) || ("A"..."Z").contains($0) || "+/=_-".unicodeScalars.contains($0) }170 guard alphabet else { return nil }171 // A slug ("my-long-article-title") shares the base64url alphabet: words of one case separated by - or _.172 let parts = value.split(whereSeparator: { $0 == "-" || $0 == "_" })173 let isSlug = parts.count >= 3 && parts.allSatisfy { part in174 part.count <= 16 && (part.allSatisfy { $0.isLowercase } || part.allSatisfy { $0.isUppercase } || part.allSatisfy { $0.isNumber }175 || (part.first?.isUppercase == true && part.dropFirst().allSatisfy { $0.isLowercase }))176 }177 if isSlug { return nil }178 let digits = scalars.filter { ("0"..."9").contains($0) }.count179 let uppers = scalars.filter { ("A"..."Z").contains($0) }.count, lowers = scalars.filter { ("a"..."z").contains($0) }.count180 let mixed = uppers >= 2 && lowers >= 2181 guard value.hasSuffix("=") || (mixed && digits >= 1) || (mixed && value.count >= 48) || value.count >= 96 else { return nil }182 var base64 = value.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")183 while base64.hasSuffix("=") { base64.removeLast() }184 base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4)185 guard let data = Data(base64Encoded: base64) else { return "" }186 return String(data: data, encoding: .utf8).map(printable) ?? ""187 }188189 private static func printable(_ text: String) -> String {190 let letters = text.unicodeScalars.filter { $0.properties.isAlphabetic || $0.properties.isWhitespace || ("0"..."9").contains($0) }.count191 return letters * 10 >= text.unicodeScalars.count * 7 ? text : ""192 }193194 /// Lowercase letters and digits; every run of anything else becomes one space. `a+b`, `a%20b` and `a-b` thus195 /// all match "a b" in a page.196 static func normalise(_ text: String) -> [UInt8] {197 var out: [UInt8] = []198 out.reserveCapacity(text.utf8.count)199 var pendingSpace = false200 for scalar in text.lowercased().unicodeScalars {201 if scalar.properties.isAlphabetic || scalar.properties.numericType != nil {202 if pendingSpace, !out.isEmpty { out.append(0x20) }203 pendingSpace = false204 out.append(contentsOf: Array(String(scalar).utf8))205 } else { pendingSpace = true }206 }207 return out208 }209210 /// FNV-1a over one window. A 64-bit collision would only cause one unnecessary confirmation.211 static func hash(_ bytes: ArraySlice<UInt8>) -> UInt64 {212 var value: UInt64 = 0xcbf2_9ce4_8422_2325213 for byte in bytes { value = (value ^ UInt64(byte)) &* 0x0000_0100_0000_01b3 }214 return value215 }216217 private static let urlPattern = try? NSRegularExpression(pattern: #"https?://[^\s<>"'`\)\]\}]+"#, options: [.caseInsensitive])218219 static func urls(in text: String) -> [String] {220 guard let urlPattern else { return [] }221 return urlPattern.matches(in: text, range: NSRange(text.startIndex..., in: text)).prefix(5_000).compactMap { match in222 Range(match.range, in: text).map { String(text[$0]) }223 }224 }225226 /// An address as compared: no trailing slash or sentence punctuation; the fragment stays, since a page script can227 /// read it. Case is kept (query values228 /// are case-sensitive data); only the scheme and host are case-insensitive, and URL parsing lowercases neither,229 /// so both sides go through the same folding of that prefix.230 static func key(_ raw: String) -> String {231 var text = raw232 while let last = text.last, ".,;:!?/".contains(last) { text.removeLast() }233 guard let schemeEnd = text.range(of: "://") else { return text }234 let rest = text[schemeEnd.upperBound...]235 let hostEnd = rest.firstIndex(where: { "/?".contains($0) }) ?? rest.endIndex236 return text[..<schemeEnd.upperBound].lowercased() + rest[..<hostEnd].lowercased() + rest[hostEnd...]237 }238}239