Skip to content

Add custom HTTP header support for Cloudflare Access & reverse-proxy auth - #100

Open
timerealm wants to merge 3 commits into
hermes-webui:mainfrom
timerealm:custom-header-support
Open

timerealm wants to merge 3 commits into
hermes-webui:mainfrom
timerealm:custom-header-support

Conversation

@timerealm

Copy link
Copy Markdown

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 — A URLProtocol subclass 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 accepting Name: Value entries (one per line). Parsed on save and persisted via CustomHeaderURLProtocol.saveCustomHeaders().
  • BrowserWindowController.swift — Registers CustomHeaderURLProtocol before the WebView loads. Also injects a meta[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

  1. Open Preferences → CUSTOM HEADERS
  2. Enter headers as Name: Value (one per line)
  3. Save & Reconnect

Example for Cloudflare Access:

CF-Access-Client-Id: eebd...access
CF-Access-Client-Secret: cfast_...

Testing

Built and tested locally on macOS 15 (Sequoia). Build succeeds with swift build -c release and bash build.sh. Verified headers are injected via curl-equivalent HTTP debugging.

Checklist

  • Builds locally (swift build -c release)
  • Builds via build.sh
  • Tested end-to-end with Cloudflare Access service tokens
  • Automated tests updated (the existing test target doesn't cover Preferences or URLProtocol — happy to add if maintainers point me at the right pattern)
  • CHANGELOG entry added

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
Copilot AI lite review requested due to automatic review settings August 26, 2026 22:22

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: Value header pairs and persist them.
  • Introduces CustomHeaderURLProtocol to 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 response and data are 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 in stopLoading() 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.

Comment on lines +263 to +265
// Register custom URLProtocol to inject HTTP headers on every request
URLProtocol.registerClass(CustomHeaderURLProtocol.self)

Comment on lines +13 to +21
/// 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)
}
}
@nesquena-hermes

Copy link
Copy Markdown
Collaborator

Exact-head review at ee18d2473 — request changes; mechanism is unsupported and exposes credentials

I reviewed the full four-file diff and current macOS 12+ WebKit/Foundation contract. This needs architectural rework rather than bounded reviewer fixes.

1. The feature’s primary mechanism does not work for WKWebView

URLProtocol.registerClass(CustomHeaderURLProtocol.self) (BrowserWindowController.swift:263-264) registers a Foundation URL loading protocol for in-process URLSession/NSURLConnection traffic. Public WKWebView HTTP/HTTPS loading runs in WebKit’s network process and does not honor custom URLProtocol classes. WebKit’s own long-standing bug/Apple guidance records WKWebView custom NSURLProtocol interception as unsupported without private API.

So this cannot reliably add headers to main navigation, subresources, fetch/XHR, or the WebSocket handshake. The current initial load (:729-730), reconnect load/reload (:1453-1467), and Cmd+R (AppDelegate.swift:822-823) are not routed through any header-bearing helper.

Cloudflare documents service tokens as per-request credentials for non-browser clients. The PR’s comment that the initial request will mint a CF_AppSession cookie for subsequent WebSockets is not established by that contract; browser CF_Authorization cookies belong to the interactive login flow and are not guaranteed for service-token requests.

2. The PR publishes the client secret into page DOM

BrowserWindowController.swift:272-292 serializes every name/value, including CF-Access-Client-Secret, into a documentStart <meta> readable by all page JavaScript and any XSS/third-party script. There is no functional consumer or reason for JS access. It also escapes only single quotes, not JavaScript string syntax comprehensively.

Delete this path entirely. Secrets must never enter DOM, logs, crash reports, UserDefaults, or page-visible state.

3. Credentials are stored in plaintext and have no origin owner

CustomHeaderURLProtocol.swift:13-28 stores values in UserDefaults. These are service credentials and belong in Keychain. The multiline preferences editor also displays them in clear text.

Worse, one global header set survives target-URL/connection-mode changes and canInit accepts every process HTTP/HTTPS request (:32-40). If the protocol is honored by any in-process URLSession, it can send the Cloudflare secret to health checks, Sparkle/update traffic, another server selected later, redirects, and future networking. Bind one Keychain record to a normalized exact origin (scheme + host + effective port), with explicit SSH/loopback semantics; never let discovery/redirects widen that authority.

4. The URLProtocol implementation is incomplete even for URLSession

