diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7e93e6..7f8cae43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ ### Fixed - **The menubar second row's quota line now names the provider the flame is warning about.** "Quota remaining" picked each provider's *headline* window — weekly, else monthly, and only then the busiest one — which is the Capacity Dock's billing horizon, not a warning: on a machine with Cursor's API window at 100% and Claude's 5-hour window at 18%, the row reported Monthly 9.5% and Weekly 5% and read as if nothing were near a limit. Each provider now contributes its worst window, per-model rows included, which is exactly what the menu-bar flame already tints by, so the two surfaces agree. A provider backing off after a failed fetch keeps its last-known window instead of dropping out, so the row no longer vanishes — resizing the status item — for the length of a retry, matching what the dock shows dimmed. The row is also capped at 24 characters, shortening a long provider name ("GitHub Copilot 12% left · 6d 3h") rather than letting the second line more than double the item's width, and the two-line title now carries a VoiceOver label that reads as one phrase instead of a string with a newline in it. With the setting off nothing changed: the snapshot that feeds the row is no longer even built on a refresh, and the title is the single-row composition it has always been. (#1310) +- **Every Copilot credential rung now follows its own GitHub host, not just the two read from files.** #1286 taught `hosts.json` and `apps.json` to carry the host their token came from, but the rungs that carried none — `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, and a token pasted into Settings — were still sent to `api.github.com`, so a user whose only Copilot credential is a GitHub Enterprise Cloud login got a 401 and a terminal failure with no way out. The environment rung now reads `GH_HOST` from the same environment as the token; the `gh` rung resolves the host from gh's own `hosts.yml` (`GH_CONFIG_DIR`, then `XDG_CONFIG_HOME/gh`, then `~/.config/gh`), picking it the way gh picks the host for `gh auth token` and without a second subprocess; and macOS Settings gains a GitHub host field next to the pasted token, defaulting to `github.com` and saved in the same Keychain record as the token so the two can never drift apart. Settings refuses a host no endpoint can be derived from at the field rather than storing it, the connection row no longer promises `api.github.com` before anything has been fetched, and every one of these new host sources is character-validated before a URL is built, so a crafted value such as `evil.com?.ghe.com` fails closed with no request instead of pointing the Authorization header at a host of its own choosing. `codeburn quota` is unchanged: it still reads only the editor-plugin files, which already carry their host. (#1306) - **Copilot live quota works for GitHub Enterprise Cloud enterprises on a `*.ghe.com` host.** Both readers hardcoded `https://api.github.com/copilot_internal/user` and threw away the host their credential came from, so a data-residency enterprise signed in on `.ghe.com` could only ever report `available: false` with "Temporarily unavailable". A discovered credential now carries its host — `hosts.json` is keyed by host and newer `apps.json` files key by `:` — and the request follows it: `api.github.com` for `github.com` and for any rung that carries no host of its own (an app-name `apps.json` key, `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, a pasted token), and `https://api..ghe.com/copilot_internal/user` for an enterprise host. The token and the host always come from the same entry, with `github.com` preferred when several hosts are signed in and otherwise the first `.ghe.com` tenant in sorted order; a host neither rule can address, such as a self-hosted GitHub Enterprise Server install, fails with a message naming that host instead of sending the credential to dotcom, and unreachable-host and HTTP failures name the host that was tried. The macOS Settings connection row now says which host answered. (#1286) ## 0.9.24 - 2026-09-04 diff --git a/docs/providers/copilot.md b/docs/providers/copilot.md index ee97b8ba..c8034b78 100644 --- a/docs/providers/copilot.md +++ b/docs/providers/copilot.md @@ -334,12 +334,21 @@ tolerates an absent, locked, or malformed source and falls through: (`gho_`, `ghu_`, `ghp_`, `ghs_`, `github_pat_`). `ghr_` refresh tokens are skipped: the usage endpoint rejects them. 3. `COPILOT_GITHUB_TOKEN`, then `GH_TOKEN`, then `GITHUB_TOKEN`, matching the - Copilot CLI's own order. A GUI-launched app rarely inherits these. + Copilot CLI's own order, with `GH_HOST` read from the same environment as + the host those tokens belong to. A GUI-launched app rarely inherits these. 4. `gh auth token`, which resolves keyring vs `~/.config/gh/hosts.yml` itself. - The binary is located the same way `CodeburnCLI` locates codeburn. + The binary is located the same way `CodeburnCLI` locates codeburn. The host + is read from that same `hosts.yml` (`GH_CONFIG_DIR`, then + `XDG_CONFIG_HOME/gh`, then `~/.config/gh`) rather than by spawning + `gh auth status`: gh writes the file for every login, keyring-backed ones + included, so a file read answers without a second subprocess. The pick + mirrors gh's own: `GH_HOST`, else the single configured host, else + `github.com`. 5. A token the user pastes into Settings, stored in CodeBurn's own - provider-scoped keychain item. A fine-grained personal access token with the - `Plan: Read-only` permission is enough. + provider-scoped keychain item together with the host typed beside it. A + fine-grained personal access token with the `Plan: Read-only` permission is + enough. Settings refuses a host no endpoint can be derived from at the + field, so an unaddressable host never reaches the keychain record. The Copilot CLI's own keychain item (generic password service `copilot-cli`) is deliberately **not** read. It is written by a Node keyring library, so @@ -353,8 +362,9 @@ Rung 4 costs a process spawn, so its answer is cached for `probeCacheTTL` `hasCredential` is the cheap eligibility answer and never spawns: it approximates rung 4 with an installed `gh` binary. -The Electron surface (`app/electron/quota/copilot.ts`) still implements only -rung 1. +Rungs 2 to 5 are the menubar's. The CLI (`src/quota/copilot.ts`) and the +Electron surface (`app/electron/quota/copilot.ts`) still implement only rung 1, +whose files already carry the host their token belongs to. ### GitHub Enterprise Cloud hosts (`*.ghe.com`) @@ -365,16 +375,25 @@ api.github.com. So a credential carries the host it was read from — `hosts.json` is keyed by host, and newer `apps.json` files key by `:` — and the request goes to `https://api..ghe.com/copilot_internal/user` for an enterprise host and -to `https://api.github.com/copilot_internal/user` for `github.com` or for any -rung that carries no host of its own (an app-name `apps.json` key, the -environment variables, `gh auth token`, a pasted token). The token and the host +to `https://api.github.com/copilot_internal/user` for `github.com` or for a +source that genuinely carries none (an app-name `apps.json` key, an +environment token with no `GH_HOST`, a gh login with no `hosts.yml` entry, a +pasted token saved before the host field existed). Every menubar rung can name +a tenant: the credential files are keyed by host, the environment rung reads +`GH_HOST`, the gh rung reads gh's `hosts.yml`, and the pasted rung saves the +host beside the token (#1306). The token and the host always come from the same entry: with several hosts signed in, `github.com` wins, otherwise the first `.ghe.com` tenant in sorted order, so the pick is stable across reads; with exactly one, that host is used. A host neither rule can address — a self-hosted GitHub Enterprise Server install, which CodeBurn does not support — fails with a message naming that host rather than falling back to api.github.com, because dotcom would reject the credential anyway and -must never receive it. Unreachable-host and HTTP failures name the host tried, +must never receive it. Every host source is untrusted text, `GH_HOST`, gh's +`hosts.yml` keys and the pasted host included: the normalized host is +character-validated before any URL is built, because a value like +`evil.com?.ghe.com` passes the `.ghe.com` suffix check but would build a URL +whose host is `api.evil.com` and hand it the Authorization header. +Unreachable-host and HTTP failures name the host tried, so the symptom is no longer a bare "Temporarily unavailable". Settings shows which host answered in the Copilot connection row. `CopilotHostEndpoint` (macOS) and the exported helpers in `src/quota/copilot.ts` (CLI) hold the diff --git a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift index 3e6015f2..8d74687c 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift @@ -5,6 +5,11 @@ import Foundation struct CapacityDockProviderCredential: Codable, Equatable, Sendable { var sourceMode: String = ProviderReferenceSourceMode.automatic.rawValue var apiKey: String = "" + /// GitHub host a pasted Copilot token belongs to, empty for dotcom. It + /// lives in the same record as the token so the two can never drift apart: + /// the host a credential is sent to always comes from the entry that + /// carried the token (#1306). Unused by the other providers. + var host: String = "" var resolvedSourceMode: ProviderReferenceSourceMode { ProviderReferenceSourceMode(rawValue: sourceMode) ?? .automatic @@ -21,7 +26,8 @@ struct CapacityDockProviderCredential: Codable, Equatable, Sendable { var sanitizedOverride: CapacityDockProviderCredentialOverride { CapacityDockProviderCredentialOverride( sourceMode: resolvedSourceMode, - apiKey: cleaned(apiKey) + apiKey: cleaned(apiKey), + host: cleaned(host) ) } @@ -31,9 +37,32 @@ struct CapacityDockProviderCredential: Codable, Equatable, Sendable { } } +/// Decoding is hand-written, and lives in an extension so the memberwise +/// initializer survives. Swift's synthesized `init(from:)` ignores a property's +/// default value and throws on a missing key, so adding any field to this +/// record would make every credential saved before it unreadable — for every +/// provider, not just the one that gained the field. +extension CapacityDockProviderCredential { + private enum CodingKeys: String, CodingKey { + case sourceMode, apiKey, host + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.init( + sourceMode: try container.decodeIfPresent(String.self, forKey: .sourceMode) + ?? ProviderReferenceSourceMode.automatic.rawValue, + apiKey: try container.decodeIfPresent(String.self, forKey: .apiKey) ?? "", + host: try container.decodeIfPresent(String.self, forKey: .host) ?? "" + ) + } +} + struct CapacityDockProviderCredentialOverride: Equatable, Sendable { var sourceMode: ProviderReferenceSourceMode var apiKey: String? + /// Only Copilot populates this; see `CapacityDockProviderCredential.host`. + var host: String? } enum CapacityDockProviderCredentialStoreError: LocalizedError, Equatable { diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift index d116316f..0a35f0e9 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift @@ -16,13 +16,18 @@ import Foundation /// GHES install today, and guessing that shape for any unrecognized host would /// send credentials to a host we never verified serves this endpoint. enum CopilotHostEndpoint { - /// Assumed for every credential source that carries no host of its own - /// (`apps.json` entries keyed by app name, the environment variables, - /// `gh auth token`, and a token pasted into Settings). + /// Assumed for every credential source that still carries no host of its + /// own: an `apps.json` entry keyed by app name, an environment token with + /// no `GH_HOST`, a `gh` login this machine has no `hosts.yml` for, and a + /// pasted token saved before the host field existed. static let defaultHost = "github.com" static let defaultAPIHost = "api.github.com" /// GitHub Enterprise Cloud with data residency. static let enterpriseCloudSuffix = ".ghe.com" + /// The variable `gh` and the Copilot CLI read to target a host other than + /// dotcom. It sits next to `GH_TOKEN` / `GITHUB_TOKEN` in the same + /// environment, so the environment rung reads both (#1306). + static let hostEnvironmentName = "GH_HOST" private static let usagePath = "/copilot_internal/user" /// Bare lowercased hostname. Tolerates surrounding whitespace, a scheme, a @@ -88,4 +93,73 @@ enum CopilotHostEndpoint { let enterprise = normalized.filter { $0.hasSuffix(enterpriseCloudSuffix) }.sorted() return enterprise.first ?? normalized.sorted().first } + + // MARK: - `gh` hosts (#1306) + + /// The GitHub hosts `gh` is logged in to, read out of its `hosts.yml`. + /// + /// That file is a mapping of host to per-host settings, so the hosts are + /// exactly its top-level keys — the only lines that start in column zero. + /// This is a key scan, not a YAML parser: nothing below the first level is + /// read, and every key is passed on untrusted, to be validated where the + /// URL is built. + static func hostsFromGhConfig(_ text: String) -> [String] { + var hosts: [String] = [] + // Split on `isNewline`, not on "\n": Swift reads CRLF as a single + // grapheme, so splitting on "\n" leaves a CRLF file as one long line. + for rawLine in text.split(whereSeparator: \.isNewline) { + let line = String(rawLine) + // Anything indented belongs to a host's block; `#` is a comment and + // `-` starts a document marker or a sequence entry, neither of + // which is a host. + guard let first = line.first, !first.isWhitespace, first != "#", first != "-" else { continue } + guard let colon = line.firstIndex(of: ":") else { continue } + let key = line[.. String? { + if let host = normalize(environmentHost) { return host } + guard let hostsConfig else { return nil } + let hosts = hostsFromGhConfig(hostsConfig) + guard !hosts.isEmpty else { return nil } + return preferredHost(among: hosts.map { Optional($0) }) + } + + /// Where `gh` keeps `hosts.yml`: `GH_CONFIG_DIR` wins, then + /// `XDG_CONFIG_HOME/gh`, then `~/.config/gh`, matching `gh`'s own order. + static func ghHostsFileURL( + environment: [String: String] = ProcessInfo.processInfo.environment, + homeDirectory: String = NSHomeDirectory() + ) -> URL { + func directory(_ name: String) -> String? { + guard let value = environment[name]?.trimmingCharacters(in: .whitespacesAndNewlines), + !value.isEmpty else { return nil } + return value + } + if let configDir = directory("GH_CONFIG_DIR") { + return URL(fileURLWithPath: configDir).appendingPathComponent("hosts.yml") + } + if let xdg = directory("XDG_CONFIG_HOME") { + return URL(fileURLWithPath: xdg).appendingPathComponent("gh/hosts.yml") + } + return URL(fileURLWithPath: homeDirectory).appendingPathComponent(".config/gh/hosts.yml") + } } diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift index 41cd30c8..d49331f5 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift @@ -78,6 +78,29 @@ enum CopilotQuotaPresentation { explicitlyDisconnected ? disconnectedSettingsDetail : noCredentialsSettingsDetail } + /// Settings connection-row detail before anything has been fetched. It + /// used to promise `api.github.com`, which is wrong for every enterprise + /// tenant now that each rung can carry its own host (#1306): with no + /// answer yet there is no host to name, so it names one only when a + /// previous snapshot already proved which host answers. + static func dormantSettingsDetail(apiHost: String?) -> String { + guard let apiHost, !apiHost.isEmpty, apiHost != CopilotHostEndpoint.defaultAPIHost else { + return "Tap Load Quota to fetch live usage from GitHub." + } + return "Tap Load Quota to fetch live usage from \(apiHost)." + } + + /// Why a host typed next to the pasted token cannot be used, or nil when + /// it can. Rejecting it in Settings turns what would otherwise be a + /// terminal fetch failure into an answer at the field the user typed — + /// and keeps an unaddressable host out of the Keychain record entirely. + static func pastedHostRejection(_ raw: String) -> String? { + let host = CopilotHostEndpoint.normalize(raw) ?? CopilotHostEndpoint.defaultHost + guard CopilotHostEndpoint.apiHost(for: host) == nil else { return nil } + return "CodeBurn cannot read Copilot quota for \(host). " + + "Use github.com or a GitHub Enterprise Cloud host (*.ghe.com)." + } + /// Snapshot age past which a loaded view stamps an "as of