@fefeding/aicmd 1.0.27 → 1.0.30

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.
Files changed (39) hide show
  1. package/README.md +2 -0
  2. package/README.zh.md +2 -0
  3. package/dist/public/ai-settings.css +22 -22
  4. package/dist/public/ai-settings.js +57 -4
  5. package/dist/public/connection-editor.css +2 -2
  6. package/dist/public/connection-editor.js +162 -43
  7. package/dist/public/selection-copy.js +42 -3
  8. package/dist/public/src/term.html +6 -6
  9. package/dist/public/src/vscode-edit.html +10 -10
  10. package/dist/public/src/vscode-term.html +13 -13
  11. package/dist/server/model/connection.entity.d.ts +17 -0
  12. package/dist/server/model/connection.entity.d.ts.map +1 -1
  13. package/dist/server/model/connection.entity.js +2 -0
  14. package/dist/server/model/connection.entity.js.map +1 -1
  15. package/dist/server/model/connection.entity.ts +19 -0
  16. package/dist/server/service/connection.service.d.ts +1 -1
  17. package/dist/server/service/connection.service.d.ts.map +1 -1
  18. package/dist/server/service/connection.service.js +32 -3
  19. package/dist/server/service/connection.service.js.map +1 -1
  20. package/dist/server/service/connection.service.ts +30 -3
  21. package/dist/server/service/monitor.service.d.ts.map +1 -1
  22. package/dist/server/service/monitor.service.js +8 -1
  23. package/dist/server/service/monitor.service.js.map +1 -1
  24. package/dist/server/service/monitor.service.ts +8 -1
  25. package/dist/server/service/rdp-tunnel.service.d.ts.map +1 -1
  26. package/dist/server/service/rdp-tunnel.service.js +50 -40
  27. package/dist/server/service/rdp-tunnel.service.js.map +1 -1
  28. package/dist/server/service/rdp-tunnel.service.ts +50 -39
  29. package/dist/server/service/ssh.service.d.ts.map +1 -1
  30. package/dist/server/service/ssh.service.js +3 -2
  31. package/dist/server/service/ssh.service.js.map +1 -1
  32. package/dist/server/service/ssh.service.ts +3 -2
  33. package/dist/server/utils/proxy.d.ts +28 -0
  34. package/dist/server/utils/proxy.d.ts.map +1 -0
  35. package/dist/server/utils/proxy.js +596 -0
  36. package/dist/server/utils/proxy.js.map +1 -0
  37. package/dist/server/utils/proxy.ts +556 -0
  38. package/dist/view/index.html +9 -9
  39. package/package.json +1 -1
