DomainDig/IntegrationService.swift

1095 lines · 42088 bytes

   1import Foundation
   2import Network
   3import os
   4import Observation
   5import Security
   6
   7@MainActor
   8@Observable
   9final class IntegrationService {
  10    static let shared = IntegrationService()
  11
  12    var targets: [IntegrationTarget]
  13    var deliveryRecords: [DeliveryRecord]
  14    var queue: [QueuedDelivery]
  15    var statusMessage: String?
  16
  17    private let defaults: UserDefaults
  18    private var processingTask: Task<Void, Never>?
  19
  20    private init(defaults: UserDefaults = .standard) {
  21        self.defaults = defaults
  22        self.targets = Self.loadTargets(defaults: defaults)
  23        self.deliveryRecords = Self.loadRecords(defaults: defaults)
  24        self.queue = Self.loadQueue(defaults: defaults)
  25    }
  26
  27    func refresh() {
  28        targets = Self.loadTargets(defaults: defaults)
  29        deliveryRecords = Self.loadRecords(defaults: defaults)
  30        queue = Self.loadQueue(defaults: defaults)
  31    }
  32
  33    func upsert(
  34        target: IntegrationTarget,
  35        webhookURL: String? = nil,
  36        slackWebhookURL: String? = nil,
  37        emailPassword: String? = nil,
  38        s3SecretAccessKey: String? = nil
  39    ) throws {
  40        var updatedTarget = target
  41
  42        switch updatedTarget.configuration {
  43        case .webhook(var configuration):
  44            if let webhookURL {
  45                try Self.validateHTTPS(webhookURL)
  46                let reference = configuration.credentialReference ?? Self.secretReference(for: updatedTarget.id, suffix: "webhook")
  47                try IntegrationSecretStore.save(secret: webhookURL, reference: reference)
  48                configuration.credentialReference = reference
  49                configuration.endpointDisplayHost = Self.hostLabel(from: webhookURL)
  50                updatedTarget.configuration = .webhook(configuration)
  51            }
  52        case .slack(var configuration):
  53            if let slackWebhookURL {
  54                try Self.validateHTTPS(slackWebhookURL)
  55                let reference = configuration.credentialReference ?? Self.secretReference(for: updatedTarget.id, suffix: "slack")
  56                try IntegrationSecretStore.save(secret: slackWebhookURL, reference: reference)
  57                configuration.credentialReference = reference
  58                configuration.destinationLabel = Self.hostLabel(from: slackWebhookURL)
  59                updatedTarget.configuration = .slack(configuration)
  60            }
  61        case .email(var configuration):
  62            if let emailPassword {
  63                let reference = configuration.credentialReference ?? Self.secretReference(for: updatedTarget.id, suffix: "smtp")
  64                try IntegrationSecretStore.save(secret: emailPassword, reference: reference)
  65                configuration.credentialReference = reference
  66                updatedTarget.configuration = .email(configuration)
  67            }
  68        case .s3(var configuration):
  69            // Validated on every save, not only when a new key is supplied:
  70            // the endpoint is editable on its own, and an http endpoint would
  71            // put the access key ID and the signature on the wire in the
  72            // clear. F3's NSAllowsArbitraryLoads means nothing else stops it.
  73            try Self.validateHTTPS(configuration.endpoint)
  74            if let s3SecretAccessKey {
  75                let reference = configuration.credentialReference ?? Self.secretReference(for: updatedTarget.id, suffix: "s3")
  76                try IntegrationSecretStore.save(secret: s3SecretAccessKey, reference: reference)
  77                configuration.credentialReference = reference
  78            }
  79            updatedTarget.configuration = .s3(configuration)
  80        }
  81
  82        if let index = targets.firstIndex(where: { $0.id == updatedTarget.id }) {
  83            targets[index] = updatedTarget
  84        } else {
  85            targets.append(updatedTarget)
  86        }
  87        targets.sort { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
  88        persistTargets()
  89        statusMessage = "Saved integration settings."
  90    }
  91
  92    func delete(targetID: UUID) {
  93        guard let target = targets.first(where: { $0.id == targetID }) else { return }
  94        deleteSecrets(for: target)
  95        targets.removeAll { $0.id == targetID }
  96        queue.removeAll { $0.integrationID == targetID }
  97        deliveryRecords.removeAll { $0.integrationID == targetID }
  98        persistTargets()
  99        persistQueue()
 100        persistRecords()
 101    }
 102
 103    func setEnabled(_ isEnabled: Bool, for targetID: UUID) {
 104        guard let index = targets.firstIndex(where: { $0.id == targetID }) else { return }
 105        targets[index].isEnabled = isEnabled
 106        persistTargets()
 107    }
 108
 109    func deliveryRecords(for targetID: UUID) -> [DeliveryRecord] {
 110        deliveryRecords
 111            .filter { $0.integrationID == targetID }
 112            .sorted { $0.timestamp > $1.timestamp }
 113    }
 114
 115    /// Queues an upload of each domain's latest report to every S3 target set
 116    /// to fire on `trigger`, one entry per configured format.
 117    ///
 118    /// Deliberately not routed through `enqueue(events:)`. That fans one event
 119    /// out to every target and applies each target's severity and event-type
 120    /// filters, which exist for alerts. Whether a completed run exports is a
 121    /// per-target setting, and a finished run is not an alert, so the filters
 122    /// must not decide it.
 123    ///
 124    /// One entry per format rather than one per report, so a PDF that fails to
 125    /// upload retries without re-sending the JSON that already landed.
 126    func enqueueExports(domains: [String], trigger: S3ExportTrigger) {
 127        guard FeatureAccessService.hasAccess(to: .bucketExport) else { return }
 128
 129        var seen = Set<String>()
 130        let normalizedDomains = domains
 131            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
 132            .filter { !$0.isEmpty && seen.insert($0).inserted }
 133        guard !normalizedDomains.isEmpty else { return }
 134
 135        var queuedAny = false
 136        for target in targets {
 137            guard target.isEnabled, case .s3(let configuration) = target.configuration else { continue }
 138            guard configuration.uploads(on: trigger) else { continue }
 139
 140            for domain in normalizedDomains {
 141                for format in configuration.formats {
 142                    queue.append(
 143                        QueuedDelivery(
 144                            integrationID: target.id,
 145                            event: MonitoringEvent(
 146                                type: .reportExported,
 147                                severity: .info,
 148                                domain: domain,
 149                                summary: "\(trigger.title): \(domain) as \(format.title)"
 150                            ),
 151                            export: ExportDelivery(format: format, trigger: trigger)
 152                        )
 153                    )
 154                    queuedAny = true
 155                }
 156            }
 157        }
 158
 159        guard queuedAny else { return }
 160        persistQueue()
 161        scheduleProcessing()
 162    }
 163
 164    func enqueue(events: [MonitoringEvent]) {
 165        guard !events.isEmpty else { return }
 166        for event in events {
 167            for target in targets {
 168                guard target.isEnabled else {
 169                    appendRecord(
 170                        DeliveryRecord(
 171                            integrationID: target.id,
 172                            eventID: event.id,
 173                            status: .skipped,
 174                            destination: destinationLabel(for: target),
 175                            summary: event.summary,
 176                            failureReason: Self.disabledTargetReason
 177                        )
 178                    )
 179                    continue
 180                }
 181
 182                if let reason = filterMismatchReason(for: event, target: target) {
 183                    appendRecord(
 184                        DeliveryRecord(
 185                            integrationID: target.id,
 186                            eventID: event.id,
 187                            status: .skipped,
 188                            destination: destinationLabel(for: target),
 189                            summary: event.summary,
 190                            failureReason: reason
 191                        )
 192                    )
 193                    continue
 194                }
 195
 196                queue.append(QueuedDelivery(integrationID: target.id, event: event))
 197                appendRecord(
 198                    DeliveryRecord(
 199                        integrationID: target.id,
 200                        eventID: event.id,
 201                        status: .pending,
 202                        destination: destinationLabel(for: target),
 203                        summary: event.summary
 204                    )
 205                )
 206            }
 207        }
 208        persistQueue()
 209        scheduleProcessing()
 210    }
 211
 212    func recordNoOutboundEvents(for runSummary: String) {
 213        let eligibleTargets = targets.filter(\.isEnabled)
 214        for target in eligibleTargets {
 215            appendRecord(
 216                DeliveryRecord(
 217                    integrationID: target.id,
 218                    eventID: UUID(),
 219                    status: .skipped,
 220                    destination: destinationLabel(for: target),
 221                    summary: runSummary,
 222                    failureReason: "Monitoring run produced no outbound events."
 223                )
 224            )
 225        }
 226    }
 227
 228    func sendTest(for targetID: UUID) {
 229        guard let target = targets.first(where: { $0.id == targetID }) else { return }
 230        let event = MonitoringEvent(
 231            type: .test,
 232            severity: .info,
 233            domain: "example.com",
 234            summary: "DomainDig integration test",
 235            details: [
 236                "source": "manual test",
 237                "environment": "local-first"
 238            ]
 239        )
 240
 241        // Real events skip a disabled target, so a test event must too —
 242        // otherwise a test succeeds against a target that silently drops
 243        // everything monitoring sends it.
 244        guard target.isEnabled else {
 245            appendRecord(
 246                DeliveryRecord(
 247                    integrationID: target.id,
 248                    eventID: event.id,
 249                    status: .skipped,
 250                    destination: destinationLabel(for: target),
 251                    summary: event.summary,
 252                    failureReason: Self.disabledTargetReason
 253                )
 254            )
 255            return
 256        }
 257
 258        queue.append(QueuedDelivery(integrationID: target.id, event: event))
 259        appendRecord(
 260            DeliveryRecord(
 261                integrationID: target.id,
 262                eventID: event.id,
 263                status: .pending,
 264                destination: destinationLabel(for: target),
 265                summary: event.summary
 266            )
 267        )
 268        persistQueue()
 269        scheduleProcessing()
 270    }
 271
 272    /// Restarting the processing task alone leaves any item still in retry
 273    /// backoff undue, so the loop would skip it and sleep again. Pulling every
 274    /// queued item forward is what makes this button mean "now".
 275    func processQueueNow() {
 276        guard !queue.isEmpty else {
 277            statusMessage = "No deliveries are waiting."
 278            return
 279        }
 280
 281        let now = Date()
 282        for index in queue.indices {
 283            queue[index].nextAttemptAt = now
 284        }
 285        persistQueue()
 286        scheduleProcessing(force: true)
 287    }
 288
 289    func localSecretReferences() -> [String] {
 290        targets.compactMap { target in
 291            switch target.configuration {
 292            case .webhook(let configuration):
 293                configuration.credentialReference
 294            case .slack(let configuration):
 295                configuration.credentialReference
 296            case .email(let configuration):
 297                configuration.credentialReference
 298            case .s3(let configuration):
 299                configuration.credentialReference
 300            }
 301        }
 302    }
 303
 304    func resetAfterLocalWipe() {
 305        processingTask?.cancel()
 306        processingTask = nil
 307        targets = []
 308        deliveryRecords = []
 309        queue = []
 310        statusMessage = nil
 311    }
 312
 313    private func scheduleProcessing(force: Bool = false) {
 314        if force {
 315            processingTask?.cancel()
 316            processingTask = nil
 317        }
 318        guard processingTask == nil else { return }
 319        processingTask = Task { [weak self] in
 320            guard let self else { return }
 321            await self.processQueueLoop()
 322        }
 323    }
 324
 325    private func processQueueLoop() async {
 326        defer { processingTask = nil }
 327
 328        while true {
 329            let dueItems = queue
 330                .enumerated()
 331                .filter { $0.element.nextAttemptAt <= Date() }
 332
 333            if dueItems.isEmpty {
 334                guard let nextAttemptAt = queue.map(\.nextAttemptAt).min() else {
 335                    break
 336                }
 337
 338                let delay = max(0.25, nextAttemptAt.timeIntervalSinceNow)
 339                do {
 340                    try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
 341                    continue
 342                } catch {
 343                    break
 344                }
 345            }
 346
 347            for entry in dueItems.reversed() {
 348                guard entry.offset < queue.count else { continue }
 349                let item = queue[entry.offset]
 350                await process(item: item, at: entry.offset)
 351            }
 352        }
 353    }
 354
 355    private func process(item: QueuedDelivery, at index: Int) async {
 356        guard let target = targets.first(where: { $0.id == item.integrationID }) else {
 357            queue.remove(at: index)
 358            persistQueue()
 359            return
 360        }
 361
 362        guard item.expiresAt > Date() else {
 363            queue.remove(at: index)
 364            persistQueue()
 365            appendRecord(
 366                DeliveryRecord(
 367                    integrationID: target.id,
 368                    eventID: item.event.id,
 369                    status: .expired,
 370                    destination: destinationLabel(for: target),
 371                    summary: item.event.summary,
 372                    failureReason: "Delivery expired before succeeding.",
 373                    attemptCount: item.attemptCount
 374                )
 375            )
 376            return
 377        }
 378
 379        do {
 380            try await deliver(item, to: target)
 381            queue.remove(at: index)
 382            persistQueue()
 383            appendRecord(
 384                DeliveryRecord(
 385                    integrationID: target.id,
 386                    eventID: item.event.id,
 387                    status: .delivered,
 388                    destination: destinationLabel(for: target),
 389                    summary: item.event.summary,
 390                    attemptCount: item.attemptCount + 1
 391                )
 392            )
 393            statusMessage = "Delivered \(item.event.summary)."
 394        } catch {
 395            var updated = item
 396            updated.attemptCount += 1
 397            updated.lastError = error.localizedDescription
 398
 399            if updated.attemptCount >= 5 {
 400                queue.remove(at: index)
 401                appendRecord(
 402                    DeliveryRecord(
 403                        integrationID: target.id,
 404                        eventID: item.event.id,
 405                        status: .failed,
 406                        destination: destinationLabel(for: target),
 407                        summary: item.event.summary,
 408                        failureReason: error.localizedDescription,
 409                        attemptCount: updated.attemptCount
 410                    )
 411                )
 412            } else {
 413                let backoff = min(pow(2, Double(updated.attemptCount)) * 30, 3600)
 414                updated.nextAttemptAt = Date().addingTimeInterval(backoff)
 415                queue[index] = updated
 416                appendRecord(
 417                    DeliveryRecord(
 418                        integrationID: target.id,
 419                        eventID: item.event.id,
 420                        status: .retrying,
 421                        destination: destinationLabel(for: target),
 422                        summary: item.event.summary,
 423                        failureReason: error.localizedDescription,
 424                        attemptCount: updated.attemptCount
 425                    )
 426                )
 427            }
 428
 429            persistQueue()
 430            statusMessage = error.localizedDescription
 431        }
 432    }
 433
 434    private func deliver(_ item: QueuedDelivery, to target: IntegrationTarget) async throws {
 435        let event = item.event
 436        switch target.configuration {
 437        case .webhook(let configuration):
 438            guard let reference = configuration.credentialReference else {
 439                throw IntegrationError.missingSecret
 440            }
 441            let webhookURLString = try IntegrationSecretStore.secret(reference: reference)
 442            try await HTTPIntegrationClient.sendJSON(
 443                payload: IntegrationEventPayload(event: event),
 444                to: webhookURLString,
 445                headers: configuration.additionalHeaders,
 446                timeoutSeconds: configuration.timeoutSeconds
 447            )
 448        case .slack(let configuration):
 449            guard let reference = configuration.credentialReference else {
 450                throw IntegrationError.missingSecret
 451            }
 452            let webhookURLString = try IntegrationSecretStore.secret(reference: reference)
 453            try await HTTPIntegrationClient.sendJSON(
 454                payload: SlackPayload(event: event),
 455                to: webhookURLString,
 456                headers: [:],
 457                timeoutSeconds: 15
 458            )
 459        case .s3(let configuration):
 460            guard let reference = configuration.credentialReference else {
 461                throw IntegrationError.missingSecret
 462            }
 463            let secretAccessKey = try IntegrationSecretStore.secret(reference: reference)
 464            let object = try Self.s3Object(for: item, configuration: configuration)
 465            let request = try S3UploadClient.request(
 466                for: object,
 467                configuration: configuration,
 468                credentials: AWSSigV4.Credentials(
 469                    accessKeyID: configuration.accessKeyID,
 470                    secretAccessKey: secretAccessKey
 471                ),
 472                now: Date()
 473            )
 474            let (data, response) = try await URLSession.shared.data(for: request)
 475            try S3UploadClient.validate(
 476                statusCode: (response as? HTTPURLResponse)?.statusCode ?? 0,
 477                body: data
 478            )
 479        case .email(let configuration):
 480            guard let reference = configuration.credentialReference else {
 481                throw IntegrationError.missingSecret
 482            }
 483            let password = try IntegrationSecretStore.secret(reference: reference)
 484            try await SMTPClient.send(
 485                event: event,
 486                configuration: configuration,
 487                password: password
 488            )
 489        }
 490    }
 491
 492    private func appendRecord(_ record: DeliveryRecord) {
 493        deliveryRecords.insert(record, at: 0)
 494        deliveryRecords = Array(deliveryRecords.prefix(250))
 495        persistRecords()
 496    }
 497
 498    private func persistTargets() {
 499        Self.save(targets, key: StorageKey.targets, defaults: defaults)
 500    }
 501
 502    private func persistRecords() {
 503        Self.save(deliveryRecords, key: StorageKey.records, defaults: defaults)
 504    }
 505
 506    private func persistQueue() {
 507        Self.save(queue, key: StorageKey.queue, defaults: defaults)
 508    }
 509
 510    /// The object to upload.
 511    ///
 512    /// An export entry names its format and renders the domain's latest stored
 513    /// report in it. Anything else — a test delivery, or an event on a target
 514    /// with no report to find — uploads the event as JSON, which is what makes
 515    /// the test action prove the endpoint, the signature and the bucket policy
 516    /// without needing a lookup first.
 517    ///
 518    /// The key is `{prefix}/{domain}/{iso8601}.{ext}`, the prefix coming from
 519    /// the configuration.
 520    private static func s3Object(
 521        for item: QueuedDelivery,
 522        configuration: S3IntegrationConfiguration
 523    ) throws -> S3UploadClient.Object {
 524        let event = item.event
 525        let domain = event.domain.isEmpty ? "unknown" : event.domain
 526        let timestamp = Self.objectTimestampFormatter.string(from: event.timestamp)
 527        let report = Self.latestReport(for: domain)
 528
 529        if let export = item.export, let report {
 530            return S3UploadClient.Object(
 531                key: "\(domain)/\(timestamp).\(export.format.fileExtension)",
 532                body: try DomainReportExporter.data(for: report, format: export.format),
 533                contentType: export.format.mimeType
 534            )
 535        }
 536
 537        let encoder = JSONEncoder()
 538        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
 539        encoder.dateEncodingStrategy = .iso8601
 540        let body: Data
 541        if let report, let encoded = try? encoder.encode(report) {
 542            body = encoded
 543        } else {
 544            body = (try? encoder.encode(IntegrationEventPayload(event: event))) ?? Data()
 545        }
 546        return S3UploadClient.Object(
 547            key: "\(domain)/\(timestamp).json",
 548            body: body,
 549            contentType: DomainExportFormat.json.mimeType
 550        )
 551    }
 552
 553    private static func latestReport(for domain: String) -> DomainReport? {
 554        guard let snapshot = MonitoringStorage.loadHistoryEntries()
 555            .first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame })?
 556            .snapshot
 557        else {
 558            return nil
 559        }
 560        return DomainReportBuilder().build(from: snapshot)
 561    }
 562
 563    private static let objectTimestampFormatter: ISO8601DateFormatter = {
 564        let formatter = ISO8601DateFormatter()
 565        formatter.timeZone = TimeZone(identifier: "UTC")
 566        return formatter
 567    }()
 568
 569    private func deleteSecrets(for target: IntegrationTarget) {
 570        switch target.configuration {
 571        case .webhook(let configuration):
 572            if let reference = configuration.credentialReference {
 573                try? IntegrationSecretStore.delete(reference: reference)
 574            }
 575        case .slack(let configuration):
 576            if let reference = configuration.credentialReference {
 577                try? IntegrationSecretStore.delete(reference: reference)
 578            }
 579        case .email(let configuration):
 580            if let reference = configuration.credentialReference {
 581                try? IntegrationSecretStore.delete(reference: reference)
 582            }
 583        case .s3(let configuration):
 584            if let reference = configuration.credentialReference {
 585                try? IntegrationSecretStore.delete(reference: reference)
 586            }
 587        }
 588    }
 589
 590    private func destinationLabel(for target: IntegrationTarget) -> String {
 591        switch target.configuration {
 592        case .webhook(let configuration):
 593            return configuration.endpointDisplayHost.isEmpty ? target.name : configuration.endpointDisplayHost
 594        case .slack(let configuration):
 595            return configuration.destinationLabel
 596        case .email(let configuration):
 597            return configuration.recipientAddresses.joined(separator: ", ")
 598        case .s3(let configuration):
 599            return configuration.bucket.isEmpty ? target.name : configuration.bucket
 600        }
 601    }
 602
 603    private func filterMismatchReason(for event: MonitoringEvent, target: IntegrationTarget) -> String? {
 604        let filters = target.filters
 605
 606        if event.severity < filters.minimumSeverity {
 607            return "Filtered by severity. Event was \(event.severity.title), target requires \(filters.minimumSeverity.title)."
 608        }
 609
 610        if !filters.eventTypes.isEmpty, !filters.eventTypes.contains(event.type) {
 611            return "Filtered by event type. Event was \(event.type.title)."
 612        }
 613
 614        if !filters.domains.isEmpty, !filters.domains.map({ $0.lowercased() }).contains(event.domain.lowercased()) {
 615            return "Filtered by domain. Event was for \(event.domain)."
 616        }
 617
 618        return nil
 619    }
 620
 621    private static func hostLabel(from string: String) -> String {
 622        URL(string: string)?.host ?? "Configured"
 623    }
 624
 625    private static let disabledTargetReason = "This integration is disabled."
 626
 627    private static func secretReference(for integrationID: UUID, suffix: String) -> String {
 628        "integration.\(integrationID.uuidString).\(suffix)"
 629    }
 630
 631    private static func validateHTTPS(_ string: String) throws {
 632        guard let url = URL(string: string) else {
 633            throw IntegrationError.invalidURL
 634        }
 635        guard url.scheme?.lowercased() == "https" else {
 636            throw IntegrationError.insecureURL
 637        }
 638    }
 639
 640    private static func loadTargets(defaults: UserDefaults) -> [IntegrationTarget] {
 641        load([IntegrationTarget].self, key: StorageKey.targets, defaults: defaults) ?? []
 642    }
 643
 644    private static func loadRecords(defaults: UserDefaults) -> [DeliveryRecord] {
 645        load([DeliveryRecord].self, key: StorageKey.records, defaults: defaults) ?? []
 646    }
 647
 648    private static func loadQueue(defaults: UserDefaults) -> [QueuedDelivery] {
 649        load([QueuedDelivery].self, key: StorageKey.queue, defaults: defaults) ?? []
 650    }
 651
 652    private static func load<T: Decodable>(_ type: T.Type, key: String, defaults: UserDefaults) -> T? {
 653        guard let data = defaults.data(forKey: key) else {
 654            return nil
 655        }
 656        return try? JSONDecoder().decode(type, from: data)
 657    }
 658
 659    private static func save<T: Encodable>(_ value: T, key: String, defaults: UserDefaults) {
 660        if let data = try? JSONEncoder().encode(value) {
 661            defaults.set(data, forKey: key)
 662        }
 663    }
 664
 665    private enum StorageKey {
 666        static let targets = "integrations.targets"
 667        static let records = "integrations.records"
 668        static let queue = "integrations.queue"
 669    }
 670}
 671
 672private struct IntegrationEventPayload: Encodable {
 673    let eventType: String
 674    let domain: String
 675    let timestamp: Date
 676    let severity: String
 677    let summary: String
 678    let details: [String: String]
 679
 680    init(event: MonitoringEvent) {
 681        self.eventType = event.type.rawValue
 682        self.domain = event.domain
 683        self.timestamp = event.timestamp
 684        self.severity = event.severity.rawValue
 685        self.summary = event.summary
 686        self.details = event.details
 687    }
 688}
 689
 690private struct SlackPayload: Encodable {
 691    let text: String
 692    let blocks: [SlackBlock]
 693
 694    init(event: MonitoringEvent) {
 695        let title = "\(event.severity.title.uppercased()) • \(event.domain)"
 696        let detailLines = event.details
 697            .sorted { $0.key < $1.key }
 698            .prefix(6)
 699            .map { "\($0.key): \($0.value)" }
 700            .joined(separator: "\n")
 701
 702        self.text = "\(title) — \(event.summary)"
 703        self.blocks = [
 704            SlackBlock(
 705                type: "section",
 706                text: .init(type: "mrkdwn", text: "*\(title)*\n\(event.summary)")
 707            ),
 708            SlackBlock(
 709                type: "section",
 710                text: .init(
 711                    type: "mrkdwn",
 712                    text: "*Event*: \(event.type.title)\n*Timestamp*: \(event.timestamp.formatted(date: .abbreviated, time: .shortened))"
 713                )
 714            ),
 715            SlackBlock(
 716                type: "section",
 717                text: .init(type: "mrkdwn", text: detailLines.isEmpty ? "_No extra details_" : detailLines)
 718            )
 719        ]
 720    }
 721}
 722
 723private struct SlackBlock: Encodable {
 724    let type: String
 725    let text: SlackText
 726}
 727
 728private struct SlackText: Encodable {
 729    let type: String
 730    let text: String
 731}
 732
 733private enum IntegrationError: LocalizedError {
 734    case invalidURL
 735    case insecureURL
 736    case missingSecret
 737    case invalidResponse(Int)
 738    case invalidSMTPPort
 739    case insecureCredentials
 740    case smtp(String)
 741    case streamClosed
 742
 743    var errorDescription: String? {
 744        switch self {
 745        case .invalidURL:
 746            return "The integration URL is invalid."
 747        case .insecureURL:
 748            return "The integration URL must use https. A webhook URL is itself a secret, so http would send it in cleartext."
 749        case .missingSecret:
 750            return "This integration is missing a saved secret."
 751        case .invalidResponse(let statusCode):
 752            return "The remote endpoint returned \(statusCode)."
 753        case .invalidSMTPPort:
 754            return "The SMTP port is invalid."
 755        case .insecureCredentials:
 756            return "SMTP credentials cannot be sent over an unencrypted connection. Use Direct TLS, usually on port 465."
 757        case .smtp(let message):
 758            return message
 759        case .streamClosed:
 760            return "The SMTP connection closed unexpectedly."
 761        }
 762    }
 763}
 764
 765private enum HTTPIntegrationClient {
 766    static func sendJSON<T: Encodable>(
 767        payload: T,
 768        to urlString: String,
 769        headers: [String: String],
 770        timeoutSeconds: Double
 771    ) async throws {
 772        guard let url = URL(string: urlString) else {
 773            throw IntegrationError.invalidURL
 774        }
 775        guard url.scheme?.lowercased() == "https" else {
 776            throw IntegrationError.insecureURL
 777        }
 778
 779        var request = URLRequest(url: url, timeoutInterval: timeoutSeconds)
 780        request.httpMethod = "POST"
 781        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
 782        for (key, value) in headers {
 783            request.setValue(value, forHTTPHeaderField: key)
 784        }
 785
 786        let encoder = JSONEncoder()
 787        encoder.dateEncodingStrategy = .iso8601
 788        request.httpBody = try encoder.encode(payload)
 789
 790        let (_, response) = try await URLSession.shared.data(for: request)
 791        guard let httpResponse = response as? HTTPURLResponse else {
 792            throw IntegrationError.invalidResponse(-1)
 793        }
 794        guard (200..<300).contains(httpResponse.statusCode) else {
 795            throw IntegrationError.invalidResponse(httpResponse.statusCode)
 796        }
 797    }
 798}
 799
 800private enum IntegrationSecretStore {
 801    static func save(secret: String, reference: String) throws {
 802        guard GenericPasswordKeychain.save(secret, reference: reference) else {
 803            throw IntegrationError.smtp("Could not save integration secret.")
 804        }
 805    }
 806
 807    static func secret(reference: String) throws -> String {
 808        guard let secret = GenericPasswordKeychain.secret(reference: reference) else {
 809            throw IntegrationError.missingSecret
 810        }
 811        return secret
 812    }
 813
 814    static func delete(reference: String) throws {
 815        GenericPasswordKeychain.delete(reference: reference)
 816    }
 817}
 818
 819/// Message construction rules the SMTP wire format imposes. Internal so the
 820/// tests can reach them; `SMTPClient` itself is file-private.
 821enum SMTPMessage {
 822    /// `nil` when a value cannot appear in a header. A bare CR or LF ends the
 823    /// header line, and whatever follows is read as further headers — so a
 824    /// domain or address carrying one could add a Bcc the user never wrote.
 825    static func validatedHeaderValue(_ value: String) -> String? {
 826        value.rangeOfCharacter(from: .newlines) == nil ? value : nil
 827    }
 828
 829    /// RFC 5321 section 4.5.2. A body line of "." alone ends the DATA command,
 830    /// after which the rest of the message is read as SMTP commands, so every
 831    /// line beginning with "." is sent doubled.
 832    static func dotStuffed(_ body: String) -> String {
 833        body
 834            .components(separatedBy: "\r\n")
 835            .map { $0.hasPrefix(".") ? "." + $0 : $0 }
 836            .joined(separator: "\r\n")
 837    }
 838}
 839
 840private enum SMTPClient {
 841    static func send(
 842        event: MonitoringEvent,
 843        configuration: EmailIntegrationConfiguration,
 844        password: String
 845    ) async throws {
 846        // `UInt16(_:)` traps above 65535, which the editor's port field allows.
 847        guard let portNumber = UInt16(exactly: configuration.port),
 848              let port = NWEndpoint.Port(rawValue: portNumber) else {
 849            throw IntegrationError.invalidSMTPPort
 850        }
 851
 852        // AUTH LOGIN sends the username and password base64-encoded, which is
 853        // not encryption. Without TLS from the first byte they would go out in
 854        // the clear, so refuse before the connection opens. STARTTLS is not an
 855        // option here: NWConnection cannot upgrade an established connection.
 856        guard configuration.username.isEmpty || configuration.securityMode == .directTLS else {
 857            throw IntegrationError.insecureCredentials
 858        }
 859
 860        let parameters: NWParameters = {
 861            switch configuration.securityMode {
 862            case .plain:
 863                return .tcp
 864            case .directTLS:
 865                let tls = NWProtocolTLS.Options()
 866                return NWParameters(tls: tls, tcp: NWProtocolTCP.Options())
 867            }
 868        }()
 869
 870        let channel = SMTPChannel(host: configuration.smtpHost, port: port, parameters: parameters)
 871        try await channel.start()
 872        _ = try await channel.readResponse(expecting: [220])
 873        _ = try await channel.sendCommand("EHLO domaindig.local", expecting: [250])
 874
 875        if !configuration.username.isEmpty {
 876            _ = try await channel.sendCommand("AUTH LOGIN", expecting: [334])
 877            _ = try await channel.sendCommand(Data(configuration.username.utf8).base64EncodedString(), expecting: [334])
 878            _ = try await channel.sendCommand(Data(password.utf8).base64EncodedString(), expecting: [235])
 879        }
 880
 881        _ = try await channel.sendCommand("MAIL FROM:<\(configuration.senderAddress)>", expecting: [250])
 882        for recipient in configuration.recipientAddresses {
 883            _ = try await channel.sendCommand("RCPT TO:<\(recipient)>", expecting: [250, 251])
 884        }
 885        _ = try await channel.sendCommand("DATA", expecting: [354])
 886
 887        let detailLines = event.details
 888            .sorted { $0.key < $1.key }
 889            .map { "\($0.key): \($0.value)" }
 890            .joined(separator: "\r\n")
 891        let recipientList = configuration.recipientAddresses.joined(separator: ", ")
 892        let subject = "[DomainDig] \(event.severity.title) \(event.domain) \(event.type.title)"
 893        guard SMTPMessage.validatedHeaderValue(configuration.senderAddress) != nil,
 894              SMTPMessage.validatedHeaderValue(recipientList) != nil,
 895              SMTPMessage.validatedHeaderValue(subject) != nil else {
 896            throw IntegrationError.smtp("The message could not be built: an address or the domain contains a line break.")
 897        }
 898
 899        let body = [
 900            "From: DomainDig <\(configuration.senderAddress)>",
 901            "To: \(recipientList)",
 902            "Subject: \(subject)",
 903            "Date: \(DateFormatter.rfc2822.string(from: Date()))",
 904            "",
 905            event.summary,
 906            "",
 907            "Domain: \(event.domain)",
 908            "Severity: \(event.severity.title)",
 909            "Event: \(event.type.title)",
 910            "Timestamp: \(event.timestamp.formatted(date: .abbreviated, time: .shortened))",
 911            detailLines
 912        ]
 913        .joined(separator: "\r\n")
 914
 915        try await channel.sendRaw(SMTPMessage.dotStuffed(body) + "\r\n.\r\n")
 916        _ = try await channel.readResponse(expecting: [250])
 917        _ = try await channel.sendCommand("QUIT", expecting: [221])
 918        await channel.cancel()
 919    }
 920}
 921
 922/// An actor, not a MainActor class. The previous shape inherited the project's
 923/// MainActor default while running its receive loop on a background dispatch
 924/// queue, so `parsedLines`/`lineWaiters`/`receiveBuffer` were declared
 925/// main-actor-protected and mutated off it — concurrent mutation while resuming
 926/// a `CheckedContinuation` can double-resume, which traps. The actor serialises
 927/// all of it and forces the Network callbacks to hop in explicitly. (Issue #27.)
 928private actor SMTPChannel {
 929    private let connection: NWConnection
 930    private var parsedLines: [String] = []
 931    private var lineWaiters: [CheckedContinuation<String, Error>] = []
 932    private var receiveBuffer = Data()
 933
 934    init(host: String, port: NWEndpoint.Port, parameters: NWParameters) {
 935        connection = NWConnection(host: NWEndpoint.Host(host), port: port, using: parameters)
 936    }
 937
 938    func start() async throws {
 939        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
 940            // The state handler can fire `.ready` and later `.failed` (or
 941            // `.failed` twice); resuming a continuation twice traps. The lock
 942            // also keeps the closure Sendable-clean without touching actor state
 943            // from the connection's queue.
 944            let hasResumed = OSAllocatedUnfairLock(initialState: false)
 945            connection.stateUpdateHandler = { state in
 946                guard let outcome = Self.startOutcome(for: state) else { return }
 947                let isFirst = hasResumed.withLock { resumed in
 948                    defer { resumed = true }
 949                    return !resumed
 950                }
 951                if isFirst { continuation.resume(with: outcome) }
 952            }
 953            connection.start(queue: .global(qos: .utility))
 954        }
 955        // Started from the actor once the connection is ready, replacing the old
 956        // dispatch-queue hop. TCP buffers anything that arrives in the gap.
 957        startReceiveLoop()
 958    }
 959
 960    /// How a connection state settles `start()`: ready succeeds, failure or
 961    /// cancellation throws, and anything else is still in progress.
 962    private static func startOutcome(for state: NWConnection.State) -> Result<Void, Error>? {
 963        switch state {
 964        case .ready:
 965            return .success(())
 966        case .failed(let error):
 967            return .failure(error)
 968        case .cancelled:
 969            return .failure(IntegrationError.streamClosed)
 970        default:
 971            return nil
 972        }
 973    }
 974
 975    func cancel() {
 976        connection.cancel()
 977    }
 978
 979    func sendCommand(_ command: String, expecting codes: Set<Int>) async throws -> String {
 980        try await sendRaw(command + "\r\n")
 981        return try await readResponse(expecting: codes)
 982    }
 983
 984    func sendCommand(_ command: String, expecting codes: [Int]) async throws -> String {
 985        try await sendCommand(command, expecting: Set(codes))
 986    }
 987
 988    func sendRaw(_ string: String) async throws {
 989        let data = Data(string.utf8)
 990        try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
 991            connection.send(content: data, completion: .contentProcessed { error in
 992                if let error {
 993                    continuation.resume(throwing: error)
 994                } else {
 995                    continuation.resume()
 996                }
 997            })
 998        }
 999    }
