easy-claude 1.1.0 → 1.2.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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # 更新记录
2
2
 
3
+ ## 1.2.0
4
+
5
+ - 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.
6
+
7
+ - Raise the minimum IP check interval to 60 seconds, including manual/network-triggered checks; migrate saved 30-second settings.
8
+ - Add ipify fallback for IP checks, preserve ipinfo as primary, and cool down rate-limited protection sources for ten minutes.
9
+ - 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.
10
+
3
11
  ## 1.1.0
4
12
 
5
13
  - 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,18 @@ 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.1.0 release notes
21
+ ## v1.2.0 release notes
20
22
 
21
- - Add a fixed local proxy and IPv4 exit allowlist; invalid, expired or disabled checks block proxy connections.
22
- - Group Network & protection and synchronize the displayed exit with protection checks.
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 green Start Claude proxy and yellow Stop Claude proxy buttons; save and restore original proxy fields. Legacy settings require confirmation before restoring defaults.
24
+ - Enforce a 60-second minimum IP check interval, including manual/network triggers; migrate saved 30-second settings.
25
+ - Fall back from ipinfo to ipify on lookup failure or rate limiting, with a ten-minute protection-source cooldown for HTTP 429.
26
+ - Keep protection heartbeats alive during menus and confirmations. Updates only inspect settings; they never silently configure proxies or restart Claude.
25
27
 
26
- [Release history](CHANGELOG.md) · [1.1.0 development and release](docs/版本/1.1.0开发管理.md)
28
+ [Release history](CHANGELOG.md) · [1.2.0 development and release](docs/版本/1.2.0开发管理.md)
27
29
 
28
30
  ## Install and run
29
31
 
package/README.zh-CN.md CHANGED
@@ -16,16 +16,18 @@ 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.1.0 更新说明
23
+ ## v1.2.0 更新说明
22
24
 
23
- - 新增固定本机代理与 IPv4 出口白名单保护,验证失败、过期或关闭开关时阻断代理连接。
24
- - 整合“网络与保护”分区,出口 IP 与保护检测同步,失败不沿用旧 IP。
25
- - 新增额度自动刷新开关,默认关闭,保留手动刷新和429冷却。
26
- - 保留正常“启动 Claude”按钮;设置文案为`跟随IP时区:ipinfo.io`。
25
+ - 新增绿色“启动Claude代理”与黄色“停止Claude代理”,用户点击后配置两端代理或按原记录恢复;旧版无记录时须确认恢复默认。
26
+ - IP最低复查间隔改为60秒,原30秒设置自动迁移;网络变化仍先阻断,等间隔到点再验证。
27
+ - ipinfo失败或限流时使用ipify备用;保护查询源429冷却10分钟,双源失败保持阻断。
28
+ - 菜单或确认框期间保持保护心跳。安装/更新只检查代理,不静默配置、不自动重开Claude。
27
29
 
28
- 历史版本见[CHANGELOG](CHANGELOG.md),本版见[开发与发布记录](docs/版本/1.1.0开发管理.md)。
30
+ 历史版本见[CHANGELOG](CHANGELOG.md),本版见[开发与发布记录](docs/版本/1.2.0开发管理.md)。
29
31
 
30
32
  ## 安装与使用
31
33
 
@@ -728,12 +728,25 @@ struct ControlPanelView: View {
728
728
  Text(L("复查间隔", "Check interval"))
729
729
  Spacer()
730
730
  Picker("", selection: $owner.protectionInterval) {
731
- ForEach([30, 60, 120, 300], id: \.self) { value in Text("\(value)s").tag(value) }
731
+ ForEach([60, 120, 300], id: \.self) { value in Text("\(value)s").tag(value) }
732
732
  }.labelsHidden().frame(width: 85)
733
733
  .onChange(of: owner.protectionInterval) { _, _ in owner.protectionConfigurationChanged() }
734
734
  }.font(.system(size: 11)).controlSize(.small)
