Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
326c5bc
feat: add an http provider so network widgets need no commands
Seb-GRAF Nov 16, 2026
143e455
fix: leave out an http value whose string holds NaN or infinity
Seb-GRAF Nov 17, 2026
a067a12
docs: say http cookies stay in memory and a package with hosts can re…
Seb-GRAF Nov 17, 2026
80e8b86
fix: refuse a package that sends another package's token to a host th…
Seb-GRAF Nov 17, 2026
4dc674c
fix: check a package's provider url against its token's hosts after y…
Seb-GRAF Nov 17, 2026
d5e3ac8
fix: refuse a package url on a provider that can send a token the pac…
Seb-GRAF Nov 17, 2026
1da81bd
fix: keep the profiles path in errors and skipped properties after th…
Seb-GRAF Nov 17, 2026
3663edb
fix: refuse a package url on a provider whose headers another file sets
Seb-GRAF Nov 17, 2026
083d04c
fix: find nothing for a JSON Pointer array index that RFC 6901 doesn'…
Seb-GRAF Nov 17, 2026
a8cfbd2
fix: accept only https for an http provider's url in the schema
Seb-GRAF Nov 17, 2026
afcda63
docs: show the weather example's temperature in the warning color bel…
Seb-GRAF Nov 17, 2026
ffd4cd2
docs: record that a package can't point another party's credentials a…
Seb-GRAF Nov 17, 2026
de4e82f
Merge branch 'main' into feat/85-http-provider
Seb-GRAF Nov 17, 2026
6edc5a6
Merge branch 'main' into feat/85-http-provider
Seb-GRAF Nov 17, 2026
4c2de43
fix: require a package to write out its http providers' url and headers
Seb-GRAF Nov 17, 2026
89087d5
docs: say an http value's string must hold a finite number
Seb-GRAF Nov 17, 2026
4b2ab94
docs: say a package http provider's headers are optional
Seb-GRAF Nov 17, 2026
3dbb2ab
fix: follow no redirect outside a package's hosts from its http provi…
Seb-GRAF Nov 18, 2026
e4c288b
Merge remote-tracking branch 'origin/main' into feat/85-http-provider
Seb-GRAF Nov 18, 2026
a4d17c8
fix: update a provider's redirect hosts on reload when only its url's…
Seb-GRAF Nov 18, 2026
d305b89
docs: say that the Store's CI doesn't publish packages with http prov…
Seb-GRAF Nov 18, 2026
6e490e0
docs: leave packages with http providers out of those the Store publi…
Seb-GRAF Nov 18, 2026
79a0d03
Merge remote-tracking branch 'origin/main' into feat/85-http-provider
Seb-GRAF Nov 18, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,14 @@ Add an entry when a pull request sets a rule, a policy or a choice not to do som
−1,000…1,000. All remaining numeric values use 0…1,000, including style height, spacing and edge
padding. These refusals apply to links; folder themes keep the ordinary configuration rules.
- **A native provider may read a macOS tool's output** (2026-11-16, [#220]). When no public API gives the data and the tool needs no permission, a native provider can run a macOS command-line tool, off the main actor and without a shell: `bluetooth` reads every connected device's battery from `system_profiler`. Apple doesn't document the tool's output keys, so a missing or renamed key leaves that value empty instead of failing the provider.
- **A package can't move another party's credentials** (2026-11-17, [#85], [#744]). A package may set the `url` of a provider, directly or in a profile, only when no file or profile gives that provider a token other than one of that package's own secrets, and no other file sets its `headers`. A package without commands can reach the Store after CI alone, so it must not point your token, a header you typed or another package's secret at its own host. In its own files, a package writes out each provider's `url` and `headers`, without `@token.` references, so StableBar needn't follow tokens to see where a request goes or what it sends. The check doesn't work out which profiles can be active together, so it can refuse an unusual but harmless setup. URLs and headers set in your own files stay free, `@token.` references included.
- **Tests keep their own time** (2026-11-08, [#491]). Code whose tests depend on time takes a clock, and the test clock lives in the repository rather than in a new dependency.
- **Blocking work stays off Swift's shared pool** (2026-11-13, [#618]). The pool has one thread per core, three on CI, and never replaces a blocked one. A slow copy or a lookup that can stall runs through `BlockingWork.run` on a GCD queue, and tests that block such work check that it does. [AGENTS.md](AGENTS.md#writing-tests) has the rule for tests.
- **Comments are for the next reader** (2026-11-10, [#533]). A comment says what the code can't, such as why it must be so, in a line or two. How the bug was found and fixed goes in the issue, the pull request and the commit message. [AGENTS.md](AGENTS.md#writing-comments) has the rule.

[#3]: https://github.com/Seb-GRAF/StableBar/issues/3
[#23]: https://github.com/Seb-GRAF/StableBar/pull/23
[#85]: https://github.com/Seb-GRAF/StableBar/issues/85
[#100]: https://github.com/Seb-GRAF/StableBar/pull/100
[#220]: https://github.com/Seb-GRAF/StableBar/issues/220
[#223]: https://github.com/Seb-GRAF/StableBar/issues/223
Expand All @@ -85,5 +87,6 @@ Add an entry when a pull request sets a rule, a policy or a choice not to do som
[#618]: https://github.com/Seb-GRAF/StableBar/issues/618
[#664]: https://github.com/Seb-GRAF/StableBar/issues/664
[#676]: https://github.com/Seb-GRAF/StableBar/issues/676
[#744]: https://github.com/Seb-GRAF/StableBar/pull/744
[#772]: https://github.com/Seb-GRAF/StableBar/issues/772
[#773]: https://github.com/Seb-GRAF/StableBar/pull/773
2 changes: 1 addition & 1 deletion Sources/StableBar/BarStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Sources/StableBar/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>
Expand Down
8 changes: 8 additions & 0 deletions Sources/StableBar/ConfigurationLoader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -510,6 +514,7 @@ struct ConfigurationLoader: Sendable {
packageBoundaries = [:]
packageNames = [:]
packageIDs = [:]
packageHosts = [:]
widgetPackageNames = [:]
widgetPackageIDs = [:]
builtInWidgetIDs = []
Expand Down Expand Up @@ -544,6 +549,7 @@ struct ConfigurationLoader: Sendable {
context.theme = theme.id
}
try layer.merge(base)
try validatePackageURLs(layer, packageIDs: packageIDs)
return try finish(layer, context: context)
}

Expand Down Expand Up @@ -856,10 +862,12 @@ struct ConfigurationLoader: Sendable {
}
}
try validateSecretReferences(.object(layer.values), package: manifest.id)
try validatePackageHosts(layer.values, manifest: manifest)
layer.values = try preparePackageDocument(layer.values, directory: directory)
for source in layer.origins.values {
packageNames[source.file] = manifest.name
packageIDs[source.file] = manifest.id
packageHosts[source.file] = manifest.hosts
}
return layer
}
Expand Down
36 changes: 34 additions & 2 deletions Sources/StableBar/DataSourceRegistry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -130,6 +130,38 @@ extension DataSourceType {
StreamSource(command: provider.command!, environment: environment)
}

static let http = http()

/// A JSON request read on a timer, with the parts of the response that `output` names. Web APIs limit how often
/// a client may ask, so it reads once a minute by default. The session drops the token on a redirect to another
/// host, follows no redirect outside a package's `hosts` and keeps no cache or cookies.
static func http(session: URLSession = .packageSources) -> DataSourceType {
DataSourceType(name: "http", isNative: false, symbol: "globe", settings: [.url, .output], optionalSettings: [.headers, .token],
continuous: false, defaultInterval: 60) { provider, _ in
PollingSource { _ in
do {
var request = URLRequest(url: provider.url!, timeoutInterval: provider.timeout)
for (name, value) in provider.headers { request.setValue(value, forHTTPHeaderField: name) }
if let reference = provider.token {
// Reading the Keychain can wait on macOS asking whether StableBar may use the token.
let token = try await BlockingWork.run { secretValue(reference) }
if !token.isEmpty { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
}
let (data, response) = try await session.data(for: request, delegate: provider.hosts.map { SourceRedirectGuard(hosts: $0) })
let body = CommandResult(stdout: data, stderr: Data())
let status = (response as! HTTPURLResponse).statusCode
guard status == 200 else {
return .output(.failure(CommandFailure(message: "The server answered with HTTP status \(status).")), process: body)
}
return .output(Result { provider.output!.output(from: try JSONDecoder().decode(ConfigurationValue.self, from: data)) },
process: body)
} catch {
return .output(.failure(error))
}
}
}
}

static let battery = DataSourceType(name: "battery", isNative: true, symbol: "battery.100percent", settings: [],
continuous: true, events: [.powerSourceChange]) { _, _ in
PushSource(monitor: PowerMonitor())
Expand Down
8 changes: 8 additions & 0 deletions Sources/StableBar/PackageSourceFetching.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}
Expand Down
99 changes: 98 additions & 1 deletion Sources/StableBar/ProviderConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,27 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable {
let diskCritical: Double
/// The providers a `merge` combines.
let providers: [String]
/// What an `http` provider requests, with `headers` and a `token` sent as `Authorization: Bearer`.
let url: URL?
let headers: [String: String]
let token: String?
let output: HTTPOutput?
/// When a package set the `url`, its `hosts`, the only ones a redirect may reach. The loader sets them.
var hosts: [String]?

enum CodingKeys: String, CodingKey, CaseIterable {
case type, command, interval, timeout, environment, whenVisible, events, calendars, lookahead, todayOnly, soon, now, processes
case sortBy, units, cpuWarning, memoryWarning, diskWarning, diskCritical, providers
case sortBy, units, cpuWarning, memoryWarning, diskWarning, diskCritical, providers, url, headers, token, output
}

init(type: String) {
self.type = type
command = nil
providers = []
url = nil
headers = [:]
token = nil
output = nil
interval = DataSourceRegistry.builtIn[type]?.defaultInterval ?? 5
timeout = 10
environment = [:]
Expand Down Expand Up @@ -61,6 +72,10 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable {
}
command = source.settings.contains(.command) ? try values.decode(String.self, forKey: .command) : nil
providers = source.settings.contains(.providers) ? try values.decode([String].self, forKey: .providers) : []
url = source.settings.contains(.url) ? try values.decode(URL.self, forKey: .url) : nil
output = source.settings.contains(.output) ? try values.decode(HTTPOutput.self, forKey: .output) : nil
headers = try values.decodeIfPresent([String: String].self, forKey: .headers) ?? [:]
token = try values.decodeIfPresent(String.self, forKey: .token)
interval = try values.decodeIfPresent(Double.self, forKey: .interval) ?? source.defaultInterval
timeout = try values.decodeIfPresent(Double.self, forKey: .timeout) ?? 10
environment = try values.decodeIfPresent([String: String].self, forKey: .environment) ?? [:]
Expand Down Expand Up @@ -89,6 +104,88 @@ struct ProviderConfiguration: Decodable, Equatable, Sendable {
guard processes >= 0 else {
throw DecodingError.dataCorruptedError(forKey: .processes, in: values, debugDescription: "A provider's processes must be zero or more.")
}
if let url, url.scheme?.lowercased() != "https" {
throw DecodingError.dataCorruptedError(forKey: .url, in: values, debugDescription: "A provider url must use https.")
}
}
}

/// What an `http` provider copies from its JSON response, each part found by a JSON Pointer such as
/// `/current/temperature_2m`. A pointer that finds nothing leaves its part out.
struct HTTPOutput: Decodable, Equatable, Sendable {
let text: String?
let fields: [String: String]
let values: [String: String]
/// Pointers to arrays: each object in one becomes a row of its members that are strings, numbers or booleans.
let lists: [String: String]

enum CodingKeys: String, CodingKey, CaseIterable { case text, fields, values, lists }

init(from decoder: Decoder) throws {
try decoder.rejectUnknownKeys(CodingKeys.self)
let container = try decoder.container(keyedBy: CodingKeys.self)
text = try container.decodeIfPresent(String.self, forKey: .text)
fields = try container.decodeIfPresent([String: String].self, forKey: .fields) ?? [:]
values = try container.decodeIfPresent([String: String].self, forKey: .values) ?? [:]
lists = try container.decodeIfPresent([String: String].self, forKey: .lists) ?? [:]
for pointer in [text ?? ""] + fields.values + values.values + lists.values where !pointer.isEmpty && !pointer.hasPrefix("/") {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "A JSON Pointer starts with /, unlike \(pointer)."))
}
}

func output(from response: ConfigurationValue) -> ScriptOutput {
ScriptOutput(text: text.flatMap { response.value(at: $0)?.text } ?? "",
fields: fields.compactMapValues { response.value(at: $0)?.text },
lists: lists.compactMapValues { pointer in
guard case let .array(rows)? = response.value(at: pointer) else { return nil }
return rows.compactMap { row in
guard case let .object(members) = row else { return nil }
return members.compactMapValues(\.text)
}
},
values: values.compactMapValues { response.value(at: $0)?.number })
}
}

extension ConfigurationValue {
/// The value that a JSON Pointer (RFC 6901) such as `/items/0/name` finds, or nil when there is none.
func value(at pointer: String) -> ConfigurationValue? {
var value = self
for token in pointer.split(separator: "/", omittingEmptySubsequences: false).dropFirst() {
let key = token.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~")
switch value {
case let .object(object):
guard let member = object[key] else { return nil }
value = member
case let .array(array):
guard let index = Int(key), String(index) == key, array.indices.contains(index) else { return nil }
value = array[index]
default:
return nil
}
}
return value
}

/// A string, a number as JSON writes it, or `true` or `false`.
fileprivate var text: String? {
switch self {
case let .string(string): string
case let .number(number): Int(exactly: number).map(String.init) ?? String(number)
case let .bool(bool): String(bool)
default: nil
}
}

/// A number, or a string that holds a finite one, as some APIs send prices. `Double` also reads `NaN` and
/// `1e400`, which JSON, and so `--query`, can't hold.
fileprivate var number: Double? {
switch self {
case let .number(number): number
case let .string(string): if let number = Double(string), number.isFinite { number } else { nil }
default: nil
}
}
}

Expand Down
16 changes: 9 additions & 7 deletions Sources/StableBar/ScriptWidget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,7 @@ struct ScriptEvent: Sendable {
var environment: [String: String] = [:]

func commandEnvironment(_ configured: [String: String], secret: @Sendable (String) -> String = packageSecret) async -> [String: String] {
// A source's token belongs to its requests only; configuration can't read it.
let resolved = configured.mapValues { value in
guard value.hasPrefix("@secret.") else { return value }
let account = String(value.dropFirst("@secret.".count))
return account.hasPrefix("source:") ? "" : secret(account)
}
var variables = resolved.merging(environment) { _, event in event }
var variables = configured.mapValues { secretValue($0, secret: secret) }.merging(environment) { _, event in event }
variables["NAME"] = configured["NAME"]
variables["CONFIG_DIR"] = configured["CONFIG_DIR"]
variables["STABLEBAR"] = configured["STABLEBAR"]
Expand All @@ -24,6 +18,14 @@ struct ScriptEvent: Sendable {
}
}

/// `value`, or the saved token that a `@secret.` reference such as `@secret.github/token` names.
func secretValue(_ value: String, secret: (String) -> String = packageSecret) -> String {
guard value.hasPrefix("@secret.") else { return value }
let account = String(value.dropFirst("@secret.".count))
// A source's token belongs to its requests only; configuration can't read it.
return account.hasPrefix("source:") ? "" : secret(account)
}

struct WidgetMenuItem: Decodable, Equatable, Sendable {
let title: String
var detail: String?
Expand Down
Loading
Loading