1000
1001    func readResponse(expecting codes: Set<Int>) async throws -> String {
1002        var lines: [String] = []
1003
1004        while true {
1005            let line = try await readLine()
1006            lines.append(line)
1007
1008            guard line.count >= 4,
1009                  let code = Int(line.prefix(3)) else {
1010                continue
1011            }
1012
1013            let delimiterIndex = line.index(line.startIndex, offsetBy: 3)
1014            if line[delimiterIndex] == " " {
1015                guard codes.contains(code) else {
1016                    throw IntegrationError.smtp(line)
1017                }
1018                return lines.joined(separator: "\n")
1019            }
1020        }
1021    }
1022
1023    private func readLine() async throws -> String {
1024        if !parsedLines.isEmpty {
1025            return parsedLines.removeFirst()
1026        }
1027
1028        return try await withCheckedThrowingContinuation { continuation in
1029            lineWaiters.append(continuation)
1030        }
1031    }
1032
1033    private func startReceiveLoop() {
1034        // The completion runs on the connection's queue; hop back onto the
1035        // actor before touching any state.
1036        connection.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] data, _, isComplete, error in
1037            guard let self else { return }
1038            Task {
1039                await self.handleReceive(data: data, isComplete: isComplete, error: error)
1040            }
1041        }
1042    }
1043
1044    private func handleReceive(data: Data?, isComplete: Bool, error: Error?) {
1045        if let error {
1046            failWaiters(with: error)
1047            return
1048        }
1049
1050        if let data, !data.isEmpty {
1051            receiveBuffer.append(data)
1052            flushBuffer()
1053        }
1054
1055        if isComplete {
1056            failWaiters(with: IntegrationError.streamClosed)
1057            return
1058        }
1059
1060        startReceiveLoop()
1061    }
1062
1063    private func flushBuffer() {
1064        let delimiter = Data("\r\n".utf8)
1065        while let range = receiveBuffer.range(of: delimiter) {
1066            let lineData = receiveBuffer.subdata(in: receiveBuffer.startIndex..<range.lowerBound)
1067            receiveBuffer.removeSubrange(receiveBuffer.startIndex..<range.upperBound)
1068            let line = String(data: lineData, encoding: .utf8) ?? ""
1069            if !lineWaiters.isEmpty {
1070                let continuation = lineWaiters.removeFirst()
1071                continuation.resume(returning: line)
1072            } else {
1073                parsedLines.append(line)
1074            }
1075        }
1076    }
1077
1078    private func failWaiters(with error: Error) {
1079        let waiters = lineWaiters
1080        lineWaiters.removeAll()
1081        for waiter in waiters {
1082            waiter.resume(throwing: error)
1083        }
1084    }
1085}
1086
1087private extension DateFormatter {
1088    static let rfc2822: DateFormatter = {
1089        let formatter = DateFormatter()
1090        formatter.locale = Locale(identifier: "en_US_POSIX")
1091        formatter.timeZone = TimeZone(secondsFromGMT: 0)
1092        formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
1093        return formatter
1094    }()
1095}