735
735
  networkRow(L("本机代理", "Local proxy"), "127.0.0.1:18197")
736
- Text(L("关闭保护或退出工具,Claude 将无法联网。", "Turning off protection or quitting blocks Claude's proxy connections."))
736
+ HStack {
737
+ Button { owner.changeClaudeProxy() } label: {
738
+ Text(owner.proxyActionText).font(.system(size: 11, weight: .medium)).foregroundColor(.black)
739
+ .padding(.horizontal, 10).padding(.vertical, 5)
740
+ .background(RoundedRectangle(cornerRadius: 5).fill(owner.proxyReport?.active == true ? Color.yellow : Color.green))
741
+ }.buttonStyle(.plain)
742
+ .disabled(owner.proxyProcess != nil || owner.proxyReport == nil)
743
+ .accessibilityIdentifier("claudeProxyAction")
744
+ if owner.proxyProcess != nil { ProgressView().controlSize(.small) }
745
+ }
746
+ if let message = owner.proxyMessage {
747
+ Text(message).font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
748
+ }
749
+ Text(L("Claude指向本机代理时,关闭保护或退出工具会阻断连接。配置变更需手动重开Claude生效。", "While Claude uses this proxy, turning off protection or quitting blocks connections. Reopen Claude manually after configuration changes."))
737
750
  .font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
738
751
  }
739
752
  if let error = owner.protectionError {
@@ -852,8 +865,68 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
852
865
  var checkedAt: String?
853
866
  var ready: Bool?
854
867
  }
868
+ struct ProxyReport: Decodable {
869
+ var active: Bool
870
+ var configured: Bool
871
+ var hasBackup: Bool?
872
+ var machinePolicy: Bool?
873
+ var needsDefaultRestore: Bool?
874
+ var needsRestart: Bool?
875
+ var restoredDefault: Bool?
876
+ var error: String?
877
+ }
878
+ @Published var proxyReport: ProxyReport?
879
+ @Published var proxyMessage: String?
880
+ @Published var proxyProcess: Process?
881
+ var proxyActionText: String {
882
+ guard proxyReport != nil else { return L("检查代理中…", "Checking proxy…") }
883
+ return proxyReport?.active == true ? L("停止Claude代理", "Stop Claude proxy") : L("启动Claude代理", "Start Claude proxy")
884
+ }
885
+ func checkProxyConfiguration() { runProxyAction("status") }
886
+ func changeClaudeProxy() { runProxyAction(proxyReport?.active == true ? "stop" : "start") }
887
+ func runProxyAction(_ action: String) {
888
+ guard proxyProcess == nil else { return }
889
+ let process = Process(), pipe = Pipe()
890
+ process.executableURL = URL(fileURLWithPath: node)
891
+ process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent().appendingPathComponent("overlay-proxy.js").path, action]
892
+ var env = ProcessInfo.processInfo.environment
893
+ env["PATH"] = searchPath
894
+ if !claudeHome.isEmpty { env["CLAUDE_CONFIG_DIR"] = claudeHome }
895
+ process.environment = env
896
+ process.standardOutput = pipe; process.standardError = FileHandle.nullDevice
897
+ process.terminationHandler = { [weak self] process in
898
+ let data = pipe.fileHandleForReading.readDataToEndOfFile()
899
+ Task { @MainActor in
900
+ guard let self, self.proxyProcess === process else { return }
901
+ self.proxyProcess = nil
902
+ guard data.count <= 8192, let result = try? JSONDecoder().decode(ProxyReport.self, from: data) else {
903
+ self.proxyReport = nil
904
+ self.proxyMessage = L("无法检查代理配置,请重开面板后重试。", "Cannot verify proxy settings. Reopen the panel to retry.")
905
+ return
906
+ }
907
+ self.proxyReport = result
908
+ if let error = result.error {
909
+ self.proxyMessage = AppLanguage.current == .zh ? error : "Proxy configuration failed. Check permissions and saved backups."
910
+ } else if result.machinePolicy == true {
911
+ self.proxyMessage = L("存在机器级代理策略,请由管理员处理。", "A machine-level proxy policy requires administrator management.")
912
+ } else if result.needsDefaultRestore == true {
913
+ let alert = NSAlert()
914
+ alert.messageText = L("旧配置缺少原始备份", "Original settings were not saved")
915
+ 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.")
916
+ alert.addButton(withTitle: L("恢复默认", "Restore defaults")); alert.addButton(withTitle: L("取消", "Cancel"))
917
+ if alert.runModal() == .alertFirstButtonReturn { self.runProxyAction("stop-default") }
918
+ } else if result.needsRestart == true {
919
+ 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."))
920
+ } else { self.proxyMessage = nil }
921
+ self.resizeControls()
922
+ }
923
+ }
924
+ proxyProcess = process
925
+ do { try process.run() }
926
+ catch { proxyProcess = nil; proxyReport = nil; proxyMessage = L("无法启动代理配置组件。", "Cannot start the proxy configuration helper.") }
927
+ }
855
928
  @Published var automaticUsageRefresh = UserDefaults.standard.bool(forKey: "automaticUsageRefresh")
