DomainDig/RedirectChainService.swift

95 lines · 3241 bytes

 1import Foundation
 2
 3struct RedirectChainService {
 4    static func trace(domain: String) async -> ServiceResult<[RedirectHop]> {
 5        guard let httpsURL = DomainHostURL.https(domain) else {
 6            return .error("Not a valid domain name")
 7        }
 8
 9        do {
10            let hops = try await followChain(startingURL: httpsURL)
11            return hops.isEmpty ? .empty("No redirect data available") : .success(hops)
12        } catch {
13            guard let httpURL = DomainHostURL.http(domain) else {
14                return .error(error.localizedDescription)
15            }
16
17            do {
18                let hops = try await followChain(startingURL: httpURL)
19                return hops.isEmpty ? .empty("No redirect data available") : .success(hops)
20            } catch {
21                return .error(error.localizedDescription)
22            }
23        }
24    }
25
26    private static func followChain(startingURL: URL) async throws -> [RedirectHop] {
27        let delegate = NoRedirectDelegate()
28        let session = URLSession(
29            configuration: .ephemeral,
30            delegate: delegate,
31            delegateQueue: nil
32        )
33        defer { session.invalidateAndCancel() }
34
35        var hops: [RedirectHop] = []
36        var currentURL = startingURL
37        let maxRedirects = 10
38
39        for step in 1...maxRedirects + 1 {
40            var request = URLRequest(url: currentURL, timeoutInterval: 10)
41            request.httpMethod = "GET"
42
43            let (_, response) = try await session.data(for: request)
44
45            guard let httpResponse = response as? HTTPURLResponse else {
46                throw URLError(.badServerResponse)
47            }
48
49            let statusCode = httpResponse.statusCode
50            let isRedirect = (300...399).contains(statusCode)
51
52            if isRedirect, let location = httpResponse.value(forHTTPHeaderField: "Location") {
53                hops.append(RedirectHop(
54                    stepNumber: step,
55                    statusCode: statusCode,
56                    url: currentURL.absoluteString,
57                    isFinal: false
58                ))
59
60                // Resolve relative redirects
61                if let nextURL = URL(string: location, relativeTo: currentURL)?.absoluteURL {
62                    currentURL = nextURL
63                } else {
64                    break
65                }
66
67                if step > maxRedirects { break }
68            } else {
69                // Non-redirect — this is the final destination
70                hops.append(RedirectHop(
71                    stepNumber: step,
72                    statusCode: statusCode,
73                    url: currentURL.absoluteString,
74                    isFinal: true
75                ))
76                break
77            }
78        }
79
80        return hops
81    }
82}
83
84private final class NoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
85    func urlSession(
86        _ _: URLSession,
87        task _: URLSessionTask,
88        willPerformHTTPRedirection _: HTTPURLResponse,
89        newRequest _: URLRequest,
90        completionHandler: @escaping (URLRequest?) -> Void
91    ) {
92        // Don't follow redirects automatically — return nil to stop
93        completionHandler(nil)
94    }
95}