Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [Unreleased]

### Added
- **Custom HTTP headers for Cloudflare Access & reverse-proxy auth — PR #100** — new CUSTOM HEADERS section in Preferences lets users configure `Name: Value` header pairs that get injected into every WKWebView request via a URLProtocol subclass. Enables the desktop app to authenticate behind Cloudflare Access (and similar edge-auth gateways) using service tokens without a browser OTP flow. Contributed by @timerealm.

## [v1.7.3] — 2026-07-18

### Fixed
Expand Down
27 changes: 27 additions & 0 deletions Sources/HermesAgent/BrowserWindowController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -260,11 +260,38 @@ class BrowserWindowController: NSWindowController, NSWindowDelegate, WKUIDelegat
let bounds = contentView.bounds
let statusBarHeight: CGFloat = connectionMode == "ssh" ? 28 : 0

// Register custom URLProtocol to inject HTTP headers on every request
URLProtocol.registerClass(CustomHeaderURLProtocol.self)

let config = WKWebViewConfiguration()
let prefs = WKPreferences()
prefs.setValue(true, forKey: "javaScriptCanAccessClipboard")
prefs.setValue(true, forKey: "DOMPasteAllowed")
config.preferences = prefs

// 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);
})();
""",
injectionTime: .atDocumentStart,
forMainFrameOnly: true
)
config.userContentController.addUserScript(headerMetaScript)
}

let pasteScript = WKUserScript(
source:
"document.addEventListener('paste', function(e) { e.stopImmediatePropagation(); }, true);",
Expand Down
81 changes: 81 additions & 0 deletions Sources/HermesAgent/CustomHeaderURLProtocol.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import Foundation

/// URLProtocol that intercepts HTTP/HTTPS requests from WKWebView
/// and adds custom headers stored in UserDefaults.
///
/// Registered dynamically in BrowserWindowController before the WebView loads.
/// Header key-value pairs are stored as JSON array under the `customHeaders` key.
final class CustomHeaderURLProtocol: URLProtocol {

private static let handledKey = "CustomHeaderURLProtocolHandled"
private static let storageKey = "customHeaders"

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

/// 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)
}

// MARK: - URLProtocol overrides

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
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}

override func startLoading() {
guard let mutableRequest = (request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else {
client?.urlProtocolDidFinishLoading(self)
return
}

// Mark as handled to prevent infinite recursion
URLProtocol.setProperty(true, forKey: Self.handledKey, in: mutableRequest)

// Add custom headers
let headers = Self.loadCustomHeaders()
for header in headers {
mutableRequest.setValue(header.value, forHTTPHeaderField: header.name)
}

let newRequest = mutableRequest as URLRequest
let session = URLSession.shared
let task = session.dataTask(with: newRequest) { [weak self] data, response, error in
guard let self = self else { return }
if let error = error {
self.client?.urlProtocol(self, didFailWithError: error)
return
}
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)
}
task.resume()
}

override func stopLoading() {
// The URLSessionTask is automatically handled; no extra cleanup needed.
}
}
60 changes: 59 additions & 1 deletion Sources/HermesAgent/PreferencesWindowController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ class PreferencesWindowController: NSWindowController {
private var pendingHotkeyKeyCode: UInt32?
private var pendingHotkeyModifiers: UInt32?
private var pendingHotkeyEnabled: Bool?
/// Multi-line text view for custom HTTP headers (e.g. Cloudflare Access service token headers).
private var headersTextView: NSTextView!

init() {
let window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 520, height: 628),
contentRect: NSRect(x: 0, y: 0, width: 520, height: 748),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false
Expand Down Expand Up @@ -153,6 +155,47 @@ class PreferencesWindowController: NSWindowController {
[usernameField, hostField, localPortField, remotePortField, targetURLField]
.forEach { $0?.delegate = self }

// ── Custom Headers section ──
_ = divider()
y -= 4 // Extra spacing before section header
_ = sectionHeader("CUSTOM HEADERS")
y -= 4 // Extra spacing after header

let headerLabel = NSTextField(labelWithString: "Headers (one per line: Name: Value)")
headerLabel.font = NSFont.systemFont(ofSize: 11)
headerLabel.textColor = .secondaryLabelColor
headerLabel.frame = NSRect(x: 164, y: y, width: 300, height: 16)
content.addSubview(headerLabel)
y -= 20

let scrollView = NSScrollView(frame: NSRect(x: 164, y: y - 72, width: 300, height: 72))
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
scrollView.autohidesScrollers = true
scrollView.borderType = .bezelBorder

let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: 284, height: 72))
textView.font = NSFont(name: "Menlo", size: 11) ?? NSFont.systemFont(ofSize: 11)
textView.isRichText = false
textView.autoresizingMask = [.width]
textView.drawsBackground = false
// Load existing headers
let savedHeaders = CustomHeaderURLProtocol.loadCustomHeaders()
if !savedHeaders.isEmpty {
textView.string = savedHeaders.map { "\($0.name): \($0.value)" }.joined(separator: "\n")
}
scrollView.documentView = textView
content.addSubview(scrollView)
headersTextView = textView

// Note about headers
let headerNote = NSTextField(labelWithString: "Sent with every request. For Cloudflare Access, use:\nCF-Access-Client-Id and CF-Access-Client-Secret")
headerNote.font = NSFont.systemFont(ofSize: 10)
headerNote.textColor = .tertiaryLabelColor
headerNote.frame = NSRect(x: 164, y: y - 110, width: 300, height: 30)
content.addSubview(headerNote)
y -= 118

// Fix #41: configurable global shortcut — replaced static label with recorder.
let shortcutLabel = NSTextField(labelWithString: "Global shortcut:")
shortcutLabel.font = NSFont.systemFont(ofSize: 13)
Expand Down Expand Up @@ -381,6 +424,21 @@ class PreferencesWindowController: NSWindowController {
if let kc = pendingHotkeyKeyCode { UserDefaults.standard.set(Int(kc), forKey: "globalHotkeyKeyCode") }
if let m = pendingHotkeyModifiers { UserDefaults.standard.set(Int(m), forKey: "globalHotkeyModifiers") }
if let en = pendingHotkeyEnabled { UserDefaults.standard.set(en, forKey: "globalHotkeyEnabled") }

// Persist custom headers from the text view
let headerLines = headersTextView.string
.components(separatedBy: .newlines)
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty && !$0.hasPrefix("#") }
let parsedHeaders: [(name: String, value: String)] = headerLines.compactMap { line in
guard let colonIndex = line.firstIndex(of: ":") else { return nil }
let name = String(line[..<colonIndex]).trimmingCharacters(in: .whitespaces)
let value = String(line[colonIndex...].dropFirst()).trimmingCharacters(in: .whitespaces)
guard !name.isEmpty else { return nil }
return (name, value)
}
CustomHeaderURLProtocol.saveCustomHeaders(parsedHeaders)

close()
onSave?()
}
Expand Down