DomainDig/RDAPService.swift
261 lines · 7737 bytes
1import Foundation
2
3enum RDAPService {
4 static func registrationStatus(for domain: String) async -> DomainAvailabilityStatus? {
5 let normalizedDomain = normalize(domain)
6 guard !normalizedDomain.isEmpty else { return nil }
7
8 switch await fetchRDAPResponse(for: normalizedDomain) {
9 case let .success(response):
10 return response.isDomainRecord ? .registered : nil
11 case .empty:
12 return nil
13 case .error:
14 return nil
15 }
16 }
17
18 static func ownership(for domain: String) async -> ServiceResult<DomainOwnership> {
19 let normalizedDomain = normalize(domain)
20 guard !normalizedDomain.isEmpty else {
21 return .empty("Unavailable")
22 }
23
24 switch await fetchRDAPResponse(for: normalizedDomain) {
25 case let .success(response):
26 let ownership = DomainOwnership(
27 registrar: response.registrarName,
28 createdDate: response.createdDate,
29 expirationDate: response.expirationDate,
30 status: response.status,
31 nameservers: response.nameservers,
32 abuseEmail: response.abuseEmail
33 )
34 return .success(ownership)
35 case let .empty(message):
36 return .empty(message)
37 case let .error(message):
38 return .error(message)
39 }
40 }
41
42 private static func normalize(_ domain: String) -> String {
43 domain
44 .trimmingCharacters(in: .whitespacesAndNewlines)
45 .lowercased()
46 }
47}
48
49private func fetchRDAPResponse(for domain: String) async -> ServiceResult<RDAPDomainResponse> {
50 guard let url = URL(string: "https://rdap.org/domain/\(domain)") else {
51 return .error("Unavailable")
52 }
53
54 do {
55 var request = URLRequest(url: url, timeoutInterval: 8)
56 request.setValue("application/rdap+json, application/json", forHTTPHeaderField: "Accept")
57
58 let (data, response) = try await URLSession.shared.data(for: request)
59 guard let httpResponse = response as? HTTPURLResponse else {
60 return .error(URLError(.badServerResponse).localizedDescription)
61 }
62
63 switch httpResponse.statusCode {
64 case 200:
65 let decoder = JSONDecoder()
66 let rdapResponse = try decoder.decode(RDAPDomainResponse.self, from: data)
67 guard rdapResponse.isDomainRecord else {
68 return .empty("Unavailable")
69 }
70 return .success(rdapResponse)
71 case 404:
72 return .empty("Unavailable")
73 default:
74 return .error("Unavailable")
75 }
76 } catch {
77 return .error(error.localizedDescription)
78 }
79}
80
81private struct RDAPDomainResponse: Decodable, Sendable {
82 let ldhName: String?
83 let objectClassName: String?
84 let unicodeName: String?
85 let handle: String?
86 let rawStatus: [String]?
87 let rawNameservers: [RDAPNameserver]?
88 let events: [RDAPEvent]?
89 let entities: [RDAPEntity]?
90
91 enum CodingKeys: String, CodingKey {
92 case ldhName
93 case objectClassName
94 case unicodeName
95 case handle
96 case rawStatus = "status"
97 case rawNameservers = "nameservers"
98 case events
99 case entities
100 }
101
102 var isDomainRecord: Bool {
103 if ldhName?.isEmpty == false {
104 return true
105 }
106 if objectClassName == "domain" {
107 return true
108 }
109 return handle != nil && unicodeName != nil
110 }
111
112 var registrarName: String? {
113 entities?.first(where: { $0.roles.contains("registrar") })?.bestDisplayName
114 }
115
116 var createdDate: Date? {
117 eventDate(for: ["registration", "registered"])
118 }
119
120 var expirationDate: Date? {
121 eventDate(for: ["expiration", "expiry", "expired"])
122 }
123
124 var abuseEmail: String? {
125 entities?.first(where: { $0.roles.contains("abuse") })?.email
126 ?? entities?.first(where: { $0.roles.contains("registrar") })?.abuseEntity?.email
127 }
128
129 var nameservers: [String] {
130 let rawValues = rawNameservers?.compactMap { $0.ldhName ?? $0.unicodeName } ?? []
131 return deduplicated(rawValues)
132 }
133
134 var status: [String] {
135 deduplicated(rawStatus ?? [])
136 }
137
138 private func eventDate(for actions: [String]) -> Date? {
139 let normalizedActions = Set(actions)
140 return events?
141 .first(where: { normalizedActions.contains($0.eventAction.lowercased()) })?
142 .parsedDate
143 }
144
145 private func deduplicated(_ values: [String]) -> [String] {
146 var seen = Set<String>()
147 return values
148 .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
149 .filter { !$0.isEmpty }
150 .filter { seen.insert($0.lowercased()).inserted }
151 }
152}
153
154private struct RDAPNameserver: Decodable, Sendable {
155 let ldhName: String?
156 let unicodeName: String?
157}
158
159private struct RDAPEvent: Decodable, Sendable {
160 let eventAction: String
161 let eventDate: String
162
163 var parsedDate: Date? {
164 RDAPDateParser.parse(eventDate)
165 }
166}
167
168private struct RDAPEntity: Decodable, Sendable {
169 let roles: [String]
170 let vcardArray: RDAPVCardArray?
171 let entities: [RDAPEntity]?
172
173 var bestDisplayName: String? {
174 vcardArray?.fullName ?? vcardArray?.organization ?? vcardArray?.email
175 }
176
177 var email: String? {
178 vcardArray?.email
179 }
180
181 var abuseEntity: RDAPEntity? {
182 entities?.first(where: { $0.roles.contains("abuse") })
183 }
184}
185
186private struct RDAPVCardArray: Decodable, Sendable {
187 let values: [[RDAPJSONValue]]
188
189 init(from decoder: Decoder) throws {
190 var container = try decoder.unkeyedContainer()
191 _ = try container.decode(String.self)
192 values = try container.decode([[RDAPJSONValue]].self)
193 }
194
195 var fullName: String? {
196 value(for: "fn")
197 }
198
199 var organization: String? {
200 value(for: "org")
201 }
202
203 var email: String? {
204 value(for: "email")
205 }
206
207 private func value(for key: String) -> String? {
208 values.first(where: { $0.first?.stringValue?.lowercased() == key })?.last?.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines)
209 }
210}
211
212private enum RDAPJSONValue: Decodable, Sendable {
213 case string(String)
214 case bool(Bool)
215 case number(Double)
216 case null
217
218 init(from decoder: Decoder) throws {
219 let container = try decoder.singleValueContainer()
220 if let value = try? container.decode(String.self) {
221 self = .string(value)
222 } else if let value = try? container.decode(Bool.self) {
223 self = .bool(value)
224 } else if let value = try? container.decode(Double.self) {
225 self = .number(value)
226 } else {
227 self = .null
228 }
229 }
230
231 var stringValue: String? {
232 switch self {
233 case let .string(value):
234 return value
235 case let .bool(value):
236 return value ? "true" : "false"
237 case let .number(value):
238 return String(value)
239 case .null:
240 return nil
241 }
242 }
243}
244
245private enum RDAPDateParser {
246 private static let iso8601WithFractional: ISO8601DateFormatter = {
247 let formatter = ISO8601DateFormatter()
248 formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
249 return formatter
250 }()
251
252 private static let iso8601: ISO8601DateFormatter = {
253 let formatter = ISO8601DateFormatter()
254 formatter.formatOptions = [.withInternetDateTime]
255 return formatter
256 }()
257
258 static func parse(_ value: String) -> Date? {
259 iso8601WithFractional.date(from: value) ?? iso8601.date(from: value)
260 }
261}