@@ -0,0 +1,556 @@
1
+ /**
2
+ * 连接代理工具:直连 / 系统代理 / 自定义代理(HTTP、HTTPS、SOCKS4、SOCKS5)。
3
+ *
4
+ * SSH 通过 ssh2 的 sock 选项使用这里建立好的 socket;RDP 隧道在 TLS 握手前
5
+ * 使用这里建立好的 socket。system 模式先读常规的 *_proxy / *_PROXY 与
6
+ * NO_PROXY / no_proxy 环境变量(小写优先),未设置时再读取操作系统代理设置
7
+ * (macOS scutil、Windows 注册表、Linux gsettings),从而与浏览器「使用系统
8
+ * 代理」的场景保持一致。
9
+ */
10
+ import * as net from 'net';
11
+ import * as tls from 'tls';
12
+ import { execFileSync } from 'child_process';
13
+ import { ConnectionEntity } from '../model/connection.entity';
14
+
15
+ type LogFn = (msg: string) => void;
16
+
17
+ export interface ResolvedProxy {
18
+ type: 'http' | 'https' | 'socks4' | 'socks5';
19
+ host: string;
20
+ port: number;
21
+ username?: string;
22
+ password?: string;
23
+ }
24
+
25
+ const DEFAULT_PORTS: Record<ResolvedProxy['type'], number> = {
26
+ http: 80,
27
+ https: 443,
28
+ socks4: 1080,
29
+ socks5: 1080,
30
+ };
31
+
32
+ /**
33
+ * 代理握手阶段多个步骤共用同一个 socket,TCP 粘包会把下一步的字节提前送来。
34
+ * 这里按 socket 暂存多余字节,而不是 unshift —— unshift 需要先 pause,
35
+ * 但显式 pause 后调用方再挂 data 监听不会自动恢复流动,连接会静默卡死。
36
+ */
37
+ const handshakeBuffers = new WeakMap<net.Socket, Buffer>();
38
+
39
+ function takeBuffered(socket: net.Socket, length: number): Buffer | null {
40
+ const buf = handshakeBuffers.get(socket);
41
+ if (!buf || buf.length < length) return null;
42
+ const result = Buffer.from(buf.subarray(0, length));
43
+ handshakeBuffers.set(socket, buf.subarray(length));
44
+ return result;
45
+ }
46
+
47
+ function appendBuffered(socket: net.Socket, chunk: Buffer): void {
48
+ const buf = handshakeBuffers.get(socket);
49
+ handshakeBuffers.set(socket, buf ? Buffer.concat([buf, chunk]) : Buffer.from(chunk));
50
+ }
51
+
52
+ function flushBuffered(socket: net.Socket): void {
53
+ const buf = handshakeBuffers.get(socket);
54
+ handshakeBuffers.delete(socket);
55
+ if (buf?.length) socket.unshift(buf);
56
+ }
57
+
58
+ /** 失败路径销毁 socket;保留一个空 error 监听,避免后续异步 error 变成未捕获异常 */
59
+ function safeDestroy(socket: net.Socket): void {
60
+ socket.removeAllListeners('error');
61
+ socket.on('error', () => {});
62
+ socket.destroy();
63
+ }
64
+
65
+ function envValue(lower: string, upper: string): string {
66
+ return process.env[lower] || process.env[upper] || '';
67
+ }
68
+
69
+ function parseProxyUrl(raw: string): ResolvedProxy | null {
70
+ try {
71
+ const url = new URL(raw.includes('://') ? raw : `http://${raw}`);
72
+ const scheme = url.protocol.replace(':', '').toLowerCase();
73
+ const type = scheme === 'socks5h' ? 'socks5' : scheme;
74
+ if (!['http', 'https', 'socks4', 'socks5'].includes(type)) return null;
75
+ const host = decodeURIComponent(url.hostname);
76
+ if (!host) return null;
77
+ return {
78
+ type: type as ResolvedProxy['type'],
79
+ host,
80
+ port: Number(url.port) || DEFAULT_PORTS[type as ResolvedProxy['type']],
81
+ username: decodeURIComponent(url.username) || undefined,
82
+ password: decodeURIComponent(url.password) || undefined,
83
+ };
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ interface SystemProxySetting {
90
+ proxy: ResolvedProxy;
91
+ bypass: string[];
92
+ }
93
+
94
+ const OS_PROXY_CACHE_MS = 3000;
95
+ let osProxyCache: { platform: string; at: number; value: SystemProxySetting | null } | null = null;
96
+
97
+ /** 系统命令只读、固定参数,失败时静默回退(例如 Linux 未装 gsettings) */
98
+ function runSystemCommand(file: string, args: string[]): string {
99
+ try {
100
+ return execFileSync(file, args, {
101
+ encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'],
102
+ }).trim();
103
+ } catch {
104
+ return '';
105
+ }
106
+ }
107
+
108
+ function proxyFromHostPort(host: string, port: string | number, type: ResolvedProxy['type']): ResolvedProxy | null {
109
+ if (!host) return null;
110
+ return { type, host, port: Number(port) || DEFAULT_PORTS[type] };
111
+ }
112
+
113
+ /** macOS:scutil --proxy */
114
+ function readMacOSProxy(): SystemProxySetting | null {
115
+ const out = runSystemCommand('scutil', ['--proxy']);
116
+ if (!out) return null;
117
+ const values: Record<string, string> = {};
118
+ const exceptions: string[] = [];
119
+ let inExceptions = false;
120
+ for (const line of out.split(/\r?\n/)) {
121
+ const text = line.trim();
122
+ if (/^ExceptionsList\s*:\s*<array>\s*\{/.test(text)) { inExceptions = true; continue; }
123
+ if (inExceptions) {
124
+ if (text === '}') { inExceptions = false; continue; }
125
+ const item = text.match(/^\d+\s*:\s*(.*)$/);
126
+ if (item) exceptions.push(item[1]);
127
+ continue;
128
+ }
129
+ const kv = text.match(/^([A-Za-z0-9]+)\s*:\s*(.*)$/);
130
+ if (kv) values[kv[1]] = kv[2];
131
+ }
132
+ const enabled = (key: string) => values[key] === '1' || values[key] === 'true';
133
+ let proxy: ResolvedProxy | null = null;
134
+ if (enabled('HTTPSEnable') && values.HTTPSProxy) {
135
+ // 系统设置里的「HTTPS 代理」指的是用于 HTTPS 流量的 HTTP 代理(CONNECT),
136
+ // 并非要求与代理本身建立 TLS,因此按 http 处理。
137
+ proxy = proxyFromHostPort(values.HTTPSProxy, values.HTTPSPort || '', 'http');
138
+ } else if (enabled('HTTPEnable') && values.HTTPProxy) {
139
+ proxy = proxyFromHostPort(values.HTTPProxy, values.HTTPPort || '', 'http');
140
+ } else if (enabled('SOCKSEnable') && values.SOCKSProxy) {
141
+ proxy = proxyFromHostPort(values.SOCKSProxy, values.SOCKSPort || '', 'socks5');
142
+ }
143
+ return proxy ? { proxy, bypass: exceptions } : null;
144
+ }
145
+
146
+ /** Windows:HKCU\...\Internet Settings(浏览器「使用系统代理」读取的同一处配置) */
147
+ function readWindowsProxy(): SystemProxySetting | null {
148
+ const out = runSystemCommand('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings']);
149
+ if (!out) return null;
150
+ const values: Record<string, string> = {};
151
+ for (const line of out.split(/\r?\n/)) {
152
+ const kv = line.trim().match(/^([A-Za-z]+)\s+REG_\w+\s+(.*)$/);
153
+ if (kv) values[kv[1]] = kv[2];
154
+ }
155
+ if (values.ProxyEnable !== '0x1' && values.ProxyEnable !== '1') return null;
156
+
157
+ let proxy: ResolvedProxy | null = null;
158
+ const server = values.ProxyServer || '';
159
+ if (/^\w+=/i.test(server)) {
160
+ const entries: Record<string, string> = {};
161
+ for (const part of server.split(';')) {
162
+ const kv = part.trim().match(/^(\w+)=(.*)$/i);
163
+ if (kv) entries[kv[1].toLowerCase()] = kv[2];
164
+ }
165
+ // 同上:ProxyServer 的 https= 是用于 HTTPS 流量的 HTTP 代理,不是 TLS 代理
166
+ const type: ResolvedProxy['type'] = entries.https || entries.http ? 'http' : 'socks5';
167
+ const address = entries.https || entries.http || entries.socks || entries.all;
168
+ if (address) {
169
+ const [host, port] = address.split(':');
170
+ proxy = proxyFromHostPort(host, port || '', type);
171
+ }
172
+ } else if (server) {
173
+ const [host, port] = server.split(':');
174
+ proxy = proxyFromHostPort(host, port || '', 'http');
175
+ }
176
+
177
+ const bypass = (values.ProxyOverride || '').split(';')
178
+ .filter(Boolean)
179
+ .map((entry) => entry === '<local>' ? 'localhost' : entry);
180
+ return proxy ? { proxy, bypass } : null;
181
+ }
182
+
183
+ /** Linux/GNOME:gsettings org.gnome.system.proxy */
184
+ function readLinuxProxy(): SystemProxySetting | null {
185
+ const unquote = (text: string) => (text.trim().match(/^'(.*)'$/s)?.[1] ?? text.trim());
186
+ if (unquote(runSystemCommand('gsettings', ['get', 'org.gnome.system.proxy', 'mode'])) !== 'manual') return null;
187
+
188
+ let proxy: ResolvedProxy | null = null;
189
+ const schemas: Array<[string, ResolvedProxy['type']]> = [['https', 'http'], ['http', 'http'], ['socks', 'socks5']];
190
+ for (const [schema, type] of schemas) {
191
+ const host = unquote(runSystemCommand('gsettings', ['get', `org.gnome.system.proxy.${schema}`, 'host']));
192
+ if (host) {
193
+ proxy = proxyFromHostPort(host, unquote(runSystemCommand('gsettings', ['get', `org.gnome.system.proxy.${schema}`, 'port'])), type);
194
+ break;
195
+ }
196
+ }
197
+ if (!proxy) return null;
198
+
199
+ const ignoreHosts = runSystemCommand('gsettings', ['get', 'org.gnome.system.proxy', 'ignore-hosts']);
200
+ const bypass = ignoreHosts.match(/'([^']*)'/g)?.map((entry) => entry.slice(1, -1)) || [];
201
+ return { proxy, bypass };
202
+ }
203
+
204
+ /** 带 3 秒缓存,避免每次连接都 fork 系统命令;平台变化立即失效 */
205
+ function readOsProxy(): SystemProxySetting | null {
206
+ const now = Date.now();
207
+ if (osProxyCache && osProxyCache.platform === process.platform && now - osProxyCache.at < OS_PROXY_CACHE_MS) {
208
+ return osProxyCache.value;
209
+ }
210
+ let value: SystemProxySetting | null = null;
211
+ try {
212
+ if (process.platform === 'darwin') value = readMacOSProxy();
213
+ else if (process.platform === 'win32') value = readWindowsProxy();
214
+ else if (process.platform === 'linux') value = readLinuxProxy();
215
+ } catch {
216
+ value = null;
217
+ }
218
+ osProxyCache = { platform: process.platform, at: now, value };
219
+ return value;
220
+ }
221
+
222
+ function ipv4ToInt(ip: string): number {
223
+ return ip.split('.').reduce((acc, part) => (acc * 256 + Number(part)) >>> 0, 0);
224
+ }
225
+
226
+ /** 单条绕过规则匹配:支持 host、*.domain、.domain、host:port、IPv4 CIDR、* */
227
+ function matchesBypassRule(hostname: string, port: number, entry: string): boolean {
228
+ if (entry === '*') return true;
229
+ let rule = entry.toLowerCase();
230
+ const colon = rule.lastIndexOf(':');
231
+ if (colon > -1 && /^\d+$/.test(rule.slice(colon + 1))) {
232
+ if (Number(rule.slice(colon + 1)) !== port) return false;
233
+ rule = rule.slice(0, colon);
234
+ }
235
+ const slash = rule.indexOf('/');
236
+ if (slash > -1 && net.isIP(hostname) === 4) {
237
+ const bits = Number(rule.slice(slash + 1));
238
+ const base = rule.slice(0, slash);
239
+ if (net.isIP(base) !== 4 || !Number.isInteger(bits) || bits < 0 || bits > 32) return false;
240
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
241
+ return (ipv4ToInt(hostname) & mask) === (ipv4ToInt(base) & mask);
242
+ }
243
+ rule = rule.replace(/^\*\./, '').replace(/^\./, '');
244
+ return hostname === rule || hostname.endsWith('.' + rule);
245
+ }
246
+
247
+ /** NO_PROXY 环境变量 + 系统代理绕过列表 */
248
+ function matchesNoProxy(host: string, port: number, extraBypass = ''): boolean {
249
+ const raw = [envValue('no_proxy', 'NO_PROXY'), extraBypass].filter(Boolean).join(',');
250
+ if (!raw) return false;
251
+ const hostname = host.toLowerCase().replace(/^\[/, '').replace(/\]$/, '');
252
+ return raw.split(/[,\s]+/).some((entry) => entry && matchesBypassRule(hostname, port, entry));
253
+ }
254
+
255
+ /** 解析某个目标连接实际使用的代理;null 表示直连 */
256
+ export function resolveProxy(connection: ConnectionEntity, targetHost: string, targetPort: number): ResolvedProxy | null {
257
+ const mode = connection.proxy?.mode || 'direct';
258
+ if (mode === 'direct') return null;
259
+
260
+ if (mode === 'system') {
261
+ // 环境变量优先(显式配置),未设置时回退到浏览器的「使用系统代理」来源
262
+ const raw = envValue('all_proxy', 'ALL_PROXY')
263
+ || envValue('https_proxy', 'HTTPS_PROXY')
264
+ || envValue('http_proxy', 'HTTP_PROXY');
265
+ const systemProxy = raw ? null : readOsProxy();
266
+ if (matchesNoProxy(targetHost, targetPort, systemProxy?.bypass.join(',') || '')) return null;
267
+ return raw ? parseProxyUrl(raw) : (systemProxy?.proxy || null);
268
+ }
269
+
270
+ const proxy = connection.proxy;
271
+ if (!proxy?.host?.trim()) return null;
272
+ const type = proxy.type || 'http';
273
+ return {
274
+ type,
275
+ host: proxy.host.trim(),
276
+ port: Number(proxy.port) || DEFAULT_PORTS[type],
277
+ username: proxy.username || undefined,
278
+ password: proxy.password || undefined,
279
+ };
280
+ }
281
+
282
+ /**
283
+ * socket 连接阶段(含代理握手)统一超时,成功后清除,避免干扰后续协议超时。
284
+ * TLSSocket 会先触发 TCP 'connect',必须等 'secureConnect' 才算连上 HTTPS 代理,
285
+ * 否则会在 TLS 握手完成前把 CONNECT 明文写出去。
286
+ */
287
+ function waitForConnect(
288
+ socket: net.Socket,
289
+ timeout: number,
290
+ label: string,
291
+ waitEvent: 'connect' | 'secureConnect' = 'connect',
292
+ ): Promise<net.Socket> {
293
+ return new Promise((resolve, reject) => {
294
+ const cleanup = () => {
295
+ socket.removeListener('error', onError);
296
+ socket.removeListener('timeout', onTimeout);
297
+ socket.removeListener(waitEvent, onConnect);
298
+ socket.setTimeout(0);
299
+ };
300
+ const onError = (err: Error) => { cleanup(); safeDestroy(socket); reject(new Error(`${label}: ${err.message}`)); };
301
+ const onTimeout = () => { cleanup(); safeDestroy(socket); reject(new Error(`${label} 超时 (${timeout}ms)`)); };
302
+ const onConnect = () => { cleanup(); resolve(socket); };
303
+ socket.once('error', onError);
304
+ socket.once('timeout', onTimeout);
305
+ socket.once(waitEvent, onConnect);
306
+ socket.setTimeout(timeout);
307
+ });
308
+ }
309
+
310
+ /** 从 socket 读取指定字节数;多读的字节留在 handshakeBuffers 中供下一步使用 */
311
+ function readExactly(socket: net.Socket, length: number, timeout: number): Promise<Buffer> {
312
+ const immediate = takeBuffered(socket, length);
313
+ if (immediate) return Promise.resolve(immediate);
314
+
315
+ return new Promise((resolve, reject) => {
316
+ let settled = false;
317
+ const cleanup = () => {
318
+ socket.removeListener('data', onData);
319
+ socket.removeListener('error', onError);
320
+ socket.removeListener('timeout', onTimeout);
321
+ socket.setTimeout(0);
322
+ };
323
+ const onError = (err: Error) => {
324
+ if (settled) return;
325
+ settled = true; cleanup(); safeDestroy(socket); reject(new Error(`代理读取失败: ${err.message}`));
326
+ };
327
+ const onTimeout = () => {
328
+ if (settled) return;
329
+ settled = true; cleanup(); safeDestroy(socket); reject(new Error(`代理响应超时 (${timeout}ms)`));
330
+ };
331
+ const onData = (chunk: Buffer) => {
332
+ if (settled) return;
333
+ appendBuffered(socket, chunk);
334
+ const data = takeBuffered(socket, length);
335
+ if (!data) return;
336
+ settled = true;
337
+ cleanup();
338
+ resolve(data);
339
+ };
340
+ socket.on('data', onData);
341
+ socket.once('error', onError);
342
+ socket.once('timeout', onTimeout);
343
+ socket.setTimeout(timeout);
344
+ });
345
+ }
346
+
347
+ /** HTTP/HTTPS 代理:CONNECT 隧道;隧道建立后返回原始 socket,由调用方叠加 TLS */
348
+ /** 在已连到代理的 socket 上发 CONNECT 并等待 2xx 响应 */
349
+ function sendConnect(socket: net.Socket, proxy: ResolvedProxy, host: string, port: number, timeout: number): Promise<void> {
350
+ const target = `${host}:${port}`;
351
+ let head = `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n`;
352
+ if (proxy.username) {
353
+ const auth = Buffer.from(`${proxy.username}:${proxy.password || ''}`).toString('base64');
354
+ head += `Proxy-Authorization: Basic ${auth}\r\n`;
355
+ }
356
+ head += 'Proxy-Connection: Keep-Alive\r\n\r\n';
357
+ socket.write(head);
358
+
359
+ return new Promise<void>((resolve, reject) => {
360
+ let text = '';
361
+ let settled = false;
362
+ const cleanup = () => {
363
+ socket.removeListener('data', onData);
364
+ socket.removeListener('error', onError);
365
+ socket.removeListener('timeout', onTimeout);
366
+ socket.setTimeout(0);
367
+ };
368
+ const onError = (err: Error) => {
369
+ if (settled) return;
370
+ settled = true; cleanup(); reject(new Error(`代理连接失败: ${err.message}`));
371
+ };
372
+ const onTimeout = () => {
373
+ if (settled) return;
374
+ settled = true; cleanup(); reject(new Error(`代理 CONNECT 超时 (${timeout}ms)`));
375
+ };
376
+ const onData = (chunk: Buffer) => {
377
+ if (settled) return;
378
+ appendBuffered(socket, chunk);
379
+ text += chunk.toString('latin1');
380
+ const end = text.indexOf('\r\n\r\n');
381
+ if (end === -1) {
382
+ if (text.length > 65536) {
383
+ settled = true; cleanup(); reject(new Error('代理 CONNECT 响应过大'));
384
+ }
385
+ return;
386
+ }
387
+ settled = true;
388
+ cleanup();
389
+ const response = text.slice(0, end + 4);
390
+ takeBuffered(socket, Buffer.byteLength(response, 'latin1'));
391
+ const match = response.match(/^HTTP\/\d(?:\.\d)?\s+(\d{3})/);
392
+ if (!match || Number(match[1]) < 200 || Number(match[1]) >= 300) {
393
+ reject(new Error(`代理拒绝 CONNECT: ${response.split('\r\n')[0]}`));
394
+ } else {
395
+ resolve();
396
+ }
397
+ };
398
+ socket.on('data', onData);
399
+ socket.once('error', onError);
400
+ socket.once('timeout', onTimeout);
401
+ socket.setTimeout(timeout);
402
+ });
403
+ }
404
+
405
+ /**
406
+ * HTTP(S) 代理:宽松策略 —— HTTPS 代理先尝试 TLS,握手失败(例如代理其实是
407
+ * 本地工具的 Mixed/HTTP 端口,或 https_proxy 里的 https:// 只是表示用于 HTTPS
408
+ * 流量)时自动降级为明文 CONNECT,不因协议标记不一致而直接断连。
409
+ */
410
+ async function connectHttpProxy(
411
+ proxy: ResolvedProxy, host: string, port: number, timeout: number, log: LogFn,
412
+ ): Promise<net.Socket> {
413
+ if (proxy.type === 'https') {
414
+ const tlsSocket = tls.connect({
415
+ host: proxy.host,
416
+ port: proxy.port,
417
+ servername: net.isIP(proxy.host) ? undefined : proxy.host,
418
+ rejectUnauthorized: true,
419
+ }) as unknown as net.Socket;
420
+ try {
421
+ // 探测超时收短:明文代理不会响应 TLS ClientHello,不能让用户等满 30 秒连接超时
422
+ await waitForConnect(
423
+ tlsSocket, Math.min(timeout, 3000),
424
+ `HTTPS 代理 ${proxy.host}:${proxy.port} TLS 握手`, 'secureConnect',
425
+ );
426
+ await sendConnect(tlsSocket, proxy, host, port, timeout);
427
+ return tlsSocket;
428
+ } catch (err: any) {
429
+ safeDestroy(tlsSocket);
430
+ log(`HTTPS 代理 ${proxy.host}:${proxy.port} TLS 握手失败,降级为明文 CONNECT: ${err.message}`);
431
+ }
432
+ }
433
+
434
+ const socket = net.createConnection({ host: proxy.host, port: proxy.port });
435
+ try {
436
+ await waitForConnect(socket, timeout, `代理 ${proxy.host}:${proxy.port}`);
437
+ await sendConnect(socket, proxy, host, port, timeout);
438
+ return socket;
439
+ } catch (err) {
440
+ safeDestroy(socket);
441
+ throw err;
442
+ }
443
+ }
444
+
445
+ function socks5Address(host: string): Buffer {
446
+ const ipv4 = net.isIP(host) === 4 ? host : '';
447
+ if (ipv4) return Buffer.concat([Buffer.from([1]), Buffer.from(ipv4.split('.').map(Number))]);
448
+ const domain = Buffer.from(host, 'utf8');
449
+ if (domain.length > 255) throw new Error('SOCKS5 代理目标域名过长');
450
+ return Buffer.concat([Buffer.from([3, domain.length]), domain]);
451
+ }
452
+
453
+ /** SOCKS5:握手(可选用户名密码)+ CONNECT 请求 */
454
+ async function connectSocks5Proxy(proxy: ResolvedProxy, host: string, port: number, timeout: number): Promise<net.Socket> {
455
+ const socket = net.createConnection({ host: proxy.host, port: proxy.port });
456
+ try {
457
+ await waitForConnect(socket, timeout, `SOCKS5 代理 ${proxy.host}:${proxy.port}`);
458
+
459
+ socket.write(proxy.username ? Buffer.from([5, 2, 2, 0]) : Buffer.from([5, 1, 0]));
460
+ const greeting = await readExactly(socket, 2, timeout);
461
+ if (greeting[0] !== 5) throw new Error(`代理不是 SOCKS5 协议 (VER=${greeting[0]})`);
462
+ if (greeting[1] === 2) {
463
+ if (!proxy.username) throw new Error('SOCKS5 代理要求用户名密码认证');
464
+ const user = Buffer.from(proxy.username, 'utf8');
465
+ const pass = Buffer.from(proxy.password || '', 'utf8');
466
+ socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([pass.length]), pass]));
467
+ const authReply = await readExactly(socket, 2, timeout);
468
+ if (authReply[1] !== 0) throw new Error(`SOCKS5 代理认证失败 (STATUS=${authReply[1]})`);
469
+ } else if (greeting[1] !== 0) {
470
+ throw new Error(`SOCKS5 代理不支持的认证方式 (METHOD=${greeting[1]})`);
471
+ }
472
+
473
+ const portBuf = Buffer.alloc(2);
474
+ portBuf.writeUInt16BE(port);
475
+ socket.write(Buffer.concat([Buffer.from([5, 1, 0]), socks5Address(host), portBuf]));
476
+
477
+ const replyHead = await readExactly(socket, 4, timeout);
478
+ if (replyHead[1] !== 0) throw new Error(`SOCKS5 代理拒绝连接 (REP=${replyHead[1]})`);
479
+ const atyp = replyHead[3];
480
+ let restLen = -1;
481
+ if (atyp === 1) restLen = 6;
482
+ else if (atyp === 4) restLen = 18;
483
+ else if (atyp === 3) restLen = (await readExactly(socket, 1, timeout))[0] + 2;
484
+ if (restLen < 0) throw new Error(`SOCKS5 代理返回未知地址类型 (ATYP=${atyp})`);
485
+ await readExactly(socket, restLen, timeout);
486
+ return socket;
487
+ } catch (err) {
488
+ safeDestroy(socket);
489
+ throw err;
490
+ }
491
+ }
492
+
493
+ /** SOCKS4/4a:域名通过 0.0.0.1 + 域名 发送(SOCKS4a 扩展) */
494
+ async function connectSocks4Proxy(proxy: ResolvedProxy, host: string, port: number, timeout: number): Promise<net.Socket> {
495
+ const socket = net.createConnection({ host: proxy.host, port: proxy.port });
496
+ try {
497
+ await waitForConnect(socket, timeout, `SOCKS4 代理 ${proxy.host}:${proxy.port}`);
498
+
499
+ const isIpv4 = net.isIP(host) === 4;
500
+ const ip = isIpv4 ? host : '0.0.0.1';
501
+ const userId = Buffer.from(proxy.username || '', 'utf8');
502
+ const address = Buffer.concat([
503
+ Buffer.from(ip.split('.').map(Number)),
504
+ userId,
505
+ Buffer.from([0]),
506
+ ...(!isIpv4 ? [Buffer.from(host, 'utf8'), Buffer.from([0])] : []),
507
+ ]);
508
+ const portBuf = Buffer.alloc(2);
509
+ portBuf.writeUInt16BE(port);
510
+ socket.write(Buffer.concat([Buffer.from([4, 1]), portBuf, address]));
511
+
512
+ const reply = await readExactly(socket, 8, timeout);
513
+ if (reply[0] !== 0 || reply[1] !== 0x5a) throw new Error(`SOCKS4 代理拒绝连接 (CD=${reply[1]})`);
514
+ return socket;
515
+ } catch (err) {
516
+ safeDestroy(socket);
517
+ throw err;
518
+ }
519
+ }
520
+
521
+ /**
522
+ * 按连接配置建立到目标的 TCP socket。
523
+ * 返回的 socket 已完成代理握手,调用方可直接交给 ssh2 / tls.connect。
524
+ */
525
+ export async function connectWithProxy(
526
+ connection: ConnectionEntity,
527
+ host: string,
528
+ port: number,
529
+ timeout = 30000,
530
+ log: LogFn = () => {},
531
+ ): Promise<net.Socket> {
532
+ const proxy = resolveProxy(connection, host, port);
533
+ if (!proxy) {
534
+ log(`直连 ${host}:${port}`);
535
+ const socket = net.createConnection({ host, port });
536
+ try {
537
+ return await waitForConnect(socket, timeout, `连接 ${host}:${port}`);
538
+ } catch (err) {
539
+ safeDestroy(socket);
540
+ throw err;
541
+ }
542
+ }
543
+
544
+ log(`通过 ${proxy.type.toUpperCase()} 代理 ${proxy.host}:${proxy.port} 连接 ${host}:${port}`);
545
+ let socket: net.Socket;
546
+ if (proxy.type === 'http' || proxy.type === 'https') {
547
+ socket = await connectHttpProxy(proxy, host, port, timeout, log);
548
+ } else if (proxy.type === 'socks5') {
549
+ socket = await connectSocks5Proxy(proxy, host, port, timeout);
550
+ } else {
551
+ socket = await connectSocks4Proxy(proxy, host, port, timeout);
552
+ }
553
+ // 握手阶段多读的字节交还给调用方(ssh2 / TLS)
554
+ flushBuffered(socket);
555
+ return socket;
556
+ }
@@ -23,7 +23,7 @@
23
23
  var __INITIAL_STATE__ = __get_templateJson('__INITIAL_STATE__');
