From 326c5bcdb1e2e7a8f189f146e3dbaad6653d9829 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:03:27 +0100 Subject: [PATCH 01/19] feat: add an http provider so network widgets need no commands --- Sources/StableBar/ConfigurationLoader.swift | 1 + Sources/StableBar/DataSourceRegistry.swift | 36 ++++++- Sources/StableBar/ProviderConfiguration.swift | 96 ++++++++++++++++++- Sources/StableBar/ScriptWidget.swift | 16 ++-- Sources/StableBar/WidgetPackage.swift | 19 +++- .../ModuleConfigurationTests.swift | 21 ++-- Tests/StableBarTests/ProviderTests.swift | 44 +++++++++ Tests/StableBarTests/ThemePackageTests.swift | 34 +++++++ docs/packages.md | 6 +- docs/providers.md | 55 ++++++++++- examples/packages/weather/config.json | 28 ++++++ examples/packages/weather/package.json | 9 ++ stablebar.schema.json | 62 +++++++++++- 13 files changed, 404 insertions(+), 23 deletions(-) create mode 100644 examples/packages/weather/config.json create mode 100644 examples/packages/weather/package.json diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index 2ab8f63c..3b08c98f 100644 --- a/Sources/StableBar/ConfigurationLoader.swift +++ b/Sources/StableBar/ConfigurationLoader.swift @@ -856,6 +856,7 @@ struct ConfigurationLoader: Sendable { } } try validateSecretReferences(.object(layer.values), package: manifest.id) + try validatePackageHosts(layer.values, hosts: manifest.hosts) layer.values = try preparePackageDocument(layer.values, directory: directory) for source in layer.origins.values { packageNames[source.file] = manifest.name diff --git a/Sources/StableBar/DataSourceRegistry.swift b/Sources/StableBar/DataSourceRegistry.swift index d0ecc564..9be76ee6 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 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) + 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/ProviderConfiguration.swift b/Sources/StableBar/ProviderConfiguration.swift index 22b93caa..30d8b04d 100644 --- a/Sources/StableBar/ProviderConfiguration.swift +++ b/Sources/StableBar/ProviderConfiguration.swift @@ -22,16 +22,25 @@ 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? enum CodingKeys: String, CodingKey, CaseIterable { case type, command, interval, timeout, environment, whenVisible, events, calendars, lookahead, 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 = [:] @@ -59,6 +68,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) ?? [:] @@ -86,6 +99,87 @@ 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), 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 one, as some APIs send prices. + fileprivate var number: Double? { + switch self { + case let .number(number): number + case let .string(string): Double(string) + default: nil + } } } diff --git a/Sources/StableBar/ScriptWidget.swift b/Sources/StableBar/ScriptWidget.swift index 4fb0f601..332bda88 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["SENDER"] = sender @@ -22,6 +16,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 403aed78..6fde17b0 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -169,6 +169,7 @@ enum WidgetPackageError: LocalizedError { case checksumMismatch(String) case archiveMismatch(String, String) case misplacedSecret(String) + case undeclaredHost(String, String) var errorDescription: String? { switch self { @@ -193,7 +194,8 @@ 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." } } } @@ -742,7 +744,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): @@ -753,6 +757,17 @@ func validateSecretReferences(_ value: ConfigurationValue, package id: String, p } } +/// Throws when a provider of the package, or of one of its profiles, requests a host that `hosts` doesn't list. +func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [String]) throws { + for (name, provider) in try document["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { + guard case let .string(url)? = provider["url"] else { continue } + guard let host = URL(string: url)?.host(), hosts.contains(host) else { throw WidgetPackageError.undeclaredHost(name, url) } + } + for profile in try document["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { + try validatePackageHosts(profile.configuration, hosts: hosts) + } +} + 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 fbb213ed..a588b185 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"}]}"#, @@ -476,7 +480,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 ffcc6e2e..062cb73d 100644 --- a/Tests/StableBarTests/ProviderTests.swift +++ b/Tests/StableBarTests/ProviderTests.swift @@ -175,6 +175,50 @@ 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", + "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"}, + "values":{"temperature":"/current/temperature_2m","price":"/price","unit":"/current_units/temperature_2m"}, + "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/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index 4fbd80d6..32f88818 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1515,6 +1515,40 @@ 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.") + ] { + 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") +} + @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 cf51414b..8595e643 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -31,7 +31,7 @@ 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. @@ -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 @@ -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` must be on a listed host; 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 fb13ed05..009aaa89 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. @@ -149,6 +149,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 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 cookies or cache, and 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), which StableBar checks when it reviews, installs and loads the package; your own configuration can still point a package's provider elsewhere. 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..78df285c --- /dev/null +++ b/examples/packages/weather/config.json @@ -0,0 +1,28 @@ +{ + "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", "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 5a91648b..876dfdcb 100644 --- a/stablebar.schema.json +++ b/stablebar.schema.json @@ -1903,6 +1903,7 @@ "enum": [ "command", "stream", + "http", "system", "network", "wifi", @@ -1934,11 +1935,39 @@ }, "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": { + "$ref": "#/definitions/string", + "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" }, @@ -1965,6 +1994,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, From 143e455307c23d52306521e4d1299134724a728a Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:50:36 +0100 Subject: [PATCH 02/19] fix: leave out an http value whose string holds NaN or infinity --- Sources/StableBar/ProviderConfiguration.swift | 5 +++-- Tests/StableBarTests/ProviderTests.swift | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/StableBar/ProviderConfiguration.swift b/Sources/StableBar/ProviderConfiguration.swift index 30d8b04d..1415cbb7 100644 --- a/Sources/StableBar/ProviderConfiguration.swift +++ b/Sources/StableBar/ProviderConfiguration.swift @@ -173,11 +173,12 @@ extension ConfigurationValue { } } - /// A number, or a string that holds one, as some APIs send prices. + /// 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): Double(string) + case let .string(string): if let number = Double(string), number.isFinite { number } else { nil } default: nil } } diff --git a/Tests/StableBarTests/ProviderTests.swift b/Tests/StableBarTests/ProviderTests.swift index 062cb73d..5413004d 100644 --- a/Tests/StableBarTests/ProviderTests.swift +++ b/Tests/StableBarTests/ProviderTests.swift @@ -178,14 +178,15 @@ private func provider(_ command: String, type: String = "stream", interval: Doub @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", + "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"}, - "values":{"temperature":"/current/temperature_2m","price":"/price","unit":"/current_units/temperature_2m"}, + "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"], From a067a12a5dd079b6a25c0038b7a3a7e9b2645f67 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:50:37 +0100 Subject: [PATCH 03/19] docs: say http cookies stay in memory and a package with hosts can redirect a provider's token --- docs/packages.md | 2 +- docs/providers.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/packages.md b/docs/packages.md index 8595e643..d7ecb9f3 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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: a package that runs commands can still reach a secret through StableBar, for example by overriding another package's widget, and a package that lists `hosts` can point another package's `http` provider, with its token, at one of them. Install packages with commands or hosts 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. Widgets, templates and providers receive `PACKAGE_DIR`, the absolute path of the installed package, for commands such as `"$PACKAGE_DIR/scripts/clock.sh"`. diff --git a/docs/providers.md b/docs/providers.md index 009aaa89..291bdf54 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -198,9 +198,9 @@ Output: - `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 cookies or cache, and a redirect to another host drops the token. `whenVisible` and `events` work as for other providers. +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), which StableBar checks when it reviews, installs and loads the package; your own configuration can still point a package's provider elsewhere. 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. +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), which StableBar checks when it reviews, installs and loads the package. Your own configuration can still point a package's provider elsewhere, and so can another package, at a host it lists; the provider's 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 From 80e8b863171b4357b70f2ef883b76a3411d76065 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 08:06:15 +0100 Subject: [PATCH 04/19] fix: refuse a package that sends another package's token to a host that package doesn't list --- Sources/StableBar/ConfigurationLoader.swift | 4 ++++ Sources/StableBar/WidgetPackage.swift | 22 ++++++++++++++++++++ Tests/StableBarTests/ThemePackageTests.swift | 20 ++++++++++++++++++ docs/packages.md | 2 +- docs/providers.md | 2 +- 5 files changed, 48 insertions(+), 2 deletions(-) diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index 3b08c98f..20dc088e 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. @@ -510,6 +511,7 @@ struct ConfigurationLoader: Sendable { packageBoundaries = [:] packageNames = [:] packageIDs = [:] + packageHosts = [:] widgetPackageNames = [:] widgetPackageIDs = [:] builtInWidgetIDs = [] @@ -531,6 +533,7 @@ struct ConfigurationLoader: Sendable { for selection in try base.values["packages"]?.decoded([WidgetPackageSelection].self, at: "packages") ?? [] where selection.enabled { try layer.merge(readSelectedPackage(selection, from: packageStore, theme: false)) } + try validateTokenHosts(layer, hosts: packageHosts, packageIDs: packageIDs) if themesDirectory != nil { try layer.merge(readBundledTheme(WidgetPackageSelection(id: "built-in"))) } @@ -862,6 +865,7 @@ struct ConfigurationLoader: Sendable { packageNames[source.file] = manifest.name packageIDs[source.file] = manifest.id } + packageHosts[manifest.id] = manifest.hosts return layer } } diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index 6fde17b0..85c9c4c0 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -170,6 +170,7 @@ enum WidgetPackageError: LocalizedError { case archiveMismatch(String, String) case misplacedSecret(String) case undeclaredHost(String, String) + case undeclaredTokenHost(String, String, String, String) var errorDescription: String? { switch self { @@ -196,6 +197,8 @@ enum WidgetPackageError: LocalizedError { 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, 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 .undeclaredTokenHost(package, provider, url, owner): + "Package \(package) points provider \(provider) at \(url), but the provider sends the token of package \(owner), whose hosts don't list that host." } } } @@ -768,6 +771,25 @@ func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [Stri } } +/// Throws when a provider of the merged package layers, or of one of their profiles, sends a package's secret as its token +/// to a host that package's `hosts` don't list, such as one another package points it at. +func validateTokenHosts(_ layer: ConfigurationLayer, hosts: [String: [String]], packageIDs: [String: String]) throws { + let providers = try layer.values["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] + var urls = providers.map { name, provider in (name, provider["url"], "providers.\(name).url") } + for profile in try layer.values["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { + for (name, provider) in try profile.configuration["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { + urls.append((name, provider["url"], "profiles.\(profile.name).configuration.providers.\(name).url")) + } + } + for case let (name, .string(url)?, path) in urls { + guard case let .string(token)? = providers[name]?["token"], token.hasPrefix("@secret.") else { continue } + let owner = String(token.dropFirst("@secret.".count).prefix { $0 != "/" }) + guard let host = URL(string: url)?.host(), hosts[owner]!.contains(host) else { + throw WidgetPackageError.undeclaredTokenHost(packageIDs[layer.origins[path]!.file]!, name, url, owner) + } + } +} + 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/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index 32f88818..b4552c5a 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1547,6 +1547,26 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St 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":{}}}"# + for (version, document) in [("1", #"{"providers":\#(issues)}"#), + ("2", #"{"profiles":[{"name":"work","configuration":{"providers":\#(issues)}}]}"#)] { + 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 error = #expect(throws: WidgetPackageError.self) { + try loader.load(directory.appending(path: "config.json"), + data: Data(#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"\#(version)"}]}"#.utf8)) + } + #expect(error?.localizedDescription == "Package evil points provider issues at https://evil.example/issues, " + + "but the provider sends the token of package github, whose hosts don't list that host.") + } + let pointed = try loader.load(directory.appending(path: "config.json"), data: Data(#""" + {"packages":[{"id":"github","version":"1"}],"providers":{"issues":{"url":"https://example.com/issues"}}} + """#.utf8)) + #expect(pointed.providers["issues"]?.url == URL(string: "https://example.com/issues")) + #expect(pointed.providers["issues"]?.token == "@secret.github/token") } @Test func manifestsDeclareWhatAPackageNeedsAndKeepTheirScreenshotInside() throws { diff --git a/docs/packages.md b/docs/packages.md index d7ecb9f3..f2efc60d 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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, and a package that lists `hosts` can point another package's `http` provider, with its token, at one of them. Install packages with commands or hosts 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. An [`http` provider](providers.md#http) that sends a package's token must request one of that package's `hosts`, so a package that points it at another host fails to load. 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"`. diff --git a/docs/providers.md b/docs/providers.md index 291bdf54..8da5465c 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -200,7 +200,7 @@ Output: 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), which StableBar checks when it reviews, installs and loads the package. Your own configuration can still point a package's provider elsewhere, and so can another package, at a host it lists; the provider's 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. +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), which StableBar checks when it reviews, installs and loads the package. A provider whose `token` is a package's secret must also request one of that package's hosts once all packages are loaded, profiles included: a package that points another package's provider, with its token, at a host that package doesn't list fails to load. Your own configuration can still point a package's provider anywhere, 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 From 4dc674c3f572c7208f92f3420b647573b46cd50b Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:02:25 +0100 Subject: [PATCH 05/19] fix: check a package's provider url against its token's hosts after your configuration merges --- Sources/StableBar/ConfigurationLoader.swift | 2 +- Sources/StableBar/WidgetPackage.swift | 18 ++++++++++-------- Tests/StableBarTests/ThemePackageTests.swift | 16 +++++++++++++--- docs/packages.md | 2 +- docs/providers.md | 2 +- 5 files changed, 26 insertions(+), 14 deletions(-) diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index 20dc088e..9646430c 100644 --- a/Sources/StableBar/ConfigurationLoader.swift +++ b/Sources/StableBar/ConfigurationLoader.swift @@ -533,7 +533,6 @@ struct ConfigurationLoader: Sendable { for selection in try base.values["packages"]?.decoded([WidgetPackageSelection].self, at: "packages") ?? [] where selection.enabled { try layer.merge(readSelectedPackage(selection, from: packageStore, theme: false)) } - try validateTokenHosts(layer, hosts: packageHosts, packageIDs: packageIDs) if themesDirectory != nil { try layer.merge(readBundledTheme(WidgetPackageSelection(id: "built-in"))) } @@ -547,6 +546,7 @@ struct ConfigurationLoader: Sendable { context.theme = theme.id } try layer.merge(base) + try validateTokenHosts(layer, hosts: packageHosts, packageIDs: packageIDs) return try finish(layer, context: context) } diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index 85c9c4c0..3f235c1a 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -771,21 +771,23 @@ func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [Stri } } -/// Throws when a provider of the merged package layers, or of one of their profiles, sends a package's secret as its token -/// to a host that package's `hosts` don't list, such as one another package points it at. +/// Throws when a package points a provider that sends a package's secret as its token, directly or in a profile, +/// at a host that the secret's package doesn't list in `hosts`, whoever set the token. func validateTokenHosts(_ layer: ConfigurationLayer, hosts: [String: [String]], packageIDs: [String: String]) throws { let providers = try layer.values["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] - var urls = providers.map { name, provider in (name, provider["url"], "providers.\(name).url") } + var requests = providers.map { name, provider in (name, provider, "providers.\(name).url") } for profile in try layer.values["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { for (name, provider) in try profile.configuration["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { - urls.append((name, provider["url"], "profiles.\(profile.name).configuration.providers.\(name).url")) + let path = provider["url"] == nil ? "providers.\(name).url" : "profiles.\(profile.name).configuration.providers.\(name).url" + requests.append((name, providers[name, default: [:]].merging(provider) { $1 }, path)) } } - for case let (name, .string(url)?, path) in urls { - guard case let .string(token)? = providers[name]?["token"], token.hasPrefix("@secret.") else { continue } + for (name, provider, path) in requests { + guard case let .string(url)? = provider["url"], case let .string(token)? = provider["token"], token.hasPrefix("@secret."), + let package = packageIDs[layer.origins[path]!.file] else { continue } let owner = String(token.dropFirst("@secret.".count).prefix { $0 != "/" }) - guard let host = URL(string: url)?.host(), hosts[owner]!.contains(host) else { - throw WidgetPackageError.undeclaredTokenHost(packageIDs[layer.origins[path]!.file]!, name, url, owner) + guard let host = URL(string: url)?.host(), hosts[owner, default: []].contains(host) else { + throw WidgetPackageError.undeclaredTokenHost(package, name, url, owner) } } } diff --git a/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index b4552c5a..daa57617 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1549,19 +1549,29 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St #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":{}}}"# for (version, document) in [("1", #"{"providers":\#(issues)}"#), - ("2", #"{"profiles":[{"name":"work","configuration":{"providers":\#(issues)}}]}"#)] { + ("2", #"{"profiles":[{"name":"work","configuration":{"providers":\#(issues)}}]}"#), + ("3", #"{"profiles":[{"name":"work","configuration":{"providers":\#(tokenless)}}]}"#)] { 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":{}}}"# + for configuration in [#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"1"}]}"#, + #"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"2"}]}"#, + #"{"packages":[{"id":"evil","version":"2"}],\#(ownIssues)}"#] { let error = #expect(throws: WidgetPackageError.self) { - try loader.load(directory.appending(path: "config.json"), - data: Data(#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"\#(version)"}]}"#.utf8)) + 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 sends the token of package github, whose hosts don't list that host.") } + let withoutToken = try loader.load(directory.appending(path: "config.json"), + data: Data(#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"3"}]}"#.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"}],"providers":{"issues":{"url":"https://example.com/issues"}}} """#.utf8)) diff --git a/docs/packages.md b/docs/packages.md index f2efc60d..98ef4355 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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 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. An [`http` provider](providers.md#http) that sends a package's token must request one of that package's `hosts`, so a package that points it at another host fails to load. 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. An [`http` provider](providers.md#http) that sends a package's token must request one of that package's `hosts`, so a package that points it at another host fails to load, even when the token comes from your own configuration. 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"`. diff --git a/docs/providers.md b/docs/providers.md index 8da5465c..78365292 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -200,7 +200,7 @@ Output: 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), which StableBar checks when it reviews, installs and loads the package. A provider whose `token` is a package's secret must also request one of that package's hosts once all packages are loaded, profiles included: a package that points another package's provider, with its token, at a host that package doesn't list fails to load. Your own configuration can still point a package's provider anywhere, 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. +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), which StableBar checks when it reviews, installs and loads the package. When a package sets the `url` of a provider whose `token` is another package's secret, such as `@secret.github/token`, directly or in a profile, the url must be on one of that package's hosts, even when the token comes from your own configuration; otherwise the package that set the url fails to load. Your own configuration can still point a provider anywhere, 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 From d5e3ac80e34cbe3645c5ee258df0dc433742e1a1 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:13:29 +0100 Subject: [PATCH 06/19] fix: refuse a package url on a provider that can send a token the package doesn't own --- Sources/StableBar/ConfigurationLoader.swift | 5 +--- Sources/StableBar/WidgetPackage.swift | 30 ++++++++++---------- Tests/StableBarTests/ThemePackageTests.swift | 15 +++++++--- docs/packages.md | 2 +- docs/providers.md | 2 +- 5 files changed, 29 insertions(+), 25 deletions(-) diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index 9646430c..e3b9c233 100644 --- a/Sources/StableBar/ConfigurationLoader.swift +++ b/Sources/StableBar/ConfigurationLoader.swift @@ -449,7 +449,6 @@ 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. @@ -511,7 +510,6 @@ struct ConfigurationLoader: Sendable { packageBoundaries = [:] packageNames = [:] packageIDs = [:] - packageHosts = [:] widgetPackageNames = [:] widgetPackageIDs = [:] builtInWidgetIDs = [] @@ -546,7 +544,7 @@ struct ConfigurationLoader: Sendable { context.theme = theme.id } try layer.merge(base) - try validateTokenHosts(layer, hosts: packageHosts, packageIDs: packageIDs) + try validatePackageURLs(layer, packageIDs: packageIDs) return try finish(layer, context: context) } @@ -865,7 +863,6 @@ struct ConfigurationLoader: Sendable { packageNames[source.file] = manifest.name packageIDs[source.file] = manifest.id } - packageHosts[manifest.id] = manifest.hosts return layer } } diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index 3f235c1a..e9611fa9 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -170,7 +170,7 @@ enum WidgetPackageError: LocalizedError { case archiveMismatch(String, String) case misplacedSecret(String) case undeclaredHost(String, String) - case undeclaredTokenHost(String, String, String, String) + case foreignToken(String, String, String) var errorDescription: String? { switch self { @@ -197,8 +197,8 @@ enum WidgetPackageError: LocalizedError { 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, 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 .undeclaredTokenHost(package, provider, url, owner): - "Package \(package) points provider \(provider) at \(url), but the provider sends the token of package \(owner), whose hosts don't list that host." + 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)." } } } @@ -771,23 +771,23 @@ func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [Stri } } -/// Throws when a package points a provider that sends a package's secret as its token, directly or in a profile, -/// at a host that the secret's package doesn't list in `hosts`, whoever set the token. -func validateTokenHosts(_ layer: ConfigurationLayer, hosts: [String: [String]], packageIDs: [String: String]) throws { +/// 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. +func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: String]) throws { let providers = try layer.values["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] - var requests = providers.map { name, provider in (name, provider, "providers.\(name).url") } + var urls = providers.map { name, provider in (name, provider["url"], "providers.\(name).url") } + var tokens = providers.mapValues { [$0["token"]] } for profile in try layer.values["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { for (name, provider) in try profile.configuration["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { - let path = provider["url"] == nil ? "providers.\(name).url" : "profiles.\(profile.name).configuration.providers.\(name).url" - requests.append((name, providers[name, default: [:]].merging(provider) { $1 }, path)) + urls.append((name, provider["url"], "profiles.\(profile.name).configuration.providers.\(name).url")) + tokens[name, default: []].append(provider["token"]) } } - for (name, provider, path) in requests { - guard case let .string(url)? = provider["url"], case let .string(token)? = provider["token"], token.hasPrefix("@secret."), - let package = packageIDs[layer.origins[path]!.file] else { continue } - let owner = String(token.dropFirst("@secret.".count).prefix { $0 != "/" }) - guard let host = URL(string: url)?.host(), hosts[owner, default: []].contains(host) else { - throw WidgetPackageError.undeclaredTokenHost(package, name, url, owner) + for case let (name, .string(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) } } } } diff --git a/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index daa57617..b5802834 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1559,17 +1559,24 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St _ = 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":"evil","version":"2"}],\#(ownIssues)}"#] { + #"{"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 sends the token of package github, whose hosts don't list that host.") + + "but the provider can send a token that isn't a secret of package evil.") } - let withoutToken = try loader.load(directory.appending(path: "config.json"), - data: Data(#"{"packages":[{"id":"github","version":"1"},{"id":"evil","version":"3"}]}"#.utf8)) + 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(#""" diff --git a/docs/packages.md b/docs/packages.md index 98ef4355..d1f1d1b3 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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 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. An [`http` provider](providers.md#http) that sends a package's token must request one of that package's `hosts`, so a package that points it at another host fails to load, even when the token comes from your own configuration. 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. 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"`. diff --git a/docs/providers.md b/docs/providers.md index 78365292..176c53a7 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -200,7 +200,7 @@ Output: 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), which StableBar checks when it reviews, installs and loads the package. When a package sets the `url` of a provider whose `token` is another package's secret, such as `@secret.github/token`, directly or in a profile, the url must be on one of that package's hosts, even when the token comes from your own configuration; otherwise the package that set the url fails to load. Your own configuration can still point a provider anywhere, 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. +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), which StableBar checks when it reviews, installs and loads the package. 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. StableBar doesn't check whether those profiles can be active together. Your own configuration can still point a provider anywhere, 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 From 1da81bd94dcd6d4466ebc78b67e9e8fac3a7ecf8 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:19 +0100 Subject: [PATCH 07/19] fix: keep the profiles path in errors and skipped properties after the package url check --- Sources/StableBar/WidgetPackage.swift | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index e9611fa9..c3ca83a7 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -774,16 +774,23 @@ func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [Stri /// 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. func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: String]) throws { - let providers = try layer.values["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] - var urls = providers.map { name, provider in (name, provider["url"], "providers.\(name).url") } - var tokens = providers.mapValues { [$0["token"]] } - for profile in try layer.values["profiles"]?.decoded([ConfigurationProfile].self) ?? [] { - for (name, provider) in try profile.configuration["providers"]?.decoded([String: [String: ConfigurationValue]].self) ?? [:] { - urls.append((name, provider["url"], "profiles.\(profile.name).configuration.providers.\(name).url")) + 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?]] = [:] + 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"]) } } - for case let (name, .string(url)?, path) in urls { + 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 } From 3663edbcd162fc040007b89af854617bb3b64288 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:20 +0100 Subject: [PATCH 08/19] fix: refuse a package url on a provider whose headers another file sets --- Sources/StableBar/WidgetPackage.swift | 12 +++++++++++- Tests/StableBarTests/ThemePackageTests.swift | 12 +++++++++++- docs/packages.md | 2 +- docs/providers.md | 2 +- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index c3ca83a7..01cc262d 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -171,6 +171,7 @@ enum WidgetPackageError: LocalizedError { case misplacedSecret(String) case undeclaredHost(String, String) case foreignToken(String, String, String) + case foreignHeaders(String, String, String) var errorDescription: String? { switch self { @@ -199,6 +200,8 @@ enum WidgetPackageError: LocalizedError { case let .undeclaredHost(provider, url): "Provider \(provider) requests \(url), but the package's hosts don't list its host." 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." } } } @@ -772,7 +775,7 @@ func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [Stri } /// 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. +/// 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"] { @@ -784,10 +787,14 @@ func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: Strin } 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)" } + } } } for (name, url, path) in urls { @@ -796,6 +803,9 @@ func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: Strin 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) + } } } diff --git a/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index b5802834..fc7a9f8a 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1550,9 +1550,11 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St 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)}}]}"#)] { + ("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")) @@ -1576,6 +1578,14 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St #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 error = #expect(throws: WidgetPackageError.self) { + try loader.load(directory.appending(path: "config.json"), data: Data(typedHeader.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) diff --git a/docs/packages.md b/docs/packages.md index d1f1d1b3..c56784ce 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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 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. 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 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"`. diff --git a/docs/providers.md b/docs/providers.md index 176c53a7..494da146 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -200,7 +200,7 @@ Output: 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), which StableBar checks when it reviews, installs and loads the package. 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. StableBar doesn't check whether those profiles can be active together. Your own configuration can still point a provider anywhere, 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. +In a package, each `http` provider's `url` must be on one of the package's [`hosts`](packages.md#store), which StableBar checks when it reviews, installs and loads the package. 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 in your configuration. StableBar doesn't check whether those profiles can be active together. Your own configuration can still point a provider anywhere, 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 From 083d04c043901e2476f9501af79eea3cd974ada5 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:20 +0100 Subject: [PATCH 09/19] fix: find nothing for a JSON Pointer array index that RFC 6901 doesn't allow --- Sources/StableBar/ProviderConfiguration.swift | 2 +- Tests/StableBarTests/ProviderTests.swift | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Sources/StableBar/ProviderConfiguration.swift b/Sources/StableBar/ProviderConfiguration.swift index 1415cbb7..60e067e2 100644 --- a/Sources/StableBar/ProviderConfiguration.swift +++ b/Sources/StableBar/ProviderConfiguration.swift @@ -154,7 +154,7 @@ extension ConfigurationValue { guard let member = object[key] else { return nil } value = member case let .array(array): - guard let index = Int(key), array.indices.contains(index) else { return nil } + guard let index = Int(key), String(index) == key, array.indices.contains(index) else { return nil } value = array[index] default: return nil diff --git a/Tests/StableBarTests/ProviderTests.swift b/Tests/StableBarTests/ProviderTests.swift index 5413004d..f01aab59 100644 --- a/Tests/StableBarTests/ProviderTests.swift +++ b/Tests/StableBarTests/ProviderTests.swift @@ -184,7 +184,8 @@ private func provider(_ command: String, type: String = "stream", interval: Doub 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"}, + "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"}} From a8cfbd24fa1d53dc9d23c8ab2960f21a818cb866 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:21 +0100 Subject: [PATCH 10/19] fix: accept only https for an http provider's url in the schema --- stablebar.schema.json | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/stablebar.schema.json b/stablebar.schema.json index 876dfdcb..b619e0f5 100644 --- a/stablebar.schema.json +++ b/stablebar.schema.json @@ -1941,7 +1941,18 @@ "$ref": "#/definitions/number" }, "url": { - "$ref": "#/definitions/string", + "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": { From afcda6300d6d0e5263925b3ca27d9a1a71a887f7 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:21 +0100 Subject: [PATCH 11/19] docs: show the weather example's temperature in the warning color below zero --- examples/packages/weather/config.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/packages/weather/config.json b/examples/packages/weather/config.json index 78df285c..8ab531b5 100644 --- a/examples/packages/weather/config.json +++ b/examples/packages/weather/config.json @@ -1,4 +1,7 @@ { + "tokens": { + "warning": { "light": "#c93400", "dark": "#ffb340" } + }, "providers": { "weather": { "type": "http", @@ -14,6 +17,7 @@ "widgets": [ { "id": "weather", "type": "provider", "provider": "weather", "position": "right", + "style": { "states": { "warning": { "foreground": "@token.warning" } } }, "layout": { "type": "row", "style": { "spacing": 4 }, "children": [ From ffd4cd23136b665cd5785935782e94f555eac588 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:22:21 +0100 Subject: [PATCH 12/19] docs: record that a package can't point another party's credentials at its host --- DECISIONS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DECISIONS.md b/DECISIONS.md index ba6fe533..5d3c58b9 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -54,12 +54,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. The check doesn't work out which profiles can be active together, so it can refuse an unusual but harmless setup. URLs set in your own files stay free. - **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 @@ -80,3 +82,4 @@ 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 From 4c2de43a1eb724f1a976a25de8f696674e270105 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:56:09 +0100 Subject: [PATCH 13/19] fix: require a package to write out its http providers' url and headers --- DECISIONS.md | 2 +- Sources/StableBar/ConfigurationLoader.swift | 2 +- Sources/StableBar/WidgetPackage.swift | 18 ++++++++++--- Tests/StableBarTests/ThemePackageTests.swift | 28 +++++++++++++++----- docs/packages.md | 2 +- docs/providers.md | 2 +- 6 files changed, 40 insertions(+), 14 deletions(-) diff --git a/DECISIONS.md b/DECISIONS.md index c8aee20e..065858f1 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -56,7 +56,7 @@ 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. The check doesn't work out which profiles can be active together, so it can refuse an unusual but harmless setup. URLs set in your own files stay free. +- **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. diff --git a/Sources/StableBar/ConfigurationLoader.swift b/Sources/StableBar/ConfigurationLoader.swift index e3b9c233..a905e32d 100644 --- a/Sources/StableBar/ConfigurationLoader.swift +++ b/Sources/StableBar/ConfigurationLoader.swift @@ -857,7 +857,7 @@ struct ConfigurationLoader: Sendable { } } try validateSecretReferences(.object(layer.values), package: manifest.id) - try validatePackageHosts(layer.values, hosts: manifest.hosts) + 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 diff --git a/Sources/StableBar/WidgetPackage.swift b/Sources/StableBar/WidgetPackage.swift index 009f8dff..63afc04f 100644 --- a/Sources/StableBar/WidgetPackage.swift +++ b/Sources/StableBar/WidgetPackage.swift @@ -170,6 +170,7 @@ enum WidgetPackageError: LocalizedError { 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) @@ -198,6 +199,8 @@ enum WidgetPackageError: LocalizedError { 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, 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): @@ -783,14 +786,19 @@ func validateSecretReferences(_ value: ConfigurationValue, package id: String, p } } -/// Throws when a provider of the package, or of one of its profiles, requests a host that `hosts` doesn't list. -func validatePackageHosts(_ document: [String: ConfigurationValue], hosts: [String]) throws { +/// 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(), hosts.contains(host) else { throw WidgetPackageError.undeclaredHost(name, url) } + 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, hosts: hosts) + try validatePackageHosts(profile.configuration, manifest: manifest) } } @@ -814,6 +822,8 @@ func validatePackageURLs(_ layer: ConfigurationLayer, packageIDs: [String: Strin 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") } } } diff --git a/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index a37017e3..cd6a1370 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1532,7 +1532,15 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St (#"{"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.") + "@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) } @@ -1579,20 +1587,28 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St + "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 error = #expect(throws: WidgetPackageError.self) { - try loader.load(directory.appending(path: "config.json"), data: Data(typedHeader.utf8)) + 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.") } - #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"}],"providers":{"issues":{"url":"https://example.com/issues"}}} + {"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") } diff --git a/docs/packages.md b/docs/packages.md index 32b98b86..bfe8532a 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -33,7 +33,7 @@ Settings support `string`, `number`, `bool` and `secret`. The first three need a 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 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 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"`. diff --git a/docs/providers.md b/docs/providers.md index a1a7cd8a..6ee86da1 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -203,7 +203,7 @@ Output: 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), which StableBar checks when it reviews, installs and loads the package. 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 in your configuration. StableBar doesn't check whether those profiles can be active together. Your own configuration can still point a provider anywhere, 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. +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 `headers`: `headers` 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. 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 From 89087d510f48742769c3af294d683c261051e785 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:56:10 +0100 Subject: [PATCH 14/19] docs: say an http value's string must hold a finite number --- docs/providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/providers.md b/docs/providers.md index 6ee86da1..8818662c 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -197,7 +197,7 @@ An `http` provider reads JSON from a web API without running a command, and copi 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 one, as some price APIs send them. +- `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. From 4b2ab94ab39f8aea7d869fc8eaac032f895d2076 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:04:41 +0100 Subject: [PATCH 15/19] docs: say a package http provider's headers are optional --- docs/providers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/providers.md b/docs/providers.md index 8818662c..ace3ddd3 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -203,7 +203,7 @@ Output: 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 `headers`: `headers` 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. 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. +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. 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 From 3dbb2ab132db57fbf46d751884029e386820ae91 Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:24:06 +0100 Subject: [PATCH 16/19] fix: follow no redirect outside a package's hosts from its http providers --- Sources/StableBar/Configuration.swift | 2 +- Sources/StableBar/ConfigurationLoader.swift | 6 ++++ Sources/StableBar/DataSourceRegistry.swift | 4 +-- Sources/StableBar/PackageSourceFetching.swift | 8 +++++ Sources/StableBar/ProviderConfiguration.swift | 2 ++ Tests/StableBarTests/StubURLProtocol.swift | 2 ++ Tests/StableBarTests/ThemePackageTests.swift | 30 +++++++++++++++++++ docs/packages.md | 2 +- docs/providers.md | 2 +- 9 files changed, 53 insertions(+), 5 deletions(-) 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 a905e32d..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 = [] @@ -862,6 +867,7 @@ struct ConfigurationLoader: Sendable { 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 c938a3ea..1c30de6c 100644 --- a/Sources/StableBar/DataSourceRegistry.swift +++ b/Sources/StableBar/DataSourceRegistry.swift @@ -134,7 +134,7 @@ extension DataSourceType { /// 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 and keeps no cache or cookies. + /// 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 @@ -147,7 +147,7 @@ extension DataSourceType { 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) + 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 { 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 3df79fff..6114efce 100644 --- a/Sources/StableBar/ProviderConfiguration.swift +++ b/Sources/StableBar/ProviderConfiguration.swift @@ -28,6 +28,8 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable { 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 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 cd6a1370..4c83fece 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1612,6 +1612,36 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St #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) +} + @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 bfe8532a..d0b29115 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -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`. It enforces `hosts` only for [`http` providers](providers.md#http), whose `url` must be on a listed host; commands can contact any host. For store packages that run commands, a maintainer checks all three 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 ace3ddd3..5629cc10 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -203,7 +203,7 @@ Output: 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. 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. +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 From a4d17c855c0f57dc9ca1ea23c445923fbc71d5fb Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:44:32 +0100 Subject: [PATCH 17/19] fix: update a provider's redirect hosts on reload when only its url's source changes --- Sources/StableBar/BarStore.swift | 2 +- Tests/StableBarTests/ThemePackageTests.swift | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Sources/StableBar/BarStore.swift b/Sources/StableBar/BarStore.swift index 31aac75d..b5693f13 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/Tests/StableBarTests/ThemePackageTests.swift b/Tests/StableBarTests/ThemePackageTests.swift index 4c83fece..984e4edf 100644 --- a/Tests/StableBarTests/ThemePackageTests.swift +++ b/Tests/StableBarTests/ThemePackageTests.swift @@ -1640,6 +1640,17 @@ func aSharedReferenceBudgetRetainsThePerCallLimitAndCountsFailedCalls(prefix: St 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 { From d305b89ec91cf8858f09587425731b1832a5d7ee Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:44:33 +0100 Subject: [PATCH 18/19] docs: say that the Store's CI doesn't publish packages with http providers yet --- docs/packages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/packages.md b/docs/packages.md index d0b29115..16479fdd 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -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 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: From 6e490e097f72e125f138596ab5382ba23c598e8a Mon Sep 17 00:00:00 2001 From: Sebastien Graf <95282692+Seb-GRAF@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:48:52 +0100 Subject: [PATCH 19/19] docs: leave packages with http providers out of those the Store publishes today --- docs/packages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/packages.md b/docs/packages.md index 16479fdd..e3849688 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -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; 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. +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: