Repository Public License
1import Diagnostics2import Foundation34/// The delimiters put around everything that comes from a page or from a tool.5///6/// The nonce is random per run and never appears in any page fetched before the run, so content written in advance7/// cannot contain a valid closing marker. Content is neutralised anyway: the bracket sequences, the tag names and8/// the nonce itself are removed from it before wrapping.9public struct DataEnvelope: Sendable, Hashable {10 public static let openTag = "ORIX_DATA"11 public static let closeTag = "END_ORIX_DATA"1213 public let nonce: String1415 /// A fresh 128-bit nonce.16 public init() {17 var generator = SystemRandomNumberGenerator()18 nonce = String(format: "%016llx%016llx", generator.next() as UInt64, generator.next() as UInt64)19 }2021 /// For tests. Characters other than letters and digits are dropped.22 public init(nonce: String) { self.nonce = String(nonce.filter { $0.isASCII && ($0.isLetter || $0.isNumber) }.prefix(64)) }2324 public func openMarker(tool: String) -> String {25 let safe = String(tool.filter { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "_" || $0 == ".") }.prefix(48))26 return "<<<\(Self.openTag) \(nonce) tool=\(safe)>>>"27 }2829 public var closeMarker: String { "<<<\(Self.closeTag) \(nonce)>>>" }3031 /// Removes from `content` anything that could be read as a marker.32 public func neutralise(_ content: String) -> String {33 var out = content.replacingOccurrences(of: "<<<", with: "‹‹‹").replacingOccurrences(of: ">>>", with: "›››")34 for tag in [Self.closeTag, Self.openTag] {35 out = out.replacingOccurrences(of: tag, with: "[marker removed]", options: .caseInsensitive)36 }37 if !nonce.isEmpty { out = out.replacingOccurrences(of: nonce, with: "[removed]", options: .caseInsensitive) }38 return out39 }4041 public func wrap(_ content: String, tool: String) -> String {42 "\(openMarker(tool: tool))\n\(neutralise(content))\n\(closeMarker)"43 }44}4546/// Redaction and size limits applied to page-derived text before it can reach a model, a log or the database.47public enum ResultSanitizer {48 private static let cardCandidate = try? NSRegularExpression(pattern: #"(?<![\d.])(?:\d[ \-]?){12,18}\d(?!\d|\.\d)"#)49 private static let jwt = try? NSRegularExpression(pattern: #"\beyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}"#)5051 /// `Redactor` (bearer tokens, key-shaped strings, `password: value` pairs) plus JSON Web Tokens and52 /// payment-card numbers (13–19 digits passing the Luhn check).53 public static func redact(_ text: String) -> String {54 var out = Redactor.redact(text)55 if let jwt { out = jwt.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "‹redacted›") }56 guard let cardCandidate else { return out }57 let matches = cardCandidate.matches(in: out, range: NSRange(out.startIndex..., in: out))58 for match in matches.reversed() {59 guard let range = Range(match.range, in: out) else { continue }60 let digits = out[range].compactMap(\.wholeNumberValue)61 if (13...19).contains(digits.count), luhn(digits) { out.replaceSubrange(range, with: "‹card number redacted›") }62 }63 return out64 }6566 static func luhn(_ digits: [Int]) -> Bool {67 guard digits.contains(where: { $0 != 0 }) else { return false }68 var sum = 069 for (offset, digit) in digits.reversed().enumerated() {70 if offset % 2 == 1 { let doubled = digit * 2; sum += doubled > 9 ? doubled - 9 : doubled } else { sum += digit }71 }72 return sum % 10 == 073 }7475 /// Cuts `text` to `limit` characters with a visible marker.76 public static func bound(_ text: String, to limit: Int) -> String { AgentText.truncate(text, to: max(0, limit)) }77}78