import Configuration import Foundation import HTTPTypes import Logging /// Everything the service reads from its environment, with the same /// `EFFEM_*` names the Go service used. Keys are read through a reader /// scoped to `effem`, so `databaseUrl` resolves `EFFEM_DATABASE_URL`. /// /// A few platform names are read unscoped as fallbacks, so a host that /// provides them needs no renaming: `PORT` for the listen port, /// `DATABASE_URL_UNPOOLED` and `DATABASE_URL` for the database, and /// `CRON_SECRET` for the cron routes. struct AppConfig: Sendable { struct Bind: Sendable, Equatable { var host: String var port: Int } struct RateLimit: Sendable, Equatable { var enabled = true var addressRate: Double = 20 var addressBurst = 200 var subjectRate: Double = 40 var subjectBurst = 400 } struct UpstreamLimits: Sendable, Equatable { var perClientRate: Double = 1 var perClientBurst = 120 var serviceRate: Double = 2 var serviceBurst = 120 } struct APNs: Sendable, Equatable { /// Where the `.p8` signing key comes from. enum Key: Sendable, Equatable { /// A file on disk (`EFFEM_APNS_KEY_PATH`). case path(String) /// The PEM text itself (`EFFEM_APNS_KEY`), for hosts without a /// file system to mount secrets into. case pem(String) } var key: Key var keyID: String var teamID: String var bundleID: String } /// How records get from Jetstream into the database. struct Ingest: Sendable, Equatable { enum Mode: String, Sendable { /// A consumer runs inside the process for as long as it lives. case service /// Nothing runs on its own; `GET /_cron/ingest` performs one /// bounded catch-up run per call. For hosts whose processes only /// live while they serve a request. case cron } var mode: Mode = .service /// How long one cron run stays connected. With a schedule of every /// minute, fifty seconds leaves room for the close handshake and the /// post-run work before the next call arrives. var runBudget: Duration = .seconds(50) } var bind = Bind(host: "0.0.0.0", port: 8080) var databaseURL = "postgres://effem:effem@localhost:5432/effem?sslmode=disable" /// The URL for the one connection that `LISTEN`s for comment events. It /// must reach Postgres directly: transaction poolers do not deliver /// notifications. var databaseListenURL: String? var databaseMaxOpenConnections = 25 var databaseMaxIdleConnections = 5 var databaseConnectionMaxIdleTime: Duration = .seconds(300) var jetstreamHosts = ["wss://jetstream.us-east.bsky.network", "wss://jetstream.us-west.bsky.network"] var plcHost = "https://plc.directory" var catalogDID = "did:web:catalog.effem.xyz" var labelerDID = "did:web:labeler.effem.xyz" var podcastIndexKey: String? var podcastIndexSecret: String? var podcastIndexUserAgent = "effem-appview/1.0" var authRequired = true var readTokens: [String: String] = [:] var adminTokens: [String: String] = [:] var adminDIDs: [String] = [] var corsOrigins = ["http://localhost:3000"] var rateLimit = RateLimit() var upstreamLimits = UpstreamLimits() var trustedProxyRanges: [String] = [] /// A header the edge in front sets to the caller's address, replacing /// anything the caller sent under that name (`X-Real-IP` on Railway). /// Unset, the caller is worked out from `X-Forwarded-For`. var clientAddressHeader: HTTPField.Name? var apns: APNs? var ingest = Ingest() /// The bearer token the cron routes require. var cronSecret: String? /// Where a short JSON notice is posted when a report arrives, so a /// moderator hears about it. Slack and Discord incoming webhooks both /// accept the body. var reportWebhookURL: URL? var logLevel: Logger.Level = .info static let secretEnvironmentVariables: Set = [ "EFFEM_DATABASE_URL", "EFFEM_DATABASE_LISTEN_URL", "DATABASE_URL", "DATABASE_URL_UNPOOLED", "EFFEM_PI_KEY", "EFFEM_PI_SECRET", "EFFEM_AUTH_READ_TOKENS", "EFFEM_AUTH_ADMIN_TOKENS", "EFFEM_APNS_KEY", "EFFEM_REPORT_WEBHOOK_URL", "CRON_SECRET", ] /// Reads the configuration. `root` is the unscoped reader; the `EFFEM_` /// keys are read through `root.scoped(to: "effem")`. static func load(from root: ConfigReader) throws -> AppConfig { let reader = root.scoped(to: "effem") var config = AppConfig() // The platform's PORT wins over the default; an explicit EFFEM_BIND wins over both. let platformPort = Self.nonEmpty(root.string(forKey: "port", default: "")) let defaultBind = platformPort.map { "0.0.0.0:\($0)" } ?? "0.0.0.0:8080" config.bind = try Bind(parsing: reader.string(forKey: "bind", default: defaultBind)) // EFFEM_DATABASE_URL, then the names hosted Postgres integrations set. The direct // (unpooled) URL comes first: the migrator's advisory lock and LISTEN need a real session. let unpooled = Self.nonEmpty(root.string(forKey: "databaseUrlUnpooled", default: "")) let pooled = Self.nonEmpty(root.string(forKey: "databaseUrl", default: "")) config.databaseURL = Self.nonEmpty(reader.string(forKey: "databaseUrl", default: "")) ?? unpooled ?? pooled ?? config.databaseURL config.databaseListenURL = Self.nonEmpty(reader.string(forKey: "databaseListenUrl", default: "")) ?? unpooled config.databaseMaxOpenConnections = reader.int(forKey: "dbMaxOpenConns", default: config.databaseMaxOpenConnections) config.databaseMaxIdleConnections = reader.int(forKey: "dbMaxIdleConns", default: config.databaseMaxIdleConnections) config.databaseConnectionMaxIdleTime = try GoDuration.parse(reader.string(forKey: "dbConnMaxIdleTime", default: "5m")) config.jetstreamHosts = reader.stringArray(forKey: "jetstreamHosts", default: config.jetstreamHosts).map(Self.trim).filter { !$0.isEmpty } config.plcHost = reader.string(forKey: "plcHost", default: config.plcHost) config.catalogDID = Self.nonEmpty(reader.string(forKey: "catalogDid", default: "")) ?? config.catalogDID config.labelerDID = Self.nonEmpty(reader.string(forKey: "labelerDid", default: "")) ?? config.labelerDID config.podcastIndexKey = Self.nonEmpty(reader.string(forKey: "piKey", default: "")) config.podcastIndexSecret = Self.nonEmpty(reader.string(forKey: "piSecret", default: "")) config.podcastIndexUserAgent = reader.string(forKey: "piUserAgent", default: config.podcastIndexUserAgent) config.authRequired = reader.bool(forKey: "authRequired", default: true) config.readTokens = try TokenMap.parse(reader.string(forKey: "authReadTokens", default: "")) config.adminTokens = try TokenMap.parse(reader.string(forKey: "authAdminTokens", default: "")) config.adminDIDs = reader.stringArray(forKey: "adminDids", default: []).map(Self.trim).filter { !$0.isEmpty } config.corsOrigins = reader.stringArray(forKey: "corsAllowedOrigins", default: config.corsOrigins).map(Self.trim).filter { !$0.isEmpty } config.rateLimit = RateLimit( enabled: reader.bool(forKey: "rateLimitEnabled", default: true), addressRate: reader.double(forKey: "rateLimitRps", default: RateLimit().addressRate), addressBurst: reader.int(forKey: "rateLimitBurst", default: RateLimit().addressBurst), subjectRate: reader.double(forKey: "rateLimitSubRps", default: RateLimit().subjectRate), subjectBurst: reader.int(forKey: "rateLimitSubBurst", default: RateLimit().subjectBurst) ) config.upstreamLimits = UpstreamLimits( perClientRate: reader.double(forKey: "piClientRps", default: UpstreamLimits().perClientRate), perClientBurst: reader.int(forKey: "piClientBurst", default: UpstreamLimits().perClientBurst), serviceRate: reader.double(forKey: "piServiceRps", default: UpstreamLimits().serviceRate), serviceBurst: reader.int(forKey: "piServiceBurst", default: UpstreamLimits().serviceBurst) ) config.trustedProxyRanges = reader.stringArray(forKey: "trustedProxyCidrs", default: []).map(Self.trim).filter { !$0.isEmpty } if let header = Self.nonEmpty(reader.string(forKey: "clientAddressHeader", default: "")) { guard let name = HTTPField.Name(header) else { throw ValidationError.message("client address header is not a valid header name: \(header)") } config.clientAddressHeader = name } let keyPEM = Self.nonEmpty(reader.string(forKey: "apnsKey", default: "")) let keyPath = Self.nonEmpty(reader.string(forKey: "apnsKeyPath", default: "")) let keyID = reader.string(forKey: "apnsKeyId", default: "") let teamID = reader.string(forKey: "apnsTeamId", default: "") let bundleID = reader.string(forKey: "apnsBundleId", default: "") if let key = keyPEM.map({ APNs.Key.pem(Self.unescapedPEM($0)) }) ?? keyPath.map(APNs.Key.path), !keyID.isEmpty, !teamID.isEmpty, !bundleID.isEmpty { config.apns = APNs(key: key, keyID: keyID, teamID: teamID, bundleID: bundleID) } let modeText = Self.nonEmpty(reader.string(forKey: "ingestMode", default: "")) ?? Ingest.Mode.service.rawValue guard let mode = Ingest.Mode(rawValue: modeText.lowercased()) else { throw ValidationError.message("ingest mode must be service or cron, got \"\(modeText)\"") } config.ingest = Ingest(mode: mode, runBudget: .seconds(reader.int(forKey: "ingestRunSeconds", default: 50))) config.cronSecret = Self.nonEmpty(root.string(forKey: "cronSecret", default: "")) if let webhook = Self.nonEmpty(reader.string(forKey: "reportWebhookUrl", default: "")) { guard let url = URL(string: webhook), let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http", url.host != nil else { throw ValidationError.message("report webhook URL must be an http or https URL") } config.reportWebhookURL = url } if let level = Logger.Level(rawValue: reader.string(forKey: "logLevel", default: "info").lowercased()) { config.logLevel = level } try config.validate() return config } enum ValidationError: Error, Equatable, CustomStringConvertible, Sendable { case message(String) var description: String { switch self { case .message(let text): return text } } } /// The rules from the Go service's `Config.Validate`, plus the Jetstream /// host, trusted-range and ingest checks. func validate() throws { func fail(_ message: String) throws { throw ValidationError.message(message) } if bind.host.isEmpty || bind.port <= 0 || bind.port > 65535 { try fail("bind must be host:port") } if databaseURL.isEmpty { try fail("database URL must not be empty") } if jetstreamHosts.isEmpty { try fail("at least one Jetstream host is required") } for host in jetstreamHosts where !(host.hasPrefix("ws://") || host.hasPrefix("wss://")) { try fail("Jetstream host must start with ws:// or wss://: \(host)") } if corsOrigins.isEmpty { try fail("at least one CORS origin is required") } for origin in corsOrigins { if origin == "*" { try fail("CORS wildcard origin is not allowed") } if !(origin.hasPrefix("http://") || origin.hasPrefix("https://")) { try fail("CORS origin must start with http:// or https://: \(origin)") } } if authRequired, readTokens.isEmpty, adminTokens.isEmpty { try fail("auth is required but no auth tokens were configured") } if rateLimit.enabled { if rateLimit.addressRate <= 0 { try fail("rate limit rps must be positive when rate limiting is enabled") } if rateLimit.addressBurst <= 0 { try fail("rate limit burst must be positive when rate limiting is enabled") } if rateLimit.subjectRate <= 0 { try fail("rate limit sub rps must be positive") } if rateLimit.subjectBurst <= 0 { try fail("rate limit sub burst must be positive") } } if upstreamLimits.perClientRate <= 0 || upstreamLimits.serviceRate <= 0 { try fail("podcast index budget rates must be positive") } if upstreamLimits.perClientBurst <= 0 || upstreamLimits.serviceBurst <= 0 { try fail("podcast index budget bursts must be positive") } for did in adminDIDs where !did.hasPrefix("did:") { try fail("admin DID \"\(did)\" must start with \"did:\"") } if databaseMaxOpenConnections <= 0 { try fail("db max open connections must be positive") } if databaseMaxIdleConnections < 0 { try fail("db max idle connections must be >= 0") } if databaseMaxIdleConnections > databaseMaxOpenConnections { try fail("db max idle (\(databaseMaxIdleConnections)) cannot exceed max open (\(databaseMaxOpenConnections))") } for range in trustedProxyRanges where CIDR(range) == nil { try fail("trusted proxy range is not a CIDR: \(range)") } if !catalogDID.hasPrefix("did:") { try fail("catalog DID must start with \"did:\"") } if !labelerDID.hasPrefix("did:") { try fail("labeler DID must start with \"did:\"") } if ingest.runBudget < .seconds(5) || ingest.runBudget > .seconds(1700) { try fail("ingest run seconds must be between 5 and 1700") } } var podcastIndexConfigured: Bool { podcastIndexKey != nil && podcastIndexSecret != nil } var trustedProxyCIDRs: [CIDR] { trustedProxyRanges.compactMap(CIDR.init) } private static func trim(_ value: String) -> String { value.trimmingCharacters(in: .whitespacesAndNewlines) } private static func nonEmpty(_ value: String) -> String? { let trimmed = trim(value) return trimmed.isEmpty ? nil : trimmed } /// Environment editors often store a multi-line PEM with literal `\n` /// sequences; both forms are accepted. static func unescapedPEM(_ value: String) -> String { value.contains("\\n") && !value.contains("\n") ? value.replacingOccurrences(of: "\\n", with: "\n") : value } } extension AppConfig.Bind { /// Parses `host:port`, `:port` (all interfaces) or a bare port. init(parsing text: String) throws { let value = text.trimmingCharacters(in: .whitespaces) guard let colon = value.lastIndex(of: ":") else { guard let port = Int(value) else { throw AppConfig.ValidationError.message("bind must be host:port") } self.init(host: "0.0.0.0", port: port) return } let host = String(value[.. [String: String] { var result: [String: String] = [:] let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { return result } for pair in trimmed.split(separator: ",") { let item = pair.trimmingCharacters(in: .whitespacesAndNewlines) if item.isEmpty { continue } let parts = item.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) guard parts.count == 2 else { throw AppConfig.ValidationError.message("invalid token mapping \"\(item)\", expected token=subject") } let token = parts[0].trimmingCharacters(in: .whitespaces) let subject = parts[1].trimmingCharacters(in: .whitespaces) if token.isEmpty { throw AppConfig.ValidationError.message("empty token in mapping \"\(item)\"") } if subject.isEmpty { throw AppConfig.ValidationError.message("empty subject in mapping \"\(item)\"") } if result[token] != nil { throw AppConfig.ValidationError.message("duplicate token mapping for \"\(token)\"") } result[token] = subject } return result } } /// Parses durations the way Go's flag package does: `5m`, `30s`, `1h30m`, /// `250ms`. A bare number is taken as seconds. enum GoDuration { static func parse(_ text: String) throws -> Duration { let value = text.trimmingCharacters(in: .whitespaces) if let seconds = Double(value) { return .seconds(seconds) } var total: Double = 0 var number = "" var unit = "" func flush() throws { guard let amount = Double(number) else { throw AppConfig.ValidationError.message("invalid duration: \(text)") } switch unit { case "ms": total += amount / 1000 case "s": total += amount case "m": total += amount * 60 case "h": total += amount * 3600 default: throw AppConfig.ValidationError.message("invalid duration unit in: \(text)") } number = "" unit = "" } for character in value { if character.isNumber || character == "." { if !unit.isEmpty { try flush() } number.append(character) } else { unit.append(character) } } guard !number.isEmpty || !unit.isEmpty else { throw AppConfig.ValidationError.message("invalid duration: \(text)") } try flush() return .seconds(total) } }