dsh-github-direct 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +79 -2
- package/cordis.patch.yml +18 -0
- package/docs/DETAIL.md +73 -0
- package/docs/DETAIL.zh.md +68 -0
- package/icon.svg +23 -0
- package/index.js +988 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +44 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dashuiyu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-github-direct
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**不用梯子,也能打开 GitHub。**
|
|
4
|
+
|
|
5
|
+
装进 DeepSeek Harness(DSH)后,本机会多一条 `127.0.0.1:7890` 的本地通道:
|
|
6
|
+
DoH 解析 GitHub 的真实地址、用真实 HTTPS 请求挑出能用的节点、把流量直接转发过去。
|
|
7
|
+
没有机场、没有订阅、没有要你填的服务器地址,也不用改 hosts。
|
|
8
|
+
|
|
9
|
+
## 为什么它能通
|
|
10
|
+
|
|
11
|
+
国内打开 GitHub 卡住,通常不是"墙"一堵了之,而是三件具体的事:
|
|
12
|
+
|
|
13
|
+
1. **DNS 被投毒**:运营商 DNS 甚至部分公共 DoH 会返回 `20.247.166.x` 这类假地址,TLS 握手立刻断。
|
|
14
|
+
2. **假 IP 假活**:有些被污染的地址能完成 TCP 和 TLS 握手,却永远不回 HTTP —— 浏览器就那样一直转圈。
|
|
15
|
+
3. **真 IP 会漂移**:GitHub 的边缘节点每隔一段时间换一批,昨天能用的 IP 今天可能就废了。
|
|
16
|
+
|
|
17
|
+
所以这个插件做三件事:**用 DoH 拿地址 → 用真实 GET 请求验证每个地址 → 选最快的那个连**。
|
|
18
|
+
这三步都在本机完成,全程不经过第三方代理服务器。
|
|
19
|
+
|
|
20
|
+
## 四个工具
|
|
21
|
+
|
|
22
|
+
| 工具 | 作用 |
|
|
23
|
+
| --- | --- |
|
|
24
|
+
| `github_direct_status` | 通道是否在跑、系统代理指向哪、最近探活选中的 IP 和耗时 |
|
|
25
|
+
| `github_direct_probe` | 重新探活,逐个 IP 打印真实 HTTPS 耗时(能看出是投毒还是假活) |
|
|
26
|
+
| `github_direct_proxy` | 系统代理 `on` / `off` / `guard` / `status`(`guard` 会自动还原"代理开着但通道已死") |
|
|
27
|
+
| `github_direct_run` | 自动带代理环境变量执行命令,例如 `git clone` / `git push` / `npm install` |
|
|
28
|
+
|
|
29
|
+
## 安装
|
|
30
|
+
|
|
31
|
+
在 DSH 里让它装这个包:
|
|
32
|
+
|
|
33
|
+
```
|
|
34
|
+
plugin_manager: install_bundle target=https://www.npmjs.com/package/dsh-github-direct
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
或者你已经把源码放在本机,直接把目录作为 `target` 传进去。装完通道会随插件自动启动。
|
|
38
|
+
|
|
39
|
+
## 用法
|
|
40
|
+
|
|
41
|
+
浏览器打不开 GitHub:
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
github_direct_proxy action=on
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
这一次之后浏览器走本地通道;不用了再 `action=off`。中途 DSH 重启、通道没起来,
|
|
48
|
+
下一次 `action=guard` 会检测到"代理开着但端口没人监听"并自动还原 —— 不会再出现整台电脑像断网的情况。
|
|
49
|
+
|
|
50
|
+
命令行 clone 卡住:
|
|
51
|
+
|
|
52
|
+
```
|
|
53
|
+
github_direct_run command="git clone --depth 1 https://github.com/octocat/Hello-World.git"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
只想确认现在通不通:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
github_direct_probe
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## 配置
|
|
63
|
+
|
|
64
|
+
改 `cordis.patch.yml` 里那三个值,或在插件设置页里改:
|
|
65
|
+
|
|
66
|
+
- `port`:本地端口,默认 `7890`
|
|
67
|
+
- `autoStart`:是否随插件启动通道,默认 `true`
|
|
68
|
+
- `systemProxy`:是否自动打开系统代理,默认 `false`
|
|
69
|
+
|
|
70
|
+
## 边界
|
|
71
|
+
|
|
72
|
+
- 它只优化 **GitHub 及其相关域名**,不是全局翻墙工具;其它网站该怎样还怎样。
|
|
73
|
+
- `raw.githubusercontent.com` 的 `185.199.x` 段在国内多数网络下是 IP 级封禁,
|
|
74
|
+
插件会走 `ghproxy.net` 之类的镜像读取 raw 文件(`github_direct_run` 里 `curl` raw 地址时同样适用)。
|
|
75
|
+
- 系统代理只改当前用户(HKCU),不动系统级设置,不需要管理员权限。
|
|
76
|
+
- 不收集任何数据,不驻留后台服务;插件卸载后通道随之关闭。
|
|
77
|
+
|
|
78
|
+
## 许可
|
|
79
|
+
|
|
80
|
+
MIT
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# dsh-github-direct · 插件清单
|
|
2
|
+
#
|
|
3
|
+
# 安装后本机就会有一条 127.0.0.1:7890 的直连通道(SOCKS5 + HTTP CONNECT 同端口),
|
|
4
|
+
# 不依赖任何梯子/机场/外部代理软件。
|
|
5
|
+
#
|
|
6
|
+
# config 里可调的三项:
|
|
7
|
+
# port 本地端口,默认 7890。被占用时改这里,工具会自动跟着换。
|
|
8
|
+
# autoStart 是否随插件启动通道,默认 true。改 false 则要手动触发一次工具才起。
|
|
9
|
+
# systemProxy 是否顺手把 Windows 系统代理指到通道上,默认 false。
|
|
10
|
+
# 开着的好处是浏览器不用任何插件;坏处是通道停了会像断网,
|
|
11
|
+
# 所以有 github_direct_proxy 的 guard 动作兜底(会自动还原)。
|
|
12
|
+
- insert:
|
|
13
|
+
- id: github-direct
|
|
14
|
+
name: dsh-github-direct
|
|
15
|
+
config:
|
|
16
|
+
port: 7890
|
|
17
|
+
autoStart: true
|
|
18
|
+
systemProxy: false
|
package/docs/DETAIL.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# GitHub direct — how it works
|
|
2
|
+
|
|
3
|
+
## The problem
|
|
4
|
+
|
|
5
|
+
GitHub is often unreachable from mainland China networks even when the rest of the internet is fine.
|
|
6
|
+
The failure is rarely a single blocked IP. Three separate things happen:
|
|
7
|
+
|
|
8
|
+
1. **Poisoned DNS.** Carrier DNS, and sometimes public DoH resolvers, answer `github.com`
|
|
9
|
+
with addresses such as `20.247.166.64` that drop the TLS handshake immediately.
|
|
10
|
+
2. **Fake-alive addresses.** Some polluted addresses complete the TCP and TLS handshake and then
|
|
11
|
+
never send an HTTP byte. The browser shows a spinner forever; nothing times out for minutes.
|
|
12
|
+
3. **IP churn.** GitHub's edge nodes rotate. An address that worked last week may be dead today,
|
|
13
|
+
so a hard-coded hosts entry fails without warning.
|
|
14
|
+
|
|
15
|
+
## The approach
|
|
16
|
+
|
|
17
|
+
The plugin runs a local tunnel on `127.0.0.1:7890` that speaks **both** SOCKS5 and HTTP CONNECT on
|
|
18
|
+
the same port, so any client works (`git`, `curl`, browsers, npm).
|
|
19
|
+
|
|
20
|
+
For a connection to a GitHub host the tunnel:
|
|
21
|
+
|
|
22
|
+
1. Resolves candidates: a seed list of known GitHub edge addresses plus live DoH answers
|
|
23
|
+
(`doh.pub`, `1.12.12.12`, `dns.alidns.com` in that order — the resolver that returns clean
|
|
24
|
+
answers first wins).
|
|
25
|
+
2. Probes candidates in parallel with a **complete HTTPS request** (`GET /` plus `Host:`), and only
|
|
26
|
+
accepts an address that returns a real status line that is not a 5xx. This is what rejects the
|
|
27
|
+
fake-alive addresses; a TLS handshake alone is not evidence.
|
|
28
|
+
3. Caches the fastest usable address for ten minutes and retries with a fresh probe after a failure.
|
|
29
|
+
4. Relays bytes both ways once the TCP connection is up.
|
|
30
|
+
|
|
31
|
+
Non-GitHub hosts bypass probing and use system DNS, so ordinary browsing keeps its normal latency.
|
|
32
|
+
|
|
33
|
+
## Tools
|
|
34
|
+
|
|
35
|
+
| Tool | Purpose |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `github_direct_status` | Tunnel state, system proxy state, last probe result per host, connection counters |
|
|
38
|
+
| `github_direct_probe` | Re-probe one host or the usual three, print every candidate IP with its HTTPS latency |
|
|
39
|
+
| `github_direct_proxy` | `on` / `off` / `guard` / `status` for the Windows per-user system proxy |
|
|
40
|
+
| `github_direct_run` | Run a command with `HTTP(S)_PROXY` and `ALL_PROXY` pointed at the tunnel |
|
|
41
|
+
|
|
42
|
+
`guard` exists because a stale system proxy pointing at a dead port makes the whole machine look
|
|
43
|
+
offline — including campus-network captive portals. `guard` detects "proxy enabled, nobody
|
|
44
|
+
listening" and restores the previous value.
|
|
45
|
+
|
|
46
|
+
## Configuration
|
|
47
|
+
|
|
48
|
+
```yaml
|
|
49
|
+
- insert:
|
|
50
|
+
- id: github-direct
|
|
51
|
+
name: dsh-github-direct
|
|
52
|
+
config:
|
|
53
|
+
port: 7890 # local port for the tunnel
|
|
54
|
+
autoStart: true # start the tunnel with the plugin
|
|
55
|
+
systemProxy: false # also point the Windows system proxy here on activation
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Security
|
|
59
|
+
|
|
60
|
+
- Everything happens on the loopback interface; no third-party proxy server is involved.
|
|
61
|
+
- No telemetry, no credential handling, no background daemon outside the plugin lifetime.
|
|
62
|
+
- The system proxy change is per-user (`HKCU`) and the previous value is backed up to
|
|
63
|
+
`~/.dsh/github-direct.sysproxy.json` the first time it is enabled.
|
|
64
|
+
|
|
65
|
+
## Troubleshooting
|
|
66
|
+
|
|
67
|
+
- **Browser still fails after `on`**: run `github_direct_probe`. Every candidate `不可用` means the
|
|
68
|
+
network blocks that whole range — try another network or report the addresses.
|
|
69
|
+
- **`git clone` hangs but the browser works**: use `github_direct_run`, which injects the proxy
|
|
70
|
+
variables; `git` does not read the Windows system proxy.
|
|
71
|
+
- **Someone else's proxy is already running on 7890**: change `port` in the config.
|
|
72
|
+
- **`raw.githubusercontent.com` returns 000**: that IP range is blocked outright; use the
|
|
73
|
+
`ghproxy.net` mirror prefix.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# GitHub 直连(不用梯子)—— 原理与用法
|
|
2
|
+
|
|
3
|
+
## 问题出在哪
|
|
4
|
+
|
|
5
|
+
国内打不开 GitHub,往往不是"整个网被切断",而是三件具体的事叠在一起:
|
|
6
|
+
|
|
7
|
+
1. **DNS 被投毒**:运营商 DNS,甚至部分公共 DoH,会把 `github.com` 解析成 `20.247.166.64`
|
|
8
|
+
这类假地址,TLS 握手当场断掉。
|
|
9
|
+
2. **假活地址**:有些污染地址能把 TCP 和 TLS 握手都走完,却永远不返回一个字节的 HTTP。
|
|
10
|
+
浏览器就一直转圈,几分钟都不超时。
|
|
11
|
+
3. **真 IP 会漂移**:GitHub 的边缘节点隔段时间换一批,上周写进 hosts 的地址这周可能已经死了,
|
|
12
|
+
而且不会报错,只是慢、卡、超时。
|
|
13
|
+
|
|
14
|
+
## 插件怎么解决
|
|
15
|
+
|
|
16
|
+
插件在 `127.0.0.1:7890` 起一条本地通道,**同一个端口同时说 SOCKS5 和 HTTP CONNECT**,
|
|
17
|
+
所以 `git`、`curl`、浏览器、npm 都能直接用。
|
|
18
|
+
|
|
19
|
+
一旦目标是 GitHub 域名,通道会:
|
|
20
|
+
|
|
21
|
+
1. 汇总候选地址:一份已知可用的 GitHub 边缘 IP 种子表,加上实时 DoH 答案
|
|
22
|
+
(`doh.pub` → `1.12.12.12` → `dns.alidns.com`,谁先给出干净答案用谁)。
|
|
23
|
+
2. **并发探活,但判据是完整的 HTTPS 请求**(发 `GET /` 带 `Host:` 头),只有拿到真实状态行、
|
|
24
|
+
且不是 5xx 的地址才算可用。这一步专门用来踢掉"握手成功但不回数据"的假活 IP ——
|
|
25
|
+
只看 TLS 握手是会被骗的。
|
|
26
|
+
3. 把最快的地址缓存十分钟;连接失败时清缓存、强制重探,再换一个地址重试。
|
|
27
|
+
4. TCP 通了以后双向转发字节流。
|
|
28
|
+
|
|
29
|
+
非 GitHub 域名不做探活,直接走系统 DNS,所以日常上网不会被拖慢。
|
|
30
|
+
|
|
31
|
+
## 四个工具
|
|
32
|
+
|
|
33
|
+
| 工具 | 作用 |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `github_direct_status` | 通道状态、系统代理指向、每个域名最近选中的 IP 和耗时、转发计数 |
|
|
36
|
+
| `github_direct_probe` | 重新探活,逐个 IP 打印真实 HTTPS 耗时(能区分"投毒"和"假活") |
|
|
37
|
+
| `github_direct_proxy` | Windows 用户级系统代理 `on` / `off` / `guard` / `status` |
|
|
38
|
+
| `github_direct_run` | 自动带 `HTTP(S)_PROXY`、`ALL_PROXY` 执行命令(clone / push / 安装依赖) |
|
|
39
|
+
|
|
40
|
+
`guard` 是防呆:系统代理开着、通道却已经死了的时候,整台电脑会像断网(连校园网认证页都打不开)。
|
|
41
|
+
`guard` 会检测"代理开着但端口没人监听",自动把代理还原成开之前的值。
|
|
42
|
+
|
|
43
|
+
## 配置
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
- insert:
|
|
47
|
+
- id: github-direct
|
|
48
|
+
name: dsh-github-direct
|
|
49
|
+
config:
|
|
50
|
+
port: 7890 # 本地端口
|
|
51
|
+
autoStart: true # 随插件启动通道
|
|
52
|
+
systemProxy: false # 启动时顺手打开 Windows 系统代理
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 安全
|
|
56
|
+
|
|
57
|
+
- 所有连接都发生在本机回环地址上,不经过任何第三方代理服务器。
|
|
58
|
+
- 没有埋点、不碰凭据、不在插件生命周期之外留后台进程。
|
|
59
|
+
- 系统代理只改当前用户(`HKCU`),第一次开启时会把原值备份到 `~/.dsh/github-direct.sysproxy.json`。
|
|
60
|
+
|
|
61
|
+
## 排查
|
|
62
|
+
|
|
63
|
+
- **`on` 之后浏览器还是打不开**:跑 `github_direct_probe`。如果每个候选都不可用,说明当前网络
|
|
64
|
+
封了整段地址,换网络试。
|
|
65
|
+
- **浏览器能开、`git clone` 却卡住**:用 `github_direct_run`,它会注入代理环境变量;
|
|
66
|
+
`git` 不读 Windows 系统代理。
|
|
67
|
+
- **提示 7890 被占用**:改配置里的 `port`。
|
|
68
|
+
- **`raw.githubusercontent.com` 返回 000**:那段 IP 是直接封的,用 `ghproxy.net` 镜像前缀取文件。
|
package/icon.svg
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="GitHub direct">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#161b22"/>
|
|
5
|
+
<stop offset="1" stop-color="#0b0f14"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
<linearGradient id="line" x1="0" y1="0" x2="1" y2="0">
|
|
8
|
+
<stop offset="0" stop-color="#3fb950"/>
|
|
9
|
+
<stop offset="1" stop-color="#58a6ff"/>
|
|
10
|
+
</linearGradient>
|
|
11
|
+
</defs>
|
|
12
|
+
<rect x="1" y="1" width="62" height="62" rx="15" fill="url(#bg)" stroke="#30363d" stroke-width="1.5"/>
|
|
13
|
+
<!-- 直连链路 -->
|
|
14
|
+
<path d="M15 41 L49 23" stroke="url(#line)" stroke-width="3.2" stroke-linecap="round"/>
|
|
15
|
+
<!-- 近端:本机 -->
|
|
16
|
+
<circle cx="15" cy="41" r="6" fill="#0d1117" stroke="#3fb950" stroke-width="2.6"/>
|
|
17
|
+
<circle cx="15" cy="41" r="1.9" fill="#3fb950"/>
|
|
18
|
+
<!-- 远端:GitHub -->
|
|
19
|
+
<circle cx="49" cy="23" r="7.5" fill="#0d1117" stroke="#58a6ff" stroke-width="2.6"/>
|
|
20
|
+
<path d="M49 18.2a4.8 4.8 0 0 0-1.5 9.36c.24.04.33-.1.33-.23v-1.3c-1.34.29-1.62-.6-1.62-.6-.22-.56-.53-.71-.53-.71-.44-.3.03-.29.03-.29.48.03.73.5.73.5.43.74 1.13.53 1.4.4.04-.31.17-.53.3-.65-1.07-.12-2.2-.54-2.2-2.4 0-.53.19-.96.5-1.3-.05-.12-.22-.62.05-1.29 0 0 .4-.13 1.32.5a4.6 4.6 0 0 1 2.4 0c.92-.63 1.32-.5 1.32-.5.27.67.1 1.17.05 1.29.31.34.5.77.5 1.3 0 1.87-1.13 2.28-2.21 2.4.18.15.33.44.33.9v1.33c0 .13.09.28.34.23A4.8 4.8 0 0 0 49 18.2Z" fill="#c9d1d9"/>
|
|
21
|
+
<!-- 闪电:不用绕路 -->
|
|
22
|
+
<path d="M33.5 15.5 L28 26 h4.6 L31 34.5 L37.5 23.6 h-4.7 Z" fill="#f0b429"/>
|
|
23
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub 直连(不用梯子)—— DSH 宿主插件。
|
|
3
|
+
*
|
|
4
|
+
* 在本机 127.0.0.1:7890 起一个同端口双协议代理(SOCKS5 + HTTP CONNECT),
|
|
5
|
+
* 自己用 DoH 解析 GitHub 的真实 IP、用真实 HTTPS 请求探活排序,
|
|
6
|
+
* 再把流量转发过去。整个链路不依赖任何外部代理软件、不需要机场、不需要改 hosts。
|
|
7
|
+
*
|
|
8
|
+
* 四个模型工具:
|
|
9
|
+
* github_direct_status 通道状态 / 系统代理状态 / 最近的探活结果
|
|
10
|
+
* github_direct_probe 重新探活 GitHub 各域名,列出每个 IP 的耗时
|
|
11
|
+
* github_direct_proxy 系统代理开关(on / off / guard / status)
|
|
12
|
+
* github_direct_run 套上代理环境变量执行一条命令(git clone 等)
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-github-direct
|
|
15
|
+
*/
|
|
16
|
+
import net from 'node:net'
|
|
17
|
+
import tls from 'node:tls'
|
|
18
|
+
import https from 'node:https'
|
|
19
|
+
import dns from 'node:dns'
|
|
20
|
+
import os from 'node:os'
|
|
21
|
+
import { execFile, spawn } from 'node:child_process'
|
|
22
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
23
|
+
import { dirname, join } from 'node:path'
|
|
24
|
+
|
|
25
|
+
/** 只依赖 tools 服务:工具随插件卸载自动摘除。 */
|
|
26
|
+
export const inject = ['tools']
|
|
27
|
+
|
|
28
|
+
const DEFAULT_PORT = 7890
|
|
29
|
+
const DEFAULT_HOST = '127.0.0.1'
|
|
30
|
+
const PROBE_TIMEOUT_MS = 6000
|
|
31
|
+
const QUALITY_TTL_MS = 600_000
|
|
32
|
+
const FAIL_TTL_MS = 60_000
|
|
33
|
+
|
|
34
|
+
// ------------------------------------------------------------------ 候选 IP
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* GitHub 各域名的已知可用 IP。DoH 被投毒时(返回 20.247.166.x 这类假地址)
|
|
38
|
+
* 这里就是兜底:这些是 AS36459 / AS8075 的真实边缘节点,会随时间漂移,
|
|
39
|
+
* 所以每个域名给多个,再靠下面的探活挑最快的。
|
|
40
|
+
*/
|
|
41
|
+
const SEED_IPS = {
|
|
42
|
+
'github.com': ['20.205.243.166', '20.27.177.113', '20.200.245.247', '20.26.156.215', '140.82.114.4', '140.82.112.4'],
|
|
43
|
+
'api.github.com': ['20.205.243.168', '140.82.114.6', '20.27.177.116'],
|
|
44
|
+
'codeload.github.com': ['140.82.114.9', '20.205.243.165', '20.27.177.113'],
|
|
45
|
+
'gist.github.com': ['20.205.243.166', '140.82.114.4'],
|
|
46
|
+
'raw.githubusercontent.com': ['185.199.108.133', '185.199.109.133', '185.199.110.133', '185.199.111.133'],
|
|
47
|
+
'objects.githubusercontent.com': ['185.199.108.133', '185.199.109.133'],
|
|
48
|
+
'github.githubassets.com': ['185.199.108.154', '185.199.109.154'],
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** DoH 端点:腾讯优先(实测最干净),阿里垫底(曾被投毒)。 */
|
|
52
|
+
const DOH_ENDPOINTS = [
|
|
53
|
+
{ url: 'https://doh.pub/dns-query', servername: 'doh.pub' },
|
|
54
|
+
{ url: 'https://1.12.12.12/dns-query', servername: 'doh.pub' },
|
|
55
|
+
{ url: 'https://223.5.5.5/dns-query', servername: 'dns.alidns.com' },
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
const GITHUB_HOST_RE = /(^|\.)(github\.com|githubusercontent\.com|githubassets\.com|github\.io)$/i
|
|
59
|
+
|
|
60
|
+
// ------------------------------------------------------------------ 小工具
|
|
61
|
+
|
|
62
|
+
function num(value, fallback) {
|
|
63
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : fallback
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function str(value) {
|
|
67
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function sleep(ms) {
|
|
71
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function argsOf(value) {
|
|
75
|
+
return value !== null && typeof value === 'object' ? value : {}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function stamp() {
|
|
79
|
+
const d = new Date()
|
|
80
|
+
const p = (v) => String(v).padStart(2, '0')
|
|
81
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 工具返回值必须是可无损序列化的 JSON:把 undefined 字段剔掉(宿主不接受带 undefined 的对象)。 */
|
|
85
|
+
function jsonSafe(value) {
|
|
86
|
+
if (Array.isArray(value)) return value.map(jsonSafe)
|
|
87
|
+
if (value !== null && typeof value === 'object') {
|
|
88
|
+
const out = {}
|
|
89
|
+
for (const [key, item] of Object.entries(value)) {
|
|
90
|
+
if (item !== undefined) out[key] = jsonSafe(item)
|
|
91
|
+
}
|
|
92
|
+
return out
|
|
93
|
+
}
|
|
94
|
+
return value
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// ------------------------------------------------------------------ DoH
|
|
98
|
+
|
|
99
|
+
/** 一次 DoH JSON 查询,返回 A 记录列表(失败返回空数组,不抛)。 */
|
|
100
|
+
function dohQuery(endpoint, host) {
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
const target = new URL(endpoint.url)
|
|
103
|
+
const query = `${target.pathname}?name=${encodeURIComponent(host)}&type=A`
|
|
104
|
+
const request = https.request(
|
|
105
|
+
{
|
|
106
|
+
host: target.hostname,
|
|
107
|
+
port: 443,
|
|
108
|
+
path: query,
|
|
109
|
+
method: 'GET',
|
|
110
|
+
servername: endpoint.servername,
|
|
111
|
+
headers: { host: endpoint.servername, accept: 'application/dns-json' },
|
|
112
|
+
timeout: 5000,
|
|
113
|
+
rejectUnauthorized: true,
|
|
114
|
+
},
|
|
115
|
+
(response) => {
|
|
116
|
+
let body = ''
|
|
117
|
+
response.setEncoding('utf8')
|
|
118
|
+
response.on('data', (chunk) => {
|
|
119
|
+
if (body.length < 65536) body += chunk
|
|
120
|
+
})
|
|
121
|
+
response.on('end', () => {
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(body)
|
|
124
|
+
const answers = Array.isArray(parsed.Answer) ? parsed.Answer : []
|
|
125
|
+
resolve(
|
|
126
|
+
answers
|
|
127
|
+
.filter((a) => a && (a.type === 1 || a.type === 28) && typeof a.data === 'string' && net.isIP(a.data))
|
|
128
|
+
.map((a) => a.data),
|
|
129
|
+
)
|
|
130
|
+
} catch {
|
|
131
|
+
resolve([])
|
|
132
|
+
}
|
|
133
|
+
})
|
|
134
|
+
},
|
|
135
|
+
)
|
|
136
|
+
request.on('timeout', () => request.destroy(new Error('DoH 超时')))
|
|
137
|
+
request.on('error', () => resolve([]))
|
|
138
|
+
request.end()
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 多端点累积查询:拿到网段内地址就提前收工,全失败返回空。 */
|
|
143
|
+
async function dohResolve(host) {
|
|
144
|
+
const found = []
|
|
145
|
+
for (const endpoint of DOH_ENDPOINTS) {
|
|
146
|
+
const ips = await dohQuery(endpoint, host)
|
|
147
|
+
for (const ip of ips) if (!found.includes(ip)) found.push(ip)
|
|
148
|
+
if (found.length > 0) break
|
|
149
|
+
}
|
|
150
|
+
return found
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 系统 DNS 兜底。 */
|
|
154
|
+
function systemResolve(host, timeoutMs = 3000) {
|
|
155
|
+
return new Promise((resolve) => {
|
|
156
|
+
const timer = setTimeout(() => resolve([]), timeoutMs)
|
|
157
|
+
dns.lookup(host, { all: true, family: 4 }, (error, addresses) => {
|
|
158
|
+
clearTimeout(timer)
|
|
159
|
+
if (error || !Array.isArray(addresses)) resolve([])
|
|
160
|
+
else resolve(addresses.map((a) => a.address))
|
|
161
|
+
})
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ------------------------------------------------------------------ 探活
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 用真实的 HTTPS 请求判断一个 IP 能不能用。
|
|
169
|
+
*
|
|
170
|
+
* 只看 TCP/TLS 握手是不够的:被投毒的 140.82.114.3 能完成握手却永远不回数据,
|
|
171
|
+
* 表现就是浏览器一直转圈。所以必须发一个完整请求并拿到 HTTP 状态行。
|
|
172
|
+
*/
|
|
173
|
+
function httpProbe(host, ip, port = 443, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
174
|
+
return new Promise((resolve) => {
|
|
175
|
+
const started = Date.now()
|
|
176
|
+
let settled = false
|
|
177
|
+
let buffer = ''
|
|
178
|
+
const finish = (result) => {
|
|
179
|
+
if (settled) return
|
|
180
|
+
settled = true
|
|
181
|
+
try {
|
|
182
|
+
socket.destroy()
|
|
183
|
+
} catch {
|
|
184
|
+
/* ignore */
|
|
185
|
+
}
|
|
186
|
+
resolve(result)
|
|
187
|
+
}
|
|
188
|
+
const socket = tls.connect({ host: ip, port, servername: host, rejectUnauthorized: false })
|
|
189
|
+
socket.setTimeout(timeoutMs)
|
|
190
|
+
socket.on('secureConnect', () => {
|
|
191
|
+
socket.write(
|
|
192
|
+
`GET / HTTP/1.1\r\nHost: ${host}\r\nUser-Agent: dsh-github-direct\r\nAccept: */*\r\nConnection: close\r\n\r\n`,
|
|
193
|
+
)
|
|
194
|
+
})
|
|
195
|
+
socket.on('data', (chunk) => {
|
|
196
|
+
buffer += chunk.toString('latin1')
|
|
197
|
+
const match = /^HTTP\/1\.[01] (\d{3})/.exec(buffer)
|
|
198
|
+
if (match) {
|
|
199
|
+
const status = Number(match[1])
|
|
200
|
+
finish({ ip, ok: status < 500, ms: Date.now() - started, status })
|
|
201
|
+
}
|
|
202
|
+
if (buffer.length > 8192) finish({ ip, ok: false, ms: Date.now() - started, error: '响应异常' })
|
|
203
|
+
})
|
|
204
|
+
socket.on('timeout', () => finish({ ip, ok: false, ms: Date.now() - started, error: '超时' }))
|
|
205
|
+
socket.on('error', (error) => finish({ ip, ok: false, ms: Date.now() - started, error: error.message }))
|
|
206
|
+
socket.on('close', () => finish({ ip, ok: false, ms: Date.now() - started, error: '连接被关闭' }))
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 并发探活一组候选 IP,按耗时升序返回。 */
|
|
211
|
+
async function raceProbe(host, candidates, port = 443) {
|
|
212
|
+
const results = await Promise.all(candidates.map((ip) => httpProbe(host, ip, port)))
|
|
213
|
+
const usable = results.filter((r) => r.ok === true).sort((a, b) => a.ms - b.ms)
|
|
214
|
+
return { usable, all: results }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 宿主进程的 PATH 常常没有 git / curl 这些命令行工具(Electron 从桌面启动时尤其如此),
|
|
219
|
+
* 这里补几个常见安装位置,再用 DSH 自带的 winuxcmd 兜底。
|
|
220
|
+
*/
|
|
221
|
+
function binSearchDirs() {
|
|
222
|
+
const home = os.homedir()
|
|
223
|
+
const dirs = [
|
|
224
|
+
'C:\\Program Files\\Git\\cmd',
|
|
225
|
+
'C:\\Program Files (x86)\\Git\\cmd',
|
|
226
|
+
join(home, 'AppData', 'Local', 'Programs', 'Git', 'cmd'),
|
|
227
|
+
]
|
|
228
|
+
try {
|
|
229
|
+
const shells = join(home, '.dsh', 'dsh-ops', 'shells')
|
|
230
|
+
// shells/<family>/<hash>/winuxcmd/usr/bin —— 两级目录,都扫一遍
|
|
231
|
+
const pushShell = (root) => {
|
|
232
|
+
const usrBin = join(root, 'winuxcmd', 'usr', 'bin')
|
|
233
|
+
if (existsSync(join(usrBin, 'git.exe'))) dirs.push(usrBin)
|
|
234
|
+
const bin = join(root, 'winuxcmd', 'bin')
|
|
235
|
+
if (existsSync(bin)) dirs.push(bin)
|
|
236
|
+
}
|
|
237
|
+
for (const family of readdirSync(shells)) {
|
|
238
|
+
const familyDir = join(shells, family)
|
|
239
|
+
pushShell(familyDir)
|
|
240
|
+
try {
|
|
241
|
+
for (const variant of readdirSync(familyDir)) pushShell(join(familyDir, variant))
|
|
242
|
+
} catch {
|
|
243
|
+
/* 不是目录就跳过 */
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
} catch {
|
|
247
|
+
/* 没有就给原始 PATH */
|
|
248
|
+
}
|
|
249
|
+
return dirs.filter((dir) => existsSync(dir))
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ------------------------------------------------------------------ 共享状态
|
|
253
|
+
|
|
254
|
+
const state = {
|
|
255
|
+
listening: false,
|
|
256
|
+
startedAt: 0,
|
|
257
|
+
lastError: undefined,
|
|
258
|
+
quality: new Map(), // host -> {at, entries: [{ip, ms, ok}]}
|
|
259
|
+
lastProbe: new Map(), // host -> {at, chosen, entries}
|
|
260
|
+
counters: { accepted: 0, relayed: 0, failed: 0 },
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function cacheGet(host) {
|
|
264
|
+
const hit = state.quality.get(host)
|
|
265
|
+
if (hit === undefined) return undefined
|
|
266
|
+
const ttl = hit.entries.some((e) => e.ok) ? QUALITY_TTL_MS : FAIL_TTL_MS
|
|
267
|
+
if (Date.now() - hit.at > ttl) {
|
|
268
|
+
state.quality.delete(host)
|
|
269
|
+
return undefined
|
|
270
|
+
}
|
|
271
|
+
return hit
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** 选一个当前最快的可用 IP;缓存过期就重新探活。 */
|
|
275
|
+
async function bestIp(host, force = false) {
|
|
276
|
+
if (!force) {
|
|
277
|
+
const hit = cacheGet(host)
|
|
278
|
+
const fast = hit?.entries.find((e) => e.ok)
|
|
279
|
+
if (fast !== undefined) return fast.ip
|
|
280
|
+
}
|
|
281
|
+
const seeds = SEED_IPS[host] ?? []
|
|
282
|
+
const fromDoh = await dohResolve(host)
|
|
283
|
+
const candidates = [...new Set([...seeds, ...fromDoh])]
|
|
284
|
+
if (candidates.length === 0) {
|
|
285
|
+
const fallback = await systemResolve(host)
|
|
286
|
+
candidates.push(...fallback)
|
|
287
|
+
}
|
|
288
|
+
if (candidates.length === 0) throw new Error(`解析不到 ${host} 的任何 IP(DoH 与系统 DNS 都失败)`)
|
|
289
|
+
const { usable, all } = await raceProbe(host, candidates)
|
|
290
|
+
state.quality.set(host, { at: Date.now(), entries: all })
|
|
291
|
+
state.lastProbe.set(host, { at: Date.now(), chosen: usable[0]?.ip, entries: all })
|
|
292
|
+
if (usable.length === 0) throw new Error(`候选 IP 全部不可用:${candidates.join(', ')}`)
|
|
293
|
+
return usable[0].ip
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ------------------------------------------------------------------ 连接
|
|
297
|
+
|
|
298
|
+
/** 建立到目标的 TCP 连接;GitHub 域名先探活挑 IP,失败则清缓存换一个再试。 */
|
|
299
|
+
async function connectTarget(host, port, attempts = 3) {
|
|
300
|
+
if (net.isIP(host)) return dial(host, port)
|
|
301
|
+
const isGithub = GITHUB_HOST_RE.test(host)
|
|
302
|
+
let lastError
|
|
303
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
304
|
+
try {
|
|
305
|
+
const ip = isGithub ? await bestIp(host, attempt > 0) : (await systemResolve(host))[0] ?? host
|
|
306
|
+
return await dial(ip, port)
|
|
307
|
+
} catch (error) {
|
|
308
|
+
lastError = error
|
|
309
|
+
if (attempt < attempts - 1) await sleep(200 * (attempt + 1))
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
throw lastError ?? new Error(`连接 ${host}:${port} 失败`)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function dial(host, port, timeoutMs = 10_000) {
|
|
316
|
+
return new Promise((resolve, reject) => {
|
|
317
|
+
const socket = net.connect({ host, port })
|
|
318
|
+
const timer = setTimeout(() => {
|
|
319
|
+
socket.destroy()
|
|
320
|
+
reject(new Error(`连接 ${host}:${port} 超时`))
|
|
321
|
+
}, timeoutMs)
|
|
322
|
+
socket.once('connect', () => {
|
|
323
|
+
clearTimeout(timer)
|
|
324
|
+
socket.setNoDelay(true)
|
|
325
|
+
resolve(socket)
|
|
326
|
+
})
|
|
327
|
+
socket.once('error', (error) => {
|
|
328
|
+
clearTimeout(timer)
|
|
329
|
+
reject(error)
|
|
330
|
+
})
|
|
331
|
+
})
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** 双向转发,任何一端断开就收掉另一端。 */
|
|
335
|
+
function relay(client, upstream, preamble) {
|
|
336
|
+
state.counters.relayed += 1
|
|
337
|
+
const kill = () => {
|
|
338
|
+
client.destroy()
|
|
339
|
+
upstream.destroy()
|
|
340
|
+
}
|
|
341
|
+
client.on('error', kill)
|
|
342
|
+
upstream.on('error', kill)
|
|
343
|
+
client.on('close', kill)
|
|
344
|
+
upstream.on('close', kill)
|
|
345
|
+
if (preamble !== undefined && preamble.length > 0) upstream.write(preamble)
|
|
346
|
+
client.pipe(upstream)
|
|
347
|
+
upstream.pipe(client)
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ------------------------------------------------------------------ 请求读取
|
|
351
|
+
|
|
352
|
+
/** 把 socket 的字节流包成「读够 n 字节 / 读一行」的接口。 */
|
|
353
|
+
class Reader {
|
|
354
|
+
constructor(socket) {
|
|
355
|
+
this.socket = socket
|
|
356
|
+
this.buffer = Buffer.alloc(0)
|
|
357
|
+
this.error = undefined
|
|
358
|
+
this.waiters = []
|
|
359
|
+
socket.on('data', (chunk) => {
|
|
360
|
+
this.buffer = Buffer.concat([this.buffer, chunk])
|
|
361
|
+
this.wake()
|
|
362
|
+
})
|
|
363
|
+
socket.on('end', () => {
|
|
364
|
+
this.error = this.error ?? new Error('连接已关闭')
|
|
365
|
+
this.wake()
|
|
366
|
+
})
|
|
367
|
+
socket.on('error', (error) => {
|
|
368
|
+
this.error = error
|
|
369
|
+
this.wake()
|
|
370
|
+
})
|
|
371
|
+
socket.on('close', () => {
|
|
372
|
+
this.error = this.error ?? new Error('连接已关闭')
|
|
373
|
+
this.wake()
|
|
374
|
+
})
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
wake() {
|
|
378
|
+
const waiters = this.waiters
|
|
379
|
+
this.waiters = []
|
|
380
|
+
for (const resolve of waiters) resolve()
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
wait() {
|
|
384
|
+
if (this.error !== undefined) return Promise.reject(this.error)
|
|
385
|
+
return new Promise((resolve) => this.waiters.push(resolve))
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async take(n) {
|
|
389
|
+
while (this.buffer.length < n) await this.wait()
|
|
390
|
+
const out = this.buffer.subarray(0, n)
|
|
391
|
+
this.buffer = this.buffer.subarray(n)
|
|
392
|
+
return out
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async line(max = 16_384) {
|
|
396
|
+
for (;;) {
|
|
397
|
+
const index = this.buffer.indexOf('\r\n')
|
|
398
|
+
if (index >= 0) {
|
|
399
|
+
const out = this.buffer.subarray(0, index).toString('latin1')
|
|
400
|
+
this.buffer = this.buffer.subarray(index + 2)
|
|
401
|
+
return out
|
|
402
|
+
}
|
|
403
|
+
if (this.buffer.length > max) throw new Error('请求头过长')
|
|
404
|
+
await this.wait()
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
rest() {
|
|
409
|
+
const out = this.buffer
|
|
410
|
+
this.buffer = Buffer.alloc(0)
|
|
411
|
+
return out
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ------------------------------------------------------------------ 协议处理
|
|
416
|
+
|
|
417
|
+
async function handleClient(socket) {
|
|
418
|
+
state.counters.accepted += 1
|
|
419
|
+
socket.setNoDelay(true)
|
|
420
|
+
const reader = new Reader(socket)
|
|
421
|
+
try {
|
|
422
|
+
const head = await reader.take(1)
|
|
423
|
+
if (head[0] === 0x05) await handleSocks5(socket, reader)
|
|
424
|
+
else await handleHttp(socket, reader, head)
|
|
425
|
+
} catch (error) {
|
|
426
|
+
state.counters.failed += 1
|
|
427
|
+
state.lastError = error instanceof Error ? error.message : String(error)
|
|
428
|
+
try {
|
|
429
|
+
socket.destroy()
|
|
430
|
+
} catch {
|
|
431
|
+
/* ignore */
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function handleSocks5(socket, reader) {
|
|
437
|
+
// 版本字节已在 handleClient 里 peek 掉,这里只读方法数量与方法列表
|
|
438
|
+
const methodCount = (await reader.take(1))[0]
|
|
439
|
+
if (methodCount > 0) await reader.take(methodCount)
|
|
440
|
+
socket.write(Buffer.from([0x05, 0x00]))
|
|
441
|
+
|
|
442
|
+
const request = await reader.take(4)
|
|
443
|
+
if (request[0] !== 0x05) throw new Error('SOCKS 版本不对')
|
|
444
|
+
const command = request[1]
|
|
445
|
+
const addressType = request[3]
|
|
446
|
+
|
|
447
|
+
let host
|
|
448
|
+
if (addressType === 0x01) {
|
|
449
|
+
host = (await reader.take(4)).join('.')
|
|
450
|
+
} else if (addressType === 0x03) {
|
|
451
|
+
const length = (await reader.take(1))[0]
|
|
452
|
+
host = (await reader.take(length)).toString('utf8')
|
|
453
|
+
} else if (addressType === 0x04) {
|
|
454
|
+
const raw = await reader.take(16)
|
|
455
|
+
const groups = []
|
|
456
|
+
for (let i = 0; i < 16; i += 2) groups.push(raw.readUInt16BE(i).toString(16))
|
|
457
|
+
host = groups.join(':')
|
|
458
|
+
} else {
|
|
459
|
+
throw new Error(`不支持的 SOCKS 地址类型 ${addressType}`)
|
|
460
|
+
}
|
|
461
|
+
const port = (await reader.take(2)).readUInt16BE(0)
|
|
462
|
+
|
|
463
|
+
if (command !== 0x01) {
|
|
464
|
+
socket.write(Buffer.from([0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
|
465
|
+
return
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
let upstream
|
|
469
|
+
try {
|
|
470
|
+
upstream = await connectTarget(host, port)
|
|
471
|
+
} catch {
|
|
472
|
+
socket.write(Buffer.from([0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
|
473
|
+
throw new Error(`SOCKS 连接 ${host}:${port} 失败`)
|
|
474
|
+
}
|
|
475
|
+
socket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]))
|
|
476
|
+
relay(socket, upstream, reader.rest())
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async function handleHttp(socket, reader, firstByte) {
|
|
480
|
+
const requestLine = firstByte.toString('latin1') + (await reader.line())
|
|
481
|
+
const headerLines = []
|
|
482
|
+
for (;;) {
|
|
483
|
+
const line = await reader.line()
|
|
484
|
+
if (line === '') break
|
|
485
|
+
headerLines.push(line)
|
|
486
|
+
}
|
|
487
|
+
const [method, target] = requestLine.split(' ')
|
|
488
|
+
if (method === undefined || target === undefined) throw new Error('请求行不合法')
|
|
489
|
+
|
|
490
|
+
if (method === 'CONNECT') {
|
|
491
|
+
const hostPort = target.split(':')
|
|
492
|
+
const host = hostPort[0]
|
|
493
|
+
const port = Number(hostPort[1] ?? '443')
|
|
494
|
+
let upstream
|
|
495
|
+
try {
|
|
496
|
+
upstream = await connectTarget(host, port)
|
|
497
|
+
} catch (error) {
|
|
498
|
+
socket.end('HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n')
|
|
499
|
+
throw error
|
|
500
|
+
}
|
|
501
|
+
socket.write('HTTP/1.1 200 Connection Established\r\nProxy-Agent: dsh-github-direct\r\n\r\n')
|
|
502
|
+
relay(socket, upstream, reader.rest())
|
|
503
|
+
return
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// 普通 HTTP 正向代理:绝对 URI → 原样改成 origin-form 转发
|
|
507
|
+
if (!target.startsWith('http://')) throw new Error('只支持 CONNECT 与 http:// 绝对地址')
|
|
508
|
+
const url = new URL(target)
|
|
509
|
+
const host = url.hostname
|
|
510
|
+
const port = Number(url.port || 80)
|
|
511
|
+
let upstream
|
|
512
|
+
try {
|
|
513
|
+
upstream = await connectTarget(host, port)
|
|
514
|
+
} catch {
|
|
515
|
+
socket.end('HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n')
|
|
516
|
+
return
|
|
517
|
+
}
|
|
518
|
+
const kept = headerLines.filter((line) => {
|
|
519
|
+
const name = line.split(':')[0]?.toLowerCase()
|
|
520
|
+
return name !== 'proxy-connection' && name !== 'connection'
|
|
521
|
+
})
|
|
522
|
+
upstream.write(
|
|
523
|
+
`${method} ${url.pathname}${url.search} HTTP/1.1\r\n${kept.join('\r\n')}\r\nConnection: close\r\n\r\n`,
|
|
524
|
+
)
|
|
525
|
+
relay(socket, upstream, reader.rest())
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// ------------------------------------------------------------------ 服务端
|
|
529
|
+
|
|
530
|
+
let server
|
|
531
|
+
|
|
532
|
+
function startProxy(port, host = DEFAULT_HOST) {
|
|
533
|
+
if (server !== undefined) return { started: false, port, host }
|
|
534
|
+
const created = net.createServer((socket) => {
|
|
535
|
+
handleClient(socket).catch(() => {
|
|
536
|
+
try {
|
|
537
|
+
socket.destroy()
|
|
538
|
+
} catch {
|
|
539
|
+
/* ignore */
|
|
540
|
+
}
|
|
541
|
+
})
|
|
542
|
+
})
|
|
543
|
+
created.on('error', (error) => {
|
|
544
|
+
state.listening = false
|
|
545
|
+
state.lastError = error.message
|
|
546
|
+
})
|
|
547
|
+
created.listen(port, host, () => {
|
|
548
|
+
state.listening = true
|
|
549
|
+
state.startedAt = Date.now()
|
|
550
|
+
})
|
|
551
|
+
server = created
|
|
552
|
+
return { started: true, port, host }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function stopProxy() {
|
|
556
|
+
if (server === undefined) return false
|
|
557
|
+
try {
|
|
558
|
+
server.close()
|
|
559
|
+
} catch {
|
|
560
|
+
/* ignore */
|
|
561
|
+
}
|
|
562
|
+
server = undefined
|
|
563
|
+
state.listening = false
|
|
564
|
+
return true
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function portAlive(port, host = DEFAULT_HOST, timeoutMs = 400) {
|
|
568
|
+
return new Promise((resolve) => {
|
|
569
|
+
const socket = net.connect({ host, port })
|
|
570
|
+
const done = (value) => {
|
|
571
|
+
socket.destroy()
|
|
572
|
+
resolve(value)
|
|
573
|
+
}
|
|
574
|
+
socket.setTimeout(timeoutMs)
|
|
575
|
+
socket.once('connect', () => done(true))
|
|
576
|
+
socket.once('timeout', () => done(false))
|
|
577
|
+
socket.once('error', () => done(false))
|
|
578
|
+
})
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// ------------------------------------------------------------------ 系统代理(Windows)
|
|
582
|
+
|
|
583
|
+
const REG_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'
|
|
584
|
+
const BACKUP_PATH = join(os.homedir(), '.dsh', 'github-direct.sysproxy.json')
|
|
585
|
+
|
|
586
|
+
function regExec(args) {
|
|
587
|
+
return new Promise((resolve) => {
|
|
588
|
+
execFile('reg.exe', args, { windowsHide: true, timeout: 8000 }, (error, stdout, stderr) => {
|
|
589
|
+
resolve({ ok: error === null, out: `${stdout ?? ''}${stderr ?? ''}`.trim(), error: error?.message })
|
|
590
|
+
})
|
|
591
|
+
})
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async function regQuery(name) {
|
|
595
|
+
const result = await regExec(['query', REG_KEY, '/v', name])
|
|
596
|
+
if (!result.ok) return undefined
|
|
597
|
+
const match = /REG_\w+\s+(.+)$/m.exec(result.out)
|
|
598
|
+
return match?.[1]?.trim()
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
async function regSet(name, type, value) {
|
|
602
|
+
return regExec(['add', REG_KEY, '/v', name, '/t', type, '/d', String(value), '/f'])
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function readBackup() {
|
|
606
|
+
try {
|
|
607
|
+
return JSON.parse(readFileSync(BACKUP_PATH, 'utf8'))
|
|
608
|
+
} catch {
|
|
609
|
+
return undefined
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function writeBackup(data) {
|
|
614
|
+
mkdirSync(dirname(BACKUP_PATH), { recursive: true })
|
|
615
|
+
writeFileSync(BACKUP_PATH, `${JSON.stringify(data, null, 2)}\n`, 'utf8')
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
async function systemProxyStatus() {
|
|
619
|
+
const enabled = await regQuery('ProxyEnable')
|
|
620
|
+
const proxyServer = await regQuery('ProxyServer')
|
|
621
|
+
return { enabled: enabled === '0x1', proxyServer: proxyServer ?? '' }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
async function systemProxyOn(port) {
|
|
625
|
+
const alive = await portAlive(port)
|
|
626
|
+
if (!alive) throw new Error(`本地通道没在 ${DEFAULT_HOST}:${port} 监听,先让插件启动(github_direct_status 会拉起)`)
|
|
627
|
+
const before = await systemProxyStatus()
|
|
628
|
+
if (existsSync(BACKUP_PATH) === false) writeBackup({ proxyEnable: before.enabled ? 1 : 0, proxyServer: before.proxyServer })
|
|
629
|
+
await regSet('ProxyEnable', 'REG_DWORD', 1)
|
|
630
|
+
await regSet('ProxyServer', 'REG_SZ', `${DEFAULT_HOST}:${port}`)
|
|
631
|
+
return await systemProxyStatus()
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
async function systemProxyOff() {
|
|
635
|
+
const backup = readBackup()
|
|
636
|
+
await regSet('ProxyEnable', 'REG_DWORD', 0)
|
|
637
|
+
if (backup?.proxyServer !== undefined && backup.proxyServer !== '') {
|
|
638
|
+
await regSet('ProxyServer', 'REG_SZ', backup.proxyServer)
|
|
639
|
+
}
|
|
640
|
+
return await systemProxyStatus()
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** 防呆:代理开着但端口上没人监听 → 自动还原,避免整机像断网。 */
|
|
644
|
+
async function systemProxyGuard(port) {
|
|
645
|
+
const before = await systemProxyStatus()
|
|
646
|
+
if (!before.enabled) return { ...before, restored: false }
|
|
647
|
+
const alive = await portAlive(port)
|
|
648
|
+
if (alive) return { ...before, restored: false }
|
|
649
|
+
const after = await systemProxyOff()
|
|
650
|
+
return { ...after, restored: true }
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// ------------------------------------------------------------------ 插件配置
|
|
654
|
+
|
|
655
|
+
const DEFAULTS = { port: DEFAULT_PORT, autoStart: true, systemProxy: false }
|
|
656
|
+
|
|
657
|
+
function resolveConfig(config) {
|
|
658
|
+
const source = argsOf(config)
|
|
659
|
+
return {
|
|
660
|
+
port: num(source.port, DEFAULT_PORT),
|
|
661
|
+
autoStart: source.autoStart === false ? false : DEFAULTS.autoStart,
|
|
662
|
+
systemProxy: source.systemProxy === true,
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// ------------------------------------------------------------------ 工具定义
|
|
667
|
+
|
|
668
|
+
const stringProp = (description) => ({ type: 'string', description })
|
|
669
|
+
const numberProp = (description) => ({ type: 'number', description })
|
|
670
|
+
const boolProp = (description) => ({ type: 'boolean', description })
|
|
671
|
+
|
|
672
|
+
function textRender(fn) {
|
|
673
|
+
return (args, value) => [{ type: 'text', text: fn(argsOf(value)).join('\n') }]
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const statusTool = (cfg) => ({
|
|
677
|
+
name: 'github_direct_status',
|
|
678
|
+
description:
|
|
679
|
+
'查看 GitHub 直连通道状态:本地端口是否在监听、系统代理是否指向它、最近一次探活选中的 IP 和耗时。' +
|
|
680
|
+
'不挂梯子、不用机场:通道自带 DoH 解析与真实 HTTPS 探活。第一次调用会自动拉起通道。',
|
|
681
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
682
|
+
output: {
|
|
683
|
+
schema: {
|
|
684
|
+
type: 'object',
|
|
685
|
+
properties: {
|
|
686
|
+
ok: { type: 'boolean' },
|
|
687
|
+
running: { type: 'boolean' },
|
|
688
|
+
address: { type: 'string' },
|
|
689
|
+
uptimeSeconds: { type: 'number' },
|
|
690
|
+
systemProxy: { type: 'object', additionalProperties: true },
|
|
691
|
+
probed: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
692
|
+
counters: { type: 'object', additionalProperties: true },
|
|
693
|
+
lastError: { type: 'string' },
|
|
694
|
+
},
|
|
695
|
+
additionalProperties: true,
|
|
696
|
+
},
|
|
697
|
+
render: textRender((value) => {
|
|
698
|
+
const lines = [`通道:${value.running ? '运行中' : '未运行'} ${value.address}`]
|
|
699
|
+
if (value.running) lines.push(`已运行 ${String(value.uptimeSeconds)} 秒,转发 ${String(value.counters?.relayed ?? 0)} 条连接`)
|
|
700
|
+
lines.push(`系统代理:${value.systemProxy?.enabled ? '开' : '关'}(${value.systemProxy?.proxyServer || '未设置'})`)
|
|
701
|
+
const probed = Array.isArray(value.probed) ? value.probed : []
|
|
702
|
+
if (probed.length > 0) {
|
|
703
|
+
lines.push('最近探活:')
|
|
704
|
+
for (const item of probed) lines.push(`- ${item.host} → ${item.ip ?? '无可用'} ${item.ms !== undefined ? item.ms + 'ms' : ''}`)
|
|
705
|
+
}
|
|
706
|
+
if (value.lastError !== undefined) lines.push(`最近错误:${value.lastError}`)
|
|
707
|
+
return lines
|
|
708
|
+
}),
|
|
709
|
+
},
|
|
710
|
+
timeoutMs: 60_000,
|
|
711
|
+
isConcurrencySafe: () => true,
|
|
712
|
+
async execute() {
|
|
713
|
+
if (!state.listening && cfg.autoStart) startProxy(cfg.port)
|
|
714
|
+
await sleep(120)
|
|
715
|
+
const running = state.listening
|
|
716
|
+
const probed = [...state.lastProbe.entries()].map(([host, entry]) => ({
|
|
717
|
+
host,
|
|
718
|
+
ip: entry.chosen,
|
|
719
|
+
ms: entry.entries.find((e) => e.ip === entry.chosen)?.ms,
|
|
720
|
+
at: entry.at,
|
|
721
|
+
}))
|
|
722
|
+
return jsonSafe({
|
|
723
|
+
ok: running,
|
|
724
|
+
running,
|
|
725
|
+
address: `${DEFAULT_HOST}:${cfg.port}`,
|
|
726
|
+
uptimeSeconds: running ? Math.round((Date.now() - state.startedAt) / 1000) : 0,
|
|
727
|
+
systemProxy: await systemProxyStatus(),
|
|
728
|
+
probed,
|
|
729
|
+
counters: { ...state.counters },
|
|
730
|
+
lastError: state.lastError,
|
|
731
|
+
})
|
|
732
|
+
},
|
|
733
|
+
})
|
|
734
|
+
|
|
735
|
+
const probeTool = (cfg) => ({
|
|
736
|
+
name: 'github_direct_probe',
|
|
737
|
+
description:
|
|
738
|
+
'重新探活 GitHub 域名,列出每个候选 IP 的真实 HTTPS 耗时,并让通道改用最快的那个。' +
|
|
739
|
+
'浏览器一直转圈、clone 卡住时先跑它:能直接看出是 DNS 投毒还是某个 IP 假活。',
|
|
740
|
+
parameters: {
|
|
741
|
+
type: 'object',
|
|
742
|
+
properties: {
|
|
743
|
+
host: stringProp('只探一个域名,如 github.com;省略则探常用的 github.com / api / codeload。'),
|
|
744
|
+
force: boolProp('忽略缓存,强制重新探测。'),
|
|
745
|
+
},
|
|
746
|
+
additionalProperties: false,
|
|
747
|
+
},
|
|
748
|
+
output: {
|
|
749
|
+
schema: {
|
|
750
|
+
type: 'object',
|
|
751
|
+
properties: {
|
|
752
|
+
ok: { type: 'boolean' },
|
|
753
|
+
hosts: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
754
|
+
},
|
|
755
|
+
additionalProperties: true,
|
|
756
|
+
},
|
|
757
|
+
render: textRender((value) => {
|
|
758
|
+
const lines = []
|
|
759
|
+
for (const host of value.hosts ?? []) {
|
|
760
|
+
lines.push(`${host.host} → ${host.chosen ?? '无可用 IP'}`)
|
|
761
|
+
for (const entry of host.entries ?? []) {
|
|
762
|
+
lines.push(` ${entry.ip} ${entry.ok ? entry.ms + 'ms ' + entry.status : '不可用(' + (entry.error ?? '') + ')'}`)
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
return lines.length > 0 ? lines : ['没有可探测的域名']
|
|
766
|
+
}),
|
|
767
|
+
},
|
|
768
|
+
timeoutMs: 90_000,
|
|
769
|
+
isConcurrencySafe: () => false,
|
|
770
|
+
async execute(rawArgs) {
|
|
771
|
+
const args = argsOf(rawArgs)
|
|
772
|
+
const requested = str(args.host)
|
|
773
|
+
const hosts = requested !== undefined ? [requested] : ['github.com', 'api.github.com', 'codeload.github.com']
|
|
774
|
+
if (!state.listening && cfg.autoStart) startProxy(cfg.port)
|
|
775
|
+
const report = []
|
|
776
|
+
for (const host of hosts) {
|
|
777
|
+
const seeds = SEED_IPS[host] ?? []
|
|
778
|
+
const fromDoh = await dohResolve(host)
|
|
779
|
+
const candidates = [...new Set([...seeds, ...fromDoh])]
|
|
780
|
+
if (candidates.length === 0) {
|
|
781
|
+
report.push({ host, chosen: undefined, doh: [], entries: [] })
|
|
782
|
+
continue
|
|
783
|
+
}
|
|
784
|
+
const { usable, all } = await raceProbe(host, candidates)
|
|
785
|
+
state.quality.set(host, { at: Date.now(), entries: all })
|
|
786
|
+
state.lastProbe.set(host, { at: Date.now(), chosen: usable[0]?.ip, entries: all })
|
|
787
|
+
report.push({ host, chosen: usable[0]?.ip, doh: fromDoh, entries: all })
|
|
788
|
+
}
|
|
789
|
+
return jsonSafe({ ok: report.some((r) => r.chosen !== undefined), hosts: report })
|
|
790
|
+
},
|
|
791
|
+
})
|
|
792
|
+
|
|
793
|
+
const proxyTool = (cfg) => ({
|
|
794
|
+
name: 'github_direct_proxy',
|
|
795
|
+
description:
|
|
796
|
+
'管理 Windows 系统代理:on 把所有程序指向本地直连通道,off 还原,guard 检查「代理开着但通道已死」并自动还原,status 只读。' +
|
|
797
|
+
'浏览器打不开 GitHub 时用 on;不需要时用 off,避免通道没起来时整机像断网。',
|
|
798
|
+
parameters: {
|
|
799
|
+
type: 'object',
|
|
800
|
+
properties: {
|
|
801
|
+
action: { type: 'string', enum: ['on', 'off', 'guard', 'status'], description: '要执行的动作。' },
|
|
802
|
+
},
|
|
803
|
+
required: ['action'],
|
|
804
|
+
additionalProperties: false,
|
|
805
|
+
},
|
|
806
|
+
output: {
|
|
807
|
+
schema: {
|
|
808
|
+
type: 'object',
|
|
809
|
+
properties: {
|
|
810
|
+
ok: { type: 'boolean' },
|
|
811
|
+
action: { type: 'string' },
|
|
812
|
+
enabled: { type: 'boolean' },
|
|
813
|
+
proxyServer: { type: 'string' },
|
|
814
|
+
restored: { type: 'boolean' },
|
|
815
|
+
message: { type: 'string' },
|
|
816
|
+
},
|
|
817
|
+
additionalProperties: true,
|
|
818
|
+
},
|
|
819
|
+
render: textRender((value) => {
|
|
820
|
+
const lines = [`系统代理:${value.enabled ? '开' : '关'}(${value.proxyServer || '未设置'})`]
|
|
821
|
+
if (value.restored === true) lines.push('检测到代理指向已停止的通道,已自动还原 —— 不会再出现「整机断网」')
|
|
822
|
+
if (value.message !== undefined) lines.push(value.message)
|
|
823
|
+
return lines
|
|
824
|
+
}),
|
|
825
|
+
},
|
|
826
|
+
timeoutMs: 30_000,
|
|
827
|
+
isConcurrencySafe: () => false,
|
|
828
|
+
async execute(rawArgs) {
|
|
829
|
+
const args = argsOf(rawArgs)
|
|
830
|
+
const action = str(args.action) ?? 'status'
|
|
831
|
+
if (action === 'on') {
|
|
832
|
+
if (!state.listening && cfg.autoStart) startProxy(cfg.port)
|
|
833
|
+
await sleep(150)
|
|
834
|
+
const status = await systemProxyOn(cfg.port)
|
|
835
|
+
return jsonSafe({ ok: true, action, ...status })
|
|
836
|
+
}
|
|
837
|
+
if (action === 'off') {
|
|
838
|
+
const status = await systemProxyOff()
|
|
839
|
+
return jsonSafe({ ok: true, action, ...status })
|
|
840
|
+
}
|
|
841
|
+
if (action === 'guard') {
|
|
842
|
+
const status = await systemProxyGuard(cfg.port)
|
|
843
|
+
return jsonSafe({ ok: true, action, ...status })
|
|
844
|
+
}
|
|
845
|
+
const status = await systemProxyStatus()
|
|
846
|
+
return jsonSafe({ ok: true, action: 'status', ...status })
|
|
847
|
+
},
|
|
848
|
+
})
|
|
849
|
+
|
|
850
|
+
const runTool = (cfg) => ({
|
|
851
|
+
name: 'github_direct_run',
|
|
852
|
+
description:
|
|
853
|
+
'在本地直连通道下执行一条命令(git clone / git push / npm 装 GitHub 依赖 / curl),自动注入 HTTP(S)_PROXY 与 ALL_PROXY。' +
|
|
854
|
+
'不用梯子、不用手动配环境变量;命令失败会带上退出码和输出。',
|
|
855
|
+
parameters: {
|
|
856
|
+
type: 'object',
|
|
857
|
+
properties: {
|
|
858
|
+
command: stringProp('要执行的命令,例如 git clone --depth 1 https://github.com/octocat/Hello-World.git(必填)。'),
|
|
859
|
+
cwd: stringProp('工作目录;省略用当前会话目录。'),
|
|
860
|
+
timeoutMs: numberProp('超时毫秒数,默认 120000。'),
|
|
861
|
+
},
|
|
862
|
+
required: ['command'],
|
|
863
|
+
additionalProperties: false,
|
|
864
|
+
},
|
|
865
|
+
output: {
|
|
866
|
+
schema: {
|
|
867
|
+
type: 'object',
|
|
868
|
+
properties: {
|
|
869
|
+
ok: { type: 'boolean' },
|
|
870
|
+
exitCode: { type: 'number' },
|
|
871
|
+
stdout: { type: 'string' },
|
|
872
|
+
stderr: { type: 'string' },
|
|
873
|
+
proxy: { type: 'string' },
|
|
874
|
+
times: { type: 'number' },
|
|
875
|
+
},
|
|
876
|
+
additionalProperties: true,
|
|
877
|
+
},
|
|
878
|
+
render: textRender((value) => {
|
|
879
|
+
const lines = [`命令结束:退出码 ${String(value.exitCode)}(经 ${value.proxy})`]
|
|
880
|
+
const out = (value.stdout ?? '').trim()
|
|
881
|
+
const err = (value.stderr ?? '').trim()
|
|
882
|
+
if (out !== '') lines.push('stdout:', out.slice(-4000))
|
|
883
|
+
if (err !== '') lines.push('stderr:', err.slice(-4000))
|
|
884
|
+
return lines
|
|
885
|
+
}),
|
|
886
|
+
},
|
|
887
|
+
timeoutMs: 10 * 60 * 1000,
|
|
888
|
+
isConcurrencySafe: () => false,
|
|
889
|
+
async execute(rawArgs, exec) {
|
|
890
|
+
const args = argsOf(rawArgs)
|
|
891
|
+
const command = str(args.command)
|
|
892
|
+
if (command === undefined) throw new Error('command 不能为空')
|
|
893
|
+
if (!state.listening && cfg.autoStart) {
|
|
894
|
+
startProxy(cfg.port)
|
|
895
|
+
await sleep(200)
|
|
896
|
+
}
|
|
897
|
+
const proxy = `socks5h://${DEFAULT_HOST}:${cfg.port}`
|
|
898
|
+
const cwd = str(args.cwd) ?? exec?.cwd ?? process.cwd()
|
|
899
|
+
const timeout = num(args.timeoutMs, 120_000)
|
|
900
|
+
const env = {
|
|
901
|
+
...process.env,
|
|
902
|
+
HTTP_PROXY: proxy,
|
|
903
|
+
HTTPS_PROXY: proxy,
|
|
904
|
+
ALL_PROXY: proxy,
|
|
905
|
+
http_proxy: proxy,
|
|
906
|
+
https_proxy: proxy,
|
|
907
|
+
all_proxy: proxy,
|
|
908
|
+
NO_PROXY: 'localhost,127.0.0.1,.npmmirror.com,.aliyun.com',
|
|
909
|
+
no_proxy: 'localhost,127.0.0.1,.npmmirror.com,.aliyun.com',
|
|
910
|
+
PATH: [...binSearchDirs(), process.env.PATH ?? ''].filter((part) => part !== '').join(';'),
|
|
911
|
+
}
|
|
912
|
+
const shell = process.env.ComSpec ?? 'cmd.exe'
|
|
913
|
+
const started = Date.now()
|
|
914
|
+
const child = spawn(shell, ['/d', '/s', '/c', command], { cwd, env, windowsHide: true })
|
|
915
|
+
let stdout = ''
|
|
916
|
+
let stderr = ''
|
|
917
|
+
child.stdout?.on('data', (chunk) => {
|
|
918
|
+
if (stdout.length < 200_000) stdout += chunk.toString('utf8')
|
|
919
|
+
})
|
|
920
|
+
child.stderr?.on('data', (chunk) => {
|
|
921
|
+
if (stderr.length < 200_000) stderr += chunk.toString('utf8')
|
|
922
|
+
})
|
|
923
|
+
const exitCode = await new Promise((resolve) => {
|
|
924
|
+
const timer = setTimeout(() => {
|
|
925
|
+
try {
|
|
926
|
+
child.kill()
|
|
927
|
+
} catch {
|
|
928
|
+
/* ignore */
|
|
929
|
+
}
|
|
930
|
+
resolve(-1)
|
|
931
|
+
}, timeout)
|
|
932
|
+
child.once('close', (code) => {
|
|
933
|
+
clearTimeout(timer)
|
|
934
|
+
resolve(typeof code === 'number' ? code : -1)
|
|
935
|
+
})
|
|
936
|
+
child.once('error', (error) => {
|
|
937
|
+
clearTimeout(timer)
|
|
938
|
+
stderr += `\n${error.message}`
|
|
939
|
+
resolve(-1)
|
|
940
|
+
})
|
|
941
|
+
})
|
|
942
|
+
return jsonSafe({
|
|
943
|
+
ok: exitCode === 0,
|
|
944
|
+
exitCode,
|
|
945
|
+
stdout: stdout.trim(),
|
|
946
|
+
stderr: stderr.trim(),
|
|
947
|
+
proxy,
|
|
948
|
+
times: Math.round((Date.now() - started) / 1000),
|
|
949
|
+
})
|
|
950
|
+
},
|
|
951
|
+
})
|
|
952
|
+
|
|
953
|
+
// ------------------------------------------------------------------ 入口
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* 启动直连通道并注册四个工具。
|
|
957
|
+
* @param ctx - 宿主上下文(需要 tools 服务)。
|
|
958
|
+
* @param config - 插件配置行:port / autoStart / systemProxy。
|
|
959
|
+
*/
|
|
960
|
+
export function apply(ctx, config) {
|
|
961
|
+
const cfg = resolveConfig(config)
|
|
962
|
+
const disposers = [statusTool(cfg), probeTool(cfg), proxyTool(cfg), runTool(cfg)].map((definition) =>
|
|
963
|
+
ctx.tools.register(definition),
|
|
964
|
+
)
|
|
965
|
+
if (cfg.autoStart) startProxy(cfg.port)
|
|
966
|
+
// 首次启动时预热一次 github.com,用户第一次打开网页就不用干等
|
|
967
|
+
if (cfg.autoStart) {
|
|
968
|
+
bestIp('github.com').catch(() => {
|
|
969
|
+
/* 探活失败不影响通道本身,真正连接时会再试 */
|
|
970
|
+
})
|
|
971
|
+
}
|
|
972
|
+
if (cfg.systemProxy) {
|
|
973
|
+
systemProxyGuard(cfg.port)
|
|
974
|
+
.then((status) => {
|
|
975
|
+
if (!status.enabled) return systemProxyOn(cfg.port)
|
|
976
|
+
return status
|
|
977
|
+
})
|
|
978
|
+
.catch(() => {
|
|
979
|
+
/* 系统代理不是必需,失败不影响通道 */
|
|
980
|
+
})
|
|
981
|
+
}
|
|
982
|
+
const teardown = () => {
|
|
983
|
+
for (const dispose of disposers) dispose()
|
|
984
|
+
stopProxy()
|
|
985
|
+
}
|
|
986
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => teardown, 'github-direct.tools()')
|
|
987
|
+
else if (typeof ctx.on === 'function') ctx.on('dispose', teardown)
|
|
988
|
+
}
|
package/locale/en.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "GitHub direct",
|
|
4
|
+
"description": "Opens GitHub without a VPN: a local SOCKS5/HTTP tunnel on 127.0.0.1:7890 that resolves GitHub through DoH, probes IPs with real HTTPS requests, and can flip the Windows system proxy.",
|
|
5
|
+
"detail": "docs/DETAIL.md"
|
|
6
|
+
}
|
|
7
|
+
}
|
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-github-direct",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "GitHub 直连(不用梯子):本地 127.0.0.1:7890 双协议通道,DoH 解析 + 真实 HTTPS 探活 + 系统代理开关,装完即用。",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"dsh",
|
|
8
|
+
"dsh-plugin",
|
|
9
|
+
"dsh-bundle",
|
|
10
|
+
"github",
|
|
11
|
+
"proxy",
|
|
12
|
+
"doh",
|
|
13
|
+
"china-network"
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "dashuiyu",
|
|
17
|
+
"homepage": "https://github.com/dashuiyu/dsh-github-direct",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/dashuiyu/dsh-github-direct.git"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/dashuiyu/dsh-github-direct/issues"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./index.js",
|
|
27
|
+
"./locale/*.json": "./locale/*.json",
|
|
28
|
+
"./icon": "./icon.svg"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"index.js",
|
|
32
|
+
"cordis.patch.yml",
|
|
33
|
+
"locale/*.json",
|
|
34
|
+
"docs",
|
|
35
|
+
"icon.svg",
|
|
36
|
+
"README.md",
|
|
37
|
+
"LICENSE"
|
|
38
|
+
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"dsh": {
|
|
43
|
+
"bundle": {
|
|
44
|
+
"patch": "./cordis.patch.yml"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
6
47
|
}
|