DomainDig/Models.swift

9384a668bf36f23f71e25d05b490d1040d308845
domain-dig/DomainDig/Models.swift history · blame · raw

1023 lines · 34944 bytes

   1import Foundation
   2
   3enum ServiceResult<Value> {
   4    case success(Value)
   5    case empty(String)
   6    case error(String)
   7}
   8
   9enum ConfidenceLevel: String, Codable {
  10    case high
  11    case medium
  12    case low
  13
  14    var title: String {
  15        rawValue.capitalized
  16    }
  17}
  18
  19enum InspectionErrorKind: String, Codable {
  20    case network
  21    case timeout
  22    case rateLimited
  23    case parsing
  24    case unsupported
  25    case unavailable
  26    case unknown
  27
  28    var title: String {
  29        switch self {
  30        case .network:
  31            return "Network"
  32        case .timeout:
  33            return "Timeout"
  34        case .rateLimited:
  35            return "Rate limited"
  36        case .parsing:
  37            return "Parsing"
  38        case .unsupported:
  39            return "Unsupported"
  40        case .unavailable:
  41            return "Unavailable"
  42        case .unknown:
  43            return "Unknown"
  44        }
  45    }
  46}
  47
  48struct InspectionFailure: Codable, Equatable {
  49    let kind: InspectionErrorKind
  50    let message: String
  51    let details: String?
  52}
  53
  54struct SectionProvenance: Codable, Equatable {
  55    let source: String
  56    let collectedAt: Date
  57    let provider: String?
  58    let resolver: String?
  59    let resultSource: LookupResultSource
  60}
  61
  62enum LookupResultSource: String, Codable {
  63    case live
  64    case cached
  65    case mixed
  66    case snapshot
  67
  68    var label: String {
  69        switch self {
  70        case .live:
  71            return "Live"
  72        case .cached:
  73            return "Cached"
  74        case .mixed:
  75            return "Mixed"
  76        case .snapshot:
  77            return "Snapshot"
  78        }
  79    }
  80}
  81
  82enum LookupSectionKind: String, Codable, CaseIterable {
  83    case dns
  84    case availability
  85    case ssl
  86    case hsts
  87    case httpHeaders
  88    case reachability
  89    case ipGeolocation
  90    case emailSecurity
  91    case ownership
  92    case ptr
  93    case redirectChain
  94    case subdomains
  95    case portScan
  96    case suggestions
  97}
  98
  99enum DomainAvailabilityStatus: String, Codable {
 100    case available
 101    case registered
 102    case unknown
 103}
 104
 105struct DomainAvailabilityResult: Codable {
 106    let domain: String
 107    let status: DomainAvailabilityStatus
 108}
 109
 110struct DomainSuggestionResult: Identifiable, Codable {
 111    let id: UUID
 112    let domain: String
 113    let status: DomainAvailabilityStatus
 114
 115    init(id: UUID = UUID(), domain: String, status: DomainAvailabilityStatus) {
 116        self.id = id
 117        self.domain = domain
 118        self.status = status
 119    }
 120}
 121
 122struct WatchedDomain: Codable, Identifiable {
 123    let id: UUID
 124    let domain: String
 125    let createdAt: Date
 126    var lastKnownAvailability: DomainAvailabilityStatus?
 127
 128    init(
 129        id: UUID = UUID(),
 130        domain: String,
 131        createdAt: Date = Date(),
 132        lastKnownAvailability: DomainAvailabilityStatus? = nil
 133    ) {
 134        self.id = id
 135        self.domain = domain
 136        self.createdAt = createdAt
 137        self.lastKnownAvailability = lastKnownAvailability
 138    }
 139}
 140
 141enum ChangeSeverity: Int, Codable, CaseIterable, Comparable {
 142    case low
 143    case medium
 144    case high
 145
 146    static func < (lhs: ChangeSeverity, rhs: ChangeSeverity) -> Bool {
 147        lhs.rawValue < rhs.rawValue
 148    }
 149
 150    var title: String {
 151        switch self {
 152        case .low:
 153            return "Low"
 154        case .medium:
 155            return "Medium"
 156        case .high:
 157            return "High"
 158        }
 159    }
 160}
 161
 162enum CertificateWarningLevel: String, Codable {
 163    case none
 164    case warning
 165    case critical
 166
 167    var title: String {
 168        switch self {
 169        case .none:
 170            return "Healthy"
 171        case .warning:
 172            return "Warning"
 173        case .critical:
 174            return "Critical"
 175        }
 176    }
 177}
 178
 179struct DomainChangeSummary: Codable, Equatable {
 180    let hasChanges: Bool
 181    let changedSections: [String]
 182    let message: String
 183    let severity: ChangeSeverity
 184    let generatedAt: Date
 185    let observedFacts: [String]
 186    let inferredConclusions: [String]
 187    let contextNote: String?
 188
 189    init(
 190        hasChanges: Bool,
 191        changedSections: [String],
 192        message: String,
 193        severity: ChangeSeverity,
 194        generatedAt: Date,
 195        observedFacts: [String] = [],
 196        inferredConclusions: [String] = [],
 197        contextNote: String? = nil
 198    ) {
 199        self.hasChanges = hasChanges
 200        self.changedSections = changedSections
 201        self.message = message
 202        self.severity = severity
 203        self.generatedAt = generatedAt
 204        self.observedFacts = observedFacts
 205        self.inferredConclusions = inferredConclusions
 206        self.contextNote = contextNote
 207    }
 208
 209    init(from decoder: Decoder) throws {
 210        let container = try decoder.container(keyedBy: CodingKeys.self)
 211        hasChanges = try container.decodeIfPresent(Bool.self, forKey: .hasChanges) ?? false
 212        changedSections = try container.decodeIfPresent([String].self, forKey: .changedSections) ?? []
 213        generatedAt = try container.decode(Date.self, forKey: .generatedAt)
 214        severity = try container.decodeIfPresent(ChangeSeverity.self, forKey: .severity) ?? (hasChanges ? .medium : .low)
 215        message = try container.decodeIfPresent(String.self, forKey: .message)
 216            ?? (changedSections.isEmpty ? "No meaningful changes" : changedSections.joined(separator: " • "))
 217        observedFacts = try container.decodeIfPresent([String].self, forKey: .observedFacts) ?? []
 218        inferredConclusions = try container.decodeIfPresent([String].self, forKey: .inferredConclusions) ?? []
 219        contextNote = try container.decodeIfPresent(String.self, forKey: .contextNote)
 220    }
 221}
 222
 223enum BatchLookupSource: String, Codable {
 224    case manual
 225    case watchlistRefresh
 226    case workflow
 227}
 228
 229enum BatchLookupStatus: String, Codable {
 230    case pending
 231    case running
 232    case completed
 233    case failed
 234}
 235
 236struct BatchLookupResult: Identifiable, Codable, Equatable {
 237    let id: UUID
 238    let domain: String
 239    let historyEntryID: UUID?
 240    let resultSource: LookupResultSource
 241    let availability: DomainAvailabilityStatus?
 242    let primaryIP: String?
 243    let quickStatus: String
 244    let summaryMessage: String?
 245    let changeSeverity: ChangeSeverity?
 246    let certificateWarningLevel: CertificateWarningLevel
 247    let timestamp: Date
 248    let status: BatchLookupStatus
 249    let errorMessage: String?
 250
 251    init(
 252        id: UUID = UUID(),
 253        domain: String,
 254        historyEntryID: UUID?,
 255        resultSource: LookupResultSource = .live,
 256        availability: DomainAvailabilityStatus?,
 257        primaryIP: String?,
 258        quickStatus: String,
 259        summaryMessage: String? = nil,
 260        changeSeverity: ChangeSeverity? = nil,
 261        certificateWarningLevel: CertificateWarningLevel = .none,
 262        timestamp: Date,
 263        status: BatchLookupStatus,
 264        errorMessage: String? = nil
 265    ) {
 266        self.id = id
 267        self.domain = domain
 268        self.historyEntryID = historyEntryID
 269        self.resultSource = resultSource
 270        self.availability = availability
 271        self.primaryIP = primaryIP
 272        self.quickStatus = quickStatus
 273        self.summaryMessage = summaryMessage
 274        self.changeSeverity = changeSeverity
 275        self.certificateWarningLevel = certificateWarningLevel
 276        self.timestamp = timestamp
 277        self.status = status
 278        self.errorMessage = errorMessage
 279    }
 280
 281    var hasMeaningfulChange: Bool {
 282        quickStatus == "Changed"
 283            || quickStatus == "High"
 284            || certificateWarningLevel != .none
 285            || status == .failed
 286    }
 287}
 288
 289struct BatchSweepSummary: Identifiable, Equatable {
 290    let id = UUID()
 291    let source: BatchLookupSource
 292    let totalDomains: Int
 293    let changedDomains: Int
 294    let unchangedDomains: Int
 295    let warningDomains: Int
 296    let results: [BatchLookupResult]
 297    let generatedAt: Date
 298}
 299
 300struct DomainWorkflow: Codable, Identifiable, Equatable {
 301    let id: UUID
 302    var name: String
 303    var domains: [String]
 304    var createdAt: Date
 305    var updatedAt: Date
 306    var notes: String?
 307
 308    init(
 309        id: UUID = UUID(),
 310        name: String,
 311        domains: [String],
 312        createdAt: Date = Date(),
 313        updatedAt: Date = Date(),
 314        notes: String? = nil
 315    ) {
 316        self.id = id
 317        self.name = name
 318        self.domains = domains
 319        self.createdAt = createdAt
 320        self.updatedAt = updatedAt
 321        self.notes = notes
 322    }
 323}
 324
 325struct WorkflowRunSummary: Identifiable, Equatable {
 326    let id = UUID()
 327    let workflowID: UUID
 328    let workflowName: String
 329    let totalDomains: Int
 330    let changedDomains: Int
 331    let unchangedDomains: Int
 332    let warningDomains: Int
 333    let results: [BatchLookupResult]
 334    let generatedAt: Date
 335}
 336
 337enum DataCapability: String, Codable {
 338    case ownershipHistory
 339    case dnsHistory
 340    case extendedSubdomains
 341    case domainPricing
 342}
 343
 344enum HistoryDateFilter: String, CaseIterable, Identifiable {
 345    case today
 346    case last7Days
 347    case all
 348
 349    var id: String { rawValue }
 350
 351    var title: String {
 352        switch self {
 353        case .today:
 354            return "Today"
 355        case .last7Days:
 356            return "Last 7 Days"
 357        case .all:
 358            return "All"
 359        }
 360    }
 361}
 362
 363enum ChangeFilterOption: String, CaseIterable, Identifiable {
 364    case all
 365    case changed
 366    case unchanged
 367
 368    var id: String { rawValue }
 369
 370    var title: String {
 371        switch self {
 372        case .all:
 373            return "All"
 374        case .changed:
 375            return "Changed"
 376        case .unchanged:
 377            return "Unchanged"
 378        }
 379    }
 380}
 381
 382enum HistorySortOption: String, CaseIterable, Identifiable {
 383    case newest
 384    case oldest
 385    case domain
 386
 387    var id: String { rawValue }
 388
 389    var title: String {
 390        switch self {
 391        case .newest:
 392            return "Newest"
 393        case .oldest:
 394            return "Oldest"
 395        case .domain:
 396            return "Domain A-Z"
 397        }
 398    }
 399}
 400
 401enum WatchlistFilterOption: String, CaseIterable, Identifiable {
 402    case all
 403    case pinnedOnly
 404    case changedOnly
 405
 406    var id: String { rawValue }
 407
 408    var title: String {
 409        switch self {
 410        case .all:
 411            return "All"
 412        case .pinnedOnly:
 413            return "Pinned Only"
 414        case .changedOnly:
 415            return "Changed Only"
 416        }
 417    }
 418}
 419
 420enum WatchlistSortOption: String, CaseIterable, Identifiable {
 421    case pinned
 422    case recentlyUpdated
 423    case alphabetical
 424
 425    var id: String { rawValue }
 426
 427    var title: String {
 428        switch self {
 429        case .pinned:
 430            return "Pinned"
 431        case .recentlyUpdated:
 432            return "Recently Updated"
 433        case .alphabetical:
 434            return "Alphabetical"
 435        }
 436    }
 437}
 438
 439enum PremiumCapability: String, Codable {
 440    case unlimitedTrackedDomains
 441    case automatedMonitoring
 442    case pushAlerts
 443    case batchTracking
 444    case advancedExports
 445}
 446
 447struct TrackedDomain: Codable, Identifiable, Equatable {
 448    let id: UUID
 449    var domain: String
 450    var createdAt: Date
 451    var updatedAt: Date
 452    var note: String?
 453    var isPinned: Bool
 454    var lastKnownAvailability: DomainAvailabilityStatus?
 455    var lastSnapshotID: UUID?
 456    var lastChangeSummary: DomainChangeSummary?
 457    var lastChangeSeverity: ChangeSeverity?
 458    var certificateWarningLevel: CertificateWarningLevel
 459    var certificateDaysRemaining: Int?
 460
 461    init(
 462        id: UUID = UUID(),
 463        domain: String,
 464        createdAt: Date = Date(),
 465        updatedAt: Date = Date(),
 466        note: String? = nil,
 467        isPinned: Bool = false,
 468        lastKnownAvailability: DomainAvailabilityStatus? = nil,
 469        lastSnapshotID: UUID? = nil,
 470        lastChangeSummary: DomainChangeSummary? = nil,
 471        lastChangeSeverity: ChangeSeverity? = nil,
 472        certificateWarningLevel: CertificateWarningLevel = .none,
 473        certificateDaysRemaining: Int? = nil
 474    ) {
 475        self.id = id
 476        self.domain = domain
 477        self.createdAt = createdAt
 478        self.updatedAt = updatedAt
 479        self.note = note
 480        self.isPinned = isPinned
 481        self.lastKnownAvailability = lastKnownAvailability
 482        self.lastSnapshotID = lastSnapshotID
 483        self.lastChangeSummary = lastChangeSummary
 484        self.lastChangeSeverity = lastChangeSeverity
 485        self.certificateWarningLevel = certificateWarningLevel
 486        self.certificateDaysRemaining = certificateDaysRemaining
 487    }
 488
 489    init(from decoder: Decoder) throws {
 490        let container = try decoder.container(keyedBy: CodingKeys.self)
 491        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
 492        domain = try container.decode(String.self, forKey: .domain)
 493        createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
 494        updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt) ?? createdAt
 495        note = try container.decodeIfPresent(String.self, forKey: .note)
 496        isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) ?? false
 497        lastKnownAvailability = try container.decodeIfPresent(DomainAvailabilityStatus.self, forKey: .lastKnownAvailability)
 498        lastSnapshotID = try container.decodeIfPresent(UUID.self, forKey: .lastSnapshotID)
 499        lastChangeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .lastChangeSummary)
 500        lastChangeSeverity = try container.decodeIfPresent(ChangeSeverity.self, forKey: .lastChangeSeverity) ?? lastChangeSummary?.severity
 501        certificateWarningLevel = try container.decodeIfPresent(CertificateWarningLevel.self, forKey: .certificateWarningLevel) ?? .none
 502        certificateDaysRemaining = try container.decodeIfPresent(Int.self, forKey: .certificateDaysRemaining)
 503    }
 504}
 505
 506// MARK: - DNS Models
 507
 508enum DNSRecordType: String, CaseIterable, Codable {
 509    case A
 510    case AAAA
 511    case MX
 512    case NS
 513    case TXT
 514    case CNAME
 515    case SOA
 516    case SRV
 517    case CAA
 518    case DS
 519    case PTR
 520
 521    var queryType: Int {
 522        switch self {
 523        case .A: return 1
 524        case .AAAA: return 28
 525        case .MX: return 15
 526        case .NS: return 2
 527        case .TXT: return 16
 528        case .CNAME: return 5
 529        case .SOA: return 6
 530        case .SRV: return 33
 531        case .CAA: return 257
 532        case .DS: return 43
 533        case .PTR: return 12
 534        }
 535    }
 536
 537    var usesRawDataValue: Bool {
 538        switch self {
 539        case .TXT, .SOA, .DS:
 540            return true
 541        default:
 542            return false
 543        }
 544    }
 545}
 546
 547struct DNSRecord: Identifiable, Codable {
 548    var id = UUID()
 549    let value: String
 550    let ttl: Int
 551}
 552
 553struct DNSSection: Identifiable, Codable {
 554    var id = UUID()
 555    let recordType: DNSRecordType
 556    var records: [DNSRecord]
 557    var wildcardRecords: [DNSRecord] = []
 558    var dnssecSigned: Bool?
 559    var error: String?
 560}
 561
 562// MARK: - SSL Models
 563
 564struct SSLCertificateInfo: Codable {
 565    struct CertChainEntry: Codable {
 566        let subject: String
 567        let issuer: String
 568    }
 569
 570    let commonName: String
 571    let subjectAltNames: [String]
 572    let issuer: String
 573    let validFrom: Date
 574    let validUntil: Date
 575    let daysUntilExpiry: Int
 576    let chainDepth: Int
 577    let tlsVersion: String?
 578    let cipherSuite: String?
 579    let chain: [CertChainEntry]
 580
 581    init(
 582        commonName: String,
 583        subjectAltNames: [String],
 584        issuer: String,
 585        validFrom: Date,
 586        validUntil: Date,
 587        daysUntilExpiry: Int,
 588        chainDepth: Int,
 589        tlsVersion: String? = nil,
 590        cipherSuite: String? = nil,
 591        chain: [CertChainEntry] = []
 592    ) {
 593        self.commonName = commonName
 594        self.subjectAltNames = subjectAltNames
 595        self.issuer = issuer
 596        self.validFrom = validFrom
 597        self.validUntil = validUntil
 598        self.daysUntilExpiry = daysUntilExpiry
 599        self.chainDepth = chainDepth
 600        self.tlsVersion = tlsVersion
 601        self.cipherSuite = cipherSuite
 602        self.chain = chain
 603    }
 604
 605    init(from decoder: Decoder) throws {
 606        let container = try decoder.container(keyedBy: CodingKeys.self)
 607        commonName = try container.decode(String.self, forKey: .commonName)
 608        subjectAltNames = try container.decode([String].self, forKey: .subjectAltNames)
 609        issuer = try container.decode(String.self, forKey: .issuer)
 610        validFrom = try container.decode(Date.self, forKey: .validFrom)
 611        validUntil = try container.decode(Date.self, forKey: .validUntil)
 612        daysUntilExpiry = try container.decode(Int.self, forKey: .daysUntilExpiry)
 613        chainDepth = try container.decode(Int.self, forKey: .chainDepth)
 614        tlsVersion = try container.decodeIfPresent(String.self, forKey: .tlsVersion)
 615        cipherSuite = try container.decodeIfPresent(String.self, forKey: .cipherSuite)
 616        chain = try container.decodeIfPresent([CertChainEntry].self, forKey: .chain) ?? []
 617    }
 618}
 619
 620// MARK: - HTTP Headers Models
 621
 622struct HTTPHeader: Identifiable, Codable {
 623    var id = UUID()
 624    let name: String
 625    let value: String
 626
 627    static let securityHeaders: Set<String> = [
 628        "strict-transport-security",
 629        "x-frame-options",
 630        "x-content-type-options",
 631        "content-security-policy",
 632        "referrer-policy"
 633    ]
 634
 635    var isSecurityHeader: Bool {
 636        Self.securityHeaders.contains(name.lowercased())
 637    }
 638}
 639
 640// MARK: - Reachability Models
 641
 642struct PortReachability: Identifiable, Codable {
 643    var id = UUID()
 644    let port: UInt16
 645    let reachable: Bool
 646    let latencyMs: Int?
 647}
 648
 649// MARK: - IP Geolocation Models
 650
 651struct IPGeolocation: Codable {
 652    let ip: String
 653    let city: String?
 654    let region: String?
 655    let country_name: String?
 656    let org: String?
 657    let latitude: Double?
 658    let longitude: Double?
 659}
 660
 661// MARK: - Ownership Models
 662
 663struct DomainOwnership: Codable, Equatable {
 664    let registrar: String?
 665    let createdDate: Date?
 666    let expirationDate: Date?
 667    let status: [String]
 668    let nameservers: [String]
 669    let abuseEmail: String?
 670
 671    init(
 672        registrar: String? = nil,
 673        createdDate: Date? = nil,
 674        expirationDate: Date? = nil,
 675        status: [String] = [],
 676        nameservers: [String] = [],
 677        abuseEmail: String? = nil
 678    ) {
 679        self.registrar = registrar
 680        self.createdDate = createdDate
 681        self.expirationDate = expirationDate
 682        self.status = status
 683        self.nameservers = nameservers
 684        self.abuseEmail = abuseEmail
 685    }
 686
 687    init(from decoder: Decoder) throws {
 688        let container = try decoder.container(keyedBy: CodingKeys.self)
 689        registrar = try container.decodeIfPresent(String.self, forKey: .registrar)
 690        createdDate = try container.decodeIfPresent(Date.self, forKey: .createdDate)
 691        expirationDate = try container.decodeIfPresent(Date.self, forKey: .expirationDate)
 692        status = try container.decodeIfPresent([String].self, forKey: .status) ?? []
 693        nameservers = try container.decodeIfPresent([String].self, forKey: .nameservers) ?? []
 694        abuseEmail = try container.decodeIfPresent(String.self, forKey: .abuseEmail)
 695    }
 696}
 697
 698struct DiscoveredSubdomain: Codable, Equatable, Hashable, Identifiable {
 699    var id: String { hostname }
 700    let hostname: String
 701}
 702
 703// MARK: - Email Security Models
 704
 705struct EmailSecurityResult: Codable {
 706    let spf: EmailSecurityRecord
 707    let dmarc: EmailSecurityRecord
 708    let dkim: EmailSecurityRecord
 709    let bimi: EmailSecurityRecord
 710    let mtaSts: MTASTSResult?
 711
 712    init(
 713        spf: EmailSecurityRecord,
 714        dmarc: EmailSecurityRecord,
 715        dkim: EmailSecurityRecord,
 716        bimi: EmailSecurityRecord = EmailSecurityRecord(found: false, value: nil),
 717        mtaSts: MTASTSResult? = nil
 718    ) {
 719        self.spf = spf
 720        self.dmarc = dmarc
 721        self.dkim = dkim
 722        self.bimi = bimi
 723        self.mtaSts = mtaSts
 724    }
 725
 726    init(from decoder: Decoder) throws {
 727        let container = try decoder.container(keyedBy: CodingKeys.self)
 728        spf = try container.decode(EmailSecurityRecord.self, forKey: .spf)
 729        dmarc = try container.decode(EmailSecurityRecord.self, forKey: .dmarc)
 730        dkim = try container.decode(EmailSecurityRecord.self, forKey: .dkim)
 731        bimi = try container.decodeIfPresent(EmailSecurityRecord.self, forKey: .bimi)
 732            ?? EmailSecurityRecord(found: false, value: nil)
 733        mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts)
 734    }
 735}
 736
 737struct EmailSecurityRecord: Codable {
 738    let found: Bool
 739    let value: String?
 740    let matchedSelector: String?
 741
 742    init(found: Bool, value: String?, matchedSelector: String? = nil) {
 743        self.found = found
 744        self.value = value
 745        self.matchedSelector = matchedSelector
 746    }
 747
 748    init(from decoder: Decoder) throws {
 749        let container = try decoder.container(keyedBy: CodingKeys.self)
 750        found = try container.decode(Bool.self, forKey: .found)
 751        value = try container.decodeIfPresent(String.self, forKey: .value)
 752        matchedSelector = try container.decodeIfPresent(String.self, forKey: .matchedSelector)
 753    }
 754}
 755
 756struct MTASTSResult: Codable {
 757    let txtFound: Bool
 758    let policyMode: String?
 759}
 760
 761// MARK: - Redirect Chain Models
 762
 763struct RedirectHop: Identifiable, Codable {
 764    var id = UUID()
 765    let stepNumber: Int
 766    let statusCode: Int
 767    let url: String
 768    let isFinal: Bool
 769}
 770
 771// MARK: - Port Scan Models
 772
 773enum PortScanKind: String, Codable {
 774    case standard
 775    case custom
 776}
 777
 778struct PortScanResult: Identifiable, Codable {
 779    var id = UUID()
 780    let port: UInt16
 781    let service: String
 782    let open: Bool
 783    var banner: String?
 784    let kind: PortScanKind
 785    let durationMs: Int?
 786
 787    nonisolated init(
 788        port: UInt16,
 789        service: String,
 790        open: Bool,
 791        banner: String? = nil,
 792        kind: PortScanKind = .standard,
 793        durationMs: Int? = nil
 794    ) {
 795        self.port = port
 796        self.service = service
 797        self.open = open
 798        self.banner = banner
 799        self.kind = kind
 800        self.durationMs = durationMs
 801    }
 802
 803    init(from decoder: Decoder) throws {
 804        let container = try decoder.container(keyedBy: CodingKeys.self)
 805        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
 806        port = try container.decode(UInt16.self, forKey: .port)
 807        service = try container.decode(String.self, forKey: .service)
 808        open = try container.decode(Bool.self, forKey: .open)
 809        banner = try container.decodeIfPresent(String.self, forKey: .banner)
 810        kind = try container.decodeIfPresent(PortScanKind.self, forKey: .kind) ?? .standard
 811        durationMs = try container.decodeIfPresent(Int.self, forKey: .durationMs)
 812    }
 813}
 814
 815// MARK: - History Models
 816
 817struct HistoryEntry: Identifiable, Codable {
 818    var id = UUID()
 819    let domain: String
 820    let timestamp: Date
 821    var trackedDomainID: UUID?
 822    var note: String?
 823    let dnsSections: [DNSSection]
 824    let sslInfo: SSLCertificateInfo?
 825    let httpHeaders: [HTTPHeader]
 826    let reachabilityResults: [PortReachability]
 827    let ipGeolocation: IPGeolocation?
 828    var emailSecurity: EmailSecurityResult?
 829    var mtaSts: MTASTSResult?
 830    var ownership: DomainOwnership?
 831    var ptrRecord: String?
 832    var redirectChain: [RedirectHop]
 833    var subdomains: [DiscoveredSubdomain]
 834    var portScanResults: [PortScanResult]
 835    var hstsPreloaded: Bool?
 836    var availabilityResult: DomainAvailabilityResult?
 837    var suggestions: [DomainSuggestionResult]
 838    var appVersion: String
 839    var resultSource: LookupResultSource
 840    var dataSources: [String]
 841    var provenanceBySection: [LookupSectionKind: SectionProvenance]
 842    var availabilityConfidence: ConfidenceLevel?
 843    var ownershipConfidence: ConfidenceLevel?
 844    var subdomainConfidence: ConfidenceLevel?
 845    var emailSecurityConfidence: ConfidenceLevel?
 846    var geolocationConfidence: ConfidenceLevel?
 847    var errorDetails: [LookupSectionKind: InspectionFailure]
 848    var isPartialSnapshot: Bool
 849    var validationIssues: [String]
 850    var resolverDisplayName: String
 851    var resolverURLString: String
 852    var totalLookupDurationMs: Int?
 853    var primaryIP: String?
 854    var finalRedirectURL: String?
 855    var tlsStatusSummary: String?
 856    var emailSecuritySummary: String?
 857    var httpGradeSummary: String?
 858    var changeSummary: DomainChangeSummary?
 859    var sslError: String?
 860    var httpHeadersError: String?
 861    var reachabilityError: String?
 862    var ipGeolocationError: String?
 863    var emailSecurityError: String?
 864    var ownershipError: String?
 865    var ptrError: String?
 866    var redirectChainError: String?
 867    var subdomainsError: String?
 868    var portScanError: String?
 869
 870    init(domain: String, timestamp: Date, trackedDomainID: UUID? = nil, note: String? = nil, dnsSections: [DNSSection],
 871         sslInfo: SSLCertificateInfo?, httpHeaders: [HTTPHeader],
 872         reachabilityResults: [PortReachability], ipGeolocation: IPGeolocation?,
 873         emailSecurity: EmailSecurityResult? = nil, mtaSts: MTASTSResult? = nil, ownership: DomainOwnership? = nil,
 874         ptrRecord: String? = nil, redirectChain: [RedirectHop] = [], subdomains: [DiscoveredSubdomain] = [],
 875         portScanResults: [PortScanResult] = [],
 876         hstsPreloaded: Bool? = nil, availabilityResult: DomainAvailabilityResult? = nil,
 877         suggestions: [DomainSuggestionResult] = [], appVersion: String = "2.7.0",
 878         resultSource: LookupResultSource = .snapshot, dataSources: [String] = [],
 879         provenanceBySection: [LookupSectionKind: SectionProvenance] = [:],
 880         availabilityConfidence: ConfidenceLevel? = nil, ownershipConfidence: ConfidenceLevel? = nil,
 881         subdomainConfidence: ConfidenceLevel? = nil, emailSecurityConfidence: ConfidenceLevel? = nil,
 882         geolocationConfidence: ConfidenceLevel? = nil,
 883         errorDetails: [LookupSectionKind: InspectionFailure] = [:], isPartialSnapshot: Bool = false,
 884         validationIssues: [String] = [], resolverDisplayName: String, resolverURLString: String,
 885         totalLookupDurationMs: Int? = nil, primaryIP: String? = nil, finalRedirectURL: String? = nil,
 886         tlsStatusSummary: String? = nil, emailSecuritySummary: String? = nil, httpGradeSummary: String? = nil,
 887         changeSummary: DomainChangeSummary? = nil, sslError: String? = nil, httpHeadersError: String? = nil,
 888         reachabilityError: String? = nil, ipGeolocationError: String? = nil,
 889         emailSecurityError: String? = nil, ownershipError: String? = nil, ptrError: String? = nil,
 890         redirectChainError: String? = nil, subdomainsError: String? = nil, portScanError: String? = nil) {
 891        self.domain = domain
 892        self.timestamp = timestamp
 893        self.trackedDomainID = trackedDomainID
 894        self.note = note
 895        self.dnsSections = dnsSections
 896        self.sslInfo = sslInfo
 897        self.httpHeaders = httpHeaders
 898        self.reachabilityResults = reachabilityResults
 899        self.ipGeolocation = ipGeolocation
 900        self.emailSecurity = emailSecurity
 901        self.mtaSts = mtaSts ?? emailSecurity?.mtaSts
 902        self.ownership = ownership
 903        self.ptrRecord = ptrRecord
 904        self.redirectChain = redirectChain
 905        self.subdomains = subdomains
 906        self.portScanResults = portScanResults
 907        self.hstsPreloaded = hstsPreloaded
 908        self.availabilityResult = availabilityResult
 909        self.suggestions = suggestions
 910        self.appVersion = appVersion
 911        self.resultSource = resultSource
 912        self.dataSources = dataSources
 913        self.provenanceBySection = provenanceBySection
 914        self.availabilityConfidence = availabilityConfidence
 915        self.ownershipConfidence = ownershipConfidence
 916        self.subdomainConfidence = subdomainConfidence
 917        self.emailSecurityConfidence = emailSecurityConfidence
 918        self.geolocationConfidence = geolocationConfidence
 919        self.errorDetails = errorDetails
 920        self.isPartialSnapshot = isPartialSnapshot
 921        self.validationIssues = validationIssues
 922        self.resolverDisplayName = resolverDisplayName
 923        self.resolverURLString = resolverURLString
 924        self.totalLookupDurationMs = totalLookupDurationMs
 925        self.primaryIP = primaryIP
 926        self.finalRedirectURL = finalRedirectURL
 927        self.tlsStatusSummary = tlsStatusSummary
 928        self.emailSecuritySummary = emailSecuritySummary
 929        self.httpGradeSummary = httpGradeSummary
 930        self.changeSummary = changeSummary
 931        self.sslError = sslError
 932        self.httpHeadersError = httpHeadersError
 933        self.reachabilityError = reachabilityError
 934        self.ipGeolocationError = ipGeolocationError
 935        self.emailSecurityError = emailSecurityError
 936        self.ownershipError = ownershipError
 937        self.ptrError = ptrError
 938        self.redirectChainError = redirectChainError
 939        self.subdomainsError = subdomainsError
 940        self.portScanError = portScanError
 941    }
 942
 943    init(from decoder: Decoder) throws {
 944        let container = try decoder.container(keyedBy: CodingKeys.self)
 945        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
 946        domain = try container.decodeIfPresent(String.self, forKey: .domain) ?? "unknown-domain"
 947        timestamp = try container.decodeIfPresent(Date.self, forKey: .timestamp) ?? .distantPast
 948        trackedDomainID = try container.decodeIfPresent(UUID.self, forKey: .trackedDomainID)
 949        note = try container.decodeIfPresent(String.self, forKey: .note)
 950        dnsSections = try container.decodeIfPresent([DNSSection].self, forKey: .dnsSections) ?? []
 951        sslInfo = try container.decodeIfPresent(SSLCertificateInfo.self, forKey: .sslInfo)
 952        httpHeaders = try container.decodeIfPresent([HTTPHeader].self, forKey: .httpHeaders) ?? []
 953        reachabilityResults = try container.decodeIfPresent([PortReachability].self, forKey: .reachabilityResults) ?? []
 954        ipGeolocation = try container.decodeIfPresent(IPGeolocation.self, forKey: .ipGeolocation)
 955        emailSecurity = try container.decodeIfPresent(EmailSecurityResult.self, forKey: .emailSecurity)
 956        mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts) ?? emailSecurity?.mtaSts
 957        ownership = try container.decodeIfPresent(DomainOwnership.self, forKey: .ownership)
 958        ptrRecord = try container.decodeIfPresent(String.self, forKey: .ptrRecord)
 959        redirectChain = try container.decodeIfPresent([RedirectHop].self, forKey: .redirectChain) ?? []
 960        subdomains = try container.decodeIfPresent([DiscoveredSubdomain].self, forKey: .subdomains) ?? []
 961        portScanResults = try container.decodeIfPresent([PortScanResult].self, forKey: .portScanResults) ?? []
 962        hstsPreloaded = try container.decodeIfPresent(Bool.self, forKey: .hstsPreloaded)
 963        availabilityResult = try container.decodeIfPresent(DomainAvailabilityResult.self, forKey: .availabilityResult)
 964        suggestions = try container.decodeIfPresent([DomainSuggestionResult].self, forKey: .suggestions) ?? []
 965        appVersion = try container.decodeIfPresent(String.self, forKey: .appVersion) ?? "2.6.0"
 966        resultSource = try container.decodeIfPresent(LookupResultSource.self, forKey: .resultSource) ?? .snapshot
 967        dataSources = try container.decodeIfPresent([String].self, forKey: .dataSources) ?? []
 968        provenanceBySection = try container.decodeIfPresent([LookupSectionKind: SectionProvenance].self, forKey: .provenanceBySection) ?? [:]
 969        availabilityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .availabilityConfidence)
 970        ownershipConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .ownershipConfidence)
 971        subdomainConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .subdomainConfidence)
 972        emailSecurityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .emailSecurityConfidence)
 973        geolocationConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .geolocationConfidence)
 974        errorDetails = try container.decodeIfPresent([LookupSectionKind: InspectionFailure].self, forKey: .errorDetails) ?? [:]
 975        validationIssues = try container.decodeIfPresent([String].self, forKey: .validationIssues) ?? HistoryEntry.defaultValidationIssues(domain: domain, timestamp: timestamp)
 976        isPartialSnapshot = try container.decodeIfPresent(Bool.self, forKey: .isPartialSnapshot) ?? !validationIssues.isEmpty
 977        resolverDisplayName = try container.decodeIfPresent(String.self, forKey: .resolverDisplayName) ?? "Cloudflare"
 978        resolverURLString = try container.decodeIfPresent(String.self, forKey: .resolverURLString) ?? DNSResolverOption.defaultURLString
 979        totalLookupDurationMs = try container.decodeIfPresent(Int.self, forKey: .totalLookupDurationMs)
 980        primaryIP = try container.decodeIfPresent(String.self, forKey: .primaryIP)
 981        finalRedirectURL = try container.decodeIfPresent(String.self, forKey: .finalRedirectURL)
 982        tlsStatusSummary = try container.decodeIfPresent(String.self, forKey: .tlsStatusSummary)
 983        emailSecuritySummary = try container.decodeIfPresent(String.self, forKey: .emailSecuritySummary)
 984        httpGradeSummary = try container.decodeIfPresent(String.self, forKey: .httpGradeSummary)
 985        changeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .changeSummary)
 986        sslError = try container.decodeIfPresent(String.self, forKey: .sslError)
 987        httpHeadersError = try container.decodeIfPresent(String.self, forKey: .httpHeadersError)
 988        reachabilityError = try container.decodeIfPresent(String.self, forKey: .reachabilityError)
 989        ipGeolocationError = try container.decodeIfPresent(String.self, forKey: .ipGeolocationError)
 990        emailSecurityError = try container.decodeIfPresent(String.self, forKey: .emailSecurityError)
 991        ownershipError = try container.decodeIfPresent(String.self, forKey: .ownershipError)
 992        ptrError = try container.decodeIfPresent(String.self, forKey: .ptrError)
 993        redirectChainError = try container.decodeIfPresent(String.self, forKey: .redirectChainError)
 994        subdomainsError = try container.decodeIfPresent(String.self, forKey: .subdomainsError)
 995        portScanError = try container.decodeIfPresent(String.self, forKey: .portScanError)
 996    }
 997
 998    private static func defaultValidationIssues(domain: String, timestamp: Date) -> [String] {
 999        var issues: [String] = []
1000        if domain == "unknown-domain" {
1001            issues.append("Missing domain in stored snapshot")
1002        }
1003        if timestamp == .distantPast {
1004            issues.append("Missing collection timestamp in stored snapshot")
1005        }
1006        return issues
1007    }
1008}
1009
1010// MARK: - Cloudflare DNS-over-HTTPS Response
1011
1012struct CloudflareDNSResponse: Decodable {
1013    let Status: Int
1014    let AD: Bool?
1015    let Answer: [CloudflareDNSAnswer]?
1016
1017    struct CloudflareDNSAnswer: Decodable {
1018        let name: String
1019        let type: Int
1020        let TTL: Int
1021        let data: String
1022    }
1023}