856
- var protectionIsAllowed: Bool { protectionEnabled && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
929
+ var protectionIsAllowed: Bool { protectionEnabled && proxyReport?.configured == true && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
857
930
  var networkIPText: String {
858
931
  guard protectionEnabled else { return displayMessage(ipText) }
859
932
  guard protectionError == nil, let report = protectionReport else { return L("IP 未知", "IP unknown") }
@@ -877,7 +950,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
877
950
  }
878
951
  @Published var protectionEnabled = UserDefaults.standard.bool(forKey: "ipProtectionEnabled")
879
952
  @Published var protectionIPs = UserDefaults.standard.string(forKey: "ipProtectionAddresses") ?? ""
880
- @Published var protectionInterval = UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60
953
+ @Published var protectionInterval = max(60, UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60)
881
954
  @Published var protectionReport: ProtectionReport?
882
955
  @Published var protectionError: String?
883
956
  var protectionProcess: Process?
@@ -892,6 +965,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
892
965
  if !protectionEnabled {
893
966
  return protectionProcess != nil && protectionReport?.state != "off" ? L("正在阻断代理…", "Blocking proxy…") : L("保护已关闭 · 代理已阻断", "Protection off · proxy blocked")
894
967
  }
968
+ guard proxyReport?.configured == true else { return L("Claude代理未配置完成 · 未受保护", "Claude proxy is not configured · unprotected") }
895
969
  switch protectionReport?.state {
896
970
  case "allowed": return L("代理已放通 · 出口 IP 符合白名单", "Proxy allowed · exit IP matches the allowlist")
897
971
  case "checking": return L("验证中 · 代理已阻断", "Verifying · proxy blocked")
@@ -920,13 +994,14 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
920
994
  var controlHeight: CGFloat {
921
995
  let state = currentControlState()
922
996
  let quotaHeight: CGFloat = state.login ? 155 : CGFloat(max(1, state.quotas.count)) * 62 + (state.mode == "ready" ? 0 : 65)
923
- let total = quotaHeight + 310 + (controlsExpanded ? (followIPTimeZone ? 395 : 460) : 0)
997
+ let total = quotaHeight + 310 + (controlsExpanded ? (followIPTimeZone ? 455 : 520) : 0)
924
998
  return min(total, max(280, (status?.button?.window?.screen?.visibleFrame.height ?? NSScreen.main?.visibleFrame.height ?? 900) - 65))
925
999
  }
926
1000
  var status: NSStatusItem?
927
1001
  var timer: Timer?
928
1002
  var ipQuery: Process?
929
1003
  var ipLastAttempt = Date.distantPast
1004
+ var ipLastProbeUptime = -Double.infinity
930
1005
  var ipText = L("正在获取IP…", "Fetching IP…")
931
1006
  var query: Process?
932
1007
  var updater: Process?
@@ -958,6 +1033,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
958
1033
  node = args[1]; script = args[2]; searchPath = args[3]
959
1034
  claudeHome = args.count > 4 ? args[4] : ""
960
1035
  let prefs = UserDefaults.standard
1036
+ if let previous = prefs.object(forKey: "ipProtectionInterval") as? Int, previous < 60 {
1037
+ prefs.set(60, forKey: "ipProtectionInterval")
1038
+ }
961
1039
  if prefs.object(forKey: "leftInset") != nil {
962
1040
  inset = CGPoint(x: prefs.double(forKey: "leftInset"), y: prefs.double(forKey: "bottomInset"))
963
1041
  }
@@ -1019,6 +1097,8 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1019
1097
  controlPopover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
1020
1098
  controlPopover.contentViewController = NSHostingController(rootView: ControlPanelView(owner: self))
1021
1099
  timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
1100
+ // 授权确认或菜单跟踪期间也要维持保护心跳。
1101
+ if let timer { RunLoop.main.add(timer, forMode: .common) }
1022
1102
  NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
1023
1103
  NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(protectionNetworkChanged), name: NSWorkspace.didWakeNotification, object: nil)
1024
1104
  protectionPathMonitor.pathUpdateHandler = { [weak self] _ in
@@ -1026,6 +1106,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1026
1106
  }
1027
1107
  protectionPathMonitor.start(queue: DispatchQueue(label: "easy-claude.network"))
1028
1108
  startProtectionService()
1109
+ checkProxyConfiguration()
1029
1110
  tick()
1030
1111
  }
1031
1112
  func setProtectionEnabled(_ enabled: Bool) {
@@ -1160,6 +1241,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1160
1241
  if controlPopover.contentSize != size { controlPopover.contentSize = size }
1161
1242
  }
1162
1243
  @objc func openControls() {
1244
+ checkProxyConfiguration()
1163
1245
  guard let button = status?.button else { return }
1164
1246
  if NSApp.currentEvent?.type == .rightMouseUp {
1165
1247
  let menu = makeMenu(); status?.menu = menu; button.performClick(nil); status?.menu = nil
@@ -1290,7 +1372,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1290
1372
  if followIPTimeZone { refreshIP() }
1291
1373
  }
1292
1374
  @objc func refreshIP() {
1293
- guard ipQuery == nil else { return }
1375
+ let uptime = ProcessInfo.processInfo.systemUptime
1376
+ guard ipQuery == nil, uptime - ipLastProbeUptime >= 60 else { return }
1377
+ ipLastProbeUptime = uptime
1294
1378
  ipLastAttempt = Date()
1295
1379
  let process = Process(), pipe = Pipe()
1296
1380
  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.1.0</string>
8
+ <key>CFBundleShortVersionString</key><string>1.2.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/>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-claude",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
5
  "type": "module",
6
6
  "bin": {
@@ -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();
@@ -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, probeHTTPS } from './guard.js';
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 = signal => probeHTTPS('https://ipinfo.io/json', { signal, family: 4, timeout: 12000 }),
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 = performance.now(), stopped = false, holding = false, verification = 0;
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 || guard.controller) return;
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 = performance.now();
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 = performance.now(); return; }
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 < 30 || command.interval > 300) throw new Error('复查间隔应为30至300秒');
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 (performance.now() - heartbeat >= heartbeatTimeout) { void stop(); return; }
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 && performance.now() - lastCheck >= interval) void verify(true);
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
- try { data = JSON.parse(await request('https://ipinfo.io/json')); }
22
- catch { throw new Error(L('IP异常', 'IP unavailable')); }
23
- if (!data || typeof data.ip !== 'string' || !isIP(data.ip)) throw new Error(L('IP异常', 'IP unavailable'));
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') {