DomainDig/DomainName.swift
137 lines · 5856 bytes
1import Foundation
2
3/// Validation for the inspected domain, applied at the two input boundaries:
4/// `DomainViewModel.run()` and the bulk paste field.
5///
6/// Nothing downstream routes through this. `DomainViewModel.normalizedDomain` is
7/// the key that matches already-stored rows, and the import and automation paths
8/// accept whatever is already on disk, so tightening those would turn tracking,
9/// workflow lookups and imports into silent no-ops for any stored domain these
10/// rules reject.
11///
12/// The invariant runs one way: everything `validate` accepts can be built into a
13/// request URL by `DomainHostURL`. The reverse does not hold — `-x.com` forms a
14/// URL and is still rejected here.
15enum DomainName {
16 private static let maximumLabelBytes = 63
17 private static let maximumHostBytes = 253
18 private static let probeLabelCharacters = 8
19
20 /// The normalized host on success. A Unicode host is returned as typed; only
21 /// the length limits are measured on its IDNA-encoded form.
22 static func validate(_ raw: String) -> Result<String, DomainNameError> {
23 let host = normalize(raw)
24 guard !host.isEmpty else { return .failure(.empty) }
25
26 // `%`-escapes are rejected rather than decoded: `DomainHostURL` reads
27 // `https://ex%20ample.com` as host `ex ample.com`, so decoding here
28 // would hand the sections a host with a space in it.
29 if let invalid = host.first(where: { !isHostCharacter($0) }) {
30 return .failure(.invalidCharacter(invalid))
31 }
32
33 let labels = host.components(separatedBy: ".")
34 guard labels.count > 1 else { return .failure(.singleLabel) }
35
36 if let malformed = labels.first(where: { $0.isEmpty || $0.first == "-" || $0.last == "-" }) {
37 return .failure(.malformedLabel(malformed))
38 }
39
40 // The limits apply to the encoded host, which is what the section
41 // services send, so they are measured on the punycode form.
42 guard let encoded = DomainHostURL.https(host)?.host else {
43 // `URL` refuses a host whose encoded label is over the limit instead
44 // of reporting which label it was, so the labels are re-encoded one
45 // at a time: a label that will not encode even truncated to
46 // `probeLabelCharacters` (short enough that it cannot reach the
47 // limit whatever it encodes to) is malformed rather than too long.
48 if let malformed = labels.first(where: { !canEncode(String($0.prefix(probeLabelCharacters))) }) {
49 return .failure(.malformedLabel(malformed))
50 }
51 return .failure(.labelTooLong)
52 }
53
54 guard encoded.components(separatedBy: ".").allSatisfy({ $0.utf8.count <= maximumLabelBytes }) else {
55 return .failure(.labelTooLong)
56 }
57 guard encoded.utf8.count <= maximumHostBytes else { return .failure(.tooLong) }
58
59 return .success(host)
60 }
61
62 private static func normalize(_ raw: String) -> String {
63 var host = raw.trimmingCharacters(in: .whitespacesAndNewlines)
64
65 if let separator = host.range(of: "://"), isScheme(host[..<separator.lowerBound]) {
66 host = String(host[separator.upperBound...])
67 }
68
69 // A query can follow the host with no path at all: `example.com?q=1`.
70 host = String(host.prefix { $0 != "/" && $0 != "?" })
71
72 if let userInfo = host.lastIndex(of: "@") {
73 host = String(host[host.index(after: userInfo)...])
74 }
75 if let port = host.lastIndex(of: ":") {
76 host = String(host[..<port])
77 }
78 if host.hasSuffix(".") {
79 host.removeLast()
80 }
81
82 // NFC so a decomposed "ü" measures the same as a precomposed one.
83 return host.lowercased().precomposedStringWithCanonicalMapping
84 }
85
86 private static func isScheme(_ candidate: Substring) -> Bool {
87 guard let first = candidate.first, first.isASCII, first.isLetter else { return false }
88 return candidate.allSatisfy { character in
89 character.isASCII && (character.isLetter || character.isNumber || "+-.".contains(character))
90 }
91 }
92
93 /// Non-ASCII is left to IDNA; whatever it cannot encode fails the
94 /// `DomainHostURL` guard in `validate`.
95 private static func isHostCharacter(_ character: Character) -> Bool {
96 guard character.isASCII else { return !character.isWhitespace }
97 return character.isLetter || character.isNumber || character == "-" || character == "."
98 }
99
100 private static func canEncode(_ label: String) -> Bool {
101 guard label.contains(where: { !$0.isASCII }) else { return true }
102 // The ASCII suffix keeps the probe a two-label host.
103 return DomainHostURL.https("\(label).test") != nil
104 }
105}
106
107enum DomainNameError: LocalizedError, Equatable {
108 case empty
109 case singleLabel
110 case invalidCharacter(Character)
111 case malformedLabel(String)
112 case labelTooLong
113 case tooLong
114
115 var errorDescription: String? {
116 switch self {
117 case .empty:
118 return "Enter a domain to inspect."
119 case .singleLabel:
120 return "Enter a full domain, such as example.com."
121 case .invalidCharacter(let character):
122 if character.isWhitespace {
123 return "A domain cannot contain spaces."
124 }
125 return "A domain cannot contain \(character)."
126 case .malformedLabel(let label):
127 if label.isEmpty {
128 return "A domain cannot contain an empty part."
129 }
130 return "\(label) is not a valid part of a domain name."
131 case .labelTooLong:
132 return "Each part of a domain can be at most 63 bytes."
133 case .tooLong:
134 return "A domain can be at most 253 bytes."
135 }
136 }
137}