Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ConnectionDetails.swift

282 lines10.4 KB

1import Foundation
2​
3struct ConnectionDetails: Equatable, Sendable {
4 var endpoint: String
5 var pairingCode: String?
6}
7​
8enum ConnectionDetailsError: LocalizedError, Equatable {
9 case empty
10 case invalidAddress
11 case unsupportedScheme
12​
13 var errorDescription: String? {
14 switch self {
15 case .empty:
16 "Paste a T3 pairing link or enter your server address."
17 case .invalidAddress:
18 "That connection link does not include a valid server address."
19 case .unsupportedScheme:
20 "Use an HTTP or HTTPS T3 server address."
21 }
22 }
24​
25/// Parses the pairing links emitted by local, shared, and hosted T3 environments.
26enum ConnectionDetailsParser {
27 private static let tokenNames = [
28 "token",
29 "pairing_token",
30 "pairingToken",
31 "pairing_code",
32 "pairingCode",
33 "code",
34 ]
35 private static let endpointNames = ["host", "endpoint", "server", "url"]
36 private static let wrappedPairingURLNames = ["pairingUrl", "pairing_url"]
37​
38 static func parse(_ input: String) throws -> ConnectionDetails {
39 let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
40 guard !trimmed.isEmpty else { throw ConnectionDetailsError.empty }
41​
42 let extracted = trimmed.lowercased().hasPrefix("t3code:")
43 ? trimmed
44 : (firstURL(in: trimmed) ?? trimmed)
45 let candidate = trimmingTrailingProsePunctuation(extracted)
46 let loweredCandidate = candidate.lowercased()
47 if candidate.contains("://")
48 || loweredCandidate.hasPrefix("t3code:")
49 || loweredCandidate.hasPrefix("t3:") {
50 return try parseURL(candidate)
51 }
52​
53 let pieces = candidate
54 .split(whereSeparator: \.isWhitespace)
55 .map(String.init)
56 guard let address = pieces.first else { throw ConnectionDetailsError.empty }
57 let code = pieces.dropFirst().first(where: { !$0.isEmpty })
58 return ConnectionDetails(
59 endpoint: try normalizedEndpoint(address),
60 pairingCode: normalizedCode(code)
61 )
62 }
63​
64 static func normalizedEndpoint(_ input: String) throws -> String {
65 let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
66 guard !trimmed.isEmpty else { throw ConnectionDetailsError.empty }
67​
68 let value: String
69 if trimmed.contains("://") {
70 value = trimmed
71 } else {
72 let address = bracketBareIPv6(trimmed)
73 value = "\(EndpointNetworkScope.isLocalHost(trimmed) ? "http" : "https")://\(address)"
74 }
75​
76 guard var components = URLComponents(string: value),
77 let scheme = components.scheme?.lowercased()
78 else {
79 throw ConnectionDetailsError.invalidAddress
80 }
81​
82 switch scheme {
83 case "http", "https":
84 break
85 case "ws":
86 components.scheme = "http"
87 case "wss":
88 components.scheme = "https"
89 default:
90 throw ConnectionDetailsError.unsupportedScheme
91 }
92​
93 guard let host = components.host, !host.isEmpty else {
94 throw ConnectionDetailsError.invalidAddress
95 }
96​
97 components.path = ""
98 components.query = nil
99 components.fragment = nil
100 guard var normalized = components.url?.absoluteString else {
101 throw ConnectionDetailsError.invalidAddress
102 }
103 while normalized.hasSuffix("/") {
104 normalized.removeLast()
105 }
106 return normalized
107 }
108​
109 private static func parseURL(_ input: String) throws -> ConnectionDetails {
110 guard let components = URLComponents(string: input),
111 let scheme = components.scheme?.lowercased()
112 else {
113 throw ConnectionDetailsError.invalidAddress
114 }
115​
116 let fragmentItems = URLComponents(string: "?\(components.fragment ?? "")")?.queryItems ?? []
117 let queryItems = components.queryItems ?? []
118 let allItems = queryItems + fragmentItems
119 let token = firstValue(named: tokenNames, in: allItems)
120​
121 if ["t3", "t3code", "t3code-swiftui", "t3code-swiftui-dev"].contains(scheme) {
122 if let wrappedPairingURL = firstValue(named: wrappedPairingURLNames, in: allItems) {
123 var wrapped = try parse(wrappedPairingURL)
124 if wrapped.pairingCode == nil {
125 wrapped.pairingCode = normalizedCode(token)
126 }
127 return wrapped
128 }
129 guard let target = firstValue(named: endpointNames, in: allItems) else {
130 throw ConnectionDetailsError.invalidAddress
131 }
132 return ConnectionDetails(
133 endpoint: try normalizedEndpoint(target),
134 pairingCode: normalizedCode(token)
135 )
136 }
137​
138 guard ["http", "https", "ws", "wss"].contains(scheme) else {
139 throw ConnectionDetailsError.unsupportedScheme
140 }
141​
142 let advertisedHost = firstValue(named: endpointNames, in: queryItems)
143 return ConnectionDetails(
144 endpoint: try normalizedEndpoint(advertisedHost ?? input),
145 pairingCode: normalizedCode(token)
146 )
147 }
148​
149 private static func firstValue(named names: [String], in items: [URLQueryItem]) -> String? {
150 items.first { item in
151 names.contains { $0.caseInsensitiveCompare(item.name) == .orderedSame }
152 }?.value
153 }
154​
155 private static func normalizedCode(_ input: String?) -> String? {
156 let value = input?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
157 return value.isEmpty ? nil : value
158 }
159​
160 private static func firstURL(in input: String) -> String? {
161 guard let expression = try? NSRegularExpression(
162 pattern: #"(?i)(?:(?:https?|wss?|t3)://|t3code(?:-swiftui(?:-dev)?)?:(?://)?)[^\s<>"']+"#
163 ) else {
164 return nil
165 }
166 let range = NSRange(input.startIndex..., in: input)
167 guard let match = expression.firstMatch(in: input, range: range),
168 let swiftRange = Range(match.range, in: input)
169 else {
170 return nil
171 }
172 return trimmingTrailingProsePunctuation(String(input[swiftRange]))
173 }
174​
175 /// Pairing links are commonly copied from sentences and terminal output.
176 /// Remove punctuation belonging to that prose while retaining balanced URL
177 /// delimiters such as the closing bracket around an IPv6 host.
178 static func trimmingTrailingProsePunctuation(_ input: String) -> String {
179 var value = input
180 while let last = value.last {
181 let shouldTrim = switch last {
182 case ".", ",", ";", "!":
183 true
184 case "?":
185 value.dropLast().contains("?")
186 case ")":
187 value.filter { $0 == ")" }.count > value.filter { $0 == "(" }.count
188 case "]":
189 value.filter { $0 == "]" }.count > value.filter { $0 == "[" }.count
190 case "}":
191 value.filter { $0 == "}" }.count > value.filter { $0 == "{" }.count
192 default:
193 false
194 }
195 guard shouldTrim else { break }
196 value.removeLast()
197 }
198 return value
199 }
200​
201 private static func bracketBareIPv6(_ value: String) -> String {
202 guard value.contains(":"),
203 !value.hasPrefix("["),
204 value.filter({ $0 == ":" }).count > 1
205 else {
206 return value
207 }
208 return "[\(value)]"
209 }
211​
212enum EndpointNetworkScope {
213 static func isLocal(_ endpoint: String) -> Bool {
214 guard let host = URLComponents(string: endpoint)?.host else { return false }
215 return isLocalHost(host)
216 }
217​
218 static func isLocalHost(_ rawHost: String) -> Bool {
219 let host = hostWithoutPort(rawHost).lowercased()
220​
221 if host == "localhost" || host.hasSuffix(".local") || host == "::1" {
222 return true
223 }
224​
225 let octets = host.split(separator: ".").compactMap { Int($0) }
226 if octets.count == 4, octets.allSatisfy({ 0 ... 255 ~= $0 }) {
227 return octets[0] == 10
228 || octets[0] == 127
229 || (octets[0] == 169 && octets[1] == 254)
230 || (octets[0] == 172 && 16 ... 31 ~= octets[1])
231 || (octets[0] == 192 && octets[1] == 168)
232 }
233​
234 guard host.contains(":"),
235 let firstHextetText = host.split(separator: ":", omittingEmptySubsequences: true).first,
236 let firstHextet = UInt16(firstHextetText, radix: 16)
237 else {
238 return false
239 }
240 return firstHextet & 0xffc0 == 0xfe80
241 || firstHextet & 0xfe00 == 0xfc00
242 }
243​
244 private static func hostWithoutPort(_ rawHost: String) -> String {
245 let value = rawHost.trimmingCharacters(in: .whitespacesAndNewlines)
246 if value.hasPrefix("["),
247 let closingBracket = value.firstIndex(of: "]") {
248 return String(value[value.index(after: value.startIndex) ..< closingBracket])
249 }
250​
251 if value.filter({ $0 == ":" }).count == 1,
252 let colon = value.lastIndex(of: ":"),
253 value[value.index(after: colon)...].allSatisfy(\.isNumber) {
254 return String(value[..<colon])
255 }
256 return value
257 }
259​
260enum ConnectionErrorCopy {
261 static func message(for rawMessage: String?) -> String {
262 let message = rawMessage?
263 .trimmingCharacters(in: .whitespacesAndNewlines)
264 .lowercased() ?? ""
265​
266 if message.isEmpty || message == "cancelled" || message == "canceled" {
267 return "The connection stopped before it finished. Make sure T3 Code is running, then try again."
268 }
269 if message.contains("expired") || message.contains("invalid_credential")
270 || message.contains("invalid credential") || message.contains("401") {
271 return "That pairing code is invalid or has expired. Create a new code on the host and try again."
272 }
273 if message.contains("timed out") || message.contains("timeout") {
274 return "The server took too long to respond. Check the address and that both devices are online."
275 }
276 if message.contains("offline") || message.contains("network")
277 || message.contains("could not connect") || message.contains("not connected") {
278 return "This iPhone could not reach the server. Check the address and network, then try again."
279 }
280 return "T3 Code could not complete pairing. Check the server address and use a fresh pairing code."
281 }