easy-claude 1.0.3 → 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 +17 -0
- package/README.md +26 -9
- package/README.zh-CN.md +28 -13
- package/bin/easy-claude.js +5 -2
- package/native/Overlay.swift +353 -35
- package/native/build/EasyClaudeOverlay.app/Contents/Info.plist +1 -1
- package/native/build/EasyClaudeOverlay.app/Contents/MacOS/EasyClaudeOverlay +0 -0
- package/package.json +3 -1
- package/src/ip-guard/gateway.js +57 -0
- package/src/ip-guard/guard.js +136 -0
- package/src/ip-guard/launcher.js +51 -0
- package/src/ip-guard/service.js +108 -0
- package/src/overlay-guard.js +6 -0
- package/src/overlay-proxy.js +10 -0
- package/src/proxy-config.js +184 -0
- package/src/public-ip.js +10 -3
|
@@ -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,136 @@
|
|
|
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 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
|
+
|
|
73
|
+
export class Guard extends EventEmitter {
|
|
74
|
+
constructor({ allowed, probe, ttl = 1000, timeout = 500, cooldown = 1000, now = () => performance.now() }) {
|
|
75
|
+
super();
|
|
76
|
+
for (const value of [ttl, timeout, cooldown]) if (!Number.isFinite(value) || value <= 0) throw new Error('无效时间配置');
|
|
77
|
+
this.allowed = new Set(allowed.map(normalizeIP));
|
|
78
|
+
this.probe = probe; this.ttl = ttl; this.timeout = timeout;
|
|
79
|
+
this.cooldown = cooldown; this.now = now;
|
|
80
|
+
this.enabled = false; this.state = 'off'; this.generation = 0;
|
|
81
|
+
this.expires = 0; this.retryAt = 0; this.family = null;
|
|
82
|
+
}
|
|
83
|
+
revoke(reason = '等待验证') {
|
|
84
|
+
this.generation++;
|
|
85
|
+
this.controller?.abort(); this.controller = null;
|
|
86
|
+
clearTimeout(this.leaseTimer);
|
|
87
|
+
this.expires = 0; this.family = null;
|
|
88
|
+
this.state = this.enabled ? 'blocked' : 'off'; this.reason = reason;
|
|
89
|
+
this.emit('blocked');
|
|
90
|
+
}
|
|
91
|
+
enable() { this.enabled = true; this.revoke(); }
|
|
92
|
+
disable() { this.enabled = false; this.revoke('保护已关闭'); }
|
|
93
|
+
changeAllowed(allowed) {
|
|
94
|
+
this.revoke('白名单修改');
|
|
95
|
+
this.allowed = new Set(allowed.map(normalizeIP));
|
|
96
|
+
}
|
|
97
|
+
usable() {
|
|
98
|
+
if (this.state === 'allowed' && this.now() >= this.expires) this.revoke('检测过期');
|
|
99
|
+
return this.enabled && this.state === 'allowed';
|
|
100
|
+
}
|
|
101
|
+
async verify({ keepLease = false } = {}) {
|
|
102
|
+
if (!this.enabled || this.controller || this.now() < this.retryAt) return false;
|
|
103
|
+
const retaining = keepLease && this.usable();
|
|
104
|
+
if (!retaining) this.revoke();
|
|
105
|
+
const generation = this.generation, controller = new AbortController();
|
|
106
|
+
this.controller = controller;
|
|
107
|
+
if (!retaining) this.state = 'checking';
|
|
108
|
+
let timer;
|
|
109
|
+
try {
|
|
110
|
+
const raw = await Promise.race([
|
|
111
|
+
Promise.resolve().then(() => this.probe(controller.signal)),
|
|
112
|
+
new Promise((_, reject) => { timer = setTimeout(() => {
|
|
113
|
+
controller.abort(); reject(new Error('检测超时'));
|
|
114
|
+
}, this.timeout); })
|
|
115
|
+
]);
|
|
116
|
+
if (generation !== this.generation || controller.signal.aborted || !this.enabled) return false;
|
|
117
|
+
const ip = normalizeIP(raw);
|
|
118
|
+
this.lastIP = ip;
|
|
119
|
+
if (!this.allowed.has(ip)) throw new Error('出口不在白名单');
|
|
120
|
+
this.expires = this.now() + this.ttl; this.family = isIP(ip);
|
|
121
|
+
this.state = 'allowed'; this.reason = ''; this.retryAt = 0;
|
|
122
|
+
clearTimeout(this.leaseTimer);
|
|
123
|
+
this.leaseTimer = setTimeout(() => this.revoke('检测过期'), this.ttl);
|
|
124
|
+
return true;
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (generation === this.generation) {
|
|
127
|
+
this.revoke(error.message);
|
|
128
|
+
if (error.rateLimited) this.retryAt = this.now() + this.cooldown;
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
} finally {
|
|
132
|
+
clearTimeout(timer);
|
|
133
|
+
if (this.controller === controller) this.controller = null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -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,108 @@
|
|
|
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, createExitIPProbe } 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 = createExitIPProbe(), now = () => performance.now(),
|
|
11
|
+
heartbeatTimeout = 15000 } = {}) {
|
|
12
|
+
const guard = new Guard({ allowed: [], probe, ttl: 75000, timeout: 13000, cooldown: 600000, now });
|
|
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 = now(), stopped = false, holding = false, verification = 0, requested = false;
|
|
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) 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;
|
|
35
|
+
const attempt = ++verification;
|
|
36
|
+
lastCheck = now();
|
|
37
|
+
const pending = guard.verify({ keepLease }); report();
|
|
38
|
+
await pending;
|
|
39
|
+
if (attempt === verification) checkedAt = new Date().toISOString();
|
|
40
|
+
report();
|
|
41
|
+
};
|
|
42
|
+
guard.on('blocked', report);
|
|
43
|
+
const control = net.createServer(socket => { socket.on('error', () => {}); socket.end(JSON.stringify(status()) + '\n'); });
|
|
44
|
+
const stop = async () => {
|
|
45
|
+
if (stopped) return;
|
|
46
|
+
stopped = true; verification++; clearInterval(timer); guard.revoke('控制程序已退出');
|
|
47
|
+
reader.close(); await gateway.close();
|
|
48
|
+
await new Promise(resolve => control.close(resolve));
|
|
49
|
+
};
|
|
50
|
+
let timer, reader;
|
|
51
|
+
try {
|
|
52
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
53
|
+
const directory = await lstat(dirname(path));
|
|
54
|
+
if (!directory.isDirectory() || directory.uid !== process.getuid() || (directory.mode & 0o077)) throw new Error('保护通信目录权限不安全');
|
|
55
|
+
try {
|
|
56
|
+
const file = await lstat(path);
|
|
57
|
+
if (!file.isSocket() || file.uid !== process.getuid()) throw new Error('保护通信路径不安全');
|
|
58
|
+
const active = await new Promise((resolve, reject) => {
|
|
59
|
+
const socket = net.connect(path);
|
|
60
|
+
socket.setTimeout(1000, () => { socket.destroy(); reject(new Error('已有保护服务没有响应')); });
|
|
61
|
+
socket.once('connect', () => { socket.destroy(); resolve(true); });
|
|
62
|
+
socket.once('error', error => ['ECONNREFUSED', 'ENOENT'].includes(error.code) ? resolve(false) : reject(error));
|
|
63
|
+
});
|
|
64
|
+
if (active) throw new Error('已有保护服务正在运行');
|
|
65
|
+
await unlink(path);
|
|
66
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
67
|
+
await new Promise((resolve, reject) => { control.once('error', reject); control.listen(path, resolve); });
|
|
68
|
+
await chmod(path, 0o600);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
guard.revoke(); await gateway.close(); control.close(); throw error;
|
|
71
|
+
}
|
|
72
|
+
reader = createInterface({ input, crlfDelay: Infinity });
|
|
73
|
+
reader.on('line', line => {
|
|
74
|
+
if (line.length > 4096) { verification++; guard.revoke(); fault = '控制消息过大'; report(); return; }
|
|
75
|
+
try {
|
|
76
|
+
const command = JSON.parse(line);
|
|
77
|
+
if (command.action === 'heartbeat') { heartbeat = now(); return; }
|
|
78
|
+
if (command.action === 'configure') {
|
|
79
|
+
holding = true;
|
|
80
|
+
verification++; guard.revoke('配置修改');
|
|
81
|
+
if (typeof command.enabled !== 'boolean') throw new Error('保护配置无效');
|
|
82
|
+
if (!command.enabled) { holding = false; guard.disable(); fault = ''; report(); return; }
|
|
83
|
+
const ips = command.ips.map(normalizeIP);
|
|
84
|
+
if (!ips.length || ips.length > 20 || ips.some(ip => net.isIP(ip) !== 4)) throw new Error('请输入 IPv4 白名单;当前版本关闭 IPv6 转发');
|
|
85
|
+
if (!Number.isInteger(command.interval) || command.interval < 60 || command.interval > 300) throw new Error('复查间隔应为60至300秒');
|
|
86
|
+
guard.changeAllowed(ips); guard.ttl = command.interval * 1000 + 15000;
|
|
87
|
+
interval = command.interval * 1000; holding = false; guard.enable(); fault = ''; void verify();
|
|
88
|
+
} else if (command.action === 'invalidate' || command.action === 'verify') {
|
|
89
|
+
if (guard.enabled) { verification++; guard.revoke('网络变化或重新检测'); report(); void verify(); }
|
|
90
|
+
} else if (command.action === 'hold') {
|
|
91
|
+
holding = true; verification++; guard.revoke('白名单正在编辑'); report();
|
|
92
|
+
} else if (command.action === 'launchDesktop') {
|
|
93
|
+
// Electron辅助进程需要自行初始化沙箱,外层sandbox-exec会使它们启动即崩溃。
|
|
94
|
+
throw new Error('桌面受保护启动暂不可用:嵌套沙箱冲突。请关闭保护后正常启动Claude;不会自动回退直连。');
|
|
95
|
+
} else throw new Error('未知保护命令');
|
|
96
|
+
} catch (error) { verification++; guard.revoke('配置或控制错误'); fault = error.message; report(); }
|
|
97
|
+
});
|
|
98
|
+
reader.on('close', () => { void stop(); });
|
|
99
|
+
output.on('error', () => { void stop(); });
|
|
100
|
+
timer = setInterval(() => {
|
|
101
|
+
if (now() - heartbeat >= heartbeatTimeout) { void stop(); return; }
|
|
102
|
+
const wasAllowed = guard.state === 'allowed'; guard.usable();
|
|
103
|
+
if (wasAllowed && guard.state !== 'allowed') report();
|
|
104
|
+
if (guard.enabled && !fault && now() >= guard.retryAt && now() - lastCheck >= (requested ? 60000 : interval)) void verify(!requested);
|
|
105
|
+
}, 500);
|
|
106
|
+
report();
|
|
107
|
+
return { guard, port, status, stop, verify };
|
|
108
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { proxyStatus, changeProxy } from './proxy-config.js';
|
|
2
|
+
try {
|
|
3
|
+
if (process.platform !== 'darwin') throw new Error('Claude代理配置仅支持macOS');
|
|
4
|
+
const action = process.argv[2] || 'status';
|
|
5
|
+
console.log(JSON.stringify(action === 'status' ? await proxyStatus() : await changeProxy(action)));
|
|
6
|
+
} catch (error) {
|
|
7
|
+
const status = await proxyStatus().catch(() => ({ active: false, configured: false }));
|
|
8
|
+
console.log(JSON.stringify({ ...status, error: error.message }));
|
|
9
|
+
process.exitCode = 1;
|
|
10
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { promises as fs, constants } from 'node:fs';
|
|
2
|
+
import { join, dirname, basename } from 'node:path';
|
|
3
|
+
import { homedir, userInfo } from 'node:os';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { DEFAULT_PROXY_PORT, DEFAULT_PROXY_URL, proxyEnvironment } from './ip-guard/launcher.js';
|
|
8
|
+
|
|
9
|
+
const run = promisify(execFile);
|
|
10
|
+
const wanted = proxyEnvironment(DEFAULT_PROXY_PORT, {});
|
|
11
|
+
const keys = Object.keys(wanted);
|
|
12
|
+
const hash = data => createHash('sha256').update(data).digest('hex');
|
|
13
|
+
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
14
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
export function proxyPaths() {
|
|
16
|
+
return {
|
|
17
|
+
cli: join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json'),
|
|
18
|
+
desktop: join('/Library/Managed Preferences', userInfo().username, 'com.anthropic.claudefordesktop.plist'),
|
|
19
|
+
machine: '/Library/Managed Preferences/com.anthropic.claudefordesktop.plist',
|
|
20
|
+
state: join(homedir(), 'Library/Application Support/easy-claude/proxy-state.json')
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
async function file(path) {
|
|
24
|
+
try {
|
|
25
|
+
const stat = await fs.lstat(path);
|
|
26
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) throw new Error('配置文件类型或大小不安全');
|
|
27
|
+
return { stat, data: await fs.readFile(path) };
|
|
28
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
29
|
+
}
|
|
30
|
+
function json(data) {
|
|
31
|
+
let value;
|
|
32
|
+
try { value = JSON.parse(data); } catch { throw new Error('配置JSON无效,请先修复原文件'); }
|
|
33
|
+
if (!object(value) || (value.env !== undefined && !object(value.env))) throw new Error('配置结构无效,未修改原文件');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
async function desktopValue(path) {
|
|
37
|
+
if (!await file(path)) return null;
|
|
38
|
+
try { return (await run('/usr/bin/plutil', ['-extract', 'egressProxyUrl', 'raw', '-o', '-', path], { timeout: 5000, maxBuffer: 8192 })).stdout.replace(/\n$/, ''); }
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (((error.stdout || '') + (error.stderr || '')).includes('No value at that key path')) return null;
|
|
41
|
+
throw new Error('无法读取桌面代理策略,请检查文件权限或管理员策略');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async function snapshot(paths) {
|
|
45
|
+
const saved = await file(paths.state);
|
|
46
|
+
if (!saved) return null;
|
|
47
|
+
if (saved.stat.uid !== process.getuid() || saved.stat.mode & 0o077) throw new Error('代理备份记录权限不安全');
|
|
48
|
+
const value = json(saved.data);
|
|
49
|
+
if (value.version !== 1 || value.cli !== paths.cli || value.desktop !== paths.desktop) throw new Error('代理配置目录已变化,请先恢复原目录配置');
|
|
50
|
+
if ((value.desktopBackup !== null && !/^[a-f0-9]{64}$/.test(value.desktopHash || '')) || (value.cliBackup !== null && !/^[a-f0-9]{64}$/.test(value.cliHash || ''))) throw new Error('代理备份校验信息无效');
|
|
51
|
+
for (const [key, target, pattern] of [['cliBackup', paths.cli, /^settings\.bak-\d{8}-\d{6}\.json$/],
|
|
52
|
+
['desktopBackup', paths.desktop, /^com\.anthropic\.claudefordesktop\.bak-\d{8}-\d{6}\.plist$/]]) {
|
|
53
|
+
if (value[key] !== null && (typeof value[key] !== 'string' || dirname(value[key]) !== dirname(target) || !pattern.test(basename(value[key])))) throw new Error('代理备份路径无效');
|
|
54
|
+
}
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
export async function proxyStatus({ paths = proxyPaths() } = {}) {
|
|
58
|
+
const cliFile = await file(paths.cli), env = cliFile ? json(cliFile.data).env || {} : {};
|
|
59
|
+
const desktop = await desktopValue(paths.desktop);
|
|
60
|
+
const machine = await desktopValue(paths.machine);
|
|
61
|
+
const saved = await snapshot(paths);
|
|
62
|
+
return {
|
|
63
|
+
active: desktop === DEFAULT_PROXY_URL || keys.some(key => env[key] === wanted[key] && !key.toLowerCase().includes('no_proxy')),
|
|
64
|
+
configured: machine === null && desktop === DEFAULT_PROXY_URL && keys.every(key => env[key] === wanted[key]),
|
|
65
|
+
hasBackup: saved !== null,
|
|
66
|
+
machinePolicy: machine !== null
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
async function privateDirectory(path) {
|
|
70
|
+
await fs.mkdir(path, { recursive: true, mode: 0o700 });
|
|
71
|
+
const stat = await fs.lstat(path);
|
|
72
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid() || stat.mode & 0o077) throw new Error('代理备份目录权限不安全');
|
|
73
|
+
}
|
|
74
|
+
async function atomic(path, data, mode = 0o600) {
|
|
75
|
+
const temp = path + '.easy-' + randomBytes(8).toString('hex');
|
|
76
|
+
try { await fs.writeFile(temp, data, { flag: 'wx', mode }); await fs.rename(temp, path); }
|
|
77
|
+
finally { await fs.unlink(temp).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
|
|
78
|
+
}
|
|
79
|
+
function stamp() {
|
|
80
|
+
const d = new Date(), two = n => String(n).padStart(2, '0');
|
|
81
|
+
return `${d.getFullYear()}${two(d.getMonth() + 1)}${two(d.getDate())}-${two(d.getHours())}${two(d.getMinutes())}${two(d.getSeconds())}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 管理员只运行系统自带工具;恢复时在plist内部复制字段,旧代理凭据不进入命令参数。
|
|
85
|
+
export function desktopScript(action, paths, saved, rollback = null) {
|
|
86
|
+
const dir = dirname(paths.desktop), token = '__easy_proxy_' + randomBytes(6).toString('hex');
|
|
87
|
+
const safe = path => `\n[ ! -L ${quote(path)} ]\n[ "$(/usr/bin/stat -f %u ${quote(path)})" = 0 ]\nmode=$(/usr/bin/stat -f %Lp ${quote(path)})\n[ $((0$mode & 022)) -eq 0 ]`;
|
|
88
|
+
let script = `set -eu\n[ ! -L ${quote(dirname(dir))} ]\n/bin/mkdir -p ${quote(dirname(dir))}${safe(dirname(dir))}\n[ ! -L ${quote(dir)} ]\n/bin/mkdir -p ${quote(dir)}${safe(dir)}\ncd ${quote(dir)}\n`;
|
|
89
|
+
script += `target=${quote(paths.desktop)}\nif [ -e "$target" ]; then ${safe(paths.desktop)}\n/usr/bin/plutil -lint "$target" >/dev/null\nfi\n`;
|
|
90
|
+
script += `if [ -e ${quote(paths.machine)} ]; then /usr/bin/plutil -lint ${quote(paths.machine)} >/dev/null; if /usr/bin/plutil -type egressProxyUrl ${quote(paths.machine)} >/dev/null 2>&1; then exit 1; fi; fi\n`;
|
|
91
|
+
if (action === 'start') {
|
|
92
|
+
if (saved.desktopBackup) {
|
|
93
|
+
script += `[ -f "$target" ]\n[ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk '{print $1}')" = ${quote(saved.desktopHash)} ]\n[ ! -e ${quote(saved.desktopBackup)} ]\n/bin/cp -p "$target" ${quote(saved.desktopBackup)}\n`;
|
|
94
|
+
} else { script += '[ ! -e "$target" ]\n'; }
|
|
95
|
+
} else { script += `current=$(/usr/bin/plutil -extract egressProxyUrl raw -o - "$target" 2>/dev/null || true)\n[ "$current" = ${quote(DEFAULT_PROXY_URL)} ] || exit 0\n`; }
|
|
96
|
+
if (action === 'stop-default' && rollback?.desktopBackup) {
|
|
97
|
+
script += `[ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk '{print $1}')" = ${quote(rollback.desktopHash)} ]\n[ ! -e ${quote(rollback.desktopBackup)} ]\n/bin/cp -p "$target" ${quote(rollback.desktopBackup)}\n`;
|
|
98
|
+
}
|
|
99
|
+
script += 'sourceHash=\nif [ -e "$target" ]; then sourceHash=$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk \'{print $1}\'); fi\n';
|
|
100
|
+
script += `temp=$(/usr/bin/mktemp ${quote(join(dir, '.easy-proxy.XXXXXX'))})\ntrap '/bin/rm -f "$temp"' EXIT\nif [ -e "$target" ]; then /bin/cp -p "$target" "$temp"; else /usr/bin/plutil -create xml1 "$temp"; /bin/chmod 644 "$temp"; fi\n`;
|
|
101
|
+
if (action === 'start') script += `/usr/bin/plutil -replace egressProxyUrl -string ${quote(DEFAULT_PROXY_URL)} "$temp"\n`;
|
|
102
|
+
else {
|
|
103
|
+
script += '/usr/bin/plutil -remove egressProxyUrl "$temp"\n';
|
|
104
|
+
if (saved?.desktopBackup) {
|
|
105
|
+
script += `${safe(saved.desktopBackup)}\n[ "$(/usr/bin/shasum -a 256 ${quote(saved.desktopBackup)} | /usr/bin/awk '{print $1}')" = ${quote(saved.desktopHash)} ]\n`;
|
|
106
|
+
script += `if /usr/bin/plutil -type egressProxyUrl ${quote(saved.desktopBackup)} >/dev/null 2>&1; then\n/usr/libexec/PlistBuddy -c ${quote(`Add :${token} dict`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Merge ${basename(saved.desktopBackup)} :${token}`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Copy :${token}:egressProxyUrl :egressProxyUrl`)} "$temp"\n/usr/libexec/PlistBuddy -c ${quote(`Delete :${token}`)} "$temp"\nfi\n`;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return script + '/usr/bin/plutil -lint "$temp" >/dev/null\nif [ -e "$target" ]; then [ "$(/usr/bin/shasum -a 256 "$target" | /usr/bin/awk \'{print $1}\')" = "$sourceHash" ]; else [ -z "$sourceHash" ]; fi\n/bin/mv -f "$temp" "$target"\n';
|
|
110
|
+
}
|
|
111
|
+
async function administrator({ script }) {
|
|
112
|
+
try { await run('/usr/bin/osascript', ['-e', 'on run argv', '-e', 'do shell script (item 1 of argv) with administrator privileges', '-e', 'end run', script], { timeout: 120000, maxBuffer: 8192 }); }
|
|
113
|
+
catch (error) { throw new Error((error.stderr || '').includes('-128') ? '已取消管理员授权' : '桌面代理操作失败,请检查管理员策略和权限'); }
|
|
114
|
+
}
|
|
115
|
+
export async function changeProxy(action, { paths = proxyPaths(), admin = administrator } = {}) {
|
|
116
|
+
if (!['start', 'stop', 'stop-default'].includes(action)) throw new Error('未知代理操作');
|
|
117
|
+
const before = await proxyStatus({ paths });
|
|
118
|
+
if (action === 'start' && before.configured) return before;
|
|
119
|
+
if (before.machinePolicy) throw new Error('存在机器级代理策略,请由管理员管理;未覆盖该策略');
|
|
120
|
+
let saved = await snapshot(paths);
|
|
121
|
+
let rollback = null;
|
|
122
|
+
if (action === 'stop-default' && saved) throw new Error('已有原配置备份,请使用停止操作恢复');
|
|
123
|
+
if (action === 'stop' && !saved && before.active) return { ...before, needsDefaultRestore: true };
|
|
124
|
+
if (action !== 'start' && !before.active) return before;
|
|
125
|
+
if (action === 'start' && before.active && !saved) throw new Error('旧配置没有原始备份,请先停止并确认恢复默认');
|
|
126
|
+
const cliFile = await file(paths.cli), current = cliFile ? json(cliFile.data) : {};
|
|
127
|
+
if (cliFile && (cliFile.stat.uid !== process.getuid() || cliFile.stat.mode & 0o022)) throw new Error('CLI配置文件归属或权限不安全,未修改');
|
|
128
|
+
const next = { ...current, env: { ...(current.env || {}) } };
|
|
129
|
+
await fs.mkdir(dirname(paths.cli), { recursive: true, mode: 0o700 });
|
|
130
|
+
const directory = await fs.lstat(dirname(paths.cli));
|
|
131
|
+
if (!directory.isDirectory() || directory.isSymbolicLink() || directory.uid !== process.getuid() || directory.mode & 0o022) throw new Error('CLI配置目录不安全');
|
|
132
|
+
if (action === 'stop-default') {
|
|
133
|
+
const time = stamp(), desktopFile = await file(paths.desktop);
|
|
134
|
+
rollback = { desktopBackup: desktopFile ? join(dirname(paths.desktop), `com.anthropic.claudefordesktop.bak-${time}.plist`) : null,
|
|
135
|
+
desktopHash: desktopFile ? hash(desktopFile.data) : null };
|
|
136
|
+
if (cliFile) {
|
|
137
|
+
const backup = join(dirname(paths.cli), `settings.bak-${time}.json`);
|
|
138
|
+
await fs.copyFile(paths.cli, backup, constants.COPYFILE_EXCL); await fs.chmod(backup, 0o600);
|
|
139
|
+
if (hash(await fs.readFile(backup)) !== hash(cliFile.data)) throw new Error('CLI配置在备份期间已变化,未修改');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (action === 'start') {
|
|
143
|
+
await privateDirectory(dirname(paths.state));
|
|
144
|
+
const time = stamp(), desktopFile = await file(paths.desktop);
|
|
145
|
+
saved = { version: 1, cli: paths.cli, desktop: paths.desktop,
|
|
146
|
+
cliBackup: cliFile ? join(dirname(paths.cli), `settings.bak-${time}.json`) : null,
|
|
147
|
+
desktopBackup: desktopFile ? join(dirname(paths.desktop), `com.anthropic.claudefordesktop.bak-${time}.plist`) : null,
|
|
148
|
+
desktopHash: desktopFile ? hash(desktopFile.data) : null, cliHash: cliFile ? hash(cliFile.data) : null };
|
|
149
|
+
if (cliFile) {
|
|
150
|
+
await fs.copyFile(paths.cli, saved.cliBackup, constants.COPYFILE_EXCL); await fs.chmod(saved.cliBackup, 0o600);
|
|
151
|
+
if (hash(await fs.readFile(saved.cliBackup)) !== saved.cliHash) throw new Error('CLI配置在备份期间已变化,未修改');
|
|
152
|
+
}
|
|
153
|
+
await atomic(paths.state, JSON.stringify(saved));
|
|
154
|
+
Object.assign(next.env, wanted);
|
|
155
|
+
} else {
|
|
156
|
+
let original = {};
|
|
157
|
+
if (saved?.cliBackup) {
|
|
158
|
+
const backup = await file(saved.cliBackup);
|
|
159
|
+
if (!backup || hash(backup.data) !== saved.cliHash) throw new Error('原始CLI备份缺失或已变化,未猜测原配置');
|
|
160
|
+
original = json(backup.data);
|
|
161
|
+
}
|
|
162
|
+
for (const key of keys) {
|
|
163
|
+
if (next.env[key] !== wanted[key]) continue;
|
|
164
|
+
if (Object.hasOwn(original.env || {}, key)) next.env[key] = original.env[key];
|
|
165
|
+
else delete next.env[key];
|
|
166
|
+
}
|
|
167
|
+
if (!Object.keys(next.env).length && !Object.hasOwn(original, 'env')) delete next.env;
|
|
168
|
+
}
|
|
169
|
+
try {
|
|
170
|
+
const desktop = await desktopValue(paths.desktop);
|
|
171
|
+
if (action === 'start' || desktop === DEFAULT_PROXY_URL) await admin({ action, paths, saved: action === 'stop-default' ? null : saved, script: desktopScript(action, paths, action === 'stop-default' ? null : saved, rollback) });
|
|
172
|
+
const latest = await file(paths.cli);
|
|
173
|
+
if ((latest ? hash(latest.data) : null) !== (cliFile ? hash(cliFile.data) : null)) throw new Error('CLI配置在操作期间已变化,请重试;未覆盖新内容');
|
|
174
|
+
if (action !== 'start' && saved?.cliBackup === null && !Object.keys(next).length) await fs.unlink(paths.cli).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
175
|
+
else await atomic(paths.cli, JSON.stringify(next, null, 2) + '\n', cliFile ? cliFile.stat.mode & 0o777 : 0o600);
|
|
176
|
+
if (action !== 'start') await fs.unlink(paths.state).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
177
|
+
const result = await proxyStatus({ paths });
|
|
178
|
+
if (action === 'start' && !result.configured) throw new Error('代理配置未完全验证成功,请检查两端配置');
|
|
179
|
+
return { ...result, needsRestart: true, restoredDefault: action === 'stop-default' };
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (action === 'start' && !(await proxyStatus({ paths }).catch(() => ({ active: true }))).active) await fs.unlink(paths.state).catch(() => {});
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/public-ip.js
CHANGED
|
@@ -18,9 +18,16 @@ export async function readPublicIP({ run = promisify(execFile), env = process.en
|
|
|
18
18
|
return stdout;
|
|
19
19
|
};
|
|
20
20
|
let data;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
for (const url of ['https://ipinfo.io/json', 'https://api.ipify.org?format=json']) {
|
|
22
|
+
try {
|
|
23
|
+
const value = JSON.parse(await request(url));
|
|
24
|
+
if (!value || typeof value.ip !== 'string' || !isIP(value.ip)) throw new Error('Invalid IP');
|
|
25
|
+
// 备用只提供IP,不能将旧城市或时区附在新的出口上。
|
|
26
|
+
data = url.includes('ipinfo.io') ? value : { ip: value.ip };
|
|
27
|
+
break;
|
|
28
|
+
} catch { /* 主源失败时仅尝试一次独立备用查询。 */ }
|
|
29
|
+
}
|
|
30
|
+
if (!data) throw new Error(L('IP异常', 'IP unavailable'));
|
|
24
31
|
const ip = data.ip;
|
|
25
32
|
let city = null, timezone = null;
|
|
26
33
|
if (typeof data.city === 'string') {
|