24
24
  if(!__INITIAL_STATE__) __INITIAL_STATE__ = __get_templateJson('__DEFAULTINITIAL_STATE__');
25
25
  </script>
26
- <link rel="icon" href="/public/favicon.ico?v=mwvs9iuv" />
26
+ <link rel="icon" href="/public/favicon.ico?v=mww88qi9" />
27
27
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
28
28
  <title>AICmd - AI Terminal</title>
29
29
  <meta name="description" content="{{description}}">
@@ -32,14 +32,14 @@
32
32
  console.error(event);
33
33
  });
34
34
  </script>
35
- <script type="module" crossorigin src="/public/index.js?v=mwvs9iuv"></script>
36
- <link rel="modulepreload" crossorigin href="/public/vscode-clipboard.js?v=mwvs9iuv">
37
- <link rel="modulepreload" crossorigin href="/public/vue.js?v=mwvs9iuv">
38
- <link rel="modulepreload" crossorigin href="/public/bootstrap.js?v=mwvs9iuv">
39
- <link rel="modulepreload" crossorigin href="/public/selection-copy.js?v=mwvs9iuv">
40
- <link rel="stylesheet" crossorigin href="/public/bootstrap.css?v=mwvs9iuv">
41
- <link rel="stylesheet" crossorigin href="/public/selection-copy.css?v=mwvs9iuv">
42
- <link rel="stylesheet" crossorigin href="/public/index.css?v=mwvs9iuv">
35
+ <script type="module" crossorigin src="/public/index.js?v=mww88qi9"></script>
36
+ <link rel="modulepreload" crossorigin href="/public/vscode-clipboard.js?v=mww88qi9">
37
+ <link rel="modulepreload" crossorigin href="/public/vue.js?v=mww88qi9">
38
+ <link rel="modulepreload" crossorigin href="/public/bootstrap.js?v=mww88qi9">
39
+ <link rel="modulepreload" crossorigin href="/public/selection-copy.js?v=mww88qi9">
40
+ <link rel="stylesheet" crossorigin href="/public/bootstrap.css?v=mww88qi9">
41
+ <link rel="stylesheet" crossorigin href="/public/selection-copy.css?v=mww88qi9">
42
+ <link rel="stylesheet" crossorigin href="/public/index.css?v=mww88qi9">
43
43
  </head>
44
44
  <body>
45
45
  <div id="app" class="min-vh-100"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fefeding/aicmd",
3
- "version": "1.0.27",
3
+ "version": "1.0.30",
4
4
  "packageManager": "pnpm@10.15.0",
5
5
  "private": false,
6
6
  "type": "commonjs",