|
| 1 | +// LoopFollow |
| 2 | +// LogRedactor.swift |
| 3 | + |
| 4 | +import CryptoKit |
| 5 | +import Foundation |
| 6 | + |
| 7 | +/// Helpers for masking secrets before they hit the log file. The "share logs" |
| 8 | +/// feature exposes the on-disk log to the user, so anything sensitive that |
| 9 | +/// flows through `LogManager.log` must be reduced to a non-recoverable form |
| 10 | +/// while keeping enough signal (short suffix, host, fingerprint) to correlate |
| 11 | +/// events during debugging. |
| 12 | +enum LogRedactor { |
| 13 | + /// Last `keep` characters of `secret`, prefixed with `…`. Matches the |
| 14 | + /// existing `.suffix(8)` convention used in `LiveActivityManager`. |
| 15 | + static func tail(_ secret: String, keep: Int = 8) -> String { |
| 16 | + if secret.isEmpty { return "(empty)" } |
| 17 | + if secret.count <= keep { return "(redacted)" } |
| 18 | + return "…\(secret.suffix(keep))" |
| 19 | + } |
| 20 | + |
| 21 | + /// First `keep` characters of `secret`, suffixed with `…`. Matches the |
| 22 | + /// existing `.prefix(8)` convention used in `LoopAPNSService`. |
| 23 | + static func head(_ secret: String, keep: Int = 8) -> String { |
| 24 | + if secret.isEmpty { return "(empty)" } |
| 25 | + if secret.count <= keep { return "(redacted)" } |
| 26 | + return "\(secret.prefix(keep))…" |
| 27 | + } |
| 28 | + |
| 29 | + /// Known managed-Nightscout host suffixes. When a URL's host ends in one |
| 30 | + /// of these, the leading subdomain (which identifies the user) is masked |
| 31 | + /// and the suffix is kept so engineers can tell which platform the user |
| 32 | + /// is on. Anything else is treated as self-hosted and reduced to the TLD. |
| 33 | + private static let knownHostSuffixes: [String] = [ |
| 34 | + "nightscoutpro.com", |
| 35 | + "10be.de", |
| 36 | + "herokuapp.com", |
| 37 | + ] |
| 38 | + |
| 39 | + /// Keep scheme + a redacted host hint, drop path and query. The Nightscout |
| 40 | + /// token rides in `?token=` and the host itself identifies the user when |
| 41 | + /// they're on a managed platform, so we mask the subdomain and keep only |
| 42 | + /// the platform suffix (or just the TLD for self-hosted setups). |
| 43 | + static func url(_ raw: String) -> String { |
| 44 | + if raw.isEmpty { return "(empty)" } |
| 45 | + if let u = URL(string: raw), let host = u.host { |
| 46 | + let scheme = u.scheme.map { "\($0)://" } ?? "" |
| 47 | + return "\(scheme)\(maskHost(host))/…" |
| 48 | + } |
| 49 | + return "(redacted)" |
| 50 | + } |
| 51 | + |
| 52 | + private static func maskHost(_ host: String) -> String { |
| 53 | + // IPv4 / IPv6 / bracketed — drop entirely. |
| 54 | + if host.range(of: "^\\d+\\.\\d+\\.\\d+\\.\\d+$", options: .regularExpression) != nil { return "***" } |
| 55 | + if host.contains(":") || host.hasPrefix("[") { return "***" } |
| 56 | + |
| 57 | + let lower = host.lowercased() |
| 58 | + for suffix in knownHostSuffixes { |
| 59 | + if lower == suffix || lower.hasSuffix("." + suffix) { |
| 60 | + return "***." + suffix |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + let parts = host.split(separator: ".", omittingEmptySubsequences: false) |
| 65 | + if parts.count >= 2, let tld = parts.last, !tld.isEmpty { |
| 66 | + return "***." + String(tld) |
| 67 | + } |
| 68 | + return "***" |
| 69 | + } |
| 70 | + |
| 71 | + /// Apple Developer Key ID — 10-char uppercase alphanumeric. Reveals |
| 72 | + /// last 2 chars only. |
| 73 | + static func keyId(_ keyId: String) -> String { |
| 74 | + if keyId.isEmpty { return "(empty)" } |
| 75 | + if keyId.count <= 2 { return "(redacted)" } |
| 76 | + return "…\(keyId.suffix(2))" |
| 77 | + } |
| 78 | + |
| 79 | + /// Apple Team ID — 10-char uppercase alphanumeric. Reveals last 2 chars. |
| 80 | + static func teamId(_ teamId: String) -> String { |
| 81 | + keyId(teamId) |
| 82 | + } |
| 83 | + |
| 84 | + /// App bundle id ("com.example.MyApp"). Mask the middle component(s) but |
| 85 | + /// keep the leading TLD and trailing app name so suffixes like |
| 86 | + /// `.watchkitapp` or `.push-type.liveactivity` remain visible. |
| 87 | + static func bundleId(_ id: String) -> String { |
| 88 | + if id.isEmpty { return "(empty)" } |
| 89 | + let parts = id.split(separator: ".", omittingEmptySubsequences: false) |
| 90 | + guard parts.count >= 3 else { return "(redacted)" } |
| 91 | + var masked = [String]() |
| 92 | + masked.append(String(parts[0])) |
| 93 | + for _ in 1 ..< parts.count - 1 { |
| 94 | + masked.append("***") |
| 95 | + } |
| 96 | + masked.append(String(parts[parts.count - 1])) |
| 97 | + return masked.joined(separator: ".") |
| 98 | + } |
| 99 | + |
| 100 | + /// Username (Dexcom Share, etc.). Preserves first character and any |
| 101 | + /// `@domain` suffix shape so engineers can tell email-shaped from not. |
| 102 | + static func username(_ name: String) -> String { |
| 103 | + if name.isEmpty { return "(empty)" } |
| 104 | + if name.contains("@") { |
| 105 | + let parts = name.split(separator: "@", maxSplits: 1).map(String.init) |
| 106 | + let local = parts[0] |
| 107 | + let domain = parts.count > 1 ? parts[1] : "" |
| 108 | + let firstLocal = local.first.map(String.init) ?? "?" |
| 109 | + let firstDomain = domain.first.map(String.init) ?? "?" |
| 110 | + return "\(firstLocal)***@\(firstDomain)***" |
| 111 | + } |
| 112 | + let first = name.first.map(String.init) ?? "?" |
| 113 | + return "\(first)***" |
| 114 | + } |
| 115 | + |
| 116 | + /// Sweep an arbitrary message string for high-confidence secret shapes. |
| 117 | + /// Idempotent. Run by `LogManager.log` on every line before write. |
| 118 | + static func sweep(_ message: String) -> String { |
| 119 | + var out = message |
| 120 | + out = redactPEM(out) |
| 121 | + out = redactTokenQuery(out) |
| 122 | + out = redactJWT(out) |
| 123 | + return out |
| 124 | + } |
| 125 | + |
| 126 | + /// Replace any `?token=…` or `&token=…` value with `***` (case-insensitive). |
| 127 | + private static func redactTokenQuery(_ s: String) -> String { |
| 128 | + guard let regex = try? NSRegularExpression( |
| 129 | + pattern: "([?&]token=)[^&\\s\"'<>]+", |
| 130 | + options: [.caseInsensitive] |
| 131 | + ) else { return s } |
| 132 | + let range = NSRange(s.startIndex ..< s.endIndex, in: s) |
| 133 | + return regex.stringByReplacingMatches(in: s, options: [], range: range, withTemplate: "$1***") |
| 134 | + } |
| 135 | + |
| 136 | + /// Collapse the body of a PEM PRIVATE KEY block to `(redacted)`. |
| 137 | + private static func redactPEM(_ s: String) -> String { |
| 138 | + guard let regex = try? NSRegularExpression( |
| 139 | + pattern: "-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----", |
| 140 | + options: [] |
| 141 | + ) else { return s } |
| 142 | + let range = NSRange(s.startIndex ..< s.endIndex, in: s) |
| 143 | + return regex.stringByReplacingMatches( |
| 144 | + in: s, options: [], range: range, |
| 145 | + withTemplate: "-----BEGIN PRIVATE KEY----- (redacted) -----END PRIVATE KEY-----" |
| 146 | + ) |
| 147 | + } |
| 148 | + |
| 149 | + /// Collapse the middle segment of a JWT (`ey…\.ey…\.…`). |
| 150 | + private static func redactJWT(_ s: String) -> String { |
| 151 | + guard let regex = try? NSRegularExpression( |
| 152 | + pattern: "ey[A-Za-z0-9_-]{8,}\\.ey[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}", |
| 153 | + options: [] |
| 154 | + ) else { return s } |
| 155 | + let range = NSRange(s.startIndex ..< s.endIndex, in: s) |
| 156 | + return regex.stringByReplacingMatches(in: s, options: [], range: range, withTemplate: "ey…<jwt>…") |
| 157 | + } |
| 158 | + |
| 159 | + /// Non-reversible fingerprint for opaque blobs we can't safely log |
| 160 | + /// (settings JSON, scanned QR code contents, etc.). |
| 161 | + static func fingerprint(_ data: Data) -> String { |
| 162 | + let digest = SHA256.hash(data: data) |
| 163 | + let hex = digest.compactMap { String(format: "%02x", $0) }.joined() |
| 164 | + return "\(data.count) bytes, sha256=\(hex.prefix(8))…" |
| 165 | + } |
| 166 | + |
| 167 | + static func fingerprint(_ string: String) -> String { |
| 168 | + fingerprint(Data(string.utf8)) |
| 169 | + } |
| 170 | +} |
0 commit comments