feat(tunnel): 通用反向隧道 server/client,按 Host/固定端口/通配路由,SSE 逐帧透传

服务端按 Host 头或固定端口把请求转给家里的 client,WS 长连接承载,
token 首次启动自动生成;响应流式逐帧回传,SSE 不受影响。
配置用 YAML(server.yml 自动生成,client.yml 手写),与项目其余配置一致。
This commit is contained in:
2026-11-15 11:33:29 +08:00
parent da8653e5e9
commit d455c2d203
9 changed files with 773 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
server.yml
client.yml
*.log
data/
+20
View File
@@ -0,0 +1,20 @@
FROM node:20-slim
ENV TZ=Asia/Shanghai
WORKDIR /app
# 国内构建慢:npm 默认源在国外。默认换成腾讯云镜像(与 app/Dockerfile 同源)。
# 境外构建或想换源:docker compose build --build-arg NPM_REGISTRY=https://registry.npmjs.org/
ARG NPM_REGISTRY=https://mirrors.cloud.tencent.com/npm/
# 只依赖 ws(纯 JS,无预编译二进制,不需要 better-sqlite3 那套 binary mirror 配置)
# 基础镜像与 app/Dockerfile 同版本(node:20-slim):服务器上已有,构建时不用再拉一遍
COPY package.json package-lock.json ./
RUN npm config set registry "$NPM_REGISTRY" \
&& npm install --omit=dev --no-audit --no-fund
COPY server.js ./
EXPOSE 19000
CMD ["node", "server.js"]
+190
View File
@@ -0,0 +1,190 @@
# tunnel · 通用反向隧道
把本机(家里)的 HTTP 服务,经一台有公网 IP 的服务器中转出去。对访问方**完全透明**——
浏览器看到的仍是标准 HTTP/SSE,服务本身不需要任何改造。
```
手机/浏览器 ──https──> nginx:443 ──> server.js ──WebSocket──> client.js ──> 127.0.0.1:<port>
(服务器) (家里)
```
- **server.js** 不认识任何业务:只按 `Host` 头(或固定端口)把字节搬给 client
- **client.js** 按 `services` 配置把请求映射到本地端口
- 新增服务 = 改 client 配置一行,**两边代码都不用动**
## 启动顺序
没有严格要求。client 连不上会 1s→30s 指数退避重连,先起谁都能自动接上。
第一次配置建议先起 server,日志会直接告诉你 client 是否连上、token 对不对。
## 快速验证(本机,不碰 nginx)
```bash
cd tunnel && npm install
cp client.example.yml client.yml # server 改成 ws://127.0.0.1:19000/tunnel,token 先留空
node server.js & # 首次启动生成 server.yml,日志打印 TOKEN
# 把 TOKEN 填进 client.yml 的 token,再:
node client.js &
curl -H "Host: agent.home.example.com" http://127.0.0.1:19000/api/health
curl -s http://127.0.0.1:19000/__tunnel/health # {"ok":true,"client":"online",...}
```
## 服务器部署
```bash
cd tunnel
docker compose up -d
docker compose logs | grep TOKEN # 首次启动自动生成,记下来填到家里 client.yml
```
**不需要先写配置**:首次启动会自动生成 `./data/server.yml`,里面带一个随机 token 并打印到日志。
第二次启动直接复用,token 不会变。
裸跑也行(不写配置同样自动生成):
```bash
node server.js # 配置落在 ./server.yml
TUNNEL_CONFIG=/path/to/server.yml node server.js
```
## 请求怎么找到对应的服务
一台服务器、一个端口,请求进来后要决定「这个请求是给 agent 还是给 NAS」。三种做法:
### 1. 看域名(有域名时最自然)
```
agent.home.example.com → 家里 8090
nas.home.example.com → 家里 5000
```
隧道读请求里的 `Host` 头决定转发给谁。配置就是 `client.yml` 的 `host` 字段:
```yaml
services:
- host: agent.home.example.com
port: 8090
```
需要 DNS 泛解析 `*.home.example.com` 指到服务器,前面再套一层 nginx 做 TLS。
### 2. 一个端口钉一个服务(没有域名,又要多个服务)
隧道同时监听好几个端口,每个端口只认一个服务名:
```
http://<服务器IP>:19001 → 固定给 agent
http://<服务器IP>:19002 → 固定给 NAS
```
`server.yml` 声明端口归属:
```yaml
routes:
- port: 19001
service: agent
- port: 19002
service: nas
```
`client.yml` 用 `name` 对上:
```yaml
services:
- name: agent
port: 8090
- name: nas
port: 5000
```
`docker-compose.yml` 里把 19001/19002 的 `ports` 放开。**完全不看 Host 头**。
### 3. 一个端口 + 通配(没有域名,只有一个服务)
最简单:所有请求都给同一个服务。
```yaml
services:
- host: "*"
port: 8090
```
浏览器开 `http://<服务器IP>:19000` 就是它。
### 怎么选
| 你的情况 | 用哪个 |
|---|---|
| 有域名 | 方式 1 |
| 没域名,只暴露一个服务 | 方式 3(一行配置) |
| 没域名,要暴露多个服务 | 方式 2(一个服务一个端口) |
方式 1 和 2 **可以同时开**:19000 走 Host 路由,19001/19002 各钉死一个服务,互不干扰。
## 家里部署
```bash
node client.js # 读同目录 client.yml
node client.js /path/to/client.yml
```
```yaml
server: "wss://agent.home.example.com/tunnel"
token: "<和服务器同一个>"
userAgent: "Mozilla/5.0 (...) Chrome/131.0.0.0 Safari/537.36"
services:
- name: agent
host: agent.home.example.com
port: 8090
```
- `name`:固定端口路由用的服务标识(有域名时可省略)
- `host`:`域名` / `*.example.com` / `"*"`(兜底)
- `userAgent`:可选,握手时伪装浏览器 UA,降低被 DPI 盯上的概率
- 断线自动重连,启动时自检每个端口可达性(不可达只告警不退出)
## 隧道协议
一条 WebSocket 承载所有请求,用 `id` 多路复用。
```jsonc
// 服务器 → 家里
{"id":"r1","op":"req","method":"POST","path":"/api/x","headers":{...},"service":"agent"}
{"id":"r1","op":"body","b64":"..."} // 请求体分帧
{"id":"r1","op":"end"}
{"id":"r1","op":"abort"} // 浏览器提前断开
// 家里 → 服务器(响应分帧,边收边转)
{"id":"r1","ev":"head","status":200,"headers":{...}}
{"id":"r1","ev":"data","b64":"..."}
{"id":"r1","ev":"end"}
{"id":"r1","ev":"error","msg":"..."}
```
`service` 只在「固定端口路由」时出现;没有它 client 就按 Host 头匹配。
## 已知边界
| 能力 | 状态 |
|---|---|
| 普通 HTTP / 大 body(测过 27 MB) | ✅ |
| SSE / 流式响应 | ✅ 逐帧透传(800ms/帧测试,间隔与直连一致) |
| 重定向(302) | ✅ 原样透传,不在隧道里跟跳 |
| 未知 Host | 502 |
| client 离线 | 503(快速失败,不挂住) |
| 固定端口路由 / `*` 通配 | ✅ |
| **WebSocket 升级** | ❌ 未实现(需双向字节流,二期) |
| HTTP/2 | ❌ 对外仍是 1.1,影响不大 |
## 排错
```bash
curl -s http://127.0.0.1:19000/__tunnel/health # client 在不在线
tail -f /tmp/tunnel-client.log # 家里端
tail -f /tmp/tunnel-server.log # 服务器端
```
- **502 没有匹配的本地服务**:`services[].host` 和请求 Host 不一致;无域名时用 `"*"` 或固定端口
- **SSE 憋着不出来**:nginx 少了 `proxy_buffering off`
- **大 body 报 `expect header not supported`**:旧版本才有,client 现在会剥掉 `Expect` 头
- **握手 401**:两边 token 不一致
+28
View File
@@ -0,0 +1,28 @@
# tunnel 本机端配置 —— 复制为 client.yml 后改(client.yml 不进版本库)
# 服务器隧道地址:对外走 TLS 用 wss,本机自测用 ws://127.0.0.1:19000/tunnel
server: "wss://agent.home.example.com/tunnel"
# 和服务器 server.yml 里的 token 一致
token: ""
# 握手 UA:伪装成浏览器,降低被 DPI 盯上的概率。不写就用内置默认值
# userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
# 请求体上限(MB),和服务端双保险
maxBodyMb: 64
# 要暴露的本地服务:加服务 = 加一项,两边代码都不用动
# 路由优先级:固定端口指定的 name → host 精确 → *.域名 通配 → "*" 兜底
services:
- name: agent
host: agent.home.example.com
port: 8090
# 没有域名时用 "*" 兜底:所有请求都给这一项(单服务形态)
# - host: "*"
# port: 8090
# - name: nas
# host: nas.home.example.com
# port: 5000
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env node
'use strict';
// 通用反向隧道 · 本机端(家里那台)
// 主动连服务器 → 收请求 → 按 Host 找本地端口 → 转发 → 流式回传
//
// 用法: node client.js [config.yml] 环境变量 TUNNEL_SERVER / TUNNEL_TOKEN 覆盖配置
// 断线自动重连(指数退避 1s → 30s),心跳由服务端 ping 驱动,本端 ws 库自动回 pong。
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const YAML = require('yaml');
const WebSocket = require('ws');
// ---------- 配置 ----------
function loadConfig() {
const file = process.argv[2] || path.join(__dirname, 'client.yml');
let cfg = {};
if (fs.existsSync(file)) {
try { cfg = YAML.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (e) {
console.error('[tunnel] ' + file + ' 不是合法 YAML:' + e.message);
process.exit(1);
}
}
cfg.server = String(process.env.TUNNEL_SERVER || cfg.server || '').trim();
cfg.token = String(process.env.TUNNEL_TOKEN || cfg.token || '').trim();
cfg.services = Array.isArray(cfg.services) ? cfg.services : [];
// 默认 UA 伪装成浏览器:跨境链路上「frp/x.x」这种 UA 是明显特征
cfg.userAgent = cfg.userAgent ||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36';
cfg.maxBodyMb = Number(cfg.maxBodyMb || 64);
if (!cfg.server || !cfg.token) {
console.error('[tunnel] 需要 server 和 token:写进 client.yml,或设 TUNNEL_SERVER / TUNNEL_TOKEN');
process.exit(1);
}
if (!cfg.services.length) {
console.error('[tunnel] services 为空:至少配一项 {host, port}');
process.exit(1);
}
return cfg;
}
const CFG = loadConfig();
function log(...a) { console.log(new Date().toISOString().slice(11, 19), '[client]', ...a); }
// ---------- 服务路由:Host → 本地端口 ----------
// 精确匹配优先;再退到「忽略端口」;最后允许 *.xxx 通配一项
// 服务匹配优先级:固定端口指定的 name → host 精确 → *.域名 通配 → "*" 兜底
// "*" 是给「服务器没有域名」的场景用的:浏览器访问 http://1.2.3.4:19000,
// Host 头是 IP,对不上任何域名,此时所有请求都交给这个服务(单服务形态)。
function pickService(meta) {
const list = CFG.services || [];
if (meta.service) {
const byName = list.find(s => String(s.name || '') === String(meta.service));
if (byName) return byName;
}
const host = String((meta.headers && meta.headers.host) || '').toLowerCase().split(':')[0];
for (const s of list) if (String(s.host || '').toLowerCase() === host) return s;
for (const s of list) {
const h = String(s.host || '').toLowerCase();
if (h.startsWith('*.') && host.endsWith(h.slice(1))) return s;
}
for (const s of list) if (s.host === '*') return s;
return null;
}
// ---------- 在途请求 ----------
// 收到 op=req 建条目,body 帧往里堆,op=end 才真正发出去;
// op=abort(手机提前断开)→ abort 本地请求,别让上游白跑。
const inflight = new Map();
let ws = null;
let backoff = 1000;
let stopping = false;
function send(obj) {
if (ws && ws.readyState === 1) {
try { ws.send(JSON.stringify(obj)); } catch (_) {}
}
}
function onMessage(raw) {
let m;
try { m = JSON.parse(raw); } catch (_) { return; }
if (m.op === 'req') {
inflight.set(m.id, { meta: m, chunks: [], size: 0, ac: new AbortController() });
} else if (m.op === 'body') {
const st = inflight.get(m.id);
if (!st) return;
const buf = Buffer.from(m.b64 || '', 'base64');
st.size += buf.length;
if (st.size > CFG.maxBodyMb * 1048576) { // 和服务端同一个上限,双保险
st.ac.abort();
inflight.delete(m.id);
return send({ id: m.id, ev: 'error', msg: 'body too large' });
}
st.chunks.push(buf);
} else if (m.op === 'end') {
const st = inflight.get(m.id);
if (!st) return;
inflight.delete(m.id);
handleRequest(m.id, st);
} else if (m.op === 'abort') {
const st = inflight.get(m.id);
if (st) { st.ac.abort(); inflight.delete(m.id); }
}
}
async function handleRequest(id, st) {
const { meta, chunks, ac } = st;
const svc = pickService(meta);
if (!svc) {
return send({ id, ev: 'error', msg: '没有匹配的本地服务: host=' + ((meta.headers || {}).host || '?') });
}
const headers = {};
for (const [k, v] of Object.entries(meta.headers || {})) {
const lk = k.toLowerCase();
if (lk === 'host' || lk === 'connection' || lk === 'content-length' || lk === 'expect') continue;
headers[k] = v;
}
// 强制不压缩:本端 fetch 会自动解压响应体,若保留 gzip 头,下游浏览器会拿明文当压缩流解析
headers['accept-encoding'] = 'identity';
const body = chunks.length ? Buffer.concat(chunks) : undefined;
try {
const r = await fetch('http://127.0.0.1:' + svc.port + meta.path, {
method: meta.method,
headers,
body,
signal: ac.signal,
redirect: 'manual', // 302 要原样交给浏览器,别在这里跟丢
});
const outHeaders = {};
r.headers.forEach((v, k) => { outHeaders[k] = v; });
delete outHeaders['content-encoding']; // 体已被 fetch 解压,长度也对不上,统一走 chunked
delete outHeaders['content-length'];
delete outHeaders['transfer-encoding'];
send({ id, ev: 'head', status: r.status, headers: outHeaders });
if (r.body) {
for await (const chunk of r.body) send({ id, ev: 'data', b64: Buffer.from(chunk).toString('base64') });
}
send({ id, ev: 'end' });
} catch (e) {
if (ac.signal.aborted) return; // 对端主动取消,不算错误
send({ id, ev: 'error', msg: (e.message || String(e)) + (e.cause ? ' | cause: ' + (e.cause.message || e.cause) : '') });
}
}
// ---------- 连接 / 重连 ----------
function connect() {
if (stopping) return;
const sep = CFG.server.includes('?') ? '&' : '?';
const url = CFG.server + sep + 'token=' + encodeURIComponent(CFG.token);
log('连接', CFG.server);
ws = new WebSocket(url, {
headers: { 'User-Agent': CFG.userAgent },
handshakeTimeout: 20000,
perMessageDeflate: false, // 关压缩:SSE 小帧多,压缩反而添乱且增加特征
});
ws.on('open', () => {
backoff = 1000;
log('已连接,暴露 ' + CFG.services.map(s => s.host + '→127.0.0.1:' + s.port).join(', '));
});
ws.on('message', onMessage);
ws.on('close', (code, reason) => {
if (stopping) return;
log('断开 code=' + code + ' ' + (reason || '') + ',' + Math.round(backoff / 1000) + 's 后重连');
setTimeout(connect, backoff);
backoff = Math.min(backoff * 2, 30000); // 指数退避,封顶 30s
});
ws.on('error', (e) => log('连接错误', e.message));
}
process.on('SIGINT', () => { stopping = true; log('退出'); try { ws && ws.close(1000, 'client shutdown'); } catch (_) {} process.exit(0); });
process.on('SIGTERM', () => { stopping = true; process.exit(0); });
// 启动自检:本地端口不通时早点说,别等服务器转发过来才报错
for (const s of CFG.services) {
const req = http.request({ host: '127.0.0.1', port: s.port, path: '/', method: 'HEAD', timeout: 3000 }, (res) => {
log('自检 ' + s.host + ' → 127.0.0.1:' + s.port + ' 可达(HTTP ' + res.statusCode + ')');
res.resume();
});
req.on('error', (e) => log('自检警告:127.0.0.1:' + s.port + ' 不可达(' + e.code + '),服务没起来?'));
req.on('timeout', () => { req.destroy(); log('自检警告:127.0.0.1:' + s.port + ' 超时'); });
req.end();
}
connect();
+24
View File
@@ -0,0 +1,24 @@
# tunnel 独立编排:只跑隧道服务端,和 agent 的 compose 互不相干
# cd tunnel && docker compose up -d
#
# 首次启动会自己生成 ./data/server.yml(含随机 token)并打印到日志:
# docker compose logs | grep TOKEN
# 把那个 token 填到家里 client.yml 的 token 即可。
services:
tunnel:
build: .
image: agent-tunnel:latest
container_name: agent-tunnel
restart: unless-stopped
ports:
# IP 直连:http://<服务器IP>:19000
- "${TUNNEL_PORT:-19000}:19000"
# 固定端口路由(一个端口钉一个服务):先在 data/server.yml 的 routes 里配好,再放开对应端口
# - "${TUNNEL_PORT_AGENT:-19001}:19001"
# - "${TUNNEL_PORT_NAS:-19002}:19002"
volumes:
# 挂目录而不是单文件:server.yml 不存在时 docker 会造个同名目录,单文件挂载会踩这个坑
- ./data:/app/data
environment:
- TZ=Asia/Shanghai
- TUNNEL_CONFIG=/app/data/server.yml
+48
View File
@@ -0,0 +1,48 @@
{
"name": "agent-tunnel",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "agent-tunnel",
"version": "0.1.0",
"dependencies": {
"ws": "^8.18.0",
"yaml": "2.6.1"
}
},
"node_modules/ws": {
"version": "8.23.0",
"resolved": "https://mirrors.cloud.tencent.com/npm/ws/-/ws-8.23.0.tgz",
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/yaml": {
"version": "2.6.1",
"resolved": "https://mirrors.cloud.tencent.com/npm/yaml/-/yaml-2.6.1.tgz",
"integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==",
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14"
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "agent-tunnel",
"version": "0.1.0",
"private": true,
"description": "通用反向隧道:把本机 HTTP 服务经服务器中转,按 Host 路由,支持流式响应",
"main": "server.js",
"scripts": {
"server": "node server.js",
"client": "node client.js"
},
"dependencies": {
"ws": "^8.18.0",
"yaml": "2.6.1"
}
}
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env node
'use strict';
// 通用反向隧道 · 服务器端
// 浏览器/手机 ──https──> nginx ──> 本进程 ──WebSocket──> 本机(家里) client ──> 127.0.0.1:port
//
// 本进程不认识任何业务:只按请求的 Host 头把字节搬给 client,client 再按自己的
// services 配置找本地端口。所以任何 HTTP 服务接进来都不用改这里的代码。
//
// 用法: node server.js [config.yml] 环境变量 TUNNEL_PORT / TUNNEL_TOKEN 覆盖配置
// 协议: 见 README.md「隧道协议」一节
const http = require('node:http');
const fs = require('node:fs');
const crypto = require('node:crypto');
const path = require('node:path');
const YAML = require('yaml');
const { WebSocketServer } = require('ws');
// ---------- 配置 ----------
function loadConfig() {
const file = process.env.TUNNEL_CONFIG || process.argv[2] || path.join(__dirname, 'server.yml');
let cfg = {};
let dirty = false;
if (fs.existsSync(file)) {
try { cfg = YAML.parse(fs.readFileSync(file, 'utf8')) || {}; } catch (e) {
console.error('[tunnel] ' + file + ' 不是合法 YAML:' + e.message);
process.exit(1);
}
} else {
dirty = true; // 没有配置文件 → 首次启动
}
cfg.port = Number(process.env.TUNNEL_PORT || cfg.port || 19000);
cfg.token = String(process.env.TUNNEL_TOKEN || cfg.token || '');
cfg.maxBodyMb = Number(cfg.maxBodyMb || 64);
cfg.heartbeatMs = Number(cfg.heartbeatMs || 25000);
// 没 token 就现生成一个随机串并落盘:省掉「先手写配置再启动」这一步,
// docker compose up -d 直接就能跑。落盘失败也不阻断(本次仍可用)。
if (!cfg.token) {
cfg.token = crypto.randomBytes(24).toString('base64url');
dirty = true;
}
if (dirty) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
const out = { port: cfg.port, token: cfg.token, maxBodyMb: cfg.maxBodyMb, heartbeatMs: cfg.heartbeatMs };
if (Array.isArray(cfg.routes) && cfg.routes.length) out.routes = cfg.routes;
// 写回带注释的模板:YAML.stringify 本身会丢掉注释,头部这几行手动拼。
// 这份自动生成的 server.yml 就是字段说明的唯一出处(不另维护示例文件)。
const head = '# tunnel 服务端配置(首次启动自动生成,可直接改,改完重启生效)\n'
+ '# port 本端口,按 Host 头路由\n'
+ '# token 必须和家里 client.yml 里的一致\n'
+ '# maxBodyMb 单请求体上限(MB)\n'
+ '# heartbeatMs 心跳间隔(ms),跨境链路靠它发现半死连接\n'
+ '# routes 可选,固定端口路由:一个端口钉死一个服务(每个 port 还要在\n'
+ '# docker-compose.yml 的 ports 里放开)。写法:\n'
+ '# routes:\n'
+ '# - port: 19001\n'
+ '# service: agent\n';
fs.writeFileSync(file, head + YAML.stringify(out));
console.log('============================================================');
console.log(' 首次启动,已生成配置:' + file);
console.log(' TOKEN: ' + cfg.token);
console.log(' ↑ 填到家里 client.yml 的 token,然后重启 client');
console.log('============================================================');
} catch (e) {
console.error('[tunnel] 写配置失败:' + e.message + '(本次 token 仅进程内有效)');
}
}
return cfg;
}
const CFG = loadConfig();
// ---------- 连接状态 ----------
let client = null; // 家里那条 WS(只允许一条,新的顶掉旧的)
const pending = new Map(); // id -> { res, timer }
let seq = 0;
const nextId = () => 'r' + (++seq).toString(36) + Math.random().toString(36).slice(2, 6);
// 逐跳头:只对单段连接有意义,不能透传
const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
'te', 'trailer', 'transfer-encoding', 'upgrade']);
function log(...a) { console.log(new Date().toISOString().slice(11, 19), '[server]', ...a); }
// ---------- HTTP:把请求搬给 client ----------
// fixedService:由「固定端口路由」传进来(无域名时一个端口对一个服务);null = 按 Host 头路由
function handleRequest(req, res, fixedService) {
// 健康检查:只在主端口答,固定端口一律当业务流量转走
if (!fixedService && req.url === '/__tunnel/health') {
return json(res, 200, {
ok: true,
client: client ? 'online' : 'offline',
pending: pending.size,
uptime_s: Math.round(process.uptime()),
});
}
if (!client || client.readyState !== 1) {
return json(res, 503, { error: 'tunnel client offline', hint: '家里那台没连上,或 token 不对' });
}
const id = nextId();
const headers = {};
for (const [k, v] of Object.entries(req.headers)) if (!HOP_BY_HOP.has(k)) headers[k] = v;
pending.set(id, { res, timer: null });
const frame = { id, op: 'req', method: req.method, path: req.url, headers };
if (fixedService) frame.service = fixedService; // 端口绑定的服务名,client 优先按它找
client.send(JSON.stringify(frame));
let size = 0;
let overflow = false;
req.on('data', (chunk) => {
if (overflow) return;
size += chunk.length;
if (size > CFG.maxBodyMb * 1048576) { // 超限直接掐,别把内存吃穿
overflow = true;
client.send(JSON.stringify({ id, op: 'abort' }));
pending.delete(id);
return json(res, 413, { error: 'body too large', limit_mb: CFG.maxBodyMb });
}
client.send(JSON.stringify({ id, op: 'body', b64: chunk.toString('base64') }));
});
req.on('end', () => { if (!overflow) client.send(JSON.stringify({ id, op: 'end' })); });
// 手机/浏览器提前断开:让家里把上游请求也停掉,别白跑
req.on('aborted', () => {
if (!pending.has(id)) return;
client.send(JSON.stringify({ id, op: 'abort' }));
pending.delete(id);
});
}
// 主端口:按 Host 路由(有域名时的常规形态)
const server = http.createServer((req, res) => handleRequest(req, res, null));
// 固定端口:routes[{port, service}],一个端口钉死一个服务(没有域名也能多服务)
const extraServers = [];
for (const r of (CFG.routes || [])) {
const port = Number(r && r.port);
const service = String((r && r.service) || '').trim();
if (!port || !service) continue;
const s2 = http.createServer((req, res) => handleRequest(req, res, service));
s2.on('error', (e) => log('固定端口 ' + port + ' 起不来:' + e.message));
s2.listen(port, () => log('固定端口 ' + port + ' → 服务 "' + service + '"'));
extraServers.push(s2);
}
// ---------- client 回传的响应事件 ----------
function onClientMessage(raw) {
let m;
try { m = JSON.parse(raw); } catch (_) { return log('丢弃坏帧'); }
const entry = pending.get(m.id);
if (!entry) return; // 已超时/已断开,安静丢弃
const { res } = entry;
try {
if (m.ev === 'head') {
const h = {};
for (const [k, v] of Object.entries(m.headers || {})) {
const lk = k.toLowerCase();
// content-length 必然对不上(客户端已解压 / 分帧传输),交给 chunked
if (HOP_BY_HOP.has(lk) || lk === 'content-length') continue;
h[k] = v;
}
res.writeHead(m.status || 502, h);
} else if (m.ev === 'data') {
res.write(Buffer.from(m.b64 || '', 'base64'));
} else if (m.ev === 'end') {
res.end();
pending.delete(m.id);
} else if (m.ev === 'error') {
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
res.end('tunnel error: ' + (m.msg || 'unknown'));
pending.delete(m.id);
}
} catch (e) {
log('回写失败', m.id, e.message);
try { res.destroy(); } catch (_) {}
pending.delete(m.id);
}
}
// ---------- WebSocket 升级:家里连上来 ----------
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url, 'http://placeholder');
if (url.pathname !== '/tunnel') { socket.destroy(); return; }
if (url.searchParams.get('token') !== CFG.token) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return log('拒绝:token 不匹配', req.socket.remoteAddress);
}
wss.handleUpgrade(req, socket, head, (ws) => {
if (client && client.readyState === 1) {
log('新连接顶掉旧连接');
try { client.close(4000, 'replaced by new connection'); } catch (_) {}
}
client = ws;
ws.isAlive = true;
log('client 已连接', req.socket.remoteAddress);
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', onClientMessage);
ws.on('close', () => {
if (client === ws) client = null;
log('client 断开,未完成请求 ' + pending.size + ' 个一并收尾');
// 连接没了,等在途的请求不可能再有响应,直接 502,别让浏览器干等
for (const [id, e] of pending) {
try { if (!e.res.headersSent) e.res.writeHead(502); e.res.end('tunnel client disconnected'); } catch (_) {}
pending.delete(id);
}
});
ws.on('error', (e) => log('client 错误', e.message));
});
});
// 心跳:跨境链路半死状态(TCP 还在但早不通了)靠这个发现
setInterval(() => {
if (!client || client.readyState !== 1) return;
if (client.isAlive === false) { log('心跳超时,踢掉 client'); try { client.terminate(); } catch (_) {} client = null; return; }
client.isAlive = false;
try { client.ping(); } catch (_) {}
}, CFG.heartbeatMs).unref();
// 在途请求超时兜底:SSE 长连接不该被砍,所以只在「还没收到 head」时计时
setInterval(() => {
const now = Date.now();
for (const [id, e] of pending) {
if (e.res.headersSent) continue;
if (!e.born) { e.born = now; continue; }
if (now - e.born > 120000) {
log('请求 120s 无响应,放弃', id);
try { e.res.writeHead(504); e.res.end('tunnel upstream timeout'); } catch (_) {}
pending.delete(id);
if (client && client.readyState === 1) client.send(JSON.stringify({ id, op: 'abort' }));
}
}
}, 10000).unref();
function json(res, code, obj) {
const body = JSON.stringify(obj);
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) });
res.end(body);
}
// SSE / 长轮询不能被 Node 的默认超时砍掉
server.timeout = 0;
server.headersTimeout = 60000;
server.keepAliveTimeout = 65000;
server.listen(CFG.port, () => {
log('监听 0.0.0.0:' + CFG.port + ',健康检查 /__tunnel/health');
log('等待 client 连接 wss://<本机域名>/tunnel?token=***');
});