Files
ShadowsocksX-NG/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlAdapters.swift
T
Qiu Yuzhou d2a8d6105c feat(system-proxy): route writes through privileged LaunchDaemon helper
Implements issue #71 with ADR-0020 (supersedes ADR-0019's endpoint-signature
cleanup, startup cleanup, and health-gate cleanup).

- New ShadowsocksX-NG2SystemProxyHelper target: app-bundled root LaunchDaemon
  (SMAppService.daemon, on-demand via MachServices) that mechanically applies
  a closed typed configuration or executes an unconditional clear. Clients are
  accepted by code-signing bundle identifier only; requests run serially on a
  shared queue (last-writer-wins).
- SystemProxyConfiguration is now the closed typed apply payload (Codable over
  JSON XPC): explicit SOCKS/HTTP/HTTPS enable + endpoints, PAC and
  auto-discovery disabled with URL/JS removed, explicit simple-hostname
  exclusion, complete ExceptionsList. Unmodeled Proxies keys are preserved and
  equivalent values skip the commit.
- Cleanup is a side effect of a persisted system-proxy intent on-to-off
  transition only: the switch itself, or the agent-off cascade (persist both
  intents off, clear, then stop listeners; failed cascade persistence records
  no transition and clears nothing). Launch with the switch off, health-gate
  closure, invalid targets, and passive events never clear. Failed clears are
  surfaced without deferred retry.
- Endpoint-signature store, ownership migration, and direct Authorization
  Services writes are removed; old signature files stay inert. Helper
  unavailability or pending approval keeps an enabled intent pending and
  surfaces the Login Items approval path (HomeView button + menu label).
2026-09-30 12:26:40 +08:00

135 lines
4.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Combine
import Foundation
/// 生产运行时 adapter(issue #47):现有 `ProxyRuntimeController` 的唯一
/// 包装,由应用组合根接线。只把控制器既有能力与观察投影到 workflow 缝上,
/// 不复制状态机、generation、健康门禁与系统代理生命周期语义。
@MainActor
final class ControllerProxyRuntimeAdapter: ProxyRuntimeAdapting {
private let controller: ProxyRuntimeController
init(controller: ProxyRuntimeController) {
self.controller = controller
}
var runtimeFacts: ProxyRuntimeFacts { controller.runtimeFacts }
var agentIntentEnabled: Bool { controller.agentIntentEnabled }
var activationFailure: ActivationFailure? { controller.lastActivationFailure }
var systemProxyIntentEnabled: Bool { controller.systemProxyIntentEnabled }
var systemProxyApplication: SystemProxyApplicationFacts {
switch controller.systemProxyState {
case .idle: return .idle
case .pending: return .pending
case .applied: return .applied
case .failed(let facts): return .failed(facts)
}
}
var systemProxyApprovalRequired: Bool { controller.systemProxyApprovalRequired }
var proxyMode: ProxyMode { controller.proxyMode }
var ruleDefaultAction: RuleDefaultAction { controller.ruleDefaultAction }
var skippedInvalidServerCount: Int { controller.skippedServers.count }
var activeTargetID: NodeID? { controller.activeTargetID }
var httpExportCapability: HTTPExportCapability {
HTTPExportCapability(listen: controller.listenSettings)
}
var terminalProxyEnvironmentCommands: TerminalProxyEnvironmentCommands {
TerminalProxyEnvironmentCommands(listen: controller.listenSettings)
}
/// 控制器的 `objectWillChange` 是 willChange 语义;主队列 hop 落地时被
/// 发布的新值已可读,workflow 重观察不会读到半程状态。
var changes: AnyPublisher<Void, Never> {
controller.objectWillChange
.map { _ in () }
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
func resyncOnLaunch() async {
await controller.resyncOnLaunch()
}
func setAgentEnabled(_ enabled: Bool) async {
await controller.setAgentEnabled(enabled)
}
func setSystemProxyEnabled(_ enabled: Bool) async {
await controller.setSystemProxyEnabled(enabled)
}
func openSystemProxyHelperApproval() async {
await controller.openSystemProxyHelperApproval()
}
func setProxyMode(_ mode: ProxyMode) async {
await controller.setProxyMode(mode)
}
func setRuleDefaultAction(_ action: RuleDefaultAction) async {
await controller.setRuleDefaultAction(action)
}
}
/// HTTP 导出能力的唯一派生点:监听设置 → 本机终端使用的可复制导出行。
/// 环境变量始终指向回环地址,避免将命令误用于其他设备。
extension HTTPExportCapability {
init(listen: SslocalListenSettings) {
let urlHost = listen.proxyLoopbackURLHost
let endpoint = "http://\(urlHost):\(listen.httpPort)"
self.init(copyableLine: "export http_proxy=\(endpoint);export https_proxy=\(endpoint);")
}
}
extension TerminalProxyEnvironmentCommands {
init(listen: SslocalListenSettings) {
let host = listen.proxyLoopbackURLHost
let httpEndpoint = "'http://\(host):\(listen.httpPort)'"
let socksEndpoint = "'socks5://\(host):\(listen.socksPort)'"
let noProxy = "'localhost,127.0.0.1,::1,.local'"
let zshBash =
[
"export http_proxy=\(httpEndpoint)",
"export https_proxy=\(httpEndpoint)",
"export all_proxy=\(socksEndpoint)",
"export no_proxy=\(noProxy)",
].joined(separator: "; ") + ";"
let fish =
[
"set -gx http_proxy \(httpEndpoint)",
"set -gx https_proxy \(httpEndpoint)",
"set -gx all_proxy \(socksEndpoint)",
"set -gx no_proxy \(noProxy)",
].joined(separator: "; ") + ";"
self.init(
zshBash: zshBash,
fish: fish)
}
}
extension SslocalListenSettings {
fileprivate var proxyLoopbackURLHost: String {
let host = listenerMode.proxyLoopbackAddress
return host.contains(":") ? "[\(host)]" : host
}
}
/// 目录侧唯一的目标事实出口(窄缝,story 28):存在性 + 显示名路径摘要;
/// 完整目录树、订阅对象与凭据不出此接口。
extension CatalogWorkflow: ProxyTargetFactsReading {
func activeTargetFacts(for targetID: NodeID?) -> ProxyActiveTargetFacts? {
guard let targetID else { return nil }
return ProxyActiveTargetFacts(id: targetID, pathSummary: tree.pathSummary(for: targetID))
}
}