DomainDig/SubdomainDiscoveryService.swift

22ecca12b4fe0e0850401754c674632f322d919d
domain-dig/DomainDig/SubdomainDiscoveryService.swift history · blame · raw

118 lines · 4181 bytes

  1import Foundation
  2
  3enum SubdomainDiscoveryService {
  4    static func discover(for domain: String, limit: Int = 25) async -> ServiceResult<[DiscoveredSubdomain]> {
  5        let normalizedDomain = normalize(domain)
  6        guard !normalizedDomain.isEmpty else {
  7            return .empty("No passive subdomains found")
  8        }
  9
 10        return await cache.subdomains(for: normalizedDomain, limit: limit)
 11    }
 12
 13    private static let cache = SubdomainDiscoveryCache()
 14
 15    private static func normalize(_ domain: String) -> String {
 16        domain
 17            .trimmingCharacters(in: .whitespacesAndNewlines)
 18            .lowercased()
 19    }
 20}
 21
 22private actor SubdomainDiscoveryCache {
 23    private var cachedResults: [String: ServiceResult<[DiscoveredSubdomain]>] = [:]
 24    private var inFlightTasks: [String: Task<ServiceResult<[DiscoveredSubdomain]>, Never>] = [:]
 25    private var lastRequestAt: Date?
 26
 27    func subdomains(for domain: String, limit: Int) async -> ServiceResult<[DiscoveredSubdomain]> {
 28        if let cachedResult = cachedResults[domain] {
 29            return cachedResult
 30        }
 31
 32        if let inFlightTask = inFlightTasks[domain] {
 33            return await inFlightTask.value
 34        }
 35
 36        let task = Task<ServiceResult<[DiscoveredSubdomain]>, Never> {
 37            await enforceRateLimit()
 38            return await fetchSubdomains(for: domain, limit: limit)
 39        }
 40        inFlightTasks[domain] = task
 41
 42        let result = await task.value
 43        cachedResults[domain] = result
 44        inFlightTasks[domain] = nil
 45        return result
 46    }
 47
 48    private func enforceRateLimit() async {
 49        if let lastRequestAt {
 50            let delay = max(0, 0.75 - Date().timeIntervalSince(lastRequestAt))
 51            if delay > 0 {
 52                try? await Task.sleep(for: .seconds(delay))
 53            }
 54        }
 55        lastRequestAt = Date()
 56    }
 57
 58    private func fetchSubdomains(for domain: String, limit: Int) async -> ServiceResult<[DiscoveredSubdomain]> {
 59        var components = URLComponents(string: "https://crt.sh/")!
 60        components.queryItems = [
 61            URLQueryItem(name: "q", value: "%.\(domain)"),
 62            URLQueryItem(name: "output", value: "json")
 63        ]
 64
 65        guard let url = components.url else {
 66            return .error("Subdomain discovery unavailable")
 67        }
 68
 69        do {
 70            let request = URLRequest(url: url, timeoutInterval: 10)
 71            let (data, response) = try await URLSession.shared.data(for: request)
 72            guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
 73                return .error("Subdomain discovery unavailable")
 74            }
 75
 76            let entries = try JSONDecoder().decode([CRTShEntry].self, from: data)
 77            let subdomains = parseSubdomains(from: entries, domain: domain, limit: limit)
 78            return subdomains.isEmpty ? .empty("No passive subdomains found") : .success(subdomains)
 79        } catch {
 80            return .error(error.localizedDescription)
 81        }
 82    }
 83
 84    private func parseSubdomains(from entries: [CRTShEntry], domain: String, limit: Int) -> [DiscoveredSubdomain] {
 85        var seen = Set<String>()
 86        var results: [DiscoveredSubdomain] = []
 87
 88        for entry in entries {
 89            let names = entry.nameValue
 90                .split(separator: "\n")
 91                .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
 92
 93            for name in names {
 94                let sanitized = name.hasPrefix("*.") ? String(name.dropFirst(2)) : name
 95                guard sanitized != domain, sanitized.hasSuffix(".\(domain)") else {
 96                    continue
 97                }
 98                guard seen.insert(sanitized).inserted else {
 99                    continue
100                }
101                results.append(DiscoveredSubdomain(hostname: sanitized))
102                if results.count == limit {
103                    return results
104                }
105            }
106        }
107
108        return results
109    }
110}
111
112private struct CRTShEntry: Decodable {
113    let nameValue: String
114
115    enum CodingKeys: String, CodingKey {
116        case nameValue = "name_value"
117    }
118}