DomainDig/Models.swift
978 lines · 33859 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}
227
228enum BatchLookupStatus: String, Codable {
229 case pending
230 case running
231 case completed
232 case failed
233}
234
235struct BatchLookupResult: Identifiable, Codable, Equatable {
236 let id: UUID
237 let domain: String
238 let historyEntryID: UUID?
239 let resultSource: LookupResultSource
240 let availability: DomainAvailabilityStatus?
241 let primaryIP: String?
242 let quickStatus: String
243 let summaryMessage: String?
244 let changeSeverity: ChangeSeverity?
245 let certificateWarningLevel: CertificateWarningLevel
246 let timestamp: Date
247 let status: BatchLookupStatus
248 let errorMessage: String?
249
250 init(
251 id: UUID = UUID(),
252 domain: String,
253 historyEntryID: UUID?,
254 resultSource: LookupResultSource = .live,
255 availability: DomainAvailabilityStatus?,
256 primaryIP: String?,
257 quickStatus: String,
258 summaryMessage: String? = nil,
259 changeSeverity: ChangeSeverity? = nil,
260 certificateWarningLevel: CertificateWarningLevel = .none,
261 timestamp: Date,
262 status: BatchLookupStatus,
263 errorMessage: String? = nil
264 ) {
265 self.id = id
266 self.domain = domain
267 self.historyEntryID = historyEntryID
268 self.resultSource = resultSource
269 self.availability = availability
270 self.primaryIP = primaryIP
271 self.quickStatus = quickStatus
272 self.summaryMessage = summaryMessage
273 self.changeSeverity = changeSeverity
274 self.certificateWarningLevel = certificateWarningLevel
275 self.timestamp = timestamp
276 self.status = status
277 self.errorMessage = errorMessage
278 }
279}
280
281struct BatchSweepSummary: Identifiable, Equatable {
282 let id = UUID()
283 let source: BatchLookupSource
284 let totalDomains: Int
285 let changedDomains: Int
286 let unchangedDomains: Int
287 let warningDomains: Int
288 let results: [BatchLookupResult]
289 let generatedAt: Date
290}
291
292enum DataCapability: String, Codable {
293 case ownershipHistory
294 case dnsHistory
295 case extendedSubdomains
296 case domainPricing
297}
298
299enum HistoryDateFilter: String, CaseIterable, Identifiable {
300 case today
301 case last7Days
302 case all
303
304 var id: String { rawValue }
305
306 var title: String {
307 switch self {
308 case .today:
309 return "Today"
310 case .last7Days:
311 return "Last 7 Days"
312 case .all:
313 return "All"
314 }
315 }
316}
317
318enum ChangeFilterOption: String, CaseIterable, Identifiable {
319 case all
320 case changed
321 case unchanged
322
323 var id: String { rawValue }
324
325 var title: String {
326 switch self {
327 case .all:
328 return "All"
329 case .changed:
330 return "Changed"
331 case .unchanged:
332 return "Unchanged"
333 }
334 }
335}
336
337enum HistorySortOption: String, CaseIterable, Identifiable {
338 case newest
339 case oldest
340 case domain
341
342 var id: String { rawValue }
343
344 var title: String {
345 switch self {
346 case .newest:
347 return "Newest"
348 case .oldest:
349 return "Oldest"
350 case .domain:
351 return "Domain A-Z"
352 }
353 }
354}
355
356enum WatchlistFilterOption: String, CaseIterable, Identifiable {
357 case all
358 case pinnedOnly
359 case changedOnly
360
361 var id: String { rawValue }
362
363 var title: String {
364 switch self {
365 case .all:
366 return "All"
367 case .pinnedOnly:
368 return "Pinned Only"
369 case .changedOnly:
370 return "Changed Only"
371 }
372 }
373}
374
375enum WatchlistSortOption: String, CaseIterable, Identifiable {
376 case pinned
377 case recentlyUpdated
378 case alphabetical
379
380 var id: String { rawValue }
381
382 var title: String {
383 switch self {
384 case .pinned:
385 return "Pinned"
386 case .recentlyUpdated:
387 return "Recently Updated"
388 case .alphabetical:
389 return "Alphabetical"
390 }
391 }
392}
393
394enum PremiumCapability: String, Codable {
395 case unlimitedTrackedDomains
396 case automatedMonitoring
397 case pushAlerts
398 case batchTracking
399 case advancedExports
400}
401
402struct TrackedDomain: Codable, Identifiable, Equatable {
403 let id: UUID
404 var domain: String
405 var createdAt: Date
406 var updatedAt: Date
407 var note: String?
408 var isPinned: Bool
409 var lastKnownAvailability: DomainAvailabilityStatus?
410 var lastSnapshotID: UUID?
411 var lastChangeSummary: DomainChangeSummary?
412 var lastChangeSeverity: ChangeSeverity?
413 var certificateWarningLevel: CertificateWarningLevel
414 var certificateDaysRemaining: Int?
415
416 init(
417 id: UUID = UUID(),
418 domain: String,
419 createdAt: Date = Date(),
420 updatedAt: Date = Date(),
421 note: String? = nil,
422 isPinned: Bool = false,
423 lastKnownAvailability: DomainAvailabilityStatus? = nil,
424 lastSnapshotID: UUID? = nil,
425 lastChangeSummary: DomainChangeSummary? = nil,
426 lastChangeSeverity: ChangeSeverity? = nil,
427 certificateWarningLevel: CertificateWarningLevel = .none,
428 certificateDaysRemaining: Int? = nil
429 ) {
430 self.id = id
431 self.domain = domain
432 self.createdAt = createdAt
433 self.updatedAt = updatedAt
434 self.note = note
435 self.isPinned = isPinned
436 self.lastKnownAvailability = lastKnownAvailability
437 self.lastSnapshotID = lastSnapshotID
438 self.lastChangeSummary = lastChangeSummary
439 self.lastChangeSeverity = lastChangeSeverity
440 self.certificateWarningLevel = certificateWarningLevel
441 self.certificateDaysRemaining = certificateDaysRemaining
442 }
443
444 init(from decoder: Decoder) throws {
445 let container = try decoder.container(keyedBy: CodingKeys.self)
446 id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
447 domain = try container.decode(String.self, forKey: .domain)
448 createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
449 updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt) ?? createdAt
450 note = try container.decodeIfPresent(String.self, forKey: .note)
451 isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) ?? false
452 lastKnownAvailability = try container.decodeIfPresent(DomainAvailabilityStatus.self, forKey: .lastKnownAvailability)
453 lastSnapshotID = try container.decodeIfPresent(UUID.self, forKey: .lastSnapshotID)
454 lastChangeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .lastChangeSummary)
455 lastChangeSeverity = try container.decodeIfPresent(ChangeSeverity.self, forKey: .lastChangeSeverity) ?? lastChangeSummary?.severity
456 certificateWarningLevel = try container.decodeIfPresent(CertificateWarningLevel.self, forKey: .certificateWarningLevel) ?? .none
457 certificateDaysRemaining = try container.decodeIfPresent(Int.self, forKey: .certificateDaysRemaining)
458 }
459}
460
461// MARK: - DNS Models
462
463enum DNSRecordType: String, CaseIterable, Codable {
464 case A
465 case AAAA
466 case MX
467 case NS
468 case TXT
469 case CNAME
470 case SOA
471 case SRV
472 case CAA
473 case DS
474 case PTR
475
476 var queryType: Int {
477 switch self {
478 case .A: return 1
479 case .AAAA: return 28
480 case .MX: return 15
481 case .NS: return 2
482 case .TXT: return 16
483 case .CNAME: return 5
484 case .SOA: return 6
485 case .SRV: return 33
486 case .CAA: return 257
487 case .DS: return 43
488 case .PTR: return 12
489 }
490 }
491
492 var usesRawDataValue: Bool {
493 switch self {
494 case .TXT, .SOA, .DS:
495 return true
496 default:
497 return false
498 }
499 }
500}
501
502struct DNSRecord: Identifiable, Codable {
503 var id = UUID()
504 let value: String
505 let ttl: Int
506}
507
508struct DNSSection: Identifiable, Codable {
509 var id = UUID()
510 let recordType: DNSRecordType
511 var records: [DNSRecord]
512 var wildcardRecords: [DNSRecord] = []
513 var dnssecSigned: Bool?
514 var error: String?
515}
516
517// MARK: - SSL Models
518
519struct SSLCertificateInfo: Codable {
520 struct CertChainEntry: Codable {
521 let subject: String
522 let issuer: String
523 }
524
525 let commonName: String
526 let subjectAltNames: [String]
527 let issuer: String
528 let validFrom: Date
529 let validUntil: Date
530 let daysUntilExpiry: Int
531 let chainDepth: Int
532 let tlsVersion: String?
533 let cipherSuite: String?
534 let chain: [CertChainEntry]
535
536 init(
537 commonName: String,
538 subjectAltNames: [String],
539 issuer: String,
540 validFrom: Date,
541 validUntil: Date,
542 daysUntilExpiry: Int,
543 chainDepth: Int,
544 tlsVersion: String? = nil,
545 cipherSuite: String? = nil,
546 chain: [CertChainEntry] = []
547 ) {
548 self.commonName = commonName
549 self.subjectAltNames = subjectAltNames
550 self.issuer = issuer
551 self.validFrom = validFrom
552 self.validUntil = validUntil
553 self.daysUntilExpiry = daysUntilExpiry
554 self.chainDepth = chainDepth
555 self.tlsVersion = tlsVersion
556 self.cipherSuite = cipherSuite
557 self.chain = chain
558 }
559
560 init(from decoder: Decoder) throws {
561 let container = try decoder.container(keyedBy: CodingKeys.self)
562 commonName = try container.decode(String.self, forKey: .commonName)
563 subjectAltNames = try container.decode([String].self, forKey: .subjectAltNames)
564 issuer = try container.decode(String.self, forKey: .issuer)
565 validFrom = try container.decode(Date.self, forKey: .validFrom)
566 validUntil = try container.decode(Date.self, forKey: .validUntil)
567 daysUntilExpiry = try container.decode(Int.self, forKey: .daysUntilExpiry)
568 chainDepth = try container.decode(Int.self, forKey: .chainDepth)
569 tlsVersion = try container.decodeIfPresent(String.self, forKey: .tlsVersion)
570 cipherSuite = try container.decodeIfPresent(String.self, forKey: .cipherSuite)
571 chain = try container.decodeIfPresent([CertChainEntry].self, forKey: .chain) ?? []
572 }
573}
574
575// MARK: - HTTP Headers Models
576
577struct HTTPHeader: Identifiable, Codable {
578 var id = UUID()
579 let name: String
580 let value: String
581
582 static let securityHeaders: Set<String> = [
583 "strict-transport-security",
584 "x-frame-options",
585 "x-content-type-options",
586 "content-security-policy",
587 "referrer-policy"
588 ]
589
590 var isSecurityHeader: Bool {
591 Self.securityHeaders.contains(name.lowercased())
592 }
593}
594
595// MARK: - Reachability Models
596
597struct PortReachability: Identifiable, Codable {
598 var id = UUID()
599 let port: UInt16
600 let reachable: Bool
601 let latencyMs: Int?
602}
603
604// MARK: - IP Geolocation Models
605
606struct IPGeolocation: Codable {
607 let ip: String
608 let city: String?
609 let region: String?
610 let country_name: String?
611 let org: String?
612 let latitude: Double?
613 let longitude: Double?
614}
615
616// MARK: - Ownership Models
617
618struct DomainOwnership: Codable, Equatable {
619 let registrar: String?
620 let createdDate: Date?
621 let expirationDate: Date?
622 let status: [String]
623 let nameservers: [String]
624 let abuseEmail: String?
625
626 init(
627 registrar: String? = nil,
628 createdDate: Date? = nil,
629 expirationDate: Date? = nil,
630 status: [String] = [],
631 nameservers: [String] = [],
632 abuseEmail: String? = nil
633 ) {
634 self.registrar = registrar
635 self.createdDate = createdDate
636 self.expirationDate = expirationDate
637 self.status = status
638 self.nameservers = nameservers
639 self.abuseEmail = abuseEmail
640 }
641
642 init(from decoder: Decoder) throws {
643 let container = try decoder.container(keyedBy: CodingKeys.self)
644 registrar = try container.decodeIfPresent(String.self, forKey: .registrar)
645 createdDate = try container.decodeIfPresent(Date.self, forKey: .createdDate)
646 expirationDate = try container.decodeIfPresent(Date.self, forKey: .expirationDate)
647 status = try container.decodeIfPresent([String].self, forKey: .status) ?? []
648 nameservers = try container.decodeIfPresent([String].self, forKey: .nameservers) ?? []
649 abuseEmail = try container.decodeIfPresent(String.self, forKey: .abuseEmail)
650 }
651}
652
653struct DiscoveredSubdomain: Codable, Equatable, Hashable, Identifiable {
654 var id: String { hostname }
655 let hostname: String
656}
657
658// MARK: - Email Security Models
659
660struct EmailSecurityResult: Codable {
661 let spf: EmailSecurityRecord
662 let dmarc: EmailSecurityRecord
663 let dkim: EmailSecurityRecord
664 let bimi: EmailSecurityRecord
665 let mtaSts: MTASTSResult?
666
667 init(
668 spf: EmailSecurityRecord,
669 dmarc: EmailSecurityRecord,
670 dkim: EmailSecurityRecord,
671 bimi: EmailSecurityRecord = EmailSecurityRecord(found: false, value: nil),
672 mtaSts: MTASTSResult? = nil
673 ) {
674 self.spf = spf
675 self.dmarc = dmarc
676 self.dkim = dkim
677 self.bimi = bimi
678 self.mtaSts = mtaSts
679 }
680
681 init(from decoder: Decoder) throws {
682 let container = try decoder.container(keyedBy: CodingKeys.self)
683 spf = try container.decode(EmailSecurityRecord.self, forKey: .spf)
684 dmarc = try container.decode(EmailSecurityRecord.self, forKey: .dmarc)
685 dkim = try container.decode(EmailSecurityRecord.self, forKey: .dkim)
686 bimi = try container.decodeIfPresent(EmailSecurityRecord.self, forKey: .bimi)
687 ?? EmailSecurityRecord(found: false, value: nil)
688 mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts)
689 }
690}
691
692struct EmailSecurityRecord: Codable {
693 let found: Bool
694 let value: String?
695 let matchedSelector: String?
696
697 init(found: Bool, value: String?, matchedSelector: String? = nil) {
698 self.found = found
699 self.value = value
700 self.matchedSelector = matchedSelector
701 }
702
703 init(from decoder: Decoder) throws {
704 let container = try decoder.container(keyedBy: CodingKeys.self)
705 found = try container.decode(Bool.self, forKey: .found)
706 value = try container.decodeIfPresent(String.self, forKey: .value)
707 matchedSelector = try container.decodeIfPresent(String.self, forKey: .matchedSelector)
708 }
709}
710
711struct MTASTSResult: Codable {
712 let txtFound: Bool
713 let policyMode: String?
714}
715
716// MARK: - Redirect Chain Models
717
718struct RedirectHop: Identifiable, Codable {
719 var id = UUID()
720 let stepNumber: Int
721 let statusCode: Int
722 let url: String
723 let isFinal: Bool
724}
725
726// MARK: - Port Scan Models
727
728enum PortScanKind: String, Codable {
729 case standard
730 case custom
731}
732
733struct PortScanResult: Identifiable, Codable {
734 var id = UUID()
735 let port: UInt16
736 let service: String
737 let open: Bool
738 var banner: String?
739 let kind: PortScanKind
740 let durationMs: Int?
741
742 nonisolated init(
743 port: UInt16,
744 service: String,
745 open: Bool,
746 banner: String? = nil,
747 kind: PortScanKind = .standard,
748 durationMs: Int? = nil
749 ) {
750 self.port = port
751 self.service = service
752 self.open = open
753 self.banner = banner
754 self.kind = kind
755 self.durationMs = durationMs
756 }
757
758 init(from decoder: Decoder) throws {
759 let container = try decoder.container(keyedBy: CodingKeys.self)
760 id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
761 port = try container.decode(UInt16.self, forKey: .port)
762 service = try container.decode(String.self, forKey: .service)
763 open = try container.decode(Bool.self, forKey: .open)
764 banner = try container.decodeIfPresent(String.self, forKey: .banner)
765 kind = try container.decodeIfPresent(PortScanKind.self, forKey: .kind) ?? .standard
766 durationMs = try container.decodeIfPresent(Int.self, forKey: .durationMs)
767 }
768}
769
770// MARK: - History Models
771
772struct HistoryEntry: Identifiable, Codable {
773 var id = UUID()
774 let domain: String
775 let timestamp: Date
776 var trackedDomainID: UUID?
777 var note: String?
778 let dnsSections: [DNSSection]
779 let sslInfo: SSLCertificateInfo?
780 let httpHeaders: [HTTPHeader]
781 let reachabilityResults: [PortReachability]
782 let ipGeolocation: IPGeolocation?
783 var emailSecurity: EmailSecurityResult?
784 var mtaSts: MTASTSResult?
785 var ownership: DomainOwnership?
786 var ptrRecord: String?
787 var redirectChain: [RedirectHop]
788 var subdomains: [DiscoveredSubdomain]
789 var portScanResults: [PortScanResult]
790 var hstsPreloaded: Bool?
791 var availabilityResult: DomainAvailabilityResult?
792 var suggestions: [DomainSuggestionResult]
793 var appVersion: String
794 var resultSource: LookupResultSource
795 var dataSources: [String]
796 var provenanceBySection: [LookupSectionKind: SectionProvenance]
797 var availabilityConfidence: ConfidenceLevel?
798 var ownershipConfidence: ConfidenceLevel?
799 var subdomainConfidence: ConfidenceLevel?
800 var emailSecurityConfidence: ConfidenceLevel?
801 var geolocationConfidence: ConfidenceLevel?
802 var errorDetails: [LookupSectionKind: InspectionFailure]
803 var isPartialSnapshot: Bool
804 var validationIssues: [String]
805 var resolverDisplayName: String
806 var resolverURLString: String
807 var totalLookupDurationMs: Int?
808 var primaryIP: String?
809 var finalRedirectURL: String?
810 var tlsStatusSummary: String?
811 var emailSecuritySummary: String?
812 var httpGradeSummary: String?
813 var changeSummary: DomainChangeSummary?
814 var sslError: String?
815 var httpHeadersError: String?
816 var reachabilityError: String?
817 var ipGeolocationError: String?
818 var emailSecurityError: String?
819 var ownershipError: String?
820 var ptrError: String?
821 var redirectChainError: String?
822 var subdomainsError: String?
823 var portScanError: String?
824
825 init(domain: String, timestamp: Date, trackedDomainID: UUID? = nil, note: String? = nil, dnsSections: [DNSSection],
826 sslInfo: SSLCertificateInfo?, httpHeaders: [HTTPHeader],
827 reachabilityResults: [PortReachability], ipGeolocation: IPGeolocation?,
828 emailSecurity: EmailSecurityResult? = nil, mtaSts: MTASTSResult? = nil, ownership: DomainOwnership? = nil,
829 ptrRecord: String? = nil, redirectChain: [RedirectHop] = [], subdomains: [DiscoveredSubdomain] = [],
830 portScanResults: [PortScanResult] = [],
831 hstsPreloaded: Bool? = nil, availabilityResult: DomainAvailabilityResult? = nil,
832 suggestions: [DomainSuggestionResult] = [], appVersion: String = "2.7.0",
833 resultSource: LookupResultSource = .snapshot, dataSources: [String] = [],
834 provenanceBySection: [LookupSectionKind: SectionProvenance] = [:],
835 availabilityConfidence: ConfidenceLevel? = nil, ownershipConfidence: ConfidenceLevel? = nil,
836 subdomainConfidence: ConfidenceLevel? = nil, emailSecurityConfidence: ConfidenceLevel? = nil,
837 geolocationConfidence: ConfidenceLevel? = nil,
838 errorDetails: [LookupSectionKind: InspectionFailure] = [:], isPartialSnapshot: Bool = false,
839 validationIssues: [String] = [], resolverDisplayName: String, resolverURLString: String,
840 totalLookupDurationMs: Int? = nil, primaryIP: String? = nil, finalRedirectURL: String? = nil,
841 tlsStatusSummary: String? = nil, emailSecuritySummary: String? = nil, httpGradeSummary: String? = nil,
842 changeSummary: DomainChangeSummary? = nil, sslError: String? = nil, httpHeadersError: String? = nil,
843 reachabilityError: String? = nil, ipGeolocationError: String? = nil,
844 emailSecurityError: String? = nil, ownershipError: String? = nil, ptrError: String? = nil,
845 redirectChainError: String? = nil, subdomainsError: String? = nil, portScanError: String? = nil) {
846 self.domain = domain
847 self.timestamp = timestamp
848 self.trackedDomainID = trackedDomainID
849 self.note = note
850 self.dnsSections = dnsSections
851 self.sslInfo = sslInfo
852 self.httpHeaders = httpHeaders
853 self.reachabilityResults = reachabilityResults
854 self.ipGeolocation = ipGeolocation
855 self.emailSecurity = emailSecurity
856 self.mtaSts = mtaSts ?? emailSecurity?.mtaSts
857 self.ownership = ownership
858 self.ptrRecord = ptrRecord
859 self.redirectChain = redirectChain
860 self.subdomains = subdomains
861 self.portScanResults = portScanResults
862 self.hstsPreloaded = hstsPreloaded
863 self.availabilityResult = availabilityResult
864 self.suggestions = suggestions
865 self.appVersion = appVersion
866 self.resultSource = resultSource
867 self.dataSources = dataSources
868 self.provenanceBySection = provenanceBySection
869 self.availabilityConfidence = availabilityConfidence
870 self.ownershipConfidence = ownershipConfidence
871 self.subdomainConfidence = subdomainConfidence
872 self.emailSecurityConfidence = emailSecurityConfidence
873 self.geolocationConfidence = geolocationConfidence
874 self.errorDetails = errorDetails
875 self.isPartialSnapshot = isPartialSnapshot
876 self.validationIssues = validationIssues
877 self.resolverDisplayName = resolverDisplayName
878 self.resolverURLString = resolverURLString
879 self.totalLookupDurationMs = totalLookupDurationMs
880 self.primaryIP = primaryIP
881 self.finalRedirectURL = finalRedirectURL
882 self.tlsStatusSummary = tlsStatusSummary
883 self.emailSecuritySummary = emailSecuritySummary
884 self.httpGradeSummary = httpGradeSummary
885 self.changeSummary = changeSummary
886 self.sslError = sslError
887 self.httpHeadersError = httpHeadersError
888 self.reachabilityError = reachabilityError
889 self.ipGeolocationError = ipGeolocationError
890 self.emailSecurityError = emailSecurityError
891 self.ownershipError = ownershipError
892 self.ptrError = ptrError
893 self.redirectChainError = redirectChainError
894 self.subdomainsError = subdomainsError
895 self.portScanError = portScanError
896 }
897
898 init(from decoder: Decoder) throws {
899 let container = try decoder.container(keyedBy: CodingKeys.self)
900 id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
901 domain = try container.decodeIfPresent(String.self, forKey: .domain) ?? "unknown-domain"
902 timestamp = try container.decodeIfPresent(Date.self, forKey: .timestamp) ?? .distantPast
903 trackedDomainID = try container.decodeIfPresent(UUID.self, forKey: .trackedDomainID)
904 note = try container.decodeIfPresent(String.self, forKey: .note)
905 dnsSections = try container.decodeIfPresent([DNSSection].self, forKey: .dnsSections) ?? []
906 sslInfo = try container.decodeIfPresent(SSLCertificateInfo.self, forKey: .sslInfo)
907 httpHeaders = try container.decodeIfPresent([HTTPHeader].self, forKey: .httpHeaders) ?? []
908 reachabilityResults = try container.decodeIfPresent([PortReachability].self, forKey: .reachabilityResults) ?? []
909 ipGeolocation = try container.decodeIfPresent(IPGeolocation.self, forKey: .ipGeolocation)
910 emailSecurity = try container.decodeIfPresent(EmailSecurityResult.self, forKey: .emailSecurity)
911 mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts) ?? emailSecurity?.mtaSts
912 ownership = try container.decodeIfPresent(DomainOwnership.self, forKey: .ownership)
913 ptrRecord = try container.decodeIfPresent(String.self, forKey: .ptrRecord)
914 redirectChain = try container.decodeIfPresent([RedirectHop].self, forKey: .redirectChain) ?? []
915 subdomains = try container.decodeIfPresent([DiscoveredSubdomain].self, forKey: .subdomains) ?? []
916 portScanResults = try container.decodeIfPresent([PortScanResult].self, forKey: .portScanResults) ?? []
917 hstsPreloaded = try container.decodeIfPresent(Bool.self, forKey: .hstsPreloaded)
918 availabilityResult = try container.decodeIfPresent(DomainAvailabilityResult.self, forKey: .availabilityResult)
919 suggestions = try container.decodeIfPresent([DomainSuggestionResult].self, forKey: .suggestions) ?? []
920 appVersion = try container.decodeIfPresent(String.self, forKey: .appVersion) ?? "2.6.0"
921 resultSource = try container.decodeIfPresent(LookupResultSource.self, forKey: .resultSource) ?? .snapshot
922 dataSources = try container.decodeIfPresent([String].self, forKey: .dataSources) ?? []
923 provenanceBySection = try container.decodeIfPresent([LookupSectionKind: SectionProvenance].self, forKey: .provenanceBySection) ?? [:]
924 availabilityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .availabilityConfidence)
925 ownershipConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .ownershipConfidence)
926 subdomainConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .subdomainConfidence)
927 emailSecurityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .emailSecurityConfidence)
928 geolocationConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .geolocationConfidence)
929 errorDetails = try container.decodeIfPresent([LookupSectionKind: InspectionFailure].self, forKey: .errorDetails) ?? [:]
930 validationIssues = try container.decodeIfPresent([String].self, forKey: .validationIssues) ?? HistoryEntry.defaultValidationIssues(domain: domain, timestamp: timestamp)
931 isPartialSnapshot = try container.decodeIfPresent(Bool.self, forKey: .isPartialSnapshot) ?? !validationIssues.isEmpty
932 resolverDisplayName = try container.decodeIfPresent(String.self, forKey: .resolverDisplayName) ?? "Cloudflare"
933 resolverURLString = try container.decodeIfPresent(String.self, forKey: .resolverURLString) ?? DNSResolverOption.defaultURLString
934 totalLookupDurationMs = try container.decodeIfPresent(Int.self, forKey: .totalLookupDurationMs)
935 primaryIP = try container.decodeIfPresent(String.self, forKey: .primaryIP)
936 finalRedirectURL = try container.decodeIfPresent(String.self, forKey: .finalRedirectURL)
937 tlsStatusSummary = try container.decodeIfPresent(String.self, forKey: .tlsStatusSummary)
938 emailSecuritySummary = try container.decodeIfPresent(String.self, forKey: .emailSecuritySummary)
939 httpGradeSummary = try container.decodeIfPresent(String.self, forKey: .httpGradeSummary)
940 changeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .changeSummary)
941 sslError = try container.decodeIfPresent(String.self, forKey: .sslError)
942 httpHeadersError = try container.decodeIfPresent(String.self, forKey: .httpHeadersError)
943 reachabilityError = try container.decodeIfPresent(String.self, forKey: .reachabilityError)
944 ipGeolocationError = try container.decodeIfPresent(String.self, forKey: .ipGeolocationError)
945 emailSecurityError = try container.decodeIfPresent(String.self, forKey: .emailSecurityError)
946 ownershipError = try container.decodeIfPresent(String.self, forKey: .ownershipError)
947 ptrError = try container.decodeIfPresent(String.self, forKey: .ptrError)
948 redirectChainError = try container.decodeIfPresent(String.self, forKey: .redirectChainError)
949 subdomainsError = try container.decodeIfPresent(String.self, forKey: .subdomainsError)
950 portScanError = try container.decodeIfPresent(String.self, forKey: .portScanError)
951 }
952
953 private static func defaultValidationIssues(domain: String, timestamp: Date) -> [String] {
954 var issues: [String] = []
955 if domain == "unknown-domain" {
956 issues.append("Missing domain in stored snapshot")
957 }
958 if timestamp == .distantPast {
959 issues.append("Missing collection timestamp in stored snapshot")
960 }
961 return issues
962 }
963}
964
965// MARK: - Cloudflare DNS-over-HTTPS Response
966
967struct CloudflareDNSResponse: Decodable {
968 let Status: Int
969 let AD: Bool?
970 let Answer: [CloudflareDNSAnswer]?
971
972 struct CloudflareDNSAnswer: Decodable {
973 let name: String
974 let type: Int
975 let TTL: Int
976 let data: String
977 }
978}