diff --git a/DECISIONS.md b/DECISIONS.md index c2a32fb7..8f22e505 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -59,12 +59,14 @@ Add an entry when a pull request sets a rule, a policy or a choice not to do som −1,000…1,000. All remaining numeric values use 0…1,000, including style height, spacing and edge padding. These refusals apply to links; folder themes keep the ordinary configuration rules. - **A native provider may read a macOS tool's output** (2026-11-16, [#220]). When no public API gives the data and the tool needs no permission, a native provider can run a macOS command-line tool, off the main actor and without a shell: `bluetooth` reads every connected device's battery from `system_profiler`. Apple doesn't document the tool's output keys, so a missing or renamed key leaves that value empty instead of failing the provider. +- **A package can't move another party's credentials** (2026-11-17, [#85], [#744]). A package may set the `url` of a provider, directly or in a profile, only when no file or profile gives that provider a token other than one of that package's own secrets, and no other file sets its `headers`. A package without commands can reach the Store after CI alone, so it must not point your token, a header you typed or another package's secret at its own host. In its own files, a package writes out each provider's `url` and `headers`, without `@token.` references, so StableBar needn't follow tokens to see where a request goes or what it sends. The check doesn't work out which profiles can be active together, so it can refuse an unusual but harmless setup. URLs and headers set in your own files stay free, `@token.` references included. - **Tests keep their own time** (2026-11-08, [#491]). Code whose tests depend on time takes a clock, and the test clock lives in the repository rather than in a new dependency. - **Blocking work stays off Swift's shared pool** (2026-11-13, [#618]). The pool has one thread per core, three on CI, and never replaces a blocked one. A slow copy or a lookup that can stall runs through `BlockingWork.run` on a GCD queue, and tests that block such work check that it does. [AGENTS.md](AGENTS.md#writing-tests) has the rule for tests. - **Comments are for the next reader** (2026-11-10, [#533]). A comment says what the code can't, such as why it must be so, in a line or two. How the bug was found and fixed goes in the issue, the pull request and the commit message. [AGENTS.md](AGENTS.md#writing-comments) has the rule. [#3]: https://github.com/Seb-GRAF/StableBar/issues/3 [#23]: https://github.com/Seb-GRAF/StableBar/pull/23 +[#85]: https://github.com/Seb-GRAF/StableBar/issues/85 [#100]: https://github.com/Seb-GRAF/StableBar/pull/100 [#220]: https://github.com/Seb-GRAF/StableBar/issues/220 [#223]: https://github.com/Seb-GRAF/StableBar/issues/223 @@ -85,5 +87,6 @@ Add an entry when a pull request sets a rule, a policy or a choice not to do som [#618]: https://github.com/Seb-GRAF/StableBar/issues/618 [#664]: https://github.com/Seb-GRAF/StableBar/issues/664 [#676]: https://github.com/Seb-GRAF/StableBar/issues/676 +[#744]: https://github.com/Seb-GRAF/StableBar/pull/744 [#772]: https://github.com/Seb-GRAF/StableBar/issues/772 [#773]: https://github.com/Seb-GRAF/StableBar/pull/773 diff --git a/Sources/StableBar/BarStore.swift b/Sources/StableBar/BarStore.swift index 7b9790cd..9c1bd356 100644 --- a/Sources/StableBar/BarStore.swift +++ b/Sources/StableBar/BarStore.swift @@ -728,7 +728,7 @@ final class BarStore: NSObject { private func display(_ next: Configuration, loader: ConfigurationLoader) { adopt(loader) - if effectiveDocument == loader.document, screenDocuments == loader.screenDocuments { + if effectiveDocument == loader.document, screenDocuments == loader.screenDocuments, configuration?.providers == next.providers { origins = loader.origins activeProfiles = loader.activeProfiles configurationError = nil diff --git a/Sources/StableBar/Configuration.swift b/Sources/StableBar/Configuration.swift index e6714a7c..988b804c 100644 --- a/Sources/StableBar/Configuration.swift +++ b/Sources/StableBar/Configuration.swift @@ -801,7 +801,7 @@ struct Configuration: Decodable, Sendable { let popups: [String: PopupConfiguration] let environment: [String: String] - let providers: [String: ProviderConfiguration] + var providers: [String: ProviderConfiguration] let groups: [String: WidgetGroupConfiguration] /// Events that enabled widgets, and the providers they show, subscribe to. let subscribedEvents: Set diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index 2ab8f63c..ea048d94 100644 --- a/Sources/StableBar/ConfigurationLoader.swift +++ b/Sources/StableBar/ConfigurationLoader.swift @@ -449,6 +449,7 @@ struct ConfigurationLoader: Sendable { private var packageBoundaries: [String: URL] = [:] private var packageNames: [String: String] = [:] private var packageIDs: [String: String] = [:] + private var packageHosts: [String: [String]] = [:] private var essentialsPopupNames: [String: String] = [:] /// What the bar warns about when it skipped properties of a configuration written for a newer release. @@ -465,6 +466,9 @@ struct ConfigurationLoader: Sendable { try readingNewerFiles { loader in var configuration = try ConfigurationValue.object(loader.compose(url, data: data, context: context, previewTheme: previewTheme)) .decoded(Configuration.self) + for name in configuration.providers.keys { + configuration.providers[name]!.hosts = loader.origins["providers.\(name).url"].flatMap { loader.packageHosts[$0.file] } + } loader.screenDocuments = [:] for kind in configuration.screensWithOwnLook { var screenLoader = loader @@ -510,6 +514,7 @@ struct ConfigurationLoader: Sendable { packageBoundaries = [:] packageNames = [:] packageIDs = [:] + packageHosts = [:] widgetPackageNames = [:] widgetPackageIDs = [:] builtInWidgetIDs = [] @@ -544,6 +549,7 @@ struct ConfigurationLoader: Sendable { context.theme = theme.id } try layer.merge(base) + try validatePackageURLs(layer, packageIDs: packageIDs) return try finish(layer, context: context) } @@ -856,10 +862,12 @@ struct ConfigurationLoader: Sendable { } } try validateSecretReferences(.object(layer.values), package: manifest.id) + try validatePackageHosts(layer.values, manifest: manifest) layer.values = try preparePackageDocument(layer.values, directory: directory) for source in layer.origins.values { packageNames[source.file] = manifest.name packageIDs[source.file] = manifest.id + packageHosts[source.file] = manifest.hosts } return layer } diff --git a/Sources/StableBar/DataSourceRegistry.swift b/Sources/StableBar/DataSourceRegistry.swift index b2d7e670..1c30de6c 100644 --- a/Sources/StableBar/DataSourceRegistry.swift +++ b/Sources/StableBar/DataSourceRegistry.swift @@ -115,8 +115,8 @@ struct DataSourceRegistry: Sendable { .filter { listed.insert($0).inserted } } - static let builtIn = DataSourceRegistry(types: [.command, .stream, .battery, .bluetooth, .system, .network, .wifi, .disk, .audio, .inputSource, - .microphone, .privacy, .calendar, .merge]) + static let builtIn = DataSourceRegistry(types: [.command, .stream, .http, .battery, .bluetooth, .system, .network, .wifi, .disk, .audio, + .inputSource, .microphone, .privacy, .calendar, .merge]) } extension DataSourceType { @@ -130,6 +130,38 @@ extension DataSourceType { StreamSource(command: provider.command!, environment: environment) } + static let http = http() + + /// A JSON request read on a timer, with the parts of the response that `output` names. Web APIs limit how often + /// a client may ask, so it reads once a minute by default. The session drops the token on a redirect to another + /// host, follows no redirect outside a package's `hosts` and keeps no cache or cookies. + static func http(session: URLSession = .packageSources) -> DataSourceType { + DataSourceType(name: "http", isNative: false, symbol: "globe", settings: [.url, .output], optionalSettings: [.headers, .token], + continuous: false, defaultInterval: 60) { provider, _ in + PollingSource { _ in + do { + var request = URLRequest(url: provider.url!, timeoutInterval: provider.timeout) + for (name, value) in provider.headers { request.setValue(value, forHTTPHeaderField: name) } + if let reference = provider.token { + // Reading the Keychain can wait on macOS asking whether StableBar may use the token. + let token = try await BlockingWork.run { secretValue(reference) } + if !token.isEmpty { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } + } + let (data, response) = try await session.data(for: request, delegate: provider.hosts.map { SourceRedirectGuard(hosts: $0) }) + let body = CommandResult(stdout: data, stderr: Data()) + let status = (response as! HTTPURLResponse).statusCode + guard status == 200 else { + return .output(.failure(CommandFailure(message: "The server answered with HTTP status \(status).")), process: body) + } + return .output(Result { provider.output!.output(from: try JSONDecoder().decode(ConfigurationValue.self, from: data)) }, + process: body) + } catch { + return .output(.failure(error)) + } + } + } + } + static let battery = DataSourceType(name: "battery", isNative: true, symbol: "battery.100percent", settings: [], continuous: true, events: [.powerSourceChange]) { _, _ in PushSource(monitor: PowerMonitor()) diff --git a/Sources/StableBar/PackageSourceFetching.swift b/Sources/StableBar/PackageSourceFetching.swift index c312356f..e65beef7 100644 --- a/Sources/StableBar/PackageSourceFetching.swift +++ b/Sources/StableBar/PackageSourceFetching.swift @@ -33,8 +33,16 @@ func redirectRequest(_ request: URLRequest, from original: URL?) -> URLRequest { } final class SourceRedirectGuard: NSObject, URLSessionTaskDelegate, Sendable { + /// The only hosts a redirect may reach, or nil for any. + let hosts: [String]? + + init(hosts: [String]? = nil) { + self.hosts = hosts + } + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { + if let hosts, !hosts.contains(where: { $0 == request.url?.host() }) { return completionHandler(nil) } completionHandler(redirectRequest(request, from: task.originalRequest?.url)) } } diff --git a/Sources/StableBar/ProviderConfiguration.swift b/Sources/StableBar/ProviderConfiguration.swift index 8ce94a4a..6114efce 100644 --- a/Sources/StableBar/ProviderConfiguration.swift +++ b/Sources/StableBar/ProviderConfiguration.swift @@ -23,16 +23,27 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable { let diskCritical: Double /// The providers a `merge` combines. let providers: [String] + /// What an `http` provider requests, with `headers` and a `token` sent as `Authorization: Bearer`. + let url: URL? + let headers: [String: String] + let token: String? + let output: HTTPOutput? + /// When a package set the `url`, its `hosts`, the only ones a redirect may reach. The loader sets them. + var hosts: [String]? enum CodingKeys: String, CodingKey, CaseIterable { case type, command, interval, timeout, environment, whenVisible, events, calendars, lookahead, todayOnly, soon, now, processes - case sortBy, units, cpuWarning, memoryWarning, diskWarning, diskCritical, providers + case sortBy, units, cpuWarning, memoryWarning, diskWarning, diskCritical, providers, url, headers, token, output } init(type: String) { self.type = type command = nil providers = [] + url = nil + headers = [:] + token = nil + output = nil interval = DataSourceRegistry.builtIn[type]?.defaultInterval ?? 5 timeout = 10 environment = [:] @@ -61,6 +72,10 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable { } command = source.settings.contains(.command) ? try values.decode(String.self, forKey: .command) : nil providers = source.settings.contains(.providers) ? try values.decode([String].self, forKey: .providers) : [] + url = source.settings.contains(.url) ? try values.decode(URL.self, forKey: .url) : nil + output = source.settings.contains(.output) ? try values.decode(HTTPOutput.self, forKey: .output) : nil + headers = try values.decodeIfPresent([String: String].self, forKey: .headers) ?? [:] + token = try values.decodeIfPresent(String.self, forKey: .token) interval = try values.decodeIfPresent(Double.self, forKey: .interval) ?? source.defaultInterval timeout = try values.decodeIfPresent(Double.self, forKey: .timeout) ?? 10 environment = try values.decodeIfPresent([String: String].self, forKey: .environment) ?? [:] @@ -89,6 +104,88 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable { guard processes >= 0 else { throw DecodingError.dataCorruptedError(forKey: .processes, in: values, debugDescription: "A provider's processes must be zero or more.") } + if let url, url.scheme?.lowercased() != "https" { + throw DecodingError.dataCorruptedError(forKey: .url, in: values, debugDescription: "A provider url must use https.") + } + } +} + +/// What an `http` provider copies from its JSON response, each part found by a JSON Pointer such as +/// `/current/temperature_2m`. A pointer that finds nothing leaves its part out. +struct HTTPOutput: Decodable, Equatable, Sendable { + let text: String? + let fields: [String: String] + let values: [String: String] + /// Pointers to arrays: each object in one becomes a row of its members that are strings, numbers or booleans. + let lists: [String: String] + + enum CodingKeys: String, CodingKey, CaseIterable { case text, fields, values, lists } + + init(from decoder: Decoder) throws { + try decoder.rejectUnknownKeys(CodingKeys.self) + let container = try decoder.container(keyedBy: CodingKeys.self) + text = try container.decodeIfPresent(String.self, forKey: .text) + fields = try container.decodeIfPresent([String: String].self, forKey: .fields) ?? [:] + values = try container.decodeIfPresent([String: String].self, forKey: .values) ?? [:] + lists = try container.decodeIfPresent([String: String].self, forKey: .lists) ?? [:] + for pointer in [text ?? ""] + fields.values + values.values + lists.values where !pointer.isEmpty && !pointer.hasPrefix("/") { + throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, + debugDescription: "A JSON Pointer starts with /, unlike \(pointer).")) + } + } + + func output(from response: ConfigurationValue) -> ScriptOutput { + ScriptOutput(text: text.flatMap { response.value(at: $0)?.text } ?? "", + fields: fields.compactMapValues { response.value(at: $0)?.text }, + lists: lists.compactMapValues { pointer in + guard case let .array(rows)? = response.value(at: pointer) else { return nil } + return rows.compactMap { row in + guard case let .object(members) = row else { return nil } + return members.compactMapValues(\.text) + } + }, + values: values.compactMapValues { response.value(at: $0)?.number }) + } +} + +extension ConfigurationValue { + /// The value that a JSON Pointer (RFC 6901) such as `/items/0/name` finds, or nil when there is none. + func value(at pointer: String) -> ConfigurationValue? { + var value = self + for token in pointer.split(separator: "/", omittingEmptySubsequences: false).dropFirst() { + let key = token.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~") + switch value { + case let .object(object): + guard let member = object[key] else { return nil } + value = member + case let .array(array): + guard let index = Int(key), String(index) == key, array.indices.contains(index) else { return nil } + value = array[index] + default: + return nil + } + } + return value + } + + /// A string, a number as JSON writes it, or `true` or `false`. + fileprivate var text: String? { + switch self { + case let .string(string): string + case let .number(number): Int(exactly: number).map(String.init) ?? String(number) + case let .bool(bool): String(bool) + default: nil + } + } + + /// A number, or a string that holds a finite one, as some APIs send prices. `Double` also reads `NaN` and + /// `1e400`, which JSON, and so `--query`, can't hold. + fileprivate var number: Double? { + switch self { + case let .number(number): number + case let .string(string): if let number = Double(string), number.isFinite { number } else { nil } + default: nil + } } } diff --git a/Sources/StableBar/ScriptWidget.swift b/Sources/StableBar/ScriptWidget.swift index a7fcf68b..684a5117 100644 --- a/Sources/StableBar/ScriptWidget.swift +++ b/Sources/StableBar/ScriptWidget.swift @@ -8,13 +8,7 @@ struct ScriptEvent: Sendable { var environment: [String: String] = [:] func commandEnvironment(_ configured: [String: String], secret: @Sendable (String) -> String = packageSecret) async -> [String: String] { - // A source's token belongs to its requests only; configuration can't read it. - let resolved = configured.mapValues { value in - guard value.hasPrefix("@secret.") else { return value } - let account = String(value.dropFirst("@secret.".count)) - return account.hasPrefix("source:") ? "" : secret(account) - } - var variables = resolved.merging(environment) { _, event in event } + var variables = configured.mapValues { secretValue($0, secret: secret) }.merging(environment) { _, event in event } variables["NAME"] = configured["NAME"] variables["CONFIG_DIR"] = configured["CONFIG_DIR"] variables["STABLEBAR"] = configured["STABLEBAR"] @@ -24,6 +18,14 @@ struct ScriptEvent: Sendable { } } +/// `value`, or the saved token that a `@secret.` reference such as `@secret.github/token` names. +func secretValue(_ value: String, secret: (String) -> String = packageSecret) -> String { + guard value.hasPrefix("@secret.") else { return value } + let account = String(value.dropFirst("@secret.".count)) + // A source's token belongs to its requests only; configuration can't read it. + return account.hasPrefix("source:") ? "" : secret(account) +} + struct WidgetMenuItem: Decodable, Equatable, Sendable { let title: String var detail: String? diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index fd19a443..63afc04f 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -169,6 +169,10 @@ enum WidgetPackageError: LocalizedError { case checksumMismatch(String) case archiveMismatch(String, String) case misplacedSecret(String) + case undeclaredHost(String, String) + case tokenInRequest(String, String) + case foreignToken(String, String, String) + case foreignHeaders(String, String, String) var errorDescription: String? { switch self { @@ -193,7 +197,14 @@ enum WidgetPackageError: LocalizedError { case let .downloadFailed(url, status): "Downloading \(url) failed with HTTP status \(status)." case let .checksumMismatch(id): "The archive of package \(id) does not match the store's checksum." case let .archiveMismatch(id, version): "The archive of package \(id) \(version) contains a different id or version." - case let .misplacedSecret(reference): "\(reference) can be used only as a whole environment value of a widget or provider that its own package defines." + case let .misplacedSecret(reference): "\(reference) can be used only as a whole environment value of a widget or provider, or as the token of a provider, that its own package defines." + case let .undeclaredHost(provider, url): "Provider \(provider) requests \(url), but the package's hosts don't list its host." + case let .tokenInRequest(package, provider): + "Package \(package) must write out the url and headers of provider \(provider), without @token. references." + case let .foreignToken(package, provider, url): + "Package \(package) points provider \(provider) at \(url), but the provider can send a token that isn't a secret of package \(package)." + case let .foreignHeaders(package, provider, url): + "Package \(package) points provider \(provider) at \(url), but the provider can send headers that package \(package) doesn't set." } } } @@ -762,7 +773,9 @@ private func rejectCommandKeys(_ value: ConfigurationValue) throws { func validateSecretReferences(_ value: ConfigurationValue, package id: String, path: [String] = []) throws { switch value { case let .string(string) where string.hasPrefix("@secret."): - guard string.hasPrefix("@secret.\(id)/"), path.count == 4, ["widgets", "providers"].contains(path[0]), path[2] == "environment" else { + let environment = path.count == 4 && ["widgets", "providers"].contains(path[0]) && path[2] == "environment" + let token = path.count == 3 && path[0] == "providers" && path[2] == "token" + guard string.hasPrefix("@secret.\(id)/"), environment || token else { throw WidgetPackageError.misplacedSecret(string) } case let .object(object): @@ -773,6 +786,59 @@ func validateSecretReferences(_ value: ConfigurationValue, package id: String, p } } +/// Throws when a provider of the package, or of one of its profiles, doesn't write out its `url` and `headers`, +/// or requests a host that the package's `hosts` don't list. +func validatePackageHosts(_ document: [String: ConfigurationValue], manifest: WidgetPackageManifest) throws { + for (name, provider) in try document["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { + guard case let .object(headers) = provider["headers"] ?? .object([:]) else { throw WidgetPackageError.tokenInRequest(manifest.id, name) } + for case let .string(value) in Array(headers.values) + [provider["url"] ?? .null] where value.hasPrefix("@token.") { + throw WidgetPackageError.tokenInRequest(manifest.id, name) + } + guard case let .string(url)? = provider["url"] else { continue } + guard let host = URL(string: url)?.host(), manifest.hosts.contains(host) else { throw WidgetPackageError.undeclaredHost(name, url) } + } + for profile in try document["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { + try validatePackageHosts(profile.configuration, manifest: manifest) + } +} + +/// Throws when a package sets the `url` of a provider, directly or in a profile, while any file or profile gives that provider +/// a token other than one of that package's secrets, or headers that another file sets. +func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: String]) throws { + var definitions = [("providers", layer.values["providers"])] + if case let .array(profiles)? = layer.values["profiles"] { + for case let .object(profile) in profiles { + if case let .string(name)? = profile["name"], case let .object(configuration)? = profile["configuration"] { + definitions.append(("profiles.\(name).configuration.providers", configuration["providers"])) + } + } + } + var urls: [(String, String, String)] = [] + var tokens: [String: [ConfigurationValue?]] = [:] + var headers: [String: [String]] = [:] + for case let (path, .object(providers)?) in definitions { + for case let (name, .object(provider)) in providers { + if case let .string(url)? = provider["url"] { urls.append((name, url, "\(path).\(name).url")) } + tokens[name, default: []].append(provider["token"]) + if case let .object(names)? = provider["headers"] { + headers[name, default: []] += names.keys.map { "\(path).\(name).headers.\($0)" } + } else if case .string? = provider["headers"] { + headers[name, default: []].append("\(path).\(name).headers") + } + } + } + for (name, url, path) in urls { + guard let package = packageIDs[layer.origins[path]!.file] else { continue } + for token in tokens[name]! { + if case let .string(token)? = token, token.hasPrefix("@secret.\(package)/") { continue } + guard token == nil || token == .null else { throw WidgetPackageError.foreignToken(package, name, url) } + } + for header in headers[name, default: []] where packageIDs[layer.origins[header]!.file] != package { + throw WidgetPackageError.foreignHeaders(package, name, url) + } + } +} + private func packageEnvironment(_ definition: [String: ConfigurationValue], directory: URL) -> [String: ConfigurationValue] { var result = definition result["environment"] = .object(["PACKAGE_DIR": .string(directory.path)]).overriding(result["environment"] ?? .object([:])) diff --git a/Tests/StableBarTests/ModuleConfigurationTests.swift b/Tests/StableBarTests/ModuleConfigurationTests.swift index e4a3424a..75f85bda 100644 --- a/Tests/StableBarTests/ModuleConfigurationTests.swift +++ b/Tests/StableBarTests/ModuleConfigurationTests.swift @@ -431,6 +431,10 @@ private func writeConfiguration(_ json: String, to url: URL) throws { (#"{"widgets":[}"#, "The given data was not valid JSON. Unexpected character '}' around line 1, column 13."), (#"{"providers":{"machine":{"type":"sytem"}},"widgets":[]}"#, "providers.machine.type: Unknown provider type."), (#"{"providers":{"feed":{"type":"stream"}},"widgets":[]}"#, "providers.feed: Missing property command."), + (#"{"providers":{"weather":{"type":"http","url":"https://api.open-meteo.com/v1/forecast"}},"widgets":[]}"#, "providers.weather: Missing property output."), + (#"{"providers":{"weather":{"type":"http","url":"http://api.open-meteo.com","output":{}}},"widgets":[]}"#, "providers.weather.url: A provider url must use https."), + (#"{"providers":{"weather":{"type":"http","url":"https://api.open-meteo.com","output":{"text":"current/temperature_2m"}}},"widgets":[]}"#, + "providers.weather.output: A JSON Pointer starts with /, unlike current/temperature_2m."), (#"{"widgets":[{"id":"disk","type":"teleport","position":"right"}]}"#, "widgets.disk: type: Unknown widget type."), (#"{"widgets":[{"id":"disk","type":"provider","provider":"teleport","position":"right"}]}"#, "Unknown provider: teleport."), (#"{"providers":{"status":{"type":"merge","providers":["battery"]}},"widgets":[{"id":"power","type":"battery","position":"right"}]}"#, @@ -477,7 +481,7 @@ private func schemaProperties(_ definition: ConfigurationValue?) throws -> Set Set ProviderConfiguration { - try JSONDecoder().decode(ProviderConfiguration.self, - from: Data(#"{"type":"\#(type.name)","\#(setting.stringValue)":\#(value)}"#.utf8)) + func provider(_ value: String?) throws -> ProviderConfiguration { + let set = value.map { [#""\#(setting.stringValue)":\#($0)"#] } ?? [] + return try JSONDecoder().decode(ProviderConfiguration.self, from: Data("{\((properties + set).joined(separator: ","))}".utf8)) } - #expect(try provider(values.valid) != ProviderConfiguration(type: type.name), "\(type.name).\(setting.stringValue)") + #expect(try provider(values.valid) != provider(nil), "\(type.name).\(setting.stringValue)") #expect(throws: (any Error).self, "\(type.name).\(setting.stringValue)") { try provider(values.invalid) } } } diff --git a/Tests/StableBarTests/ProviderTests.swift b/Tests/StableBarTests/ProviderTests.swift index cd5e006d..6eafec92 100644 --- a/Tests/StableBarTests/ProviderTests.swift +++ b/Tests/StableBarTests/ProviderTests.swift @@ -175,6 +175,52 @@ private func provider(_ command: String, type: String = "stream", interval: Doub #expect(providerRetryDelay(interval: 600, failures: 100) == 600) } +@Test func httpOutputCopiesWhatItsJSONPointersFind() throws { + let response = try JSONDecoder().decode(ConfigurationValue.self, from: Data(#""" + {"current":{"temperature_2m":21.4,"weather_code":3,"is_day":true},"current_units":{"temperature_2m":"°C"}, + "a/b":{"m~n":"escaped"},"price":"67000.12","missingPrice":"NaN","hugePrice":"1e400", + "items":[{"name":"stablebar","stars":12,"archived":false,"owner":{"login":"seb"}},"skipped",{"name":"empty","topics":[]}]} + """#.utf8)) + let output = try JSONDecoder().decode(HTTPOutput.self, from: Data(#""" + {"text":"/current/temperature_2m", + "fields":{"code":"/current/weather_code","day":"/current/is_day","unit":"/current_units/temperature_2m","escaped":"/a~1b/m~0n", + "first":"/items/0/name","missing":"/current/wind","outside":"/items/9/name","object":"/current", + "minusZero":"/items/-0/name","leadingZero":"/items/00/name","plus":"/items/+0/name"}, + "values":{"temperature":"/current/temperature_2m","price":"/price","unit":"/current_units/temperature_2m", + "missingPrice":"/missingPrice","hugePrice":"/hugePrice"}, + "lists":{"repos":"/items","missing":"/repos","object":"/current"}} + """#.utf8)).output(from: response) + #expect(output == ScriptOutput(text: "21.4", fields: ["code": "3", "day": "true", "unit": "°C", "escaped": "escaped", "first": "stablebar"], + lists: ["repos": [["name": "stablebar", "stars": "12", "archived": "false"], ["name": "empty"]]], + values: ["temperature": 21.4, "price": 67000.12])) +} + +@Test @MainActor func anHTTPProviderSendsItsHeadersAndTokenAndReportsAFailedStatus() async throws { + let registry = DataSourceRegistry(types: [.http(session: StubURLProtocol.session())]) + let url = URL(string: "https://api.http-provider.example/weather")! + let body = Data(#"{"current":{"temperature_2m":21.4}}"#.utf8) + StubURLProtocol.serve(body, at: url) + let script = ScriptWidget() + defer { script.stop() } + script.start(provider: try JSONDecoder().decode(ProviderConfiguration.self, from: Data(#""" + {"type":"http","url":"https://api.http-provider.example/weather","headers":{"Accept":"application/json"},"token":"abc", + "output":{"text":"/current/temperature_2m"}} + """#.utf8)), registry: registry) + try await awaitCondition { script.output.text == "21.4" } + let request = try #require(StubURLProtocol.requests.last { $0.url == url }) + #expect(request.value(forHTTPHeaderField: "Accept") == "application/json") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer abc") + #expect(script.diagnostics.lastStdout == String(decoding: body, as: UTF8.self)) + // Configuration can't read a source's token, so this one is empty and no header is sent. + script.start(provider: try JSONDecoder().decode(ProviderConfiguration.self, from: Data(#""" + {"type":"http","url":"https://api.http-provider.example/missing","token":"@secret.source:acme","output":{}} + """#.utf8)), registry: registry) + try await awaitCondition { script.error != nil } + #expect(script.error == "The server answered with HTTP status 404.") + let missing = try #require(StubURLProtocol.requests.last { $0.url?.path() == "/missing" && $0.url?.host() == url.host() }) + #expect(missing.value(forHTTPHeaderField: "Authorization") == nil) +} + @Test func nativeCountersMeasureDeltasAndDiscardResetNetworkCounters() { let before = NetworkCounters(received: 1_000, sent: 2_000) let rates = NetworkCounters(received: 3_000, sent: 8_000).rates(since: before, elapsed: 2) diff --git a/Tests/StableBarTests/StubURLProtocol.swift b/Tests/StableBarTests/StubURLProtocol.swift index ce426c50..2181b965 100644 --- a/Tests/StableBarTests/StubURLProtocol.swift +++ b/Tests/StableBarTests/StubURLProtocol.swift @@ -47,6 +47,8 @@ final class StubURLProtocol: URLProtocol { var next = URLRequest(url: target) next.allHTTPHeaderFields = request.allHTTPHeaderFields client?.urlProtocol(self, wasRedirectedTo: next, redirectResponse: response) + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocolDidFinishLoading(self) return } let response = HTTPURLResponse(url: url, statusCode: data == nil ? 404 : 200, httpVersion: nil, headerFields: nil)! diff --git a/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index f2143cd0..984e4edf 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1515,6 +1515,144 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St } } +@Test func packageProvidersRequestOnlyTheirHostsAndSendTheirSecretAsTheToken() throws { + let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let source = directory.appending(path: "source") + let store = WidgetPackageStore(directory: directory.appending(path: "packages")) + try writePackageFile(#""" + {"id":"github","name":"GitHub","version":"1","kind":"widgets","entry":"config.json","hosts":["api.github.com"], + "settings":{"token":{"type":"secret"}}} + """#, to: source.appending(path: "package.json")) + for (configuration, message) in [ + (#"{"providers":{"issues":{"type":"http","url":"https://example.com/issues","output":{}}}}"#, + "Provider issues requests https://example.com/issues, but the package's hosts don't list its host."), + (#"{"providers":{"issues":{"type":"http","url":"https://api.github.com@example.com/issues","output":{}}}}"#, + "Provider issues requests https://api.github.com@example.com/issues, but the package's hosts don't list its host."), + (#"{"profiles":[{"name":"work","configuration":{"providers":{"issues":{"type":"http","url":"https://example.com","output":{}}}}}]}"#, + "Provider issues requests https://example.com, but the package's hosts don't list its host."), + (#"{"providers":{"issues":{"type":"http","url":"https://api.github.com/issues","headers":{"Authorization":"@setting.token"},"output":{}}}}"#, + "@secret.github/token can be used only as a whole environment value of a widget or provider, or as the token of a provider, that its own package defines."), + (#"{"providers":{"issues":{"type":"http","url":"https://api.github.com/issues","headers":{"Authorization":"@token.auth"},"output":{}}}}"#, + "Package github must write out the url and headers of provider issues, without @token. references."), + (#"{"providers":{"issues":{"type":"http","url":"https://api.github.com/issues","headers":"@token.auth","output":{}}}}"#, + "Package github must write out the url and headers of provider issues, without @token. references."), + (#""" + {"tokens":{"apiURL":"https://api.github.com/issues"},"providers":{"issues":{"type":"http","url":"@token.apiURL","output":{}}}, + "profiles":[{"name":"work","configuration":{"tokens":{"apiURL":"https://example.com"}}}]} + """#, "Package github must write out the url and headers of provider issues, without @token. references.") + ] { + try writePackageFile(configuration, to: source.appending(path: "config.json")) + let error = #expect(throws: WidgetPackageError.self) { try store.inspect(source) } + #expect(error?.localizedDescription == message) + } + try writePackageFile(#""" + {"providers":{"issues":{"type":"http","url":"https://api.github.com/issues","token":"@setting.token", + "output":{"text":"/0/title","lists":{"issues":""}}}}, + "widgets":[{"id":"issues","type":"provider","provider":"issues","position":"right"}]} + """#, to: source.appending(path: "config.json")) + #expect(try store.install(source).commands.isEmpty) + var loader = ConfigurationLoader() + let configuration = try loader.load(directory.appending(path: "config.json"), data: Data(#"{"packages":[{"id":"github","version":"1"}]}"#.utf8)) + #expect(configuration.providers["issues"]?.token == "@secret.github/token") + + let issues = #"{"issues":{"type":"http","url":"https://evil.example/issues","output":{}}}"# + let tokenless = #"{"issues":{"type":"http","url":"https://evil.example/issues","token":null,"output":{}}}"# + let withHeaders = #"{"issues":{"type":"http","url":"https://evil.example/issues","headers":{"Accept":"application/json"},"output":{}}}"# + for (version, document) in [("1", #"{"providers":\#(issues)}"#), + ("2", #"{"profiles":[{"name":"work","configuration":{"providers":\#(issues)}}]}"#), + ("3", #"{"profiles":[{"name":"work","configuration":{"providers":\#(tokenless)}}]}"#), + ("4", #"{"providers":\#(withHeaders)}"#)] { + try writePackageFile(#"{"id":"evil","name":"Evil","version":"\#(version)","kind":"widgets","entry":"config.json","hosts":["evil.example"]}"#, + to: source.appending(path: "package.json")) + try writePackageFile(document, to: source.appending(path: "config.json")) + _ = try store.install(source) + } + let ownIssues = #""providers":{"issues":{"type":"http","url":"https://api.github.com/issues","token":"@secret.github/token","output":{}}}"# + let tokenInProfile = #""" + "providers":{"issues":{"type":"http","url":"https://api.github.com/issues","output":{}}}, + "profiles":[{"name":"mine","configuration":{"providers":{"issues":{"token":"@secret.github/token"}}}}] + """# + let typedToken = #""providers":{"issues":{"type":"http","url":"https://api.github.com/issues","token":"ghp_typed","output":{}}}"# + for configuration in [#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"1"}]}"#, + #"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"2"}]}"#, + #"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"3"}]}"#, + #"{"packages":[{"id":"evil","version":"2"}],\#(ownIssues)}"#, + #"{"packages":[{"id":"evil","version":"2"}],\#(tokenInProfile)}"#, + #"{"packages":[{"id":"evil","version":"2"}],\#(typedToken)}"#] { + let error = #expect(throws: WidgetPackageError.self) { + try loader.load(directory.appending(path: "config.json"), data: Data(configuration.utf8)) + } + #expect(error?.localizedDescription == "Package evil points provider issues at https://evil.example/issues, " + + "but the provider can send a token that isn't a secret of package evil.") + } + let typedHeader = #"{"packages":[{"id":"evil","version":"4"}],"providers":{"issues":{"headers":{"Authorization":"Bearer ghp_typed"}}}}"# + let headersToken = #""" + {"packages":[{"id":"evil","version":"2"}],"tokens":{"auth":{"Authorization":"Bearer ghp_typed"}}, + "providers":{"issues":{"type":"http","url":"https://api.github.com/issues","headers":"@token.auth","output":{}}}} + """# + for configuration in [typedHeader, headersToken] { + let error = #expect(throws: WidgetPackageError.self) { + try loader.load(directory.appending(path: "config.json"), data: Data(configuration.utf8)) + } + #expect(error?.localizedDescription == "Package evil points provider issues at https://evil.example/issues, " + + "but the provider can send headers that package evil doesn't set.") + } + let ownHeaders = try loader.load(directory.appending(path: "config.json"), data: Data(#"{"packages":[{"id":"evil","version":"4"}]}"#.utf8)) + #expect(ownHeaders.providers["issues"]?.headers == ["Accept": "application/json"]) + let withoutToken = try loader.load(directory.appending(path: "config.json"), data: Data(#"{"packages":[{"id":"evil","version":"1"}]}"#.utf8)) + #expect(withoutToken.providers["issues"]?.url == URL(string: "https://evil.example/issues")) + #expect(withoutToken.providers["issues"]?.token == nil) + let pointed = try loader.load(directory.appending(path: "config.json"), data: Data(#""" + {"packages":[{"id":"github","version":"1"}],"tokens":{"elsewhere":"https://example.com/issues","accept":{"Accept":"application/json"}}, + "providers":{"issues":{"url":"@token.elsewhere","headers":"@token.accept"}}} + """#.utf8)) + #expect(pointed.providers["issues"]?.url == URL(string: "https://example.com/issues")) + #expect(pointed.providers["issues"]?.headers == ["Accept": "application/json"]) + #expect(pointed.providers["issues"]?.token == "@secret.github/token") +} + +@Test @MainActor func aPackageProviderFollowsNoRedirectOutsideItsHosts() async throws { + let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let source = directory.appending(path: "source") + try writePackageFile(#"{"id":"weather","name":"Weather","version":"1","kind":"widgets","entry":"config.json","hosts":["api.package-redirect.example"]}"#, + to: source.appending(path: "package.json")) + try writePackageFile(#"{"providers":{"weather":{"type":"http","url":"https://api.package-redirect.example/now","output":{"text":"/text"}}}}"#, + to: source.appending(path: "config.json")) + _ = try WidgetPackageStore(directory: directory.appending(path: "packages")).install(source) + var loader = ConfigurationLoader() + let providers = try loader.load(directory.appending(path: "config.json"), data: Data(#""" + {"packages":[{"id":"weather","version":"1"}], + "providers":{"mine":{"type":"http","url":"https://api.package-redirect.example/now","output":{"text":"/text"}}}} + """#.utf8)).providers + let away = URL(string: "https://elsewhere.package-redirect.example/now")! + StubURLProtocol.redirect(URL(string: "https://api.package-redirect.example/now")!, to: away) + StubURLProtocol.serve(Data(#"{"text":"moved"}"#.utf8), at: away) + let registry = DataSourceRegistry(types: [.http(session: StubURLProtocol.session())]) + let script = ScriptWidget() + defer { script.stop() } + + script.start(provider: providers["mine"]!, registry: registry) + try await awaitCondition { script.output.text == "moved" } + let followed = StubURLProtocol.requests.filter { $0.url == away }.count + script.start(provider: providers["weather"]!, registry: registry) + try await awaitCondition { script.error != nil } + #expect(script.error == "The server answered with HTTP status 302.") + #expect(StubURLProtocol.requests.filter { $0.url == away }.count == followed) + + let url = directory.appending(path: "config.json") + try Data(#"{"packages":[{"id":"weather","version":"1"}],"providers":{"weather":{"url":"https://api.package-redirect.example/now"}}}"#.utf8) + .write(to: url) + let store = BarStore(configurationURL: url) + defer { store.stop() } + store.reloadConfiguration() + #expect(store.configuration?.providers["weather"]?.hosts == nil) + try Data(#"{"packages":[{"id":"weather","version":"1"}]}"#.utf8).write(to: url) + store.reloadConfiguration() + #expect(store.configuration?.providers["weather"]?.hosts == ["api.package-redirect.example"]) +} + @Test func manifestsDeclareWhatAPackageNeedsAndKeepTheirScreenshotInside() throws { let directory = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } diff --git a/docs/packages.md b/docs/packages.md index e2fee3c1..e3849688 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -31,9 +31,9 @@ A package is a folder containing `package.json`, its configuration, and any scri Settings support `string`, `number`, `bool` and `secret`. The first three need a matching `default`. Settings lists them in the order `package.json` gives them, each with its `title`, or its name without one. An optional `description` explains a field in the interface. String settings can declare a nonempty `choices` array to show a picker; both the default and supplied values must be among those choices. [package.schema.json](../package.schema.json) describes the manifest and setting fields; StableBar also validates their types and allowed values. Reference a setting as a whole value, such as `"fontSize": "@setting.fontSize"` or `"environment": { "FORMAT": "@setting.format" }`. Put settings needed by shell commands in environment variables and quote them normally in the script. -A `secret` setting, such as `"token": { "type": "secret", "title": "GitHub token" }`, holds an API token and has no `default` or `choices`. Reference it only as a whole value in the `environment` of a widget or provider the package defines, such as `"environment": { "GITHUB_TOKEN": "@setting.token" }`; templates, profiles and the top-level `environment` cannot use it. Type it in **Settings → Store**; **Open package** in a widget's Content inspector opens that package page. For an active package, choose **Save credentials**; ordinary setting changes do not save credentials. For a package being added, **Add to bar** applies its configuration and then saves the credentials. An error stays visible if the credential write fails. The field shows whether a token is saved without revealing it. StableBar keeps it in the login Keychain, never in a configuration file, and `--query` and Settings show `@secret./` in its place. Commands receive the token when they start, or an empty value when none is saved. **Remove** next to a saved token schedules its deletion for the next credential save or add operation. The token belongs to the package ID, so a new version keeps it, and a package selection cannot set it in `settings`. Builds that are not signed with a Developer ID, which includes current releases and local builds, change their signature with every update, so macOS asks whether StableBar may use its Keychain item the first time a command needs the token after an update; choose **Always Allow** to stop the question until the next update. +A `secret` setting, such as `"token": { "type": "secret", "title": "GitHub token" }`, holds an API token and has no `default` or `choices`. Reference it only as a whole value in the `environment` of a widget or provider the package defines, such as `"environment": { "GITHUB_TOKEN": "@setting.token" }`, or as the `token` of an [`http` provider](providers.md#http) it defines; templates, profiles and the top-level `environment` cannot use it. Type it in **Settings → Store**; **Open package** in a widget's Content inspector opens that package page. For an active package, choose **Save credentials**; ordinary setting changes do not save credentials. For a package being added, **Add to bar** applies its configuration and then saves the credentials. An error stays visible if the credential write fails. The field shows whether a token is saved without revealing it. StableBar keeps it in the login Keychain, never in a configuration file, and `--query` and Settings show `@secret./` in its place. Commands receive the token when they start, or an empty value when none is saved; an `http` provider reads it for each request and sends none while none is saved. **Remove** next to a saved token schedules its deletion for the next credential save or add operation. The token belongs to the package ID, so a new version keeps it, and a package selection cannot set it in `settings`. Builds that are not signed with a Developer ID, which includes current releases and local builds, change their signature with every update, so macOS asks whether StableBar may use its Keychain item the first time a command needs the token after an update; choose **Always Allow** to stop the question until the next update. -A secret keeps the token out of configuration files, `--query` and Settings. It does not protect it from other packages: a package that runs commands can still reach a secret through StableBar, for example by overriding another package's widget. Install packages with commands only from sources you trust. A command that prints its token still shows it in its output and in Status, and programs running under your account can reach a secret through StableBar too, since they can edit your configuration. +A secret keeps the token out of configuration files, `--query` and Settings. It does not protect it from other packages that run commands: such a package can still reach a secret through StableBar, for example by overriding another package's widget. Install packages with commands only from sources you trust. A package that sets the `url` of an [`http` provider](providers.md#http) fails to load when any file or profile gives that provider a token other than one of the package's own secrets, such as another package's secret or a token typed into your configuration, or when a file other than the package's sets the provider's `headers`. A package must also write out its `http` providers' `url` and `headers` itself, without `@token.` references. A command that prints its token still shows it in its output and in Status, and programs running under your account can reach a secret through StableBar too, since they can edit your configuration. Widgets, templates and providers receive `PACKAGE_DIR`, the absolute path of the installed package, for commands such as `"$PACKAGE_DIR/scripts/clock.sh"`. @@ -63,7 +63,7 @@ Enable an exact installed version in the root configuration: Package selections in modules merge by package ID, with later modules and the root taking precedence. Enabled packages load once before the composed modules and root properties. Root templates, tokens and widget overrides can customize them. Set `enabled` to `false` to stop loading a package; installation alone has no runtime effect. Packages cannot enable other packages. StableBar never updates a package by itself: versions remain pinned until you choose another installed version, and the [store](#store) only tells you about newer ones. -A package whose `package.json` sets `"kind": "widgets"` contains no commands, so it needs no command review. Its configuration can contain only `tokens`, `defaults`, `bar`, `groups`, `profiles`, `widgets`, `templates`, `popups` and `providers`, plus includes inside the package. Nowhere in it, including templates, popups, providers and profiles, can it set `command`, `onClick`, `onClickField`, `rightClick`, `middleClick`, `scrollUp`, `scrollDown`, `mouseEntered`, `mouseExited`, `onChange` or `environment`, so script widgets and `command` or `stream` providers are rejected too. Built-in widget types, native providers, [`open`](widgets.md#mouse-actions), [`openMenuBarItem`](popups.md), [`selectInputSourceField`](popups.md), [`selectOutputDeviceField`](popups.md), a slider's or toggle's [`set`](popups.md) and [`quitField`](popups.md), which asks before it quits anything, remain available, and built-in widgets keep their own behaviour: a `workspaces` widget still talks to AeroSpace, yabai or OmniWM. StableBar checks this when the package is reviewed, installed and loaded, and **Settings → Store** and `--inspect-package` say that it contains no commands instead of listing them. Enable it in `packages` like any widget package. [examples/packages/system-monitor](../examples/packages/system-monitor/config.json) shows CPU in the bar, in the theme's warning colors when the Mac is under strain, and a popup with CPU and memory details and the apps using the most memory or CPU, each with a button that quits it. +A package whose `package.json` sets `"kind": "widgets"` contains no commands, so it needs no command review. Its configuration can contain only `tokens`, `defaults`, `bar`, `groups`, `profiles`, `widgets`, `templates`, `popups` and `providers`, plus includes inside the package. Nowhere in it, including templates, popups, providers and profiles, can it set `command`, `onClick`, `onClickField`, `rightClick`, `middleClick`, `scrollUp`, `scrollDown`, `mouseEntered`, `mouseExited`, `onChange` or `environment`, so script widgets and `command` or `stream` providers are rejected too. Built-in widget types, native providers, [`http` providers](providers.md#http), [`open`](widgets.md#mouse-actions), [`openMenuBarItem`](popups.md), [`selectInputSourceField`](popups.md), [`selectOutputDeviceField`](popups.md), a slider's or toggle's [`set`](popups.md) and [`quitField`](popups.md), which asks before it quits anything, remain available, and built-in widgets keep their own behaviour: a `workspaces` widget still talks to AeroSpace, yabai or OmniWM. StableBar checks this when the package is reviewed, installed and loaded, and **Settings → Store** and `--inspect-package` say that it contains no commands instead of listing them. Enable it in `packages` like any widget package. [examples/packages/system-monitor](../examples/packages/system-monitor/config.json) shows CPU in the bar, in the theme's warning colors when the Mac is under strain, and a popup with CPU and memory details and the apps using the most memory or CPU, each with a button that quits it. ## Store @@ -82,7 +82,7 @@ StableBar --install-package clock --source acme A store package with a newer version is marked **Update available**. Choose **Review update**, review its setup and access, then add the new version; the old version stays installed so you can roll back. When the new version runs commands, contacts hosts or uses macOS permissions that the enabled version does not, StableBar lists them and asks before enabling it. -Every store package is open source in [stablebar-packages](https://github.com/Seb-GRAF/stablebar-packages), and that repository's CI builds and publishes the archives, not the package's author. Themes and packages that contain no commands are published once they pass CI. A maintainer reads every version of a package that runs commands before it is published. StableBar downloads the index and the archives over HTTPS and checks each archive against the SHA-256 in the index before reviewing it. +Every store package is open source in [stablebar-packages](https://github.com/Seb-GRAF/stablebar-packages), and that repository's CI builds and publishes the archives, not the package's author. Themes and packages that contain no commands or `http` providers are published once they pass CI; packages with `http` providers will be too, once the Store's CI supports them. A maintainer reads every version of a package that runs commands before it is published. StableBar downloads the index and the archives over HTTPS and checks each archive against the SHA-256 in the index before reviewing it. These optional `package.json` keys describe a package, and the review shows them: @@ -97,7 +97,7 @@ These optional `package.json` keys describe a package, and the review shows them | `permissions` | macOS permissions: `calendars`, `automation`, `accessibility`, `bluetooth` or `location` | | `hosts` | Hostnames the package contacts, such as `api.github.com` | -StableBar shows `requires`, `permissions` and `hosts` but does not enforce them. For store packages, a maintainer checks them against the code. +StableBar shows `requires`, `permissions` and `hosts`. It enforces `hosts` only for [`http` providers](providers.md#http), whose `url` and redirects must stay on listed hosts; commands can contact any host. For store packages that run commands, a maintainer checks all three against the code. ### Linking to a package diff --git a/docs/providers.md b/docs/providers.md index a7d37a84..50c489ab 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -29,7 +29,7 @@ Define a provider once and reference it from several widgets. StableBar keeps on } ``` -Provider `type` is `command`, `stream`, `system`, `network`, `wifi`, `battery`, `bluetooth`, `audio`, `inputSource`, `microphone`, `privacy`, `calendar`, `disk` or `merge`. `command` and `stream` require a shell `command`, and `merge` the `providers` it combines; see [Merge](#merge). `interval` defaults to 5 seconds: the polling interval for commands, `system` and `network` (60 seconds for `disk` and 120 for `bluetooth`), and for `calendar` until it has access; the first reconnect delay for streams; and for `wifi`, `audio`, `inputSource`, `microphone`, `privacy` and `battery`, which update when macOS reports a change, the first retry delay after a failure. That first delay is `interval`, or 1 second if `interval` is shorter. `timeout` defaults to 10 seconds and applies to command providers; streams remain running until they exit, fail, suspend or stop. Provider intervals and timeouts must be positive and finite. +Provider `type` is `command`, `stream`, `http`, `system`, `network`, `wifi`, `battery`, `bluetooth`, `audio`, `inputSource`, `microphone`, `privacy`, `calendar`, `disk` or `merge`. `command` and `stream` require a shell `command`, `http` a `url` and an `output` (see [HTTP](#http)), and `merge` the `providers` it combines (see [Merge](#merge)). `interval` defaults to 5 seconds: the polling interval for commands, `http`, `system` and `network` (60 seconds for `http` and `disk`, and 120 for `bluetooth`), and for `calendar` until it has access; the first reconnect delay for streams; and for `wifi`, `audio`, `inputSource`, `microphone`, `privacy` and `battery`, which update when macOS reports a change, the first retry delay after a failure. That first delay is `interval`, or 1 second if `interval` is shorter. `timeout` defaults to 10 seconds and applies to command and `http` providers; streams remain running until they exit, fail, suspend or stop. Provider intervals and timeouts must be positive and finite. A widget with `type` set to `system`, `network`, `wifi`, `battery`, `bluetooth`, `audio`, `inputSource`, `microphone`, `privacy`, `calendar` or `disk` uses the provider of that name. Without a definition in `providers`, it is a native provider of that type with default settings, shared by every widget that names it. An implicit `system` provider uses a 2-second interval and lists 5 apps when a consumer enables Essentials details. Define a provider with the same name to change its interval or other settings. `{ "id": "power", "type": "battery", "position": "right" }` is enough for a battery widget. @@ -152,6 +152,59 @@ With access, the provider updates at each minute and phase boundary and when you } ``` +## HTTP + +An `http` provider reads JSON from a web API without running a command, and copies the parts its `output` names into the output its widgets show. Each part is a [JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901) into the response: `/current/temperature_2m` is the `temperature_2m` member of `current`, `/items/0/name` the `name` of the first item, and an empty pointer the whole response. In a member's name, `~1` stands for `/` and `~0` for `~`. + +```json +{ + "providers": { + "weather": { + "type": "http", + "url": "https://api.open-meteo.com/v1/forecast?latitude=47.37&longitude=8.54¤t=temperature_2m", + "interval": 900, + "output": { + "text": "/current/temperature_2m", + "fields": { "unit": "/current_units/temperature_2m" }, + "values": { "temperature": "/current/temperature_2m" } + } + } + }, + "widgets": [ + { + "id": "weather", "type": "provider", "provider": "weather", "position": "right", + "layout": { + "type": "row", + "children": [ + { "type": "field", "field": "text" }, + { "type": "field", "field": "unit" } + ] + } + } + ] +} +``` + +| Setting | Default | Meaning | +| --- | --- | --- | +| `url` | required | The `https` URL to request | +| `output` | required | `text`: a pointer; `fields`, `values` and `lists`: names and their pointers | +| `headers` | none | Headers to send, such as `{ "Accept": "application/json" }` | +| `token` | none | Sent as `Authorization: Bearer `, unless it is empty | +| `interval` | `60` | Seconds between requests | +| `timeout` | `10` | Seconds to wait for the server | + +Output: + +- `text` and `fields`: a string as the response has it, a number as JSON writes it, such as `21.4`, or `true` or `false`. StableBar doesn't round numbers or add units; show a unit the API sends as a field of its own. +- `values`: a number, or a string that holds a finite one, as some price APIs send them. +- `lists`: each object in the array becomes a row of its members that are strings, numbers or booleans. Nested objects and arrays, and items that aren't objects, are left out. +- A pointer that finds nothing, or finds an object or an array where it needs text or a number, leaves its part out: `text` is then empty. + +An answer other than HTTP status 200, or one that isn't JSON, is a failure: the widget keeps its last output, shows the error and retries with backoff, as a command does. **Settings → Status** and `--query` show the last response as the provider's output. Requests keep no cache, and keep cookies only in memory until StableBar quits; a redirect to another host drops the token. `whenVisible` and `events` work as for other providers. + +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), and the package must write out its `url` and any `headers`: `headers`, when present, is an object of strings, and neither can be a `@token.` reference. A `@setting.` reference is filled in before the check. StableBar checks this when it reviews, installs and loads the package, and the provider follows no redirect to a host that the package doesn't list: it fails with the redirect's HTTP status instead. A package that sets the `url` of a provider, directly or in a profile, fails to load when any file or profile gives that provider a `token` other than one of the package's own secrets or `null`, such as another package's secret like `@secret.github/token` or a token typed into your configuration, or when a file other than the package's sets the provider's `headers`, such as an `Authorization` header or a `@token.` reference in your configuration. StableBar doesn't check whether those profiles can be active together. Your own configuration can still point a provider anywhere, with `@token.` references too, and its token goes along. A package can set `token` to a [`secret` setting](packages.md#local-widget-packages), such as `"token": "@setting.token"`, so the token stays in the Keychain. A `"kind": "widgets"` package, which runs no commands, can define `http` providers: [examples/packages/weather](../examples/packages/weather/config.json) shows the temperature from Open-Meteo. + ## Merge A `merge` provider combines the providers it names in `providers`, so one widget can show several of them, such as the battery, the network and the volume. Its output holds each one's `values`, `fields`, `lists` and `series` under the provider's name and a dot, such as `power.percent`, `net.downloadRate` and `sound.volume`. Each one's `text`, and its `icon` and `tooltip` when it has them, become fields under its name too, unless it has a field of that name: `power.icon` is the battery's own symbol, which shows the charge in quarters and a bolt while charging, and `power.tooltip` its percentage with the time left. The merge has no `text`, `icon` or `tooltip` of its own, so give its widget a `layout`. Each one's `temporary` fields show under its name for as long as they last, such as `sound.changedVolume` for 1.5 seconds after the volume changes, until another one's temporary output replaces them: `{ "type": "field", "field": "sound.changedVolume", "hideWhenEmpty": "sound.changedVolume" }` shows the new volume beside the speaker. Layouts, popups, `hoverLayout` and `rules` read these names as they read any other. diff --git a/examples/packages/weather/config.json b/examples/packages/weather/config.json new file mode 100644 index 00000000..8ab531b5 --- /dev/null +++ b/examples/packages/weather/config.json @@ -0,0 +1,32 @@ +{ + "tokens": { + "warning": { "light": "#c93400", "dark": "#ffb340" } + }, + "providers": { + "weather": { + "type": "http", + "url": "https://api.open-meteo.com/v1/forecast?latitude=47.37&longitude=8.54¤t=temperature_2m", + "interval": 900, + "output": { + "text": "/current/temperature_2m", + "fields": { "unit": "/current_units/temperature_2m" }, + "values": { "temperature": "/current/temperature_2m" } + } + } + }, + "widgets": [ + { + "id": "weather", "type": "provider", "provider": "weather", "position": "right", + "style": { "states": { "warning": { "foreground": "@token.warning" } } }, + "layout": { + "type": "row", "style": { "spacing": 4 }, + "children": [ + { "type": "symbol", "name": "thermometer.medium" }, + { "type": "field", "field": "text" }, + { "type": "field", "field": "unit" } + ] + }, + "rules": [{ "when": { "value": "temperature", "below": 0 }, "state": "warning" }] + } + ] +} diff --git a/examples/packages/weather/package.json b/examples/packages/weather/package.json new file mode 100644 index 00000000..68bf184c --- /dev/null +++ b/examples/packages/weather/package.json @@ -0,0 +1,9 @@ +{ + "id": "weather", + "name": "Weather", + "version": "1.0.0", + "kind": "widgets", + "entry": "config.json", + "description": "The temperature in Zurich from Open-Meteo, read without a script.", + "hosts": ["api.open-meteo.com"] +} diff --git a/stablebar.schema.json b/stablebar.schema.json index 9d4153a4..b461bc1b 100644 --- a/stablebar.schema.json +++ b/stablebar.schema.json @@ -1943,6 +1943,7 @@ "enum": [ "command", "stream", + "http", "system", "network", "wifi", @@ -1974,11 +1975,50 @@ }, "interval": { "$ref": "#/definitions/number", - "description": "Seconds between updates for command, system, network and disk providers, and for calendar until it has access; for stream, audio and battery, the first retry delay after a failure, which is at least 1 second. Disk providers default to 60 seconds, the others to 5." + "description": "Seconds between updates for command, http, system, network and disk providers, and for calendar until it has access; for stream, audio and battery, the first retry delay after a failure, which is at least 1 second. Http and disk providers default to 60 seconds, the others to 5." }, "timeout": { "$ref": "#/definitions/number" }, + "url": { + "anyOf": [ + { + "type": "string", + "pattern": "^https://" + }, + { + "$ref": "#/definitions/reference" + }, + { + "type": "null" + } + ], + "description": "The https URL an http provider requests. In a package, its host must be in the package's hosts." + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "HTTP headers an http provider sends with each request." + }, + "token": { + "$ref": "#/definitions/string", + "description": "Sent by an http provider as Authorization: Bearer. A package can set it to a secret setting." + }, + "output": { + "anyOf": [ + { + "$ref": "#/definitions/httpOutput" + }, + { + "$ref": "#/definitions/reference" + }, + { + "type": "null" + } + ] + }, "environment": { "$ref": "#/definitions/environment" }, @@ -2008,6 +2048,37 @@ } } }, + "httpOutput": { + "type": "object", + "additionalProperties": false, + "description": "The parts of an http provider's JSON response its output copies, each found by a JSON Pointer such as /current/temperature_2m.", + "properties": { + "text": { + "$ref": "#/definitions/string" + }, + "fields": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Field names and the pointers to their values." + }, + "values": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Value names and the pointers to their numbers, or to strings that hold numbers." + }, + "lists": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "List names and the pointers to their arrays. Each object in an array becomes a row of its string, number and boolean members." + } + } + }, "group": { "type": "object", "additionalProperties": false,