DomainDig/DomainName.swift
153 lines · 6641 bytes
7 symbols in this file
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
19 /// The normalized host on success. A Unicode host is returned as typed; only
20 /// the length limits are measured on its IDNA-encoded form.
21 static func validate(_ raw: String) -> Result<String, DomainNameError> {
22 let host = normalize(raw)
23 guard !host.isEmpty else { return .failure(.empty) }
24
25 // `%`-escapes are rejected rather than decoded: `DomainHostURL` reads
26 // `https://ex%20ample.com` as host `ex ample.com`, so decoding here
27 // would hand the sections a host with a space in it.
28 if let invalid = host.first(where: { !isHostCharacter($0) }) {
29 return .failure(.invalidCharacter(invalid))
30 }
31
32 let labels = host.components(separatedBy: ".")
33 guard labels.count > 1 else { return .failure(.singleLabel) }
34
35 if let malformed = labels.first(where: { $0.isEmpty || $0.first == "-" || $0.last == "-" }) {
36 return .failure(.malformedLabel(malformed))
37 }
38
39 // The limits apply to the encoded host, which is what the section
40 // services send, so they are measured on the punycode form.
41 guard let encoded = DomainHostURL.https(host)?.host else {
42 // `URL` refuses a host whose encoded label is over the limit
43 // instead of reporting which label it was, so the two reasons are
44 // told apart here: a label holding a character that will not encode
45 // on its own is malformed, and anything else that will not encode is
46 // too long.
47 //
48 // Probing per character rather than per prefix is what makes the
49 // position irrelevant. The earlier version probed the label's first
50 // few characters, so an unencodable character after them was
51 // reported as merely too long.
52 //
53 // Not a complete IDNA characterisation: a label refused for a
54 // combination its characters form, rather than for one of them,
55 // still falls through to `.labelTooLong`. The input is rejected
56 // either way and only the message differs.
57 if let malformed = labels.first(where: { label in
58 label.contains { !canEncode(String($0)) }
59 }) {
60 return .failure(.malformedLabel(malformed))
61 }
62 return .failure(.labelTooLong)
63 }
64
65 guard encoded.components(separatedBy: ".").allSatisfy({ $0.utf8.count <= maximumLabelBytes }) else {
66 return .failure(.labelTooLong)
67 }
68 guard encoded.utf8.count <= maximumHostBytes else { return .failure(.tooLong) }
69
70 return .success(host)
71 }
72
73 private static func normalize(_ raw: String) -> String {
74 var host = raw.trimmingCharacters(in: .whitespacesAndNewlines)
75
76 if let separator = host.range(of: "://"), isScheme(host[..<separator.lowerBound]) {
77 host = String(host[separator.upperBound...])
78 }
79
80 // A query can follow the host with no path at all: `example.com?q=1`.
81 host = String(host.prefix { $0 != "/" && $0 != "?" })
82
83 if let userInfo = host.lastIndex(of: "@") {
84 host = String(host[host.index(after: userInfo)...])
85 }
86 if let port = host.lastIndex(of: ":") {
87 host = String(host[..<port])
88 }
89 if host.hasSuffix(".") {
90 host.removeLast()
91 }
92
93 // NFC so a decomposed "ü" measures the same as a precomposed one.
94 return host.lowercased().precomposedStringWithCanonicalMapping
95 }
96
97 private static func isScheme(_ candidate: Substring) -> Bool {
98 guard let first = candidate.first, first.isASCII, first.isLetter else { return false }
99 return candidate.allSatisfy { character in
100 character.isASCII && (character.isLetter || character.isNumber || "+-.".contains(character))
101 }
102 }
103
104 /// Non-ASCII is left to IDNA; whatever it cannot encode fails the
105 /// `DomainHostURL` guard in `validate`.
106 private static func isHostCharacter(_ character: Character) -> Bool {
107 guard character.isASCII else { return !character.isWhitespace }
108 return character.isLetter || character.isNumber || character == "-" || character == "."
109 }
110
111 /// Whether `label` encodes at all, independent of length.
112 ///
113 /// An all-ASCII label always does, so only non-ASCII input reaches the
114 /// probe. Callers pass a single character to ask whether that character is
115 /// encodable anywhere in a label.
116 private static func canEncode(_ label: String) -> Bool {
117 guard label.contains(where: { !$0.isASCII }) else { return true }
118 // The ASCII suffix keeps the probe a two-label host.
119 return DomainHostURL.https("\(label).test") != nil
120 }
121}
122
123enum DomainNameError: LocalizedError, Equatable {
124 case empty
125 case singleLabel
126 case invalidCharacter(Character)
127 case malformedLabel(String)
128 case labelTooLong
129 case tooLong
130
131 var errorDescription: String? {
132 switch self {
133 case .empty:
134 return "Enter a domain to inspect."
135 case .singleLabel:
136 return "Enter a full domain, such as example.com."
137 case .invalidCharacter(let character):
138 if character.isWhitespace {
139 return "A domain cannot contain spaces."
140 }
141 return "A domain cannot contain \(character)."
142 case .malformedLabel(let label):
143 if label.isEmpty {
144 return "A domain cannot contain an empty part."
145 }
146 return "\(label) is not a valid part of a domain name."
147 case .labelTooLong:
148 return "Each part of a domain can be at most 63 bytes."
149 case .tooLong:
150 return "A domain can be at most 253 bytes."
151 }
152 }
153}