easy-claude 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +10 -6
- package/README.zh-CN.md +10 -6
- package/native/Overlay.swift +114 -6
- package/native/build/EasyClaudeOverlay.app/Contents/Info.plist +1 -1
- package/native/build/EasyClaudeOverlay.app/Contents/MacOS/EasyClaudeOverlay +0 -0
- package/package.json +3 -2
- package/src/ip-guard/guard.js +22 -0
- package/src/ip-guard/service.js +23 -16
- package/src/overlay-proxy.js +10 -0
- package/src/proxy-config.js +184 -0
- package/src/public-ip.js +10 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# 更新记录
|
|
2
2
|
|
|
3
|
+
## 1.3.0
|
|
4
|
+
|
|
5
|
+
- Add a persistent, editable Subscription day (1–31 or Not set) below automatic usage refresh, visible with settings collapsed.
|
|
6
|
+
|
|
7
|
+
## 1.2.0
|
|
8
|
+
|
|
9
|
+
- Add Start Claude proxy (green) and Stop Claude proxy (yellow) below the local proxy address. Save and restore previous proxy fields; require explicit default restoration for legacy settings without a saved baseline. Never restart Claude automatically.
|
|
10
|
+
|
|
11
|
+
- Raise the minimum IP check interval to 60 seconds, including manual/network-triggered checks; migrate saved 30-second settings.
|
|
12
|
+
- Add ipify fallback for IP checks, preserve ipinfo as primary, and cool down rate-limited protection sources for ten minutes.
|
|
13
|
+
- Keep forwarding blocked while revalidation waits; never use fallback to override a valid but non-allowlisted primary IP. IP-only fallback does not fabricate a city/time zone.
|
|
14
|
+
|
|
3
15
|
## 1.1.0
|
|
4
16
|
|
|
5
17
|
- Use a fixed local proxy for normal Claude startup; withdraw the outer desktop sandbox after nested-sandbox helper crashes. Fail closed when the switch is off or IP verification is invalid. Official proxy coverage exceptions remain documented.
|
package/README.md
CHANGED
|
@@ -14,16 +14,16 @@ Enable Exit IP protection and enter the IPv4 allowlist. Only a successful curren
|
|
|
14
14
|
|
|
15
15
|
Configuration changes require manually reopening Claude; the tool does not restart it. This is application proxy control, not an OS firewall: native updates, external browsers and programs that ignore proxy settings are not fully covered. IPv4 HTTPS CONNECT on port 443 is supported; IPv6 and other target ports are refused by this proxy. Protection covers configured proxy connections and does not guarantee control of every Claude-related network request.
|
|
16
16
|
|
|
17
|
+
Below Local proxy, click green Start Claude proxy to back up and configure Desktop and Code. Desktop changes require administrator approval. Yellow Stop Claude proxy restores saved proxy fields while preserving unrelated later edits; legacy settings without a baseline require confirmation before restoring defaults. Reopen Claude manually after configuration changes.
|
|
18
|
+
|
|
17
19
|
[Setup, proxy configuration and removal](docs/exit-ip-protection.md) · [Development verification](docs/版本/出口IP保护开发管理.md)
|
|
18
20
|
|
|
19
|
-
## v1.
|
|
21
|
+
## v1.3.0 release notes
|
|
20
22
|
|
|
21
|
-
- Add a
|
|
22
|
-
-
|
|
23
|
-
- Add an automatic usage refresh switch, off by default, retaining manual refresh and HTTP 429 cooldowns.
|
|
24
|
-
- Keep normal Launch Claude behavior and identify ipinfo.io as the time-zone lookup source.
|
|
23
|
+
- Add a persistent Subscription day row below Automatic usage refresh, visible with settings collapsed. Select day 1–31 or Not set.
|
|
24
|
+
- Subscription day is a personal note; it does not read billing or change usage resets.
|
|
25
25
|
|
|
26
|
-
[Release history](CHANGELOG.md) · [1.
|
|
26
|
+
[Release history](CHANGELOG.md) · [1.3.0 verification](docs/版本/1.3.0开发管理.md)
|
|
27
27
|
|
|
28
28
|
## Install and run
|
|
29
29
|
|
|
@@ -117,3 +117,7 @@ CLI login can expire while the desktop remains signed in. Official service respo
|
|
|
117
117
|
[Version management](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/README.md)
|
|
118
118
|
|
|
119
119
|
The Network & protection section groups the current exit, allowlist and protection status. With protection on, the displayed exit follows the protection check immediately; failures show unknown instead of an old IP. Expand More settings to edit the allowlist and interval.
|
|
120
|
+
|
|
121
|
+
## Subscription day
|
|
122
|
+
|
|
123
|
+
A Subscription day row below Automatic usage refresh stays visible with settings collapsed. Choose day 1–31 or Not set; each tool saves its own value. This is a personal note, not a billing lookup or usage reset.
|
package/README.zh-CN.md
CHANGED
|
@@ -16,16 +16,16 @@ Claude App 与 Claude Code CLI 共用固定本机代理 **http://127.0.0.1:18197
|
|
|
16
16
|
|
|
17
17
|
修改代理后需要用户自行重新打开Claude,不自动重启。此方案是应用代理控制,不是系统防火墙:官方更新器、外部浏览器及忽略代理变量的程序不一定受控。当前代理只支持IPv4 HTTPS CONNECT 443,拒绝IPv6与其他目标端口;尚不能宣称所有Claude相关流量均受保护。
|
|
18
18
|
|
|
19
|
+
在本机代理地址下点击绿色“启动Claude代理”,会先备份再配置Claude App和CLI;桌面部分需要管理员授权。黄色“停止Claude代理”恢复本工具保存的原字段,保留其他新设置;旧版/手动配置无记录时,先确认是否恢复默认网络。配置变更需手动重开Claude。
|
|
20
|
+
|
|
19
21
|
[安装、代理配置、关闭与卸载](docs/出口IP保护.md) · [开发验证记录](docs/版本/出口IP保护开发管理.md)
|
|
20
22
|
|
|
21
|
-
## v1.
|
|
23
|
+
## v1.3.0 更新说明
|
|
22
24
|
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
- 新增额度自动刷新开关,默认关闭,保留手动刷新和429冷却。
|
|
26
|
-
- 保留正常“启动 Claude”按钮;设置文案为`跟随IP时区:ipinfo.io`。
|
|
25
|
+
- 新增“订阅日期”,在“额度自动刷新”下方常驻显示,收起时也可见;支持每月1–31日(如“3日”)或“未设置”,独立保存。
|
|
26
|
+
- 订阅日期仅作个人记录,不读取账单、不改变额度重置。
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
历史见[CHANGELOG](CHANGELOG.md),本版见[开发与发布记录](docs/版本/1.3.0开发管理.md)。
|
|
29
29
|
|
|
30
30
|
## 安装与使用
|
|
31
31
|
|
|
@@ -149,3 +149,7 @@ IP地理库的城市与时区可能存在偏差或互相不一致;显示接口
|
|
|
149
149
|
额度自动刷新默认关闭,开启后每5分钟查询,重置/提醒到点每分钟确认,关闭后仅手动。服务返回429后先等待10分钟、后最长15分钟,手动刷新遵守冷却,成功后清零。网络与保护合为一个分区,保护开启时当前出口与保护检测同步更新;失败显示未知,白名单和复查周期在更多设置中修改。关闭保护时IP/城市查询每5分钟刷新。
|
|
150
150
|
|
|
151
151
|
[版本管理](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/README.md)
|
|
152
|
+
|
|
153
|
+
## 订阅日期
|
|
154
|
+
|
|
155
|
+
控制面板在“额度自动刷新”下方新增“订阅日期”,收起设置时也显示。可选每月1–31日(如“3日”)或“未设置”,各工具独立保存;只作个人记录,不查询账单、不改变额度重置。
|
package/native/Overlay.swift
CHANGED
|
@@ -653,6 +653,7 @@ struct ControlPanelView: View {
|
|
|
653
653
|
}
|
|
654
654
|
Divider()
|
|
655
655
|
setting(L("额度自动刷新", "Automatic usage refresh"), value: owner.automaticUsageRefresh) { owner.toggleAutomaticUsageRefresh() }
|
|
656
|
+
subscription
|
|
656
657
|
Divider()
|
|
657
658
|
HStack(spacing: 7) {
|
|
658
659
|
Image(systemName: "clock").foregroundStyle(.secondary)
|
|
@@ -688,6 +689,19 @@ struct ControlPanelView: View {
|
|
|
688
689
|
.preferredColorScheme(.dark)
|
|
689
690
|
.lineSpacing(2)
|
|
690
691
|
}
|
|
692
|
+
var subscription: some View {
|
|
693
|
+
HStack {
|
|
694
|
+
Text(L("订阅日期", "Subscription day")).font(.system(size: 12))
|
|
695
|
+
Spacer()
|
|
696
|
+
Picker(L("订阅日期", "Subscription day"), selection: Binding(
|
|
697
|
+
get: { owner.subscriptionDay }, set: { owner.setSubscriptionDay($0) })) {
|
|
698
|
+
Text(L("未设置", "Not set")).tag(0)
|
|
699
|
+
ForEach(1...31, id: \.self) { day in Text(L("\(day)日", "Day \(day)")).tag(day) }
|
|
700
|
+
}
|
|
701
|
+
.labelsHidden().frame(width: 110).controlSize(.small)
|
|
702
|
+
.accessibilityIdentifier("subscriptionDay")
|
|
703
|
+
}.frame(minHeight: 20)
|
|
704
|
+
}
|
|
691
705
|
func iconButton(_ label: String, _ image: String, action: @escaping () -> Void) -> some View {
|
|
692
706
|
Button(action: action) { Image(systemName: image).frame(width: 20, height: 20) }
|
|
693
707
|
.buttonStyle(.plain).help(label).accessibilityLabel(label)
|
|
@@ -728,12 +742,25 @@ struct ControlPanelView: View {
|
|
|
728
742
|
Text(L("复查间隔", "Check interval"))
|
|
729
743
|
Spacer()
|
|
730
744
|
Picker("", selection: $owner.protectionInterval) {
|
|
731
|
-
ForEach([
|
|
745
|
+
ForEach([60, 120, 300], id: \.self) { value in Text("\(value)s").tag(value) }
|
|
732
746
|
}.labelsHidden().frame(width: 85)
|
|
733
747
|
.onChange(of: owner.protectionInterval) { _, _ in owner.protectionConfigurationChanged() }
|
|
734
748
|
}.font(.system(size: 11)).controlSize(.small)
|
|
735
749
|
networkRow(L("本机代理", "Local proxy"), "127.0.0.1:18197")
|
|
736
|
-
|
|
750
|
+
HStack {
|
|
751
|
+
Button { owner.changeClaudeProxy() } label: {
|
|
752
|
+
Text(owner.proxyActionText).font(.system(size: 11, weight: .medium)).foregroundColor(.black)
|
|
753
|
+
.padding(.horizontal, 10).padding(.vertical, 5)
|
|
754
|
+
.background(RoundedRectangle(cornerRadius: 5).fill(owner.proxyReport?.active == true ? Color.yellow : Color.green))
|
|
755
|
+
}.buttonStyle(.plain)
|
|
756
|
+
.disabled(owner.proxyProcess != nil || owner.proxyReport == nil)
|
|
757
|
+
.accessibilityIdentifier("claudeProxyAction")
|
|
758
|
+
if owner.proxyProcess != nil { ProgressView().controlSize(.small) }
|
|
759
|
+
}
|
|
760
|
+
if let message = owner.proxyMessage {
|
|
761
|
+
Text(message).font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
|
762
|
+
}
|
|
763
|
+
Text(L("Claude指向本机代理时,关闭保护或退出工具会阻断连接。配置变更需手动重开Claude生效。", "While Claude uses this proxy, turning off protection or quitting blocks connections. Reopen Claude manually after configuration changes."))
|
|
737
764
|
.font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
|
738
765
|
}
|
|
739
766
|
if let error = owner.protectionError {
|
|
@@ -852,8 +879,68 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
852
879
|
var checkedAt: String?
|
|
853
880
|
var ready: Bool?
|
|
854
881
|
}
|
|
882
|
+
struct ProxyReport: Decodable {
|
|
883
|
+
var active: Bool
|
|
884
|
+
var configured: Bool
|
|
885
|
+
var hasBackup: Bool?
|
|
886
|
+
var machinePolicy: Bool?
|
|
887
|
+
var needsDefaultRestore: Bool?
|
|
888
|
+
var needsRestart: Bool?
|
|
889
|
+
var restoredDefault: Bool?
|
|
890
|
+
var error: String?
|
|
891
|
+
}
|
|
892
|
+
@Published var proxyReport: ProxyReport?
|
|
893
|
+
@Published var proxyMessage: String?
|
|
894
|
+
@Published var proxyProcess: Process?
|
|
895
|
+
var proxyActionText: String {
|
|
896
|
+
guard proxyReport != nil else { return L("检查代理中…", "Checking proxy…") }
|
|
897
|
+
return proxyReport?.active == true ? L("停止Claude代理", "Stop Claude proxy") : L("启动Claude代理", "Start Claude proxy")
|
|
898
|
+
}
|
|
899
|
+
func checkProxyConfiguration() { runProxyAction("status") }
|
|
900
|
+
func changeClaudeProxy() { runProxyAction(proxyReport?.active == true ? "stop" : "start") }
|
|
901
|
+
func runProxyAction(_ action: String) {
|
|
902
|
+
guard proxyProcess == nil else { return }
|
|
903
|
+
let process = Process(), pipe = Pipe()
|
|
904
|
+
process.executableURL = URL(fileURLWithPath: node)
|
|
905
|
+
process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent().appendingPathComponent("overlay-proxy.js").path, action]
|
|
906
|
+
var env = ProcessInfo.processInfo.environment
|
|
907
|
+
env["PATH"] = searchPath
|
|
908
|
+
if !claudeHome.isEmpty { env["CLAUDE_CONFIG_DIR"] = claudeHome }
|
|
909
|
+
process.environment = env
|
|
910
|
+
process.standardOutput = pipe; process.standardError = FileHandle.nullDevice
|
|
911
|
+
process.terminationHandler = { [weak self] process in
|
|
912
|
+
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
|
913
|
+
Task { @MainActor in
|
|
914
|
+
guard let self, self.proxyProcess === process else { return }
|
|
915
|
+
self.proxyProcess = nil
|
|
916
|
+
guard data.count <= 8192, let result = try? JSONDecoder().decode(ProxyReport.self, from: data) else {
|
|
917
|
+
self.proxyReport = nil
|
|
918
|
+
self.proxyMessage = L("无法检查代理配置,请重开面板后重试。", "Cannot verify proxy settings. Reopen the panel to retry.")
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
self.proxyReport = result
|
|
922
|
+
if let error = result.error {
|
|
923
|
+
self.proxyMessage = AppLanguage.current == .zh ? error : "Proxy configuration failed. Check permissions and saved backups."
|
|
924
|
+
} else if result.machinePolicy == true {
|
|
925
|
+
self.proxyMessage = L("存在机器级代理策略,请由管理员处理。", "A machine-level proxy policy requires administrator management.")
|
|
926
|
+
} else if result.needsDefaultRestore == true {
|
|
927
|
+
let alert = NSAlert()
|
|
928
|
+
alert.messageText = L("旧配置缺少原始备份", "Original settings were not saved")
|
|
929
|
+
alert.informativeText = L("这份代理配置并非由新按钮保存。无法确认原来的自定义代理;可以只移除 easy-claude 的代理字段,恢复应用默认网络。其他字段保留,Claude 不会自动重开。", "These settings have no saved original proxy. You may remove only easy-claude proxy fields and restore application defaults. Other settings stay intact; Claude will not restart.")
|
|
930
|
+
alert.addButton(withTitle: L("恢复默认", "Restore defaults")); alert.addButton(withTitle: L("取消", "Cancel"))
|
|
931
|
+
if alert.runModal() == .alertFirstButtonReturn { self.runProxyAction("stop-default") }
|
|
932
|
+
} else if result.needsRestart == true {
|
|
933
|
+
self.proxyMessage = result.active ? L("代理配置成功。请确认保护开启且IP验证通过,再手动重开Claude。", "Proxy configured. Ensure protection is enabled and the IP is verified, then reopen Claude manually.") : (result.restoredDefault == true ? L("已恢复默认配置,请手动重开Claude生效。", "Defaults restored. Reopen Claude manually to apply.") : L("已恢复原代理配置,请手动重开Claude生效。", "Original proxy settings restored. Reopen Claude manually to apply."))
|
|
934
|
+
} else { self.proxyMessage = nil }
|
|
935
|
+
self.resizeControls()
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
proxyProcess = process
|
|
939
|
+
do { try process.run() }
|
|
940
|
+
catch { proxyProcess = nil; proxyReport = nil; proxyMessage = L("无法启动代理配置组件。", "Cannot start the proxy configuration helper.") }
|
|
941
|
+
}
|
|
855
942
|
@Published var automaticUsageRefresh = UserDefaults.standard.bool(forKey: "automaticUsageRefresh")
|
|
856
|
-
var protectionIsAllowed: Bool { protectionEnabled && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
|
|
943
|
+
var protectionIsAllowed: Bool { protectionEnabled && proxyReport?.configured == true && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
|
|
857
944
|
var networkIPText: String {
|
|
858
945
|
guard protectionEnabled else { return displayMessage(ipText) }
|
|
859
946
|
guard protectionError == nil, let report = protectionReport else { return L("IP 未知", "IP unknown") }
|
|
@@ -877,7 +964,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
877
964
|
}
|
|
878
965
|
@Published var protectionEnabled = UserDefaults.standard.bool(forKey: "ipProtectionEnabled")
|
|
879
966
|
@Published var protectionIPs = UserDefaults.standard.string(forKey: "ipProtectionAddresses") ?? ""
|
|
880
|
-
@Published var protectionInterval = UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60
|
|
967
|
+
@Published var protectionInterval = max(60, UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60)
|
|
881
968
|
@Published var protectionReport: ProtectionReport?
|
|
882
969
|
@Published var protectionError: String?
|
|
883
970
|
var protectionProcess: Process?
|
|
@@ -892,6 +979,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
892
979
|
if !protectionEnabled {
|
|
893
980
|
return protectionProcess != nil && protectionReport?.state != "off" ? L("正在阻断代理…", "Blocking proxy…") : L("保护已关闭 · 代理已阻断", "Protection off · proxy blocked")
|
|
894
981
|
}
|
|
982
|
+
guard proxyReport?.configured == true else { return L("Claude代理未配置完成 · 未受保护", "Claude proxy is not configured · unprotected") }
|
|
895
983
|
switch protectionReport?.state {
|
|
896
984
|
case "allowed": return L("代理已放通 · 出口 IP 符合白名单", "Proxy allowed · exit IP matches the allowlist")
|
|
897
985
|
case "checking": return L("验证中 · 代理已阻断", "Verifying · proxy blocked")
|
|
@@ -913,6 +1001,11 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
913
1001
|
var ipClockCity: String?
|
|
914
1002
|
var manualClockZone = TimeZone(identifier: "America/Los_Angeles")!
|
|
915
1003
|
var manualClockCity = "硅谷"
|
|
1004
|
+
// 仅记录用户指定的每月日期,不读取账号账单或据此推算额度重置。
|
|
1005
|
+
@Published var subscriptionDay: Int = {
|
|
1006
|
+
let day = UserDefaults.standard.integer(forKey: "subscriptionDay")
|
|
1007
|
+
return (1...31).contains(day) ? day : 0
|
|
1008
|
+
}()
|
|
916
1009
|
@Published var controlRevision = 0
|
|
917
1010
|
let controlPopover = NSPopover()
|
|
918
1011
|
var controlsExpanded = false
|
|
@@ -920,13 +1013,14 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
920
1013
|
var controlHeight: CGFloat {
|
|
921
1014
|
let state = currentControlState()
|
|
922
1015
|
let quotaHeight: CGFloat = state.login ? 155 : CGFloat(max(1, state.quotas.count)) * 62 + (state.mode == "ready" ? 0 : 65)
|
|
923
|
-
let total = quotaHeight +
|
|
1016
|
+
let total = quotaHeight + 342 + (controlsExpanded ? (followIPTimeZone ? 455 : 520) : 0)
|
|
924
1017
|
return min(total, max(280, (status?.button?.window?.screen?.visibleFrame.height ?? NSScreen.main?.visibleFrame.height ?? 900) - 65))
|
|
925
1018
|
}
|
|
926
1019
|
var status: NSStatusItem?
|
|
927
1020
|
var timer: Timer?
|
|
928
1021
|
var ipQuery: Process?
|
|
929
1022
|
var ipLastAttempt = Date.distantPast
|
|
1023
|
+
var ipLastProbeUptime = -Double.infinity
|
|
930
1024
|
var ipText = L("正在获取IP…", "Fetching IP…")
|
|
931
1025
|
var query: Process?
|
|
932
1026
|
var updater: Process?
|
|
@@ -958,6 +1052,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
958
1052
|
node = args[1]; script = args[2]; searchPath = args[3]
|
|
959
1053
|
claudeHome = args.count > 4 ? args[4] : ""
|
|
960
1054
|
let prefs = UserDefaults.standard
|
|
1055
|
+
if let previous = prefs.object(forKey: "ipProtectionInterval") as? Int, previous < 60 {
|
|
1056
|
+
prefs.set(60, forKey: "ipProtectionInterval")
|
|
1057
|
+
}
|
|
961
1058
|
if prefs.object(forKey: "leftInset") != nil {
|
|
962
1059
|
inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
|
|
963
1060
|
}
|
|
@@ -1019,6 +1116,8 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
1019
1116
|
controlPopover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
|
|
1020
1117
|
controlPopover.contentViewController = NSHostingController(rootView: ControlPanelView(owner: self))
|
|
1021
1118
|
timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
|
|
1119
|
+
// 授权确认或菜单跟踪期间也要维持保护心跳。
|
|
1120
|
+
if let timer { RunLoop.main.add(timer, forMode: .common) }
|
|
1022
1121
|
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
|
|
1023
1122
|
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(protectionNetworkChanged), name: NSWorkspace.didWakeNotification, object: nil)
|
|
1024
1123
|
protectionPathMonitor.pathUpdateHandler = { [weak self] _ in
|
|
@@ -1026,6 +1125,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
1026
1125
|
}
|
|
1027
1126
|
protectionPathMonitor.start(queue: DispatchQueue(label: "easy-claude.network"))
|
|
1028
1127
|
startProtectionService()
|
|
1128
|
+
checkProxyConfiguration()
|
|
1029
1129
|
tick()
|
|
1030
1130
|
}
|
|
1031
1131
|
func setProtectionEnabled(_ enabled: Bool) {
|
|
@@ -1143,6 +1243,11 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
1143
1243
|
status?.button?.setAccessibilityLabel("Easy \(controlProduct) \(state.headline) \(state.text)")
|
|
1144
1244
|
if controlPopover.isShown { resizeControls() }
|
|
1145
1245
|
}
|
|
1246
|
+
func setSubscriptionDay(_ day: Int) {
|
|
1247
|
+
guard (0...31).contains(day) else { return }
|
|
1248
|
+
subscriptionDay = day
|
|
1249
|
+
UserDefaults.standard.set(day, forKey: "subscriptionDay")
|
|
1250
|
+
}
|
|
1146
1251
|
func setLanguage(_ value: String) {
|
|
1147
1252
|
guard AppLanguage(rawValue: value) != nil else { return }
|
|
1148
1253
|
UserDefaults.standard.set(value, forKey: "interfaceLanguage")
|
|
@@ -1160,6 +1265,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
1160
1265
|
if controlPopover.contentSize != size { controlPopover.contentSize = size }
|
|
1161
1266
|
}
|
|
1162
1267
|
@objc func openControls() {
|
|
1268
|
+
checkProxyConfiguration()
|
|
1163
1269
|
guard let button = status?.button else { return }
|
|
1164
1270
|
if NSApp.currentEvent?.type == .rightMouseUp {
|
|
1165
1271
|
let menu = makeMenu(); status?.menu = menu; button.performClick(nil); status?.menu = nil
|
|
@@ -1290,7 +1396,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
|
|
|
1290
1396
|
if followIPTimeZone { refreshIP() }
|
|
1291
1397
|
}
|
|
1292
1398
|
@objc func refreshIP() {
|
|
1293
|
-
|
|
1399
|
+
let uptime = ProcessInfo.processInfo.systemUptime
|
|
1400
|
+
guard ipQuery == nil, uptime - ipLastProbeUptime >= 60 else { return }
|
|
1401
|
+
ipLastProbeUptime = uptime
|
|
1294
1402
|
ipLastAttempt = Date()
|
|
1295
1403
|
let process = Process(), pipe = Pipe()
|
|
1296
1404
|
process.executableURL = URL(fileURLWithPath: node)
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<key>CFBundleIdentifier</key><string>com.unionschool.easy-claude.overlay</string>
|
|
6
6
|
<key>CFBundleName</key><string>Easy Claude Overlay</string>
|
|
7
7
|
<key>CFBundlePackageType</key><string>APPL</string>
|
|
8
|
-
<key>CFBundleShortVersionString</key><string>1.
|
|
8
|
+
<key>CFBundleShortVersionString</key><string>1.3.0</string>
|
|
9
9
|
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
|
10
10
|
<key>CFBundleLocalizations</key><array><string>en</string><string>zh-Hans</string><string>zh-Hant</string></array>
|
|
11
11
|
<key>LSUIElement</key><true/>
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easy-claude",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Claude Code quota rings and transparent world clock for Claude desktop",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -31,7 +31,8 @@
|
|
|
31
31
|
"test:protection": "node --test --test-timeout=15000 scripts/ip-guard-proof/verify.mjs scripts/ip-guard-proof/service-check.mjs",
|
|
32
32
|
"test:protection-ui": "python3 scripts/test-protection-ui.py",
|
|
33
33
|
"test:focus": "python3 scripts/test-focus.py",
|
|
34
|
-
"test:polling": "python3 scripts/test-polling.py"
|
|
34
|
+
"test:polling": "python3 scripts/test-polling.py",
|
|
35
|
+
"test:subscription": "python3 scripts/test-subscription.py"
|
|
35
36
|
},
|
|
36
37
|
"license": "MIT",
|
|
37
38
|
"author": "UnionSchool",
|
package/src/ip-guard/guard.js
CHANGED
|
@@ -48,6 +48,28 @@ export function probeHTTPS(url, { signal, family = 4, ca, timeout = 1000 } = {})
|
|
|
48
48
|
});
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
export const EXIT_IP_URLS = ['https://ipinfo.io/json', 'https://api.ipify.org?format=json'];
|
|
52
|
+
|
|
53
|
+
export function createExitIPProbe({ request = probeHTTPS, now = () => performance.now() } = {}) {
|
|
54
|
+
const retryAt = new Map();
|
|
55
|
+
return async signal => {
|
|
56
|
+
for (const url of EXIT_IP_URLS) {
|
|
57
|
+
if (signal.aborted) throw new Error('检测已取消');
|
|
58
|
+
if (now() < (retryAt.get(url) ?? 0)) continue;
|
|
59
|
+
try {
|
|
60
|
+
const ip = await request(url, { signal, family: 4, timeout: 5000 });
|
|
61
|
+
if (signal.aborted) throw new Error('检测已取消');
|
|
62
|
+
return normalizeIP(ip);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (signal.aborted) throw error;
|
|
65
|
+
if (error.rateLimited) retryAt.set(url, now() + 600000);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const rateLimited = EXIT_IP_URLS.every(url => now() < (retryAt.get(url) ?? 0));
|
|
69
|
+
throw Object.assign(new Error(rateLimited ? '出口 IP 查询服务均不可用(限流,10分钟后重试)' : '出口 IP 查询服务均不可用'), { rateLimited });
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
51
73
|
export class Guard extends EventEmitter {
|
|
52
74
|
constructor({ allowed, probe, ttl = 1000, timeout = 500, cooldown = 1000, now = () => performance.now() }) {
|
|
53
75
|
super();
|
package/src/ip-guard/service.js
CHANGED
|
@@ -2,21 +2,21 @@ import net from 'node:net';
|
|
|
2
2
|
import { mkdir, lstat, chmod, unlink } from 'node:fs/promises';
|
|
3
3
|
import { dirname } from 'node:path';
|
|
4
4
|
import { createInterface } from 'node:readline';
|
|
5
|
-
import { Guard, normalizeIP,
|
|
5
|
+
import { Guard, normalizeIP, createExitIPProbe } from './guard.js';
|
|
6
6
|
import { createGateway } from './gateway.js';
|
|
7
7
|
import { controlPath, DEFAULT_PROXY_PORT } from './launcher.js';
|
|
8
8
|
|
|
9
9
|
export async function startService({ input = process.stdin, output = process.stdout, path = controlPath(), proxyPort = DEFAULT_PROXY_PORT,
|
|
10
|
-
probe =
|
|
10
|
+
probe = createExitIPProbe(), now = () => performance.now(),
|
|
11
11
|
heartbeatTimeout = 15000 } = {}) {
|
|
12
|
-
const guard = new Guard({ allowed: [], probe, ttl: 75000, timeout: 13000, cooldown: 600000 });
|
|
12
|
+
const guard = new Guard({ allowed: [], probe, ttl: 75000, timeout: 13000, cooldown: 600000, now });
|
|
13
13
|
// 服务一开始先阻断,收到界面配置前绝不接受转发。
|
|
14
14
|
guard.enable();
|
|
15
15
|
const gateway = createGateway(guard);
|
|
16
16
|
await new Promise((resolve, reject) => { gateway.server.once('error', reject); gateway.server.listen(proxyPort, '127.0.0.1', resolve); });
|
|
17
17
|
const port = gateway.server.address().port;
|
|
18
18
|
let fault = '', checkedAt = null, interval = 60000;
|
|
19
|
-
let lastCheck = -Infinity, heartbeat =
|
|
19
|
+
let lastCheck = -Infinity, heartbeat = now(), stopped = false, holding = false, verification = 0, requested = false;
|
|
20
20
|
const status = () => {
|
|
21
21
|
const ready = guard.usable() && !fault;
|
|
22
22
|
return { service: 'easy-claude-ip-guard', port, enabled: guard.enabled, ready,
|
|
@@ -24,9 +24,16 @@ export async function startService({ input = process.stdin, output = process.std
|
|
|
24
24
|
};
|
|
25
25
|
const report = () => { if (!stopped && !output.destroyed) output.write(JSON.stringify(status()) + '\n'); };
|
|
26
26
|
const verify = async (keepLease = false) => {
|
|
27
|
-
if (!guard.enabled || stopped || holding
|
|
27
|
+
if (!guard.enabled || stopped || holding) return;
|
|
28
|
+
if (!keepLease) requested = true;
|
|
29
|
+
if (guard.controller || now() < guard.retryAt) return;
|
|
30
|
+
if (now() - lastCheck < 60000) {
|
|
31
|
+
if (!keepLease) { guard.reason = '等待60秒最小查询间隔'; report(); }
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
requested = false;
|
|
28
35
|
const attempt = ++verification;
|
|
29
|
-
lastCheck =
|
|
36
|
+
lastCheck = now();
|
|
30
37
|
const pending = guard.verify({ keepLease }); report();
|
|
31
38
|
await pending;
|
|
32
39
|
if (attempt === verification) checkedAt = new Date().toISOString();
|
|
@@ -36,7 +43,7 @@ export async function startService({ input = process.stdin, output = process.std
|
|
|
36
43
|
const control = net.createServer(socket => { socket.on('error', () => {}); socket.end(JSON.stringify(status()) + '\n'); });
|
|
37
44
|
const stop = async () => {
|
|
38
45
|
if (stopped) return;
|
|
39
|
-
stopped = true; clearInterval(timer); guard.revoke('控制程序已退出');
|
|
46
|
+
stopped = true; verification++; clearInterval(timer); guard.revoke('控制程序已退出');
|
|
40
47
|
reader.close(); await gateway.close();
|
|
41
48
|
await new Promise(resolve => control.close(resolve));
|
|
42
49
|
};
|
|
@@ -64,37 +71,37 @@ export async function startService({ input = process.stdin, output = process.std
|
|
|
64
71
|
}
|
|
65
72
|
reader = createInterface({ input, crlfDelay: Infinity });
|
|
66
73
|
reader.on('line', line => {
|
|
67
|
-
if (line.length > 4096) { guard.revoke(); fault = '控制消息过大'; report(); return; }
|
|
74
|
+
if (line.length > 4096) { verification++; guard.revoke(); fault = '控制消息过大'; report(); return; }
|
|
68
75
|
try {
|
|
69
76
|
const command = JSON.parse(line);
|
|
70
|
-
if (command.action === 'heartbeat') { heartbeat =
|
|
77
|
+
if (command.action === 'heartbeat') { heartbeat = now(); return; }
|
|
71
78
|
if (command.action === 'configure') {
|
|
72
79
|
holding = true;
|
|
73
|
-
guard.revoke('配置修改');
|
|
80
|
+
verification++; guard.revoke('配置修改');
|
|
74
81
|
if (typeof command.enabled !== 'boolean') throw new Error('保护配置无效');
|
|
75
82
|
if (!command.enabled) { holding = false; guard.disable(); fault = ''; report(); return; }
|
|
76
83
|
const ips = command.ips.map(normalizeIP);
|
|
77
84
|
if (!ips.length || ips.length > 20 || ips.some(ip => net.isIP(ip) !== 4)) throw new Error('请输入 IPv4 白名单;当前版本关闭 IPv6 转发');
|
|
78
|
-
if (!Number.isInteger(command.interval) || command.interval <
|
|
85
|
+
if (!Number.isInteger(command.interval) || command.interval < 60 || command.interval > 300) throw new Error('复查间隔应为60至300秒');
|
|
79
86
|
guard.changeAllowed(ips); guard.ttl = command.interval * 1000 + 15000;
|
|
80
87
|
interval = command.interval * 1000; holding = false; guard.enable(); fault = ''; void verify();
|
|
81
88
|
} else if (command.action === 'invalidate' || command.action === 'verify') {
|
|
82
|
-
if (guard.enabled) { guard.revoke('网络变化或重新检测'); report(); void verify(); }
|
|
89
|
+
if (guard.enabled) { verification++; guard.revoke('网络变化或重新检测'); report(); void verify(); }
|
|
83
90
|
} else if (command.action === 'hold') {
|
|
84
|
-
holding = true; guard.revoke('白名单正在编辑'); report();
|
|
91
|
+
holding = true; verification++; guard.revoke('白名单正在编辑'); report();
|
|
85
92
|
} else if (command.action === 'launchDesktop') {
|
|
86
93
|
// Electron辅助进程需要自行初始化沙箱,外层sandbox-exec会使它们启动即崩溃。
|
|
87
94
|
throw new Error('桌面受保护启动暂不可用:嵌套沙箱冲突。请关闭保护后正常启动Claude;不会自动回退直连。');
|
|
88
95
|
} else throw new Error('未知保护命令');
|
|
89
|
-
} catch (error) { guard.revoke('配置或控制错误'); fault = error.message; report(); }
|
|
96
|
+
} catch (error) { verification++; guard.revoke('配置或控制错误'); fault = error.message; report(); }
|
|
90
97
|
});
|
|
91
98
|
reader.on('close', () => { void stop(); });
|
|
92
99
|
output.on('error', () => { void stop(); });
|
|
93
100
|
timer = setInterval(() => {
|
|
94
|
-
if (
|
|
101
|
+
if (now() - heartbeat >= heartbeatTimeout) { void stop(); return; }
|
|
95
102
|
const wasAllowed = guard.state === 'allowed'; guard.usable();
|
|
96
103
|
if (wasAllowed && guard.state !== 'allowed') report();
|
|
97
|
-
if (guard.enabled && !fault &&
|
|
104
|
+
if (guard.enabled && !fault && now() >= guard.retryAt && now() - lastCheck >= (requested ? 60000 : interval)) void verify(!requested);
|
|
98
105
|
}, 500);
|
|
99
106
|
report();
|
|
100
107
|
return { guard, port, status, stop, verify };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { proxyStatus, changeProxy } from './proxy-config.js';
|
|
2
|
+
try {
|
|
3
|
+
if (process.platform !== 'darwin') throw new Error('Claude代理配置仅支持macOS');
|
|
4
|
+
const action = process.argv[2] || 'status';
|
|
5
|
+
console.log(JSON.stringify(action === 'status' ? await proxyStatus() : await changeProxy(action)));
|
|
6
|
+
} catch (error) {
|
|
7
|
+
const status = await proxyStatus().catch(() => ({ active: false, configured: false }));
|
|
8
|
+
console.log(JSON.stringify({ ...status, error: error.message }));
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { promises as fs, constants } from 'node:fs';
|
|
2
|
+
import { join, dirname, basename } from 'node:path';
|
|
3
|
+
import { homedir, userInfo } from 'node:os';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { DEFAULT_PROXY_PORT, DEFAULT_PROXY_URL, proxyEnvironment } from './ip-guard/launcher.js';
|
|
8
|
+
|
|
9
|
+
const run = promisify(execFile);
|
|
10
|
+
const wanted = proxyEnvironment(DEFAULT_PROXY_PORT, {});
|
|
11
|
+
const keys = Object.keys(wanted);
|
|
12
|
+
const hash = data => createHash('sha256').update(data).digest('hex');
|
|
13
|
+
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
14
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
export function proxyPaths() {
|
|
16
|
+
return {
|
|
17
|
+
cli: join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json'),
|
|
18
|
+
desktop: join('/Library/Managed Preferences', userInfo().username, 'com.anthropic.claudefordesktop.plist'),
|
|
19
|
+
machine: '/Library/Managed Preferences/com.anthropic.claudefordesktop.plist',
|
|
20
|
+
state: join(homedir(), 'Library/Application Support/easy-claude/proxy-state.json')
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
async function file(path) {
|
|
24
|
+
try {
|
|
25
|
+
const stat = await fs.lstat(path);
|
|
26
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error('配置文件类型或大小不安全');
|
|
27
|
+
return { stat, data: await fs.readFile(path) };
|
|
28
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
29
|
+
}
|
|
30
|
+
function json(data) {
|
|
31
|
+
let value;
|
|
32
|
+
try { value = JSON.parse(data); } catch { throw new Error('配置JSON无效,请先修复原文件'); }
|
|
33
|
+
if (!object(value) || (value.env !== undefined && !object(value.env))) throw new Error('配置结构无效,未修改原文件');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
async function desktopValue(path) {
|
|
37
|
+
if (!await file(path)) return null;
|
|
38
|
+
try { return (await run('/usr/bin/plutil', ['-extract', 'egressProxyUrl', 'raw', '-o', '-', path], { timeout: 5000, maxBuffer: 8192 })).stdout.replace(/\n$/, ''); }
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (((error.stdout || '') + (error.stderr || '')).includes('No value at that key path')) return null;
|
|
41
|
+
throw new Error('无法读取桌面代理策略,请检查文件权限或管理员策略');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function snapshot(paths) {
|
|
45
|
+
const saved = await file(paths.state);
|
|
46
|
+
if (!saved) return null;
|
|
47
|
+
if (saved.stat.uid !== process.getuid() || saved.stat.mode & 0o077) throw new Error('代理备份记录权限不安全');
|
|
48
|
+
const value = json(saved.data);
|
|
49
|
+
if (value.version !== 1 || value.cli !== paths.cli || value.desktop !== paths.desktop) throw new Error('代理配置目录已变化,请先恢复原目录配置');
|
|
50
|
+
if ((value.desktopBackup !== null && !/^[a-f0-9]{64}$/.test(value.desktopHash || '')) || (value.cliBackup !== null && !/^[a-f0-9]{64}$/.test(value.cliHash || ''))) throw new Error('代理备份校验信息无效');
|
|
51
|
+
for (const [key, target, pattern] of [['cliBackup', paths.cli, /^settings\.bak-\d{8}-\d{6}\.json$/],
|
|
52
|
+
['desktopBackup', paths.desktop, /^com\.anthropic\.claudefordesktop\.bak-\d{8}-\d{6}\.plist$/]]) {
|
|
53
|
+
if (value[key] !== null && (typeof value[key] !== 'string' || dirname(value[key]) !== dirname(target) || !pattern.test(basename(value[key])))) throw new Error('代理备份路径无效');
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export async function proxyStatus({ paths = proxyPaths() } = {}) {
|
|
58
|
+
const cliFile = await file(paths.cli), env = cliFile ? json(cliFile.data).env || {} : {};
|
|
59
|
+
const desktop = await desktopValue(paths.desktop);
|
|
60
|
+
const machine = await desktopValue(paths.machine);
|
|
61
|
+
const saved = await snapshot(paths);
|
|
62
|
+
return {
|
|
63
|
+
active: desktop === DEFAULT_PROXY_URL || keys.some(key => env[key] === wanted[key] && !key.toLowerCase().includes('no_proxy')),
|
|
64
|
+
configured: machine === null && desktop === DEFAULT_PROXY_URL && keys.every(key => env[key] === wanted[key]),
|
|
65
|
+
hasBackup: saved !== null,
|
|
66
|
+
machinePolicy: machine !== null
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
async function privateDirectory(path) {
|
|
70
|
+
await fs.mkdir(path, { recursive: true, mode: 0o700 });
|
|
71
|
+
const stat = await fs.lstat(path);
|
|
72
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid() || stat.mode & 0o077) throw new Error('代理备份目录权限不安全');
|
|
73
|
+
}
|
|
74
|
+
async function atomic(path, data, mode = 0o600) {
|
|
75
|
+
const temp = path + '.easy-' + randomBytes(8).toString('hex');
|
|
76
|
+
try { await fs.writeFile(temp, data, { flag: 'wx', mode }); await fs.rename(temp, path); }
|
|
77
|
+
finally { await fs.unlink(temp).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
78
|
+
}
|
|
79
|
+
function stamp() {
|
|
80
|
+
const d = new Date(), two = n => String(n).padStart(2, '0');
|
|
81
|
+
return `${d.getFullYear()}${two(d.getMonth() + 1)}${two(d.getDate())}-${two(d.getHours())}${two(d.getMinutes())}${two(d.getSeconds())}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 管理员只运行系统自带工具;恢复时在plist内部复制字段,旧代理凭据不进入命令参数。
|
|
85
|
+
export function desktopScript(action, paths, saved, rollback = null) {
|
|
86
|
+
const dir = dirname(paths.desktop), token = '__easy_proxy_' + randomBytes(6).toString('hex');
|
|
87
|
+
const safe = path => `\n[ ! -L ${quote(path)} ]\n[ "$(/usr/bin/stat -f %u ${quote(path)})" = 0 ]\nmode=$(/usr/bin/stat -f %Lp ${quote(path)})\n[ $((0$mode & 022)) -eq 0 ]`;
|
|
88
|
+
let script = `set -eu\n[ ! -L ${quote(dirname(dir))} ]\n/bin/mkdir -p ${quote(dirname(dir))}${safe(dirname(dir))}\n[ ! -L ${quote(dir)} ]\n/bin/mkdir -p ${quote(dir)}${safe(dir)}\ncd ${quote(dir)}\n`;
|
|
89
|
+
script += `target=${quote(paths.desktop)}\nif [ -e "$target" ]; then ${safe(paths.desktop)}\n/usr/bin/plutil -lint "$target" >/dev/null\nfi\n`;
|
|
90
|
+
script += `if [ -e ${quote(paths.machine)} ]; then /usr/bin/plutil -lint ${quote(paths.machine)} >/dev/null; if /usr/bin/plutil -type egressProxyUrl ${quote(paths.machine)} >/dev/null 2>&1; then exit 1; fi; fi\n`;
|
|
91
|
+
if (action === 'start') {
|
|
92
|
+
if (saved.desktopBackup) {
|
|
93
|
+
script += `[ -f "$target" ]\n[ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk '{print $1}')" = ${quote(saved.desktopHash)} ]\n[ ! -e ${quote(saved.desktopBackup)} ]\n/bin/cp -p "$target" ${quote(saved.desktopBackup)}\n`;
|
|
94
|
+
} else { script += '[ ! -e "$target" ]\n'; }
|
|
95
|
+
} else { script += `current=$(/usr/bin/plutil -extract egressProxyUrl raw -o - "$target" 2>/dev/null || true)\n[ "$current" = ${quote(DEFAULT_PROXY_URL)} ] || exit 0\n`; }
|
|
96
|
+
if (action === 'stop-default' && rollback?.desktopBackup) {
|
|
97
|
+
script += `[ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk '{print $1}')" = ${quote(rollback.desktopHash)} ]\n[ ! -e ${quote(rollback.desktopBackup)} ]\n/bin/cp -p "$target" ${quote(rollback.desktopBackup)}\n`;
|
|
98
|
+
}
|
|
99
|
+
script += 'sourceHash=\nif [ -e "$target" ]; then sourceHash=$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk \'{print $1}\'); fi\n';
|
|
100
|
+
script += `temp=$(/usr/bin/mktemp ${quote(join(dir, '.easy-proxy.XXXXXX'))})\ntrap '/bin/rm -f "$temp"' EXIT\nif [ -e "$target" ]; then /bin/cp -p "$target" "$temp"; else /usr/bin/plutil -create xml1 "$temp"; /bin/chmod 644 "$temp"; fi\n`;
|
|
101
|
+
if (action === 'start') script += `/usr/bin/plutil -replace egressProxyUrl -string ${quote(DEFAULT_PROXY_URL)} "$temp"\n`;
|
|
102
|
+
else {
|
|
103
|
+
script += '/usr/bin/plutil -remove egressProxyUrl "$temp"\n';
|
|
104
|
+
if (saved?.desktopBackup) {
|
|
105
|
+
script += `${safe(saved.desktopBackup)}\n[ "$(/usr/bin/shasum -a 256 ${quote(saved.desktopBackup)} | /usr/bin/awk '{print $1}')" = ${quote(saved.desktopHash)} ]\n`;
|
|
106
|
+
script += `if /usr/bin/plutil -type egressProxyUrl ${quote(saved.desktopBackup)} >/dev/null 2>&1; then\n/usr/libexec/PlistBuddy -c ${quote(`Add :${token} dict`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Merge ${basename(saved.desktopBackup)} :${token}`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Copy :${token}:egressProxyUrl :egressProxyUrl`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Delete :${token}`)} "$temp"\nfi\n`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return script + '/usr/bin/plutil -lint "$temp" >/dev/null\nif [ -e "$target" ]; then [ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk \'{print $1}\')" = "$sourceHash" ]; else [ -z "$sourceHash" ]; fi\n/bin/mv -f "$temp" "$target"\n';
|
|
110
|
+
}
|
|
111
|
+
async function administrator({ script }) {
|
|
112
|
+
try { await run('/usr/bin/osascript', ['-e', 'on run argv', '-e', 'do shell script (item 1 of argv) with administrator privileges', '-e', 'end run', script], { timeout: 120000, maxBuffer: 8192 }); }
|
|
113
|
+
catch (error) { throw new Error((error.stderr || '').includes('-128') ? '已取消管理员授权' : '桌面代理操作失败,请检查管理员策略和权限'); }
|
|
114
|
+
}
|
|
115
|
+
export async function changeProxy(action, { paths = proxyPaths(), admin = administrator } = {}) {
|
|
116
|
+
if (!['start', 'stop', 'stop-default'].includes(action)) throw new Error('未知代理操作');
|
|
117
|
+
const before = await proxyStatus({ paths });
|
|
118
|
+
if (action === 'start' && before.configured) return before;
|
|
119
|
+
if (before.machinePolicy) throw new Error('存在机器级代理策略,请由管理员管理;未覆盖该策略');
|
|
120
|
+
let saved = await snapshot(paths);
|
|
121
|
+
let rollback = null;
|
|
122
|
+
if (action === 'stop-default' && saved) throw new Error('已有原配置备份,请使用停止操作恢复');
|
|
123
|
+
if (action === 'stop' && !saved && before.active) return { ...before, needsDefaultRestore: true };
|
|
124
|
+
if (action !== 'start' && !before.active) return before;
|
|
125
|
+
if (action === 'start' && before.active && !saved) throw new Error('旧配置没有原始备份,请先停止并确认恢复默认');
|
|
126
|
+
const cliFile = await file(paths.cli), current = cliFile ? json(cliFile.data) : {};
|
|
127
|
+
if (cliFile && (cliFile.stat.uid !== process.getuid() || cliFile.stat.mode & 0o022)) throw new Error('CLI配置文件归属或权限不安全,未修改');
|
|
128
|
+
const next = { ...current, env: { ...(current.env || {}) } };
|
|
129
|
+
await fs.mkdir(dirname(paths.cli), { recursive: true, mode: 0o700 });
|
|
130
|
+
const directory = await fs.lstat(dirname(paths.cli));
|
|
131
|
+
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid() || directory.mode & 0o022) throw new Error('CLI配置目录不安全');
|
|
132
|
+
if (action === 'stop-default') {
|
|
133
|
+
const time = stamp(), desktopFile = await file(paths.desktop);
|
|
134
|
+
rollback = { desktopBackup: desktopFile ? join(dirname(paths.desktop), `com.anthropic.claudefordesktop.bak-${time}.plist`) : null,
|
|
135
|
+
desktopHash: desktopFile ? hash(desktopFile.data) : null };
|
|
136
|
+
if (cliFile) {
|
|
137
|
+
const backup = join(dirname(paths.cli), `settings.bak-${time}.json`);
|
|
138
|
+
await fs.copyFile(paths.cli, backup, constants.COPYFILE_EXCL); await fs.chmod(backup, 0o600);
|
|
139
|
+
if (hash(await fs.readFile(backup)) !== hash(cliFile.data)) throw new Error('CLI配置在备份期间已变化,未修改');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (action === 'start') {
|
|
143
|
+
await privateDirectory(dirname(paths.state));
|
|
144
|
+
const time = stamp(), desktopFile = await file(paths.desktop);
|
|
145
|
+
saved = { version: 1, cli: paths.cli, desktop: paths.desktop,
|
|
146
|
+
cliBackup: cliFile ? join(dirname(paths.cli), `settings.bak-${time}.json`) : null,
|
|
147
|
+
desktopBackup: desktopFile ? join(dirname(paths.desktop), `com.anthropic.claudefordesktop.bak-${time}.plist`) : null,
|
|
148
|
+
desktopHash: desktopFile ? hash(desktopFile.data) : null, cliHash: cliFile ? hash(cliFile.data) : null };
|
|
149
|
+
if (cliFile) {
|
|
150
|
+
await fs.copyFile(paths.cli, saved.cliBackup, constants.COPYFILE_EXCL); await fs.chmod(saved.cliBackup, 0o600);
|
|
151
|
+
if (hash(await fs.readFile(saved.cliBackup)) !== saved.cliHash) throw new Error('CLI配置在备份期间已变化,未修改');
|
|
152
|
+
}
|
|
153
|
+
await atomic(paths.state, JSON.stringify(saved));
|
|
154
|
+
Object.assign(next.env, wanted);
|
|
155
|
+
} else {
|
|
156
|
+
let original = {};
|
|
157
|
+
if (saved?.cliBackup) {
|
|
158
|
+
const backup = await file(saved.cliBackup);
|
|
159
|
+
if (!backup || hash(backup.data) !== saved.cliHash) throw new Error('原始CLI备份缺失或已变化,未猜测原配置');
|
|
160
|
+
original = json(backup.data);
|
|
161
|
+
}
|
|
162
|
+
for (const key of keys) {
|
|
163
|
+
if (next.env[key] !== wanted[key]) continue;
|
|
164
|
+
if (Object.hasOwn(original.env || {}, key)) next.env[key] = original.env[key];
|
|
165
|
+
else delete next.env[key];
|
|
166
|
+
}
|
|
167
|
+
if (!Object.keys(next.env).length && !Object.hasOwn(original, 'env')) delete next.env;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const desktop = await desktopValue(paths.desktop);
|
|
171
|
+
if (action === 'start' || desktop === DEFAULT_PROXY_URL) await admin({ action, paths, saved: action === 'stop-default' ? null : saved, script: desktopScript(action, paths, action === 'stop-default' ? null : saved, rollback) });
|
|
172
|
+
const latest = await file(paths.cli);
|
|
173
|
+
if ((latest ? hash(latest.data) : null) !== (cliFile ? hash(cliFile.data) : null)) throw new Error('CLI配置在操作期间已变化,请重试;未覆盖新内容');
|
|
174
|
+
if (action !== 'start' && saved?.cliBackup === null && !Object.keys(next).length) await fs.unlink(paths.cli).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
175
|
+
else await atomic(paths.cli, JSON.stringify(next, null, 2) + '\n', cliFile ? cliFile.stat.mode & 0o777 : 0o600);
|
|
176
|
+
if (action !== 'start') await fs.unlink(paths.state).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
177
|
+
const result = await proxyStatus({ paths });
|
|
178
|
+
if (action === 'start' && !result.configured) throw new Error('代理配置未完全验证成功,请检查两端配置');
|
|
179
|
+
return { ...result, needsRestart: true, restoredDefault: action === 'stop-default' };
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (action === 'start' && !(await proxyStatus({ paths }).catch(() => ({ active: true }))).active) await fs.unlink(paths.state).catch(() => {});
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/public-ip.js
CHANGED
|
@@ -18,9 +18,16 @@ export async function readPublicIP({ run = promisify(execFile), env = process.en
|
|
|
18
18
|
return stdout;
|
|
19
19
|
};
|
|
20
20
|
let data;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
for (const url of ['https://ipinfo.io/json', 'https://api.ipify.org?format=json']) {
|
|
22
|
+
try {
|
|
23
|
+
const value = JSON.parse(await request(url));
|
|
24
|
+
if (!value || typeof value.ip !== 'string' || !isIP(value.ip)) throw new Error('Invalid IP');
|
|
25
|
+
// 备用只提供IP,不能将旧城市或时区附在新的出口上。
|
|
26
|
+
data = url.includes('ipinfo.io') ? value : { ip: value.ip };
|
|
27
|
+
break;
|
|
28
|
+
} catch { /* 主源失败时仅尝试一次独立备用查询。 */ }
|
|
29
|
+
}
|
|
30
|
+
if (!data) throw new Error(L('IP异常', 'IP unavailable'));
|
|
24
31
|
const ip = data.ip;
|
|
25
32
|
let city = null, timezone = null;
|
|
26
33
|
if (typeof data.city === 'string') {
|