Repository navigation
Conversation
Add a URLProtocol subclass that injects user-configured HTTP headers into every WKWebView request, enabling authentication against Cloudflare Access (and similar reverse-proxy auth) from the desktop app. Changes: - CustomHeaderURLProtocol.swift — URLProtocol that intercepts http/https requests and injects headers from UserDefaults - PreferencesWindowController.swift — new CUSTOM HEADERS section with a multi-line text field for Name: Value entries, saved as JSON in defaults - BrowserWindowController.swift — register the protocol before the WebView loads; inject a meta tag with headers for JS/WebSocket use cases
There was a problem hiding this comment.
Pull request overview
Adds support for user-configurable custom HTTP headers that are injected into Hermes’ WKWebView requests, enabling auth flows like Cloudflare Access service tokens without relying on in-WebView browser redirects.
Changes:
- Adds a Preferences “CUSTOM HEADERS” section to capture
Name: Valueheader pairs and persist them. - Introduces
CustomHeaderURLProtocolto inject persisted headers into outgoing HTTP/HTTPS requests. - Registers the URLProtocol when constructing the WKWebView and (currently) injects header JSON into the DOM via a meta tag.
- Adds a CHANGELOG “Unreleased” entry for the feature.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| Sources/HermesAgent/PreferencesWindowController.swift | Adds UI + persistence wiring for custom headers. |
| Sources/HermesAgent/CustomHeaderURLProtocol.swift | New URLProtocol implementation that injects custom headers. |
| Sources/HermesAgent/BrowserWindowController.swift | Registers the URLProtocol and injects header metadata into the page. |
| CHANGELOG.md | Documents the new feature under Unreleased. |
Suppressed comments (5)
Sources/HermesAgent/BrowserWindowController.swift:286
- This injects the full custom header JSON (including secret values like
CF-Access-Client-Secret) into the page DOM, making it readable by any JavaScript on the page (including third-party scripts or an XSS payload). It also only escapes single quotes, so values containing backslashes/newlines can break the script. Unless there is a concrete, audited need for JS access, avoid exposing header values to the page.
// Inject custom headers as a meta tag so JavaScript can read them if needed.
// The primary mechanism is URLProtocol for HTTP requests; the CF_AppSession
// cookie set by Cloudflare Access on the initial authenticated request will
// be sent automatically with WebSocket connections by WKWebView.
let customHeaders = CustomHeaderURLProtocol.loadCustomHeaders()
if !customHeaders.isEmpty {
let headersJSON = try? JSONSerialization.data(withJSONObject: customHeaders.map { ["name": $0.name, "value": $0.value] })
let headersStr = headersJSON.flatMap { String(data: $0, encoding: .utf8) } ?? "[]"
let headerMetaScript = WKUserScript(
source: """
(function() {
const meta = document.createElement('meta');
meta.name = 'hermes-custom-headers';
meta.content = '\(headersStr.replacingOccurrences(of: "'", with: "\\'"))';
document.head.appendChild(meta);
Sources/HermesAgent/CustomHeaderURLProtocol.swift:40
canInit(with:)currently opts in for any http/https request when headers are configured. Because the protocol is registered globally, this can leak auth headers into unrelated URLSession requests (e.g., Sparkle feed checks, tunnel probes, future networking) and send secrets to the wrong hosts. Restrict interception to the app’s configured Hermes host (and loopback for SSH mode).
override class func canInit(with request: URLRequest) -> Bool {
// Only intercept http/https schemes
guard let scheme = request.url?.scheme?.lowercased(),
["http", "https"].contains(scheme) else { return false }
// Avoid re-processing requests we've already modified
if URLProtocol.property(forKey: handledKey, in: request) != nil { return false }
// Only intercept if there are custom headers configured
return !loadCustomHeaders().isEmpty
}
Sources/HermesAgent/CustomHeaderURLProtocol.swift:73
- The URLProtocol completion only forwards the response if both
responseanddataare non-nil. For valid responses with empty bodies (e.g., 204, HEAD, or zero-length responses), the client never receives the response at all, which can break WKWebView loading semantics.
if let response = response, let data = data {
self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
self.client?.urlProtocol(self, didLoad: data)
}
self.client?.urlProtocolDidFinishLoading(self)
Sources/HermesAgent/CustomHeaderURLProtocol.swift:80
stopLoading()is a no-op, so cancelled navigations/downloads can leave the underlying URLSession task running until completion. URLProtocol subclasses are expected to cancel any in-flight work instopLoading()to avoid wasted network/CPU and unintended side effects.
override func stopLoading() {
// The URLSessionTask is automatically handled; no extra cleanup needed.
}
Sources/HermesAgent/CustomHeaderURLProtocol.swift:28
- Custom header values here are intended to hold service tokens/secrets, but they’re persisted to disk in plaintext via UserDefaults. That increases the risk of accidental disclosure (backups, shared machine accounts, etc.). Consider storing header values in the Keychain (and only non-sensitive metadata in UserDefaults).
/// Save custom headers to UserDefaults (replaces existing).
static func saveCustomHeaders(_ headers: [(name: String, value: String)]) {
let json = headers.map { ["name": $0.name, "value": $0.value] }
let data = try? JSONSerialization.data(withJSONObject: json)
UserDefaults.standard.set(data, forKey: storageKey)
}
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| // Register custom URLProtocol to inject HTTP headers on every request | ||
| URLProtocol.registerClass(CustomHeaderURLProtocol.self) | ||
|
|
| /// Returns the custom headers stored in UserDefaults. | ||
| static func loadCustomHeaders() -> [(name: String, value: String)] { | ||
| guard let data = UserDefaults.standard.data(forKey: storageKey) else { return [] } | ||
| guard let json = try? JSONSerialization.jsonObject(with: data) as? [[String: String]] else { return [] } | ||
| return json.compactMap { dict in | ||
| guard let name = dict["name"], let value = dict["value"], !name.isEmpty else { return nil } | ||
| return (name, value) | ||
| } | ||
| } |
Exact-head review at
|
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Re-gate at
|
Summary
Adds a CUSTOM HEADERS section to Preferences, letting users configure arbitrary HTTP headers that get injected into every WKWebView request — enabling authentication behind Cloudflare Access (and similar reverse-proxy auth gateways) without leaving the desktop app.
Motivation
The Hermes Agent desktop app could only connect via direct SSH tunnel or plain URL — no way to authenticate against Cloudflare Access (or similar reverse-proxy auth) that sits in front of a publicly-exposed WebUI. Users had to either use the web browser, open an SSH backdoor, or suffer the "Invalid login session" error from Access's browser-auth redirect inside WKWebView.
This PR lets users paste their Cloudflare Access service token headers (or any custom auth headers) directly into the Preferences UI, and the app includes them on every HTTP request — no browser popup needed.
Changes
New file
CustomHeaderURLProtocol.swift— AURLProtocolsubclass that intercepts HTTP/HTTPS requests from WKWebView and injects headers stored in UserDefaults. Headers are saved as a JSON array of{"name", "value"}objects.Modified files
PreferencesWindowController.swift— New "CUSTOM HEADERS" section with a multi-line text field acceptingName: Valueentries (one per line). Parsed on save and persisted viaCustomHeaderURLProtocol.saveCustomHeaders().BrowserWindowController.swift— RegistersCustomHeaderURLProtocolbefore the WebView loads. Also injects ameta[name="hermes-custom-headers"]tag with the header JSON so JavaScript/WebSocket code can read the config if needed (though WKWebView handles cookie propagation to WebSocket natively).Usage
Name: Value(one per line)Example for Cloudflare Access:
Testing
Built and tested locally on macOS 15 (Sequoia). Build succeeds with
swift build -c releaseandbash build.sh. Verified headers are injected via curl-equivalent HTTP debugging.Checklist
swift build -c release)build.sh