CustomHeaderURLProtocol.swift:46-80:

  • keeps the data task only in a local variable, so stopLoading() cannot cancel it;
  • drops valid response metadata when data == nil (HEAD/204/zero-body paths);
  • unconditionally disables cache storage;
  • does not forward redirect, auth-challenge, incremental-data, or response-policy semantics correctly;
  • uses URLSession.shared, mixing a globally registered protocol with its own transport;
  • finishes loading after response-less success instead of failing;
  • has no exact-origin or redirect check.

This is not a transparent replacement for WebKit networking.

5. Input parsing is unsafe and silent

PreferencesWindowController.swift:430-442 accepts arbitrary names/values, silently discards malformed lines, permits duplicates and control characters, and allows dangerous fields (Host, Cookie, Authorization, Origin, Referer, WebSocket/proxy headers). It gives no per-line validation/error and no host binding. The unused headersVisibleLines constant also suggests the UI path was not exercised.

6. Preferences layout and Cancel lifecycle are broken

The window grows from 628 to 748 points, but buildUI() keeps var y: CGFloat = 568 even though its own comment says the starting coordinate must move with height (PreferencesWindowController.swift:31-54). The new section consumes about 194 points for only 120 added. The note overlaps the bottom controls, the global-shortcut row falls partly below zero, and Notifications / Launch at Login fall entirely below the content view. The unused headersVisibleLines constant and lack of visual/build evidence reinforce that this was not exercised.

Cancel also preserves the controller instance: PreferencesWindowController.cancel() only closes, while AppDelegate.openPreferences() sets preferencesWindow = nil only from onSave (AppDelegate.swift:873-883). Cancelled secret edits therefore remain in the retained text view and can be committed by a later unrelated Save. Recreate/discard on Cancel or keep pending values separate and clear them exactly.

Required design decision

The cleanest supported design is interactive Cloudflare Access in WKWebView, letting Cloudflare issue its normal browser cookie. If service-token support is mandatory, first prove a supported architecture:

  • main-navigation-only option: Keychain-backed exact-origin credentials applied through one authenticatedRequest(for:) helper used by initial load, reconnect, same-URL reload, and Cmd+R, but only if Cloudflare documentation + a real integration test prove the service-token response establishes a cookie that covers subresources and WebSocket after the headers disappear;
  • otherwise, a deliberately scoped local reverse-proxy/tunnel design that injects per-request credentials for the exact upstream origin and handles WebSocket/TLS/redirects correctly. That is a separate architecture/security project, not a URLProtocol patch.

Verification required

No PR CI or new tests exist. A revised PR needs Mac build/test/build.sh, Keychain migration tests, exact-origin/port and target-switch isolation, redirect-to-foreign-host rejection, forbidden/control-character validation, cancel/empty-body behavior, and a real Cloudflare Access integration proving main document, API fetch, static resources, reconnect/Cmd+R, cookie behavior, and WebSocket. Also verify secrets are absent from DOM/UserDefaults/logs.

Verdict: changes requested; below the 70–80% bounded-fix threshold. Do not merge this implementation. No branch mutation from this review lane.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@nesquena-hermes

Copy link
Copy Markdown
Collaborator

Re-gate at 628ea1999 — cosmetic tip only; every blocker remains

The only delta after reviewed head ee18d2473 is in PreferencesWindowController.swift: it removes the unused headersVisibleLines constant and changes indentation on headersTextView. No networking, storage, DOM, layout, validation, cancel, or test behavior changed.

Therefore every exact-head blocker from the prior review remains open:

  • app-registered URLProtocol still cannot intercept WKWebView HTTP/HTTPS traffic;
  • global Foundation interception remains unscoped and can leak headers to unrelated URLSession requests/redirects;
  • CF-Access-Client-Secret remains plaintext in UserDefaults and page-readable DOM;
  • initial load, reconnect, reload, and Cmd+R still do not use a supported exact-origin authenticated request path;
  • URLProtocol still cannot cancel its task and breaks empty-body/redirect/auth/cache/streaming semantics;
  • arbitrary/duplicate/control-character/forbidden headers remain accepted;
  • Preferences layout and Cancel-retained secret-edit lifecycle remain broken;
  • no tests or exact repository CI exist.

The new commit does not implement the requested Keychain/exact-origin/supported-WebKit redesign or verification matrix.

Verdict: changes requested, unchanged from the prior review. This remains below the bounded-fix threshold. No branch mutation from this lane.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants