easy-claude 1.0.2 → 1.1.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,22 @@
1
1
  # 更新记录
2
2
 
3
+ ## 1.1.0
4
+
5
+ - 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.
6
+
7
+ - Add the exit IP protection switch, local gateway and protected Claude Code launch entry (development; real Claude acceptance pending).
8
+ - Add Launch Claude immediately before Quit; never close an existing desktop automatically.
9
+ - Add a persistent automatic usage refresh switch, off by default; retain manual refresh and HTTP 429 cooldowns.
10
+ - Group Network & protection; synchronize the displayed exit with protection checks and hide stale IPs on failure. Collapse configuration into More settings.
11
+
12
+ ## 1.0.3
13
+
14
+ - Refresh usage every five minutes; keep one-minute online confirmation when a reset or availability alert is due.
15
+ - Keep usage valid between polls with a ten-minute stale-data threshold; errors and expired windows remain explicit.
16
+ - HTTP 429 pauses queries for 10 minutes, then up to 15 minutes; success restores normal polling. Manual and reminder queries obey the same cooldown.
17
+ - Keep the half-size AM/PM or Chinese day period beside the floating time, with the city below.
18
+ - Verify background quota refresh with isolated continuous-typing and marked-text checks; do not activate the official application.
19
+
3
20
  ## 1.0.2
4
21
 
5
22
  - Refresh usage every minute. HTTP 429 pauses all refresh entry points for 2/4/8/15 minutes (capped); successful queries restore the normal interval.
package/README.md CHANGED
@@ -4,15 +4,26 @@
4
4
 
5
5
  A lightweight companion for Claude: read CLI account usage, show transparent usage rings and a world clock, and manage them from a native macOS menu bar panel. No model calls or changes to the official application.
6
6
 
7
- ## v1.0.2 release notes
7
+ ## Exit IP protection (application proxy)
8
8
 
9
- - Chinese/English UI and CLI, following the system by default; save a manual language choice in **More settings → Language**.
10
- - English README by default, with a linked Simplified Chinese version.
11
- - Time first, with a half-size period suffix (`10:09 AM` / `10:09 上午`) and the city below; preserve the system 12/24-hour format.
12
- - Consistent settings row heights and spacing in both languages.
13
- - Refresh usage every minute; HTTP 429 uses 2/4/8/15-minute backoff across automatic, manual and reminder queries, resetting after success. Halve the gap below the collapsed panel’s network exit.
9
+ Automatic usage refresh is off by default. Enable it for five-minute refreshes and one-minute confirmation after resets or due alerts; disable it for manual refresh only. Both modes obey rate-limit cooldowns. IP checks and the clock run independently.
14
10
 
15
- [Release history](CHANGELOG.md) · [1.0.2 development and verification](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/1.0.2开发管理.md)
11
+ Claude Desktop and Claude Code can use the same fixed local proxy: **http://127.0.0.1:18197**. Desktop uses the official `egressProxyUrl` policy; terminal Code uses proxy variables in `~/.claude/settings.json`. Normal Dock, Spotlight and terminal startup stays unchanged. No outer sandbox or application patching is used: the earlier sandboxed desktop launcher conflicted with Chromium's own sandbox and was withdrawn.
12
+
13
+ Enable Exit IP protection and enter the IPv4 allowlist. Only a successful current IP check permits forwarding. Service absent, protection off, unknown/expired/failed check or mismatched IP blocks proxy traffic and closes existing tunnels. Opening easy-claude starts the proxy even while the switch is off; the switch must be on and verification successful to forward. The Launch Claude button before Quit opens the official app normally, only when clicked.
14
+
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
+
17
+ [Setup, proxy configuration and removal](docs/exit-ip-protection.md) · [Development verification](docs/版本/出口IP保护开发管理.md)
18
+
19
+ ## v1.1.0 release notes
20
+
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.
25
+
26
+ [Release history](CHANGELOG.md) · [1.1.0 development and release](docs/版本/1.1.0开发管理.md)
16
27
 
17
28
  ## Install and run
18
29
 
@@ -35,13 +46,13 @@ claude auth login
35
46
 
36
47
  CLI and desktop login are separate. This tool cannot verify that their accounts match. Missing or stale data is never treated as full or zero usage. API key balances and current conversation context are outside its scope.
37
48
 
38
- Usage refreshes every minute. HTTP 429 pauses requests for 2, 4, 8, then at most 15 minutes after repeated rate limits. Manual refresh and availability alerts respect the same cooldown. A successful query restores the one-minute interval; query failures never imply availability.
49
+ Automatic usage refresh is an explicit persistent switch, off by default (300 seconds normally, 60 seconds after resets or due alerts). HTTP 429 still pauses manual requests for 10 minutes, then up to 15 minutes. Successful queries clear the cooldown; failures never imply availability. The published v1.0.3 behavior is described in its release notes above.
39
50
 
40
51
  ## Usage rings and recovery
41
52
 
42
53
  The outer thick ring shows weekly usage; the inner thin ring shows the five-hour window. Only windows returned by the service are shown. The center defaults to the five-hour percentage, falling back to weekly; select a quota row to change it. The center has no percent sign. Green means more than 50% remains, orange 20–50%, and red less than 20%.
43
54
 
44
- Multiple exhausted windows wait for the latest reset among them. Reaching that time starts an online confirmation; it does not assume the account is available. Weekly countdowns use the largest remaining unit, while five-hour countdowns show hours and minutes. Absolute reset times use the system time zone and its 12/24-hour format.
55
+ Multiple exhausted windows wait for the latest reset among them. Reaching that time waits for automatic confirmation if enabled, or a manual refresh if disabled; it does not assume the account is available. Weekly countdowns use the largest remaining unit, while five-hour countdowns show hours and minutes. Absolute reset times use the system time zone and its 12/24-hour format.
45
56
 
46
57
  ## Clock and time zones
47
58
 
@@ -102,3 +113,7 @@ A matching `v<version>` tag triggers GitHub Actions validation, universal build
102
113
  ## Known limits
103
114
 
104
115
  CLI login can expire while the desktop remains signed in. Official service responses and network access determine availability. Notification sound, real logout/reboot and cross-machine multi-monitor behavior need separate acceptance; simulated UI tests do not prove those paths.
116
+
117
+ [Version management](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/README.md)
118
+
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.
package/README.zh-CN.md CHANGED
@@ -6,15 +6,26 @@
6
6
 
7
7
  需要 Node.js 22+ 与 Claude Code 订阅登录;不支持把 API Key 账单余额当作订阅额度。
8
8
 
9
- ## v1.0.2 更新说明
9
+ ## 出口 IP 保护(应用代理)
10
10
 
11
- - 支持中英文,默认跟随系统,可在更多设置中手动切换并保存,CLI沿用同一偏好。
12
- - README默认英文,另提供中文文件与双向索引,两份随包交付。
13
- - 时间数字在前,时段在右且字号减半,英文大写AM/PM;城市在下方,保持系统12/24小时制。
14
- - 同级设置行高度与间距统一,中英文均适配。
15
- - 额度改为每分钟刷新;429时依次等待2/4/8/15分钟,手动和提醒也遵守,成功恢复每分钟。收起面板网络出口下方留白缩小一半。
11
+ “额度自动刷新”默认关闭,关闭时仅手动刷新;开启后每5分钟查询,重置或提醒到点后每分钟确认。手动刷新始终保留,自动和手动均遵守限流冷却。IP复查与时钟独立运行。
16
12
 
17
- 历史记录见[CHANGELOG](CHANGELOG.md),本版管理见[开发与验收](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/1.0.2开发管理.md)。
13
+ Claude App 与 Claude Code CLI 共用固定本机代理 **http://127.0.0.1:18197**。桌面使用官方 `egressProxyUrl` 配置,终端Code使用 `~/.claude/settings.json` 的代理环境变量。保持Dock、Spotlight及终端正常启动,不添加外层沙箱或修改官方程序。此前外层沙箱与Chromium自身沙箱冲突,桌面受保护启动方案已撤回。
14
+
15
+ 在“更多设置”中填写IPv4白名单,再打开“出口 IP 保护”。只有本轮IP验证成功且匹配白名单才转发。easy-claude未运行、开关关闭、验证失败/过期/未知或IP不匹配时,代理拒绝新请求并关闭已有隧道。打开工具会启动代理,开关关闭时也保持阻断。“退出”前的“启动 Claude”仅在点击时正常打开官方应用。
16
+
17
+ 修改代理后需要用户自行重新打开Claude,不自动重启。此方案是应用代理控制,不是系统防火墙:官方更新器、外部浏览器及忽略代理变量的程序不一定受控。当前代理只支持IPv4 HTTPS CONNECT 443,拒绝IPv6与其他目标端口;尚不能宣称所有Claude相关流量均受保护。
18
+
19
+ [安装、代理配置、关闭与卸载](docs/出口IP保护.md) · [开发验证记录](docs/版本/出口IP保护开发管理.md)
20
+
21
+ ## v1.1.0 更新说明
22
+
23
+ - 新增固定本机代理与 IPv4 出口白名单保护,验证失败、过期或关闭开关时阻断代理连接。
24
+ - 整合“网络与保护”分区,出口 IP 与保护检测同步,失败不沿用旧 IP。
25
+ - 新增额度自动刷新开关,默认关闭,保留手动刷新和429冷却。
26
+ - 保留正常“启动 Claude”按钮;设置文案为`跟随IP时区:ipinfo.io`。
27
+
28
+ 历史版本见[CHANGELOG](CHANGELOG.md),本版见[开发与发布记录](docs/版本/1.1.0开发管理.md)。
18
29
 
19
30
  ## 安装与使用
20
31
 
@@ -31,7 +42,7 @@ easy-claude show
31
42
  - macOS 14+;跟随 Claude 桌面应用窗口,前台显示,后台隐藏。默认左下角账户栏右侧,32×32,透明背景,无底板和阴影。
32
43
  - 显示剩余百分比:大于 50% 为绿色、20%–50% 橙色、低于 20% 红色;未知或过期为灰色,不伪装满额。
33
44
  - 按返回的真实额度自适应:只有周额度时显示单周环和周剩余数字,不显示5小时项;只有5小时则显示单5小时环,两项都有时双环同时显示:周额度为外侧粗实线环,5 小时额度为内侧细实线环(外环未使用部分为淡色虚线底轨),中心数字默认显示 5 小时剩余百分比(环内省略 %,菜单保留),可在菜单点击“5小时”或“周”切换并记住选择;两环独立配色和判断过期。右键查看“5小时 · 剩余百分比 · 重置时间”和“周 · 剩余百分比 · 重置时间”(重置使用电脑本地时区)、刷新、恢复位置或退出,双击刷新,拖动校准。
34
- - 运行时每分钟查询,冷却期间暂停请求;超过有效期或已到重置时间的数据标为过期;接口错误会立即标记未知。
45
+ - 开启额度自动刷新后每5分钟查询,关闭后仅手动刷新;冷却期间暂停请求;超过有效期或已到重置时间的数据标为过期;接口错误会立即标记未知。
35
46
  - 不显示“7天”等底部文字,详情在悬停提示和菜单。状态栏显示产品图标和剩余额度或恢复倒计时。
36
47
  - 基于窗口边界定位,不识别头像,不读取桌面聊天或截图;无法自动核对桌面账号与 CLI 账号一致。
37
48
 
@@ -90,9 +101,9 @@ npm run build:overlay
90
101
 
91
102
  在状态栏图标 或浮窗右键菜单开启“额度可用提醒”。首次开启需允许系统通知。仅在额度耗尽且重置时间有效时启用;当前已可用或数据未知时提示刷新后重试。
92
103
 
93
- 只有5小时或只有周额度时等待对应恢复;两项都耗尽时等待较晚时间,仍有剩余的窗口不参与等待。到点后约每分钟查询,确认所有已知窗口均有剩余,才发送一次系统通知和提示音,然后自动关闭开关。若等待期间再次耗尽,会继续等到有效恢复。
104
+ 只有5小时或只有周额度时等待对应恢复;两项都耗尽时等待较晚时间,仍有剩余的窗口不参与等待。到点后按额度自动刷新开关自动或手动确认,所有已知窗口均有剩余,才发送一次系统通知和提示音,然后自动关闭开关。若等待期间再次耗尽,会继续等到有效恢复。
94
105
 
95
- 开启状态跨更新/重启保存;关闭可取消。浮窗运行时即使目标应用不在前台也能检查,断网则保留提醒并重试。休眠会延后至唤醒,工具完全退出期间不能提醒,重新启动后补查;系统通知权限、专注模式和声音设置可能影响通知展示或声音。不调用模型、不消耗对话额度。
106
+ 开启状态跨更新/重启保存;关闭可取消。提醒遵循额度自动刷新开关;关闭时需手动刷新确认,失败时保留提醒。工具完全退出期间不能提醒,重启后遵循原额度自动刷新开关;系统通知权限、专注模式和声音设置可能影响通知展示或声音。不调用模型、不消耗对话额度。
96
107
 
97
108
  ## 公网IP与城市
98
109
 
@@ -105,7 +116,7 @@ IP地理库的城市与时区可能存在偏差或互相不一致;显示接口
105
116
 
106
117
  ## 跟随IP时区
107
118
 
108
- 菜单开启“跟随IP时区”后,时钟按地理接口返回的IANA时区显示当地时间,自动处理夏令时,继续跟随系统12/24小时制;时钟下方显示IP返回的城市名称,宽度不超过时间文字,手动时区选择隐藏。IP每5分钟刷新或点击IP菜单刷新,时区同步更新。
119
+ 菜单开启“跟随IP时区:ipinfo.io”后,时钟按地理接口返回的IANA时区显示当地时间,自动处理夏令时,继续跟随系统12/24小时制;时钟下方显示IP返回的城市名称,宽度不超过时间文字,手动时区选择隐藏。地理信息每5分钟刷新;关闭保护时点击IP菜单也可刷新。保护开启时该菜单触发保护重新检测,地址同步更新,地理信息仍独立查询。
109
120
 
110
121
  关闭后恢复之前手动选择的城市和时区,并重新显示选择菜单。取不到IP或有效时区时,时钟回退到手动设置的时区,菜单提示“IP时区不可用,显示自定义时间”;开关仍开启,获取成功后继续跟随。开关和手动设置跨重启/更新保存,不保存IP历史。IP地理数据可能不准确,跟随的是出口时区,不修改电脑系统时区。
111
122
 
@@ -115,7 +126,7 @@ IP地理库的城市与时区可能存在偏差或互相不一致;显示接口
115
126
 
116
127
  登录配置保存当前Node/npm安装路径,常规原前缀npm更新可继续使用;删除或迁移Node/npm目录后,从新安装打开浮窗并关闭再开启此选项以更新路径。
117
128
 
118
- 12小时制时段按时钟所选时区计算;跟随IP时使用有效IP时区,获取失败沿用自定义时间。浮窗、城市菜单和辅助文本使用相同五时段,两工具均为时间在前、时段在右的小字布局。零点如“凌晨 00:12”、正午如“下午 12:12”;24小时制不增加时段文字,额度重置时刻继续使用系统格式。
129
+ 12小时制时段按时钟所选时区计算;跟随IP时使用有效IP时区,获取失败沿用自定义时间。浮窗、城市菜单和辅助文本使用相同五时段,Claude时间在前、时段在右;Codex时段在时间上方。零点如“凌晨 00:12”、正午如“下午 12:12”;24小时制不增加时段文字,额度重置时刻继续使用系统格式。
119
130
 
120
131
  ## 状态栏与控制面板
121
132
 
@@ -125,7 +136,7 @@ IP地理库的城市与时区可能存在偏差或互相不一致;显示接口
125
136
 
126
137
  未登录显示登录指引;点击复制只写入登录命令到剪贴板,不自动打开终端或运行命令。登录过期、查询失败分别显示,不会因为错误文字含“检查登录”就判为未登录。登录应与官方桌面使用同一账号;本工具无法替用户证明两边账号一致。时间、IP与设置不依赖订阅登录。
127
138
 
128
- 操作面板采用原生AppKit/SwiftUI,额度查询不调用模型,不新增Node第三方依赖。状态栏持续后台刷新,浮窗仍仅跟随官方应用前台窗口显示。开机启动、提醒和自动更新的原设置继续保留。
139
+ 操作面板采用原生AppKit/SwiftUI,额度查询不调用模型,不新增Node第三方依赖。状态栏持续更新本地显示,额度按自动刷新开关或手动查询;浮窗仍仅跟随官方应用前台窗口显示。开机启动、提醒和自动更新的原设置继续保留。
129
140
 
130
141
  ## 中英文界面
131
142
 
@@ -133,6 +144,8 @@ IP地理库的城市与时区可能存在偏差或互相不一致;显示接口
133
144
 
134
145
  收起面板中,网络出口文字下方至底部分隔线的空白由约48pt减至约24pt,不改变网络刷新频率或控件操作。
135
146
 
136
- - 时间浮窗:12小时制显示“10:09 上午”,时间在前,时段在右且字号为数字的一半;城市在下方。英文为“10:09 AM”,24小时制不显示时段。两工具均适用,保持现有面板边界并按宽度适配。该要求取代旧Codex上方单列时段的布局。
147
+ - 时间浮窗:12小时制显示“10:09 上午”,时间在前,时段在右且字号为数字的一半;城市在下方。英文为“10:09 AM”,24小时制不显示时段。Claude适用;Codex时段放在时间上方,保持各自浮窗边界。
148
+
149
+ 额度自动刷新默认关闭,开启后每5分钟查询,重置/提醒到点每分钟确认,关闭后仅手动。服务返回429后先等待10分钟、后最长15分钟,手动刷新遵守冷却,成功后清零。网络与保护合为一个分区,保护开启时当前出口与保护检测同步更新;失败显示未知,白名单和复查周期在更多设置中修改。关闭保护时IP/城市查询每5分钟刷新。
137
150
 
138
- 额度每60秒刷新;服务返回429后按2/4/8/15分钟退避(最长15分钟),手动刷新及提醒共用限制,成功后恢复60秒。IP仍每5分钟刷新,与额度频率独立。
151
+ [版本管理](https://github.com/UnionSchool/easy-claude/blob/main/docs/版本/README.md)
@@ -6,7 +6,7 @@ import { readUsage, formatUsage } from '../src/usage.js';
6
6
 
7
7
  const args = process.argv.slice(2);
8
8
  if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
9
- console.log(L('用法:easy-claude [usage|show|overlay|update]\n显示已登录 Claude 账号的剩余百分比和重置时间。需要 Claude Code 订阅登录。', 'Usage: easy-claude [usage|show|overlay|update]\nShow remaining usage and reset times. Requires Claude Code subscription login.'));
9
+ console.log(L('用法:easy-claude [usage|show|overlay|update|protected]\n显示已登录 Claude 账号的剩余百分比和重置时间。需要 Claude Code 订阅登录。', 'Usage: easy-claude [usage|show|overlay|update|protected]\nShow remaining usage and reset times. Requires Claude Code subscription login.'));
10
10
  } else if (args.length === 1 && ['--version', '-v', '-V'].includes(args[0])) {
11
11
  console.log(version);
12
12
  } else if (args.length === 1 && ['show', 'overlay'].includes(args[0])) {
@@ -15,10 +15,13 @@ if (args.length === 1 && ['--help', '-h'].includes(args[0])) {
15
15
  } else if (args.length === 1 && args[0] === 'update') {
16
16
  try { const { updateAndShow } = await import('../src/overlay-update.js'); await updateAndShow(); }
17
17
  catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
18
+ } else if (args[0] === 'protected') {
19
+ try { const { runProtectedCode } = await import('../src/ip-guard/launcher.js'); process.exitCode = await runProtectedCode(args.slice(1)); }
20
+ catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
18
21
  } else if (args.length === 0 || (args.length === 1 && args[0] === 'usage')) {
19
22
  try { console.log(formatUsage(await readUsage())); }
20
23
  catch (error) { console.error(`easy-claude: ${error.message}`); process.exitCode = 1; }
21
24
  } else {
22
- console.error(L('未知参数。用法:easy-claude [usage|show|overlay|update],或 easy-claude --help', 'Unknown argument. Usage: easy-claude [usage|show|overlay|update]; or easy-claude --help'));
25
+ console.error(L('未知参数。用法:easy-claude [usage|show|overlay|update|protected],或 easy-claude --help', 'Unknown argument. Usage: easy-claude [usage|show|overlay|update|protected]; or easy-claude --help'));
23
26
  process.exitCode = 1;
24
27
  }
@@ -3,6 +3,7 @@ import SwiftUI
3
3
  import CoreGraphics
4
4
  import Darwin
5
5
  import UserNotifications
6
+ import Network
6
7
 
7
8
  // 语言与地区/小时制独立:只保存用户选择,不改系统设置。
8
9
  enum AppLanguage: String, CaseIterable {
@@ -149,8 +150,8 @@ struct UsageRefreshSchedule {
149
150
  func allows(_ now: Double) -> Bool { now >= nextAllowedAt }
150
151
  mutating func receive(rateLimited: Bool, succeeded: Bool, now: Double) {
151
152
  if rateLimited {
152
- rateLimitCount = min(rateLimitCount + 1, 4)
153
- nextAllowedAt = now + min(900, 120 * pow(2, Double(rateLimitCount - 1)))
153
+ rateLimitCount = min(rateLimitCount + 1, 2)
154
+ nextAllowedAt = now + min(900, usageRateLimitBase * pow(2, Double(rateLimitCount)))
154
155
  } else if succeeded {
155
156
  rateLimitCount = 0
156
157
  nextAllowedAt = 0
@@ -521,6 +522,7 @@ enum LoginStartup {
521
522
  let controlProduct = "Claude"
522
523
  let controlLoginName = "Claude Code"
523
524
  let controlLoginCommand = "claude auth login"
525
+ let usageRateLimitBase: TimeInterval = 300
524
526
  let controlStaleSeconds: Double = 600
525
527
  func controlQuotas(_ windows: [UsageWindow]) -> [ControlQuota] { return [windows.first { $0.id == "five_hour:primary" }.map { ControlQuota(window: $0, weekly: false) }, windows.first { $0.id == "seven_day:primary" }.map { ControlQuota(window: $0, weekly: true) }].compactMap { $0 } }
526
528
 
@@ -553,7 +555,7 @@ func controlState(snapshot: Snapshot?, error: String?, code: String?, weeklySele
553
555
  let title = code == "auth_required" ? L("未登录", "Not signed in") : code == "auth_expired" ? L("登录已过期", "Login expired") : L("查询失败", "Query failed")
554
556
  return ControlState(mode: auth ? code! : "failed", text: title, headline: title, detail: displayMessage(error), quotas: [])
555
557
  }
556
- guard let snapshot else { return ControlState(mode: "loading", text: "—", headline: L("正在读取", "Loading"), detail: L("正在查询本机CLI账号额度", "Reading local CLI account usage"), quotas: []) }
558
+ guard let snapshot else { return ControlState(mode: "unknown", text: "—", headline: L("尚未读取额度", "Usage not loaded"), detail: L("点击刷新额度,或开启额度自动刷新。", "Refresh usage or enable automatic usage refresh."), quotas: []) }
557
559
  guard now - snapshot.fetchedAt <= controlStaleSeconds, snapshot.fetchedAt <= now + 5,
558
560
  !rows.isEmpty, rows.allSatisfy({ row in
559
561
  guard let remaining = row.window.remaining, remaining.isFinite, (0...100).contains(remaining) else { return false }
@@ -650,6 +652,8 @@ struct ControlPanelView: View {
650
652
  }
651
653
  }
652
654
  Divider()
655
+ setting(L("额度自动刷新", "Automatic usage refresh"), value: owner.automaticUsageRefresh) { owner.toggleAutomaticUsageRefresh() }
656
+ Divider()
653
657
  HStack(spacing: 7) {
654
658
  Image(systemName: "clock").foregroundStyle(.secondary)
655
659
  let clockParts = floatingClockLines(at: Date(), zone: owner.clock.zone)
@@ -662,15 +666,7 @@ struct ControlPanelView: View {
662
666
  Text(cityLabel(owner.clock.cityName)).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.tail)
663
667
  }.accessibilityElement(children: .combine)
664
668
  Divider()
665
- HStack(alignment: .center, spacing: 9) {
666
- Image(systemName: "network").foregroundStyle(.secondary)
667
- VStack(alignment: .leading, spacing: 4) {
668
- Text(L("网络出口", "Network exit")).font(.system(size: 12, weight: .medium))
669
- Text(displayMessage(owner.ipText)).font(.system(size: 11)).foregroundStyle(.secondary).textSelection(.enabled).lineLimit(1).minimumScaleFactor(0.7)
670
- }
671
- Spacer(minLength: 3)
672
- iconButton(L("刷新公网IP", "Refresh public IP"), "arrow.clockwise") { owner.refreshIP() }.disabled(owner.ipQuery != nil)
673
- }
669
+ protection
674
670
  if owner.controlsExpanded { settings }
675
671
  }.padding(16)
676
672
  }.scrollIndicators(.hidden)
@@ -681,6 +677,8 @@ struct ControlPanelView: View {
681
677
  }
682
678
  .buttonStyle(.plain).accessibilityIdentifier("moreSettings")
683
679
  Spacer()
680
+ Button { owner.launchClaudeApp() } label: { Label(L("启动 Claude", "Launch Claude"), systemImage: "play") }
681
+ .buttonStyle(.plain).accessibilityIdentifier("launchClaudeApp")
684
682
  Divider().frame(height: 17)
685
683
  Button { owner.quit() } label: { Label(L("退出", "Quit"), systemImage: "power") }.buttonStyle(.plain)
686
684
  }.font(.system(size: 12)).padding(.horizontal, 16).padding(.vertical, 12)
@@ -694,6 +692,62 @@ struct ControlPanelView: View {
694
692
  Button(action: action) { Image(systemName: image).frame(width: 20, height: 20) }
695
693
  .buttonStyle(.plain).help(label).accessibilityLabel(label)
696
694
  }
695
+ var protection: some View {
696
+ VStack(alignment: .leading, spacing: 10) {
697
+ HStack {
698
+ Label(L("网络与保护", "Network & protection"), systemImage: "shield")
699
+ .font(.system(size: 12, weight: .semibold))
700
+ Spacer()
701
+ Toggle(L("出口 IP 保护", "Exit IP protection"), isOn: Binding(
702
+ get: { owner.protectionEnabled }, set: { owner.setProtectionEnabled($0) }))
703
+ .toggleStyle(.switch).tint(.green).controlSize(.mini).font(.system(size: 10))
704
+ .accessibilityIdentifier("ipProtectionToggle")
705
+ }
706
+ Label(owner.protectionStateText, systemImage: "circle.fill")
707
+ .font(.system(size: 10)).foregroundStyle(owner.protectionIsAllowed ? .green : (owner.protectionEnabled ? .orange : .secondary))
708
+ networkRow(L("当前出口", "Current exit"), owner.networkIPText)
709
+ networkRow(L("允许出口", "Allowed exits"), owner.allowedIPSummary)
710
+ HStack {
711
+ Text(owner.protectionCheckedText).font(.system(size: 10)).foregroundStyle(.secondary)
712
+ Spacer()
713
+ Button(L("重新检测", "Check again")) { owner.refreshNetworkIP() }
714
+ .controlSize(.small).disabled(owner.protectionEnabled ? owner.protectionReport?.state == "checking" : owner.ipQuery != nil)
715
+ }
716
+ if owner.protectionEnabled, let reason = owner.protectionReport?.reason, !reason.isEmpty {
717
+ Text(AppLanguage.current == .zh ? reason : "Access is blocked until a current IP check matches the allowlist.")
718
+ .font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
719
+ }
720
+ if owner.controlsExpanded {
721
+ Divider()
722
+ Text(L("保护设置", "Protection settings")).font(.system(size: 11, weight: .semibold))
723
+ TextField(L("允许的 IPv4,逗号分隔", "Allowed IPv4 addresses, comma-separated"), text: $owner.protectionIPs)
724
+ .textFieldStyle(.roundedBorder).font(.system(size: 11))
725
+ .onChange(of: owner.protectionIPs) { _, _ in owner.protectionConfigurationChanged() }
726
+ .accessibilityIdentifier("ipProtectionAddresses")
727
+ HStack {
728
+ Text(L("复查间隔", "Check interval"))
729
+ Spacer()
730
+ Picker("", selection: $owner.protectionInterval) {
731
+ ForEach([30, 60, 120, 300], id: \.self) { value in Text("\(value)s").tag(value) }
732
+ }.labelsHidden().frame(width: 85)
733
+ .onChange(of: owner.protectionInterval) { _, _ in owner.protectionConfigurationChanged() }
734
+ }.font(.system(size: 11)).controlSize(.small)
735
+ networkRow(L("本机代理", "Local proxy"), "127.0.0.1:18197")
736
+ Text(L("关闭保护或退出工具,Claude 将无法联网。", "Turning off protection or quitting blocks Claude's proxy connections."))
737
+ .font(.system(size: 10)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
738
+ }
739
+ if let error = owner.protectionError {
740
+ Text(error).font(.system(size: 10)).foregroundStyle(.orange).fixedSize(horizontal: false, vertical: true)
741
+ }
742
+ }
743
+ }
744
+ func networkRow(_ label: String, _ value: String) -> some View {
745
+ HStack(alignment: .top) {
746
+ Text(label).font(.system(size: 11)).foregroundStyle(.secondary).frame(width: 66, alignment: .leading)
747
+ Text(value).font(.system(size: 11, design: .monospaced)).textSelection(.enabled)
748
+ .frame(maxWidth: .infinity, alignment: .leading).fixedSize(horizontal: false, vertical: true)
749
+ }
750
+ }
697
751
  func quota(_ row: ControlQuota) -> some View {
698
752
  let valid = state.mode == "ready" || state.mode == "waiting"
699
753
  let value = valid ? row.window.remaining : nil
@@ -732,19 +786,9 @@ struct ControlPanelView: View {
732
786
  }
733
787
  var settings: some View {
734
788
  VStack(alignment: .leading, spacing: 12) {
735
- HStack {
736
- Text(L("语言", "Language")).font(.system(size: 12))
737
- Spacer()
738
- Picker(L("语言", "Language"), selection: Binding(get: { UserDefaults.standard.string(forKey: "interfaceLanguage") ?? "system" }, set: { owner.setLanguage($0) })) {
739
- Text(L("跟随系统", "System default")).tag("system")
740
- Text("简体中文").tag("zh")
741
- Text("English").tag("en")
742
- }.labelsHidden().frame(width: 155).accessibilityIdentifier("interfaceLanguage")
743
- }
744
- Divider()
745
789
  Text(L("浮窗与时间", "Overlay & time")).font(.system(size: 10)).foregroundStyle(.secondary)
746
790
  setting(L("显示时间", "Show time"), value: owner.clockEnabled) { owner.toggleClock() }
747
- setting(L("跟随IP时区", "Follow IP time zone"), value: owner.followIPTimeZone) { owner.toggleFollowIPTimeZone() }
791
+ setting(L("跟随IP时区:ipinfo.io", "Follow IP time zone: ipinfo.io"), value: owner.followIPTimeZone) { owner.toggleFollowIPTimeZone() }
748
792
  if owner.followIPTimeZone && owner.ipClock.zone == nil {
749
793
  Text(L("IP时区不可用,暂用自定义时间", "IP time zone unavailable; using manual time")).font(.system(size: 10)).foregroundStyle(.secondary)
750
794
  }
@@ -776,7 +820,17 @@ struct ControlPanelView: View {
776
820
  if let reminder = owner.reminder { Text(L("等待恢复:", "Waiting: ") + recoveryCountdown(reminder.due, now: Date().timeIntervalSince1970)).font(.system(size: 10)).foregroundStyle(.secondary) }
777
821
  setting(L("开机启动", "Launch at login"), value: LoginStartup.enabled()) { owner.toggleLoginStartup() }
778
822
  Divider()
779
- Text(L("版本与更新", "Version & updates")).font(.system(size: 10)).foregroundStyle(.secondary)
823
+ Text(L("通用与更新", "General & updates")).font(.system(size: 10)).foregroundStyle(.secondary)
824
+ HStack {
825
+ Text(L("语言", "Language")).font(.system(size: 12))
826
+ Spacer()
827
+ Picker(L("语言", "Language"), selection: Binding(get: { UserDefaults.standard.string(forKey: "interfaceLanguage") ?? "system" }, set: { owner.setLanguage($0) })) {
828
+ Text(L("跟随系统", "System default")).tag("system")
829
+ Text("简体中文").tag("zh")
830
+ Text("English").tag("en")
831
+ }.labelsHidden().frame(width: 155).accessibilityIdentifier("interfaceLanguage")
832
+ }
833
+
780
834
  setting(L("自动更新", "Automatic updates"), value: UserDefaults.standard.bool(forKey: "automaticUpdatesEnabled")) { owner.toggleAutomaticUpdates() }
781
835
  HStack {
782
836
  Text("v\(owner.appVersion)").font(.system(size: 11))
@@ -791,6 +845,61 @@ struct ControlPanelView: View {
791
845
 
792
846
  @MainActor
793
847
  final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNotificationCenterDelegate, ObservableObject {
848
+ struct ProtectionReport: Decodable {
849
+ var state: String
850
+ var reason: String?
851
+ var ip: String?
852
+ var checkedAt: String?
853
+ var ready: Bool?
854
+ }
855
+ @Published var automaticUsageRefresh = UserDefaults.standard.bool(forKey: "automaticUsageRefresh")
856
+ var protectionIsAllowed: Bool { protectionEnabled && protectionError == nil && protectionReport?.ready == true && protectionReport?.state == "allowed" }
857
+ var networkIPText: String {
858
+ guard protectionEnabled else { return displayMessage(ipText) }
859
+ guard protectionError == nil, let report = protectionReport else { return L("IP 未知", "IP unknown") }
860
+ // 保护检测是地址展示的唯一来源,独立地理查询不能覆盖它。
861
+ if let ip = report.ip, report.state == "allowed" || (report.state == "blocked" && report.reason == "出口不在白名单") { return ip }
862
+ return report.state == "checking" ? L("正在检测…", "Checking…") : L("IP 未知", "IP unknown")
863
+ }
864
+ var allowedIPSummary: String {
865
+ let values = protectionIPs.components(separatedBy: CharacterSet(charactersIn: ",,\n ")).filter { !$0.isEmpty }
866
+ return values.isEmpty ? L("尚未设置", "Not configured") : values.joined(separator: ", ")
867
+ }
868
+ var protectionCheckedText: String {
869
+ let parser = ISO8601DateFormatter()
870
+ parser.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
871
+ guard protectionEnabled, let raw = protectionReport?.checkedAt,
872
+ let date = parser.date(from: raw) ?? ISO8601DateFormatter().date(from: raw) else {
873
+ return L("最近检测:—", "Last check: —")
874
+ }
875
+ let formatter = DateFormatter(); formatter.timeStyle = .medium
876
+ return L("最近检测:", "Last check: ") + formatter.string(from: date)
877
+ }
878
+ @Published var protectionEnabled = UserDefaults.standard.bool(forKey: "ipProtectionEnabled")
879
+ @Published var protectionIPs = UserDefaults.standard.string(forKey: "ipProtectionAddresses") ?? ""
880
+ @Published var protectionInterval = UserDefaults.standard.object(forKey: "ipProtectionInterval") as? Int ?? 60
881
+ @Published var protectionReport: ProtectionReport?
882
+ @Published var protectionError: String?
883
+ var protectionProcess: Process?
884
+ var protectionInput: FileHandle?
885
+ var protectionOutput: FileHandle?
886
+ var protectionBuffer = Data()
887
+ var protectionEditTimer: Timer?
888
+ var protectionHeartbeat: TimeInterval = 0
889
+ let protectionPathMonitor = NWPathMonitor()
890
+ var protectionStateText: String {
891
+ if let protectionError { return L("未受保护:", "Unprotected: ") + protectionError }
892
+ if !protectionEnabled {
893
+ return protectionProcess != nil && protectionReport?.state != "off" ? L("正在阻断代理…", "Blocking proxy…") : L("保护已关闭 · 代理已阻断", "Protection off · proxy blocked")
894
+ }
895
+ switch protectionReport?.state {
896
+ case "allowed": return L("代理已放通 · 出口 IP 符合白名单", "Proxy allowed · exit IP matches the allowlist")
897
+ case "checking": return L("验证中 · 代理已阻断", "Verifying · proxy blocked")
898
+ case "blocked": return L("代理已阻断 · 等待有效 IP 验证", "Proxy blocked · waiting for valid IP verification")
899
+ case "fault": return L("保护故障 · 未受保护", "Protection fault · unprotected")
900
+ default: return L("未受保护 · 正在建立保护服务", "Unprotected · starting protection service")
901
+ }
902
+ }
794
903
  let panel = NSPanel(contentRect: CGRect(x: 0, y: 0, width: 32, height: 32),
795
904
  styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
796
905
  let ring = RingView(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
@@ -811,7 +920,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
811
920
  var controlHeight: CGFloat {
812
921
  let state = currentControlState()
813
922
  let quotaHeight: CGFloat = state.login ? 155 : CGFloat(max(1, state.quotas.count)) * 62 + (state.mode == "ready" ? 0 : 65)
814
- let total: CGFloat = (controlsExpanded ? 198 : 174) + quotaHeight + (controlsExpanded ? (followIPTimeZone ? 355 : 420) : 0)
923
+ let total = quotaHeight + 310 + (controlsExpanded ? (followIPTimeZone ? 395 : 460) : 0)
815
924
  return min(total, max(280, (status?.button?.window?.screen?.visibleFrame.height ?? NSScreen.main?.visibleFrame.height ?? 900) - 65))
816
925
  }
817
926
  var status: NSStatusItem?
@@ -911,13 +1020,117 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
911
1020
  controlPopover.contentViewController = NSHostingController(rootView: ControlPanelView(owner: self))
912
1021
  timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(tick), userInfo: nil, repeats: true)
913
1022
  NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(hide), name: NSWorkspace.didDeactivateApplicationNotification, object: nil)
1023
+ NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(protectionNetworkChanged), name: NSWorkspace.didWakeNotification, object: nil)
1024
+ protectionPathMonitor.pathUpdateHandler = { [weak self] _ in
1025
+ Task { @MainActor in self?.protectionNetworkChanged() }
1026
+ }
1027
+ protectionPathMonitor.start(queue: DispatchQueue(label: "easy-claude.network"))
1028
+ startProtectionService()
914
1029
  tick()
915
1030
  }
1031
+ func setProtectionEnabled(_ enabled: Bool) {
1032
+ if enabled && protectionIPs.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
1033
+ protectionError = L("请先在更多设置中输入允许的 IPv4。", "Enter an allowed IPv4 address in More settings first.")
1034
+ resizeControls(); return
1035
+ }
1036
+ protectionEnabled = enabled
1037
+ UserDefaults.standard.set(enabled, forKey: "ipProtectionEnabled")
1038
+ protectionError = nil
1039
+ if enabled && protectionProcess == nil { startProtectionService() }
1040
+ else if protectionProcess != nil { configureProtection() }
1041
+ resizeControls()
1042
+ }
1043
+ func protectionConfigurationChanged() {
1044
+ UserDefaults.standard.set(protectionIPs, forKey: "ipProtectionAddresses")
1045
+ UserDefaults.standard.set(protectionInterval, forKey: "ipProtectionInterval")
1046
+ guard protectionEnabled else { return }
1047
+ sendProtection(["action": "hold"])
1048
+ protectionEditTimer?.invalidate()
1049
+ protectionEditTimer = Timer.scheduledTimer(withTimeInterval: 0.4, repeats: false) { [weak self] _ in
1050
+ Task { @MainActor in self?.configureProtection() }
1051
+ }
1052
+ }
1053
+ func configureProtection() {
1054
+ let ips = protectionIPs.components(separatedBy: CharacterSet(charactersIn: ",,\n "))
1055
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
1056
+ sendProtection(["action": "configure", "enabled": protectionEnabled, "ips": ips, "interval": protectionInterval])
1057
+ }
1058
+ func sendProtection(_ command: [String: Any]) {
1059
+ guard let input = protectionInput, protectionProcess?.isRunning == true else { return }
1060
+ do {
1061
+ var data = try JSONSerialization.data(withJSONObject: command); data.append(10)
1062
+ try input.write(contentsOf: data)
1063
+ } catch { protectionError = L("保护控制通信失败。", "Protection control connection failed."); protectionProcess?.terminate() }
1064
+ }
1065
+ @objc func protectionNetworkChanged() {
1066
+ if protectionEnabled { sendProtection(["action": "invalidate"]) }
1067
+ ipQuery?.terminate(); ipQuery = nil
1068
+ ipText = L("正在获取IP…", "Fetching IP…")
1069
+ receiveIPTimeZone(nil)
1070
+ refreshIP()
1071
+ }
1072
+ func startProtectionService() {
1073
+ guard protectionProcess == nil else { return }
1074
+ let process = Process(), input = Pipe(), output = Pipe()
1075
+ process.executableURL = URL(fileURLWithPath: node)
1076
+ process.arguments = [URL(fileURLWithPath: script).deletingLastPathComponent().appendingPathComponent("overlay-guard.js").path]
1077
+ process.standardInput = input; process.standardOutput = output; process.standardError = FileHandle.nullDevice
1078
+ var env = ProcessInfo.processInfo.environment; env["PATH"] = searchPath
1079
+ process.environment = env
1080
+ protectionBuffer.removeAll(); protectionReport = nil; protectionError = nil
1081
+ protectionInput = input.fileHandleForWriting; protectionOutput = output.fileHandleForReading
1082
+ output.fileHandleForReading.readabilityHandler = { [weak self] handle in
1083
+ let data = handle.availableData
1084
+ Task { @MainActor in
1085
+ guard let self, self.protectionProcess === process else { return }
1086
+ self.protectionBuffer.append(data)
1087
+ if self.protectionBuffer.count > 16384 {
1088
+ self.protectionError = L("保护服务响应无效。", "Invalid protection service response."); process.terminate(); return
1089
+ }
1090
+ while let end = self.protectionBuffer.firstIndex(of: 10) {
1091
+ let line = self.protectionBuffer.prefix(upTo: end)
1092
+ self.protectionBuffer.removeSubrange(...end)
1093
+ do {
1094
+ self.protectionReport = try JSONDecoder().decode(ProtectionReport.self, from: line)
1095
+ if self.protectionReport?.state == "fault" {
1096
+ self.protectionError = AppLanguage.current == .zh ? self.protectionReport?.reason : "Protection failed. Check the allowlist, sandbox and service."
1097
+ } else { self.protectionError = nil }
1098
+ } catch { self.protectionError = L("保护服务响应无效。", "Invalid protection service response."); process.terminate() }
1099
+ self.resizeControls()
1100
+ }
1101
+ }
1102
+ }
1103
+ process.terminationHandler = { [weak self] process in
1104
+ Task { @MainActor in
1105
+ guard let self, self.protectionProcess === process else { return }
1106
+ self.protectionOutput?.readabilityHandler = nil
1107
+ try? self.protectionInput?.close(); try? self.protectionOutput?.close()
1108
+ self.protectionInput = nil; self.protectionOutput = nil; self.protectionProcess = nil
1109
+ self.protectionReport = nil
1110
+ if self.protectionEnabled { self.protectionError = L("保护服务已退出,受保护连接不可用。", "Protection service stopped; protected connections are unavailable.") }
1111
+ self.resizeControls()
1112
+ }
1113
+ }
1114
+ protectionProcess = process
1115
+ do { try process.run(); configureProtection(); protectionHeartbeat = ProcessInfo.processInfo.systemUptime }
1116
+ catch {
1117
+ output.fileHandleForReading.readabilityHandler = nil
1118
+ try? protectionInput?.close(); try? protectionOutput?.close()
1119
+ protectionInput = nil; protectionOutput = nil; protectionProcess = nil
1120
+ protectionError = L("无法启动保护服务。", "Cannot start protection service.")
1121
+ }
1122
+ }
1123
+ @objc func launchClaudeApp() {
1124
+ guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.anthropic.claudefordesktop") else {
1125
+ protectionError = L("未找到 Claude App。", "Claude App was not found."); resizeControls(); return
1126
+ }
1127
+ NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration())
1128
+ }
916
1129
  func currentControlState(now: Double = Date().timeIntervalSince1970) -> ControlState {
917
1130
  if !usageSchedule.allows(now) {
918
1131
  let remaining = recoveryCountdown(usageSchedule.nextAllowedAt, now: now)
919
1132
  return ControlState(mode: "rate_limited", text: L("限流", "Rate limited"), headline: L("请求过于频繁", "Too many requests"),
920
- detail: L("服务限流,\(remaining)后自动重试;手动刷新也会等待。", "Rate limited. Retrying in \(remaining); manual refresh also waits."), quotas: [])
1133
+ detail: L("服务限流,\(remaining)后可手动重试。", "Rate limited. Refresh manually after \(remaining)."), quotas: [])
921
1134
  }
922
1135
  return controlState(snapshot: snapshot, error: error, code: controlErrorCode, weeklySelected: ring.showWeeklyPercentage, now: now)
923
1136
  }
@@ -960,9 +1173,17 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
960
1173
  }
961
1174
  @objc func hide() { panel.orderOut(nil); clockPanel.orderOut(nil) }
962
1175
  @objc func tick() {
1176
+ if protectionProcess?.isRunning == true && ProcessInfo.processInfo.systemUptime - protectionHeartbeat >= 5 {
1177
+ sendProtection(["action": "heartbeat"]); protectionHeartbeat = ProcessInfo.processInfo.systemUptime
1178
+ }
963
1179
  checkVersionIfNeeded()
964
1180
  if Date().timeIntervalSince(ipLastAttempt) >= 300 { refreshIP() }
965
- if Date().timeIntervalSince(lastAttempt) >= 60 { refresh() }
1181
+ if automaticUsageRefresh {
1182
+ let now = Date().timeIntervalSince1970
1183
+ let resetDue = snapshot?.windows.contains { $0.resetsAt.map { $0 <= now } ?? false } ?? false
1184
+ let reminderDue = reminder.map { $0.due <= now } ?? false
1185
+ if Date().timeIntervalSince(lastAttempt) >= (resetDue || reminderDue ? 60 : 300) { refresh() }
1186
+ }
966
1187
  refreshControls()
967
1188
  guard let rect = targetWindow() else { hide(); lastRect = nil; return }
968
1189
  lastRect = rect
@@ -1005,6 +1226,16 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1005
1226
  ring.setAccessibilityLabel("Claude \(summary)")
1006
1227
  ring.needsDisplay = true
1007
1228
  }
1229
+ @objc func toggleAutomaticUsageRefresh() {
1230
+ automaticUsageRefresh.toggle()
1231
+ UserDefaults.standard.set(automaticUsageRefresh, forKey: "automaticUsageRefresh")
1232
+ if automaticUsageRefresh { refresh() }
1233
+ }
1234
+ @objc func refreshNetworkIPMenu() { refreshNetworkIP() }
1235
+ func refreshNetworkIP() {
1236
+ if protectionEnabled { sendProtection(["action": "verify"]) }
1237
+ else { refreshIP() }
1238
+ }
1008
1239
  @objc func refresh() {
1009
1240
  guard query == nil, usageSchedule.allows(Date().timeIntervalSince1970) else { return }
1010
1241
  lastAttempt = Date()
@@ -1078,6 +1309,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1078
1309
  let city = process.terminationStatus == 0 ? value?.city : nil
1079
1310
  Task { @MainActor in
1080
1311
  guard let self else { return }
1312
+ guard self.ipQuery === process else { return }
1081
1313
  self.ipQuery = nil; self.ipText = text
1082
1314
  self.receiveIPTimeZone(timezone, city: city)
1083
1315
  }
@@ -1168,7 +1400,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1168
1400
  menu.addItem(item(lastRect == nil ? L("等待 Claude 前台窗口", "Waiting for Claude foreground window") : L("拖动圆环可调整位置", "Drag the ring to reposition"), nil))
1169
1401
  if let error { menu.addItem(item(error, nil)) }
1170
1402
  if snapshot?.restricted == true { menu.addItem(item(L("服务端提示:当前使用受限", "Server reports restricted usage"), nil)) }
1171
- let address = item(ipText, ipQuery == nil ? #selector(refreshIP) : nil)
1403
+ let address = item(networkIPText, #selector(refreshNetworkIPMenu))
1172
1404
  address.toolTip = L("点击刷新公网IP;城市为网络出口位置", "Click to refresh public IP; city is the network exit location")
1173
1405
  menu.addItem(address)
1174
1406
  menu.addItem(.separator())
@@ -1182,6 +1414,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1182
1414
  menu.addItem(option)
1183
1415
  }
1184
1416
  menu.addItem(item(query == nil ? L("立即刷新", "Refresh now") : L("正在刷新…", "Refreshing…"), query == nil ? #selector(refresh) : nil))
1417
+ let automaticUsage = item(L("额度自动刷新", "Automatic usage refresh"), #selector(toggleAutomaticUsageRefresh))
1418
+ automaticUsage.state = automaticUsageRefresh ? .on : .off
1419
+ menu.addItem(automaticUsage)
1185
1420
  let alarm = item(L("额度可用提醒", "Usage available alert"), reminderAuthorizing ? nil : #selector(toggleReminder))
1186
1421
  alarm.state = reminder == nil ? .off : .on
1187
1422
  menu.addItem(alarm)
@@ -1194,7 +1429,7 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1194
1429
  let toggle = item(L("显示时间", "Show time"), #selector(toggleClock))
1195
1430
  toggle.state = clockEnabled ? .on : .off
1196
1431
  menu.addItem(toggle)
1197
- let follow = item(L("跟随IP时区", "Follow IP time zone"), #selector(toggleFollowIPTimeZone))
1432
+ let follow = item(L("跟随IP时区:ipinfo.io", "Follow IP time zone: ipinfo.io"), #selector(toggleFollowIPTimeZone))
1198
1433
  follow.state = followIPTimeZone ? .on : .off
1199
1434
  menu.addItem(follow)
1200
1435
  if followIPTimeZone && ipClock.zone == nil {
@@ -1438,6 +1673,9 @@ final class Overlay: NSObject, NSApplicationDelegate, NSMenuDelegate, UNUserNoti
1438
1673
  }
1439
1674
  @objc func quit() { NSApp.terminate(nil) }
1440
1675
  func applicationWillTerminate(_ notification: Notification) {
1676
+ protectionEditTimer?.invalidate(); protectionPathMonitor.cancel()
1677
+ protectionOutput?.readabilityHandler = nil
1678
+ try? protectionInput?.close()
1441
1679
  ipQuery?.terminate()
1442
1680
  timer?.invalidate()
1443
1681
  query?.terminate()
@@ -1469,7 +1707,7 @@ func runControlChecks() {
1469
1707
  func state(_ snapshot: Snapshot?, error: String? = nil, code: String? = nil, weekly: Bool = false) -> ControlState {
1470
1708
  controlState(snapshot: snapshot, error: error, code: code, weeklySelected: weekly, now: now)
1471
1709
  }
1472
- precondition(state(nil).mode == "loading")
1710
+ precondition(state(nil).mode == "unknown")
1473
1711
  precondition(state(sample()).text == "94%")
1474
1712
  precondition(state(sample(), weekly: true).text == "77%")
1475
1713
  var onlyWeek = sample(); onlyWeek.windows = controlQuotas(onlyWeek.windows).filter { $0.weekly }.map { $0.window }
@@ -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.0.2</string>
8
+ <key>CFBundleShortVersionString</key><string>1.1.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.0.2",
3
+ "version": "1.1.0",
4
4
  "description": "Claude Code quota rings and transparent world clock for Claude desktop",
5
5
  "type": "module",
6
6
  "bin": {
@@ -27,7 +27,11 @@
27
27
  "test:lock": "python3 scripts/test-native-lock.py",
28
28
  "test:reminder": "python3 scripts/test-native-reminder.py",
29
29
  "test:controls": "python3 scripts/test-controls.py",
30
- "test:refresh": "python3 scripts/test-refresh.py"
30
+ "test:refresh": "python3 scripts/test-refresh.py",
31
+ "test:protection": "node --test --test-timeout=15000 scripts/ip-guard-proof/verify.mjs scripts/ip-guard-proof/service-check.mjs",
32
+ "test:protection-ui": "python3 scripts/test-protection-ui.py",
33
+ "test:focus": "python3 scripts/test-focus.py",
34
+ "test:polling": "python3 scripts/test-polling.py"
31
35
  },
32
36
  "license": "MIT",
33
37
  "author": "UnionSchool",
@@ -0,0 +1,57 @@
1
+ import http from 'node:http';
2
+ import net from 'node:net';
3
+ import { Transform } from 'node:stream';
4
+
5
+ export function createGateway(guard, targets = null) {
6
+ const sockets = new Set();
7
+ const closeConnections = () => { for (const socket of sockets) socket.destroy(); };
8
+ guard.on('blocked', closeConnections);
9
+ const server = http.createServer((_req, res) => { res.writeHead(405); res.end(); });
10
+ server.headersTimeout = 5000; server.requestTimeout = 5000;
11
+ server.on('connection', socket => {
12
+ sockets.add(socket); socket.on('close', () => sockets.delete(socket));
13
+ socket.on('error', () => {});
14
+ });
15
+ server.on('connect', (req, client, head) => {
16
+ client.on('error', () => {});
17
+ const permitted = () => guard.usable();
18
+ let target;
19
+ try {
20
+ if (targets) target = targets.get(req.url);
21
+ else {
22
+ const match = /^([a-zA-Z0-9.-]+):443$/.exec(req.url);
23
+ if (match && match[1].length <= 253 && !match[1].startsWith('-')) target = { host: match[1], port: 443, family: 4 };
24
+ }
25
+ } catch { /* 无效 CONNECT 请求在下面统一拒绝。 */ }
26
+ if (!permitted() || !target) { client.end('HTTP/1.1 403 Forbidden\r\n\r\n'); return; }
27
+ const generation = guard.generation;
28
+ if (guard.enabled && net.isIP(target.host) && net.isIP(target.host) !== guard.family) { client.end('HTTP/1.1 403 Forbidden\r\n\r\n'); return; }
29
+ const upstream = net.connect(target);
30
+ upstream.setTimeout(12000, () => upstream.destroy());
31
+ for (const socket of [client, upstream]) {
32
+ sockets.add(socket); socket.on('close', () => sockets.delete(socket));
33
+ }
34
+ upstream.on('error', () => client.destroy());
35
+ upstream.on('close', () => client.destroy());
36
+ client.on('close', () => upstream.destroy());
37
+ upstream.on('connect', () => {
38
+ if (!permitted() || generation !== guard.generation) { client.destroy(); upstream.destroy(); return; }
39
+ upstream.setTimeout(0);
40
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
41
+ if (head.length) upstream.write(head);
42
+ // 每批数据重新核对租约,防止事件循环暂停后先转发、后执行到期计时器。
43
+ const check = () => new Transform({ transform(data, _encoding, done) {
44
+ if (!permitted() || generation !== guard.generation) { client.destroy(); upstream.destroy(); done(); }
45
+ else done(null, data);
46
+ } });
47
+ const outbound = check(), inbound = check();
48
+ client.on('close', () => { outbound.destroy(); inbound.destroy(); });
49
+ client.pipe(outbound).pipe(upstream); upstream.pipe(inbound).pipe(client);
50
+ });
51
+ });
52
+ server.on('clientError', (_error, socket) => socket.destroy());
53
+ return { server, close: () => {
54
+ closeConnections(); guard.removeListener('blocked', closeConnections);
55
+ return new Promise(resolve => server.close(resolve));
56
+ } };
57
+ }
@@ -0,0 +1,114 @@
1
+ // 检测代次和短期租约共同决定代理是否可以转发。
2
+ import { EventEmitter } from 'node:events';
3
+ import { isIP } from 'node:net';
4
+ import https from 'node:https';
5
+
6
+ export function normalizeIP(value) {
7
+ if (typeof value !== 'string' || !isIP(value)) throw new Error('非法 IP');
8
+ if (isIP(value) === 4) return value;
9
+ const ip = new URL(`http://[${value}]/`).hostname.slice(1, -1);
10
+ // 防止映射地址被当作已验证的独立 IPv6 出口。
11
+ if (ip.startsWith('::ffff:')) throw new Error('暂不支持 IPv4 映射 IPv6');
12
+ return ip;
13
+ }
14
+
15
+ export function parseIPResponse(raw) {
16
+ if (Buffer.byteLength(raw) > 8192) throw new Error('响应过大');
17
+ return normalizeIP(JSON.parse(raw)?.ip);
18
+ }
19
+
20
+ export function probeHTTPS(url, { signal, family = 4, ca, timeout = 1000 } = {}) {
21
+ if (new URL(url).protocol !== 'https:') throw new Error('只允许 HTTPS');
22
+ return new Promise((resolve, reject) => {
23
+ const req = https.get(url, { signal, family, ca, agent: false, rejectUnauthorized: true }, res => {
24
+ if (res.statusCode !== 200) {
25
+ const error = Object.assign(new Error(`HTTP ${res.statusCode}`), { rateLimited: res.statusCode === 429 });
26
+ res.destroy(); reject(error); return;
27
+ }
28
+ const chunks = []; let size = 0;
29
+ res.on('data', data => {
30
+ size += data.length;
31
+ if (size > 8192) req.destroy(new Error('响应过大'));
32
+ else chunks.push(data);
33
+ });
34
+ res.on('error', reject);
35
+ res.on('end', () => {
36
+ try {
37
+ const ip = parseIPResponse(Buffer.concat(chunks).toString('utf8'));
38
+ if (isIP(ip) !== family) throw new Error('检测地址族不一致');
39
+ resolve(ip);
40
+ }
41
+ catch (error) { reject(error); }
42
+ });
43
+ });
44
+ // 总时限包含连接与响应,不能只依赖空闲 socket 超时。
45
+ const timer = setTimeout(() => req.destroy(new Error('检测超时')), timeout);
46
+ req.on('close', () => clearTimeout(timer));
47
+ req.on('error', reject);
48
+ });
49
+ }
50
+
51
+ export class Guard extends EventEmitter {
52
+ constructor({ allowed, probe, ttl = 1000, timeout = 500, cooldown = 1000, now = () => performance.now() }) {
53
+ super();
54
+ for (const value of [ttl, timeout, cooldown]) if (!Number.isFinite(value) || value <= 0) throw new Error('无效时间配置');
55
+ this.allowed = new Set(allowed.map(normalizeIP));
56
+ this.probe = probe; this.ttl = ttl; this.timeout = timeout;
57
+ this.cooldown = cooldown; this.now = now;
58
+ this.enabled = false; this.state = 'off'; this.generation = 0;
59
+ this.expires = 0; this.retryAt = 0; this.family = null;
60
+ }
61
+ revoke(reason = '等待验证') {
62
+ this.generation++;
63
+ this.controller?.abort(); this.controller = null;
64
+ clearTimeout(this.leaseTimer);
65
+ this.expires = 0; this.family = null;
66
+ this.state = this.enabled ? 'blocked' : 'off'; this.reason = reason;
67
+ this.emit('blocked');
68
+ }
69
+ enable() { this.enabled = true; this.revoke(); }
70
+ disable() { this.enabled = false; this.revoke('保护已关闭'); }
71
+ changeAllowed(allowed) {
72
+ this.revoke('白名单修改');
73
+ this.allowed = new Set(allowed.map(normalizeIP));
74
+ }
75
+ usable() {
76
+ if (this.state === 'allowed' && this.now() >= this.expires) this.revoke('检测过期');
77
+ return this.enabled && this.state === 'allowed';
78
+ }
79
+ async verify({ keepLease = false } = {}) {
80
+ if (!this.enabled || this.controller || this.now() < this.retryAt) return false;
81
+ const retaining = keepLease && this.usable();
82
+ if (!retaining) this.revoke();
83
+ const generation = this.generation, controller = new AbortController();
84
+ this.controller = controller;
85
+ if (!retaining) this.state = 'checking';
86
+ let timer;
87
+ try {
88
+ const raw = await Promise.race([
89
+ Promise.resolve().then(() => this.probe(controller.signal)),
90
+ new Promise((_, reject) => { timer = setTimeout(() => {
91
+ controller.abort(); reject(new Error('检测超时'));
92
+ }, this.timeout); })
93
+ ]);
94
+ if (generation !== this.generation || controller.signal.aborted || !this.enabled) return false;
95
+ const ip = normalizeIP(raw);
96
+ this.lastIP = ip;
97
+ if (!this.allowed.has(ip)) throw new Error('出口不在白名单');
98
+ this.expires = this.now() + this.ttl; this.family = isIP(ip);
99
+ this.state = 'allowed'; this.reason = ''; this.retryAt = 0;
100
+ clearTimeout(this.leaseTimer);
101
+ this.leaseTimer = setTimeout(() => this.revoke('检测过期'), this.ttl);
102
+ return true;
103
+ } catch (error) {
104
+ if (generation === this.generation) {
105
+ this.revoke(error.message);
106
+ if (error.rateLimited) this.retryAt = this.now() + this.cooldown;
107
+ }
108
+ return false;
109
+ } finally {
110
+ clearTimeout(timer);
111
+ if (this.controller === controller) this.controller = null;
112
+ }
113
+ }
114
+ }
@@ -0,0 +1,51 @@
1
+ import net from 'node:net';
2
+ import { spawn } from 'node:child_process';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { L } from '../language.js';
6
+
7
+ export const DEFAULT_PROXY_PORT = 18197;
8
+ export const DEFAULT_PROXY_URL = `http://127.0.0.1:${DEFAULT_PROXY_PORT}`;
9
+
10
+ export function controlPath(env = process.env) {
11
+ return join(env.EASY_CLAUDE_GUARD_DIR || join(tmpdir(), `easy-claude-guard-${process.getuid()}`), 'control.sock');
12
+ }
13
+
14
+ export function proxyEnvironment(port, env = process.env) {
15
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid proxy port');
16
+ const proxy = `http://127.0.0.1:${port}`;
17
+ return { ...env, HTTP_PROXY: proxy, HTTPS_PROXY: proxy, http_proxy: proxy, https_proxy: proxy,
18
+ ALL_PROXY: proxy, all_proxy: proxy, NO_PROXY: 'localhost,127.0.0.1,::1,.local', no_proxy: 'localhost,127.0.0.1,::1,.local' };
19
+ }
20
+
21
+ export function readGuardStatus({ path = controlPath(), timeout = 2000 } = {}) {
22
+ return new Promise((resolve, reject) => {
23
+ const socket = net.connect(path); let data = '';
24
+ const timer = setTimeout(() => socket.destroy(new Error('Protection service timeout')), timeout);
25
+ socket.on('data', chunk => {
26
+ data += chunk;
27
+ if (data.length > 8192) { socket.destroy(new Error('Invalid protection status')); return; }
28
+ if (!data.includes('\n')) return;
29
+ try {
30
+ const status = JSON.parse(data.slice(0, data.indexOf('\n')));
31
+ if (status.service !== 'easy-claude-ip-guard' || !status.enabled || !status.ready) throw new Error('Protection service unavailable');
32
+ proxyEnvironment(status.port);
33
+ socket.destroy(); resolve(status);
34
+ } catch (error) { socket.destroy(); reject(error); }
35
+ });
36
+ socket.on('error', reject);
37
+ socket.on('close', () => { clearTimeout(timer); if (!data.includes('\n')) reject(new Error('Protection service disconnected')); });
38
+ });
39
+ }
40
+
41
+ export async function runProtectedCode(args, { readStatus = readGuardStatus, start = spawn, env = process.env, platform = process.platform } = {}) {
42
+ if (platform !== 'darwin') throw new Error(L('受保护启动仅支持 macOS。', 'Protected launch requires macOS.'));
43
+ let status;
44
+ try { status = await readStatus(); }
45
+ catch { throw new Error(L('请先在 easy-claude 面板开启保护并等待 IP 验证通过。', 'Enable protection in easy-claude and wait for IP verification.')); }
46
+ return new Promise((resolve, reject) => {
47
+ const child = start('claude', args, { env: proxyEnvironment(status.port, env), stdio: 'inherit' });
48
+ child.on('error', () => reject(new Error(L('受保护启动失败,没有回退直连。', 'Protected launch failed; direct access was not used.'))));
49
+ child.on('exit', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
50
+ });
51
+ }
@@ -0,0 +1,101 @@
1
+ import net from 'node:net';
2
+ import { mkdir, lstat, chmod, unlink } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { Guard, normalizeIP, probeHTTPS } from './guard.js';
6
+ import { createGateway } from './gateway.js';
7
+ import { controlPath, DEFAULT_PROXY_PORT } from './launcher.js';
8
+
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 }),
11
+ heartbeatTimeout = 15000 } = {}) {
12
+ const guard = new Guard({ allowed: [], probe, ttl: 75000, timeout: 13000, cooldown: 600000 });
13
+ // 服务一开始先阻断,收到界面配置前绝不接受转发。
14
+ guard.enable();
15
+ const gateway = createGateway(guard);
16
+ await new Promise((resolve, reject) => { gateway.server.once('error', reject); gateway.server.listen(proxyPort, '127.0.0.1', resolve); });
17
+ const port = gateway.server.address().port;
18
+ let fault = '', checkedAt = null, interval = 60000;
19
+ let lastCheck = -Infinity, heartbeat = performance.now(), stopped = false, holding = false, verification = 0;
20
+ const status = () => {
21
+ const ready = guard.usable() && !fault;
22
+ return { service: 'easy-claude-ip-guard', port, enabled: guard.enabled, ready,
23
+ state: fault ? 'fault' : guard.state, reason: fault || guard.reason || '', ip: guard.lastIP || null, checkedAt };
24
+ };
25
+ const report = () => { if (!stopped && !output.destroyed) output.write(JSON.stringify(status()) + '\n'); };
26
+ const verify = async (keepLease = false) => {
27
+ if (!guard.enabled || stopped || holding || guard.controller) return;
28
+ const attempt = ++verification;
29
+ lastCheck = performance.now();
30
+ const pending = guard.verify({ keepLease }); report();
31
+ await pending;
32
+ if (attempt === verification) checkedAt = new Date().toISOString();
33
+ report();
34
+ };
35
+ guard.on('blocked', report);
36
+ const control = net.createServer(socket => { socket.on('error', () => {}); socket.end(JSON.stringify(status()) + '\n'); });
37
+ const stop = async () => {
38
+ if (stopped) return;
39
+ stopped = true; clearInterval(timer); guard.revoke('控制程序已退出');
40
+ reader.close(); await gateway.close();
41
+ await new Promise(resolve => control.close(resolve));
42
+ };
43
+ let timer, reader;
44
+ try {
45
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
46
+ const directory = await lstat(dirname(path));
47
+ if (!directory.isDirectory() || directory.uid !== process.getuid() || (directory.mode & 0o077)) throw new Error('保护通信目录权限不安全');
48
+ try {
49
+ const file = await lstat(path);
50
+ if (!file.isSocket() || file.uid !== process.getuid()) throw new Error('保护通信路径不安全');
51
+ const active = await new Promise((resolve, reject) => {
52
+ const socket = net.connect(path);
53
+ socket.setTimeout(1000, () => { socket.destroy(); reject(new Error('已有保护服务没有响应')); });
54
+ socket.once('connect', () => { socket.destroy(); resolve(true); });
55
+ socket.once('error', error => ['ECONNREFUSED', 'ENOENT'].includes(error.code) ? resolve(false) : reject(error));
56
+ });
57
+ if (active) throw new Error('已有保护服务正在运行');
58
+ await unlink(path);
59
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
60
+ await new Promise((resolve, reject) => { control.once('error', reject); control.listen(path, resolve); });
61
+ await chmod(path, 0o600);
62
+ } catch (error) {
63
+ guard.revoke(); await gateway.close(); control.close(); throw error;
64
+ }
65
+ reader = createInterface({ input, crlfDelay: Infinity });
66
+ reader.on('line', line => {
67
+ if (line.length > 4096) { guard.revoke(); fault = '控制消息过大'; report(); return; }
68
+ try {
69
+ const command = JSON.parse(line);
70
+ if (command.action === 'heartbeat') { heartbeat = performance.now(); return; }
71
+ if (command.action === 'configure') {
72
+ holding = true;
73
+ guard.revoke('配置修改');
74
+ if (typeof command.enabled !== 'boolean') throw new Error('保护配置无效');
75
+ if (!command.enabled) { holding = false; guard.disable(); fault = ''; report(); return; }
76
+ const ips = command.ips.map(normalizeIP);
77
+ 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秒');
79
+ guard.changeAllowed(ips); guard.ttl = command.interval * 1000 + 15000;
80
+ interval = command.interval * 1000; holding = false; guard.enable(); fault = ''; void verify();
81
+ } else if (command.action === 'invalidate' || command.action === 'verify') {
82
+ if (guard.enabled) { guard.revoke('网络变化或重新检测'); report(); void verify(); }
83
+ } else if (command.action === 'hold') {
84
+ holding = true; guard.revoke('白名单正在编辑'); report();
85
+ } else if (command.action === 'launchDesktop') {
86
+ // Electron辅助进程需要自行初始化沙箱,外层sandbox-exec会使它们启动即崩溃。
87
+ throw new Error('桌面受保护启动暂不可用:嵌套沙箱冲突。请关闭保护后正常启动Claude;不会自动回退直连。');
88
+ } else throw new Error('未知保护命令');
89
+ } catch (error) { guard.revoke('配置或控制错误'); fault = error.message; report(); }
90
+ });
91
+ reader.on('close', () => { void stop(); });
92
+ output.on('error', () => { void stop(); });
93
+ timer = setInterval(() => {
94
+ if (performance.now() - heartbeat >= heartbeatTimeout) { void stop(); return; }
95
+ const wasAllowed = guard.state === 'allowed'; guard.usable();
96
+ if (wasAllowed && guard.state !== 'allowed') report();
97
+ if (guard.enabled && !fault && performance.now() - lastCheck >= interval) void verify(true);
98
+ }, 500);
99
+ report();
100
+ return { guard, port, status, stop, verify };
101
+ }
@@ -0,0 +1,6 @@
1
+ import { startService } from './ip-guard/service.js';
2
+ try { await startService(); }
3
+ catch {
4
+ console.log(JSON.stringify({ state: 'fault', reason: '保护服务启动失败,请检查端口、沙箱或已有进程', ready: false }));
5
+ process.exitCode = 1;
6
+ }