@hamsterbase/evidra 0.10.1 → 0.11.1
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/package.json
CHANGED
|
@@ -16,10 +16,29 @@ description: 按需启动、复用或查看当前项目的 Evidra 报告服务
|
|
|
16
16
|
| 用户主动要求公网分享或公网访问 | `bash "<本 skill 目录>/scripts/share.sh" --public` |
|
|
17
17
|
| 关闭公网分享、收回公网链接或仅用内网 | `bash "<本 skill 目录>/scripts/share.sh" --lan` |
|
|
18
18
|
|
|
19
|
-
用户查看报告地址时,可先运行 `status.sh`;若未运行再运行 `share.sh`
|
|
19
|
+
用户查看报告地址时,可先运行 `status.sh`;若未运行再运行 `share.sh` 启动本机与局域网报告。默认模式会显示已有的公网链接。`--public` 开启分享,连续 30 分钟无公网访问时自动收回。使用 Named Tunnel 时,每次显式运行 `--public` 都会替换当前项目的地址。`--lan` 会立即收回当前项目的公网访问。
|
|
20
20
|
|
|
21
21
|
脚本优先使用仓库根目录的 Evidra 依赖或源码入口,否则查找未被 Git 忽略的子项目中声明并安装的 `@hamsterbase/evidra`。只有一个候选时自动使用;多个候选时可在命令末尾传入子项目目录(例如 `playground`)来选择。报告的 `--repo` 始终是 Git 仓库根目录,无需为了启动报告在根目录新增依赖。
|
|
22
22
|
|
|
23
|
+
## Named Tunnel 随机公网域名
|
|
24
|
+
|
|
25
|
+
脚本逐项优先读取 `process.env`,未设置的变量从当前用户的 `~/.config/evidra/share.env`(dotenv 格式,权限 `600`)读取。四项都未配置时沿用 Quick Tunnel。只配置了一部分时,`--public` 会列出缺项。
|
|
26
|
+
|
|
27
|
+
| 环境变量 | 值 |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `EVIDRA_SHARE_DOMAIN` | 托管在 Cloudflare 的域,例如 `example.com`。生成 `preview-<随机值>.example.com`。 |
|
|
30
|
+
| `EVIDRA_SHARE_TUNNEL_TOKEN` | 这台机器专用的远程管理 Named Tunnel 的连接 token。 |
|
|
31
|
+
| `EVIDRA_SHARE_ZONE_ID` | 上述域在 Cloudflare 的 Zone ID。 |
|
|
32
|
+
| `EVIDRA_SHARE_DNS_TOKEN` | 仅授权上述 Zone 的 API token,权限为 Zone → DNS → Edit。 |
|
|
33
|
+
|
|
34
|
+
首次使用时按以下步骤配置,以 `example.com` 为例。
|
|
35
|
+
|
|
36
|
+
1. 在 Zero Trust 的 Self-hosted Access 应用中添加 `preview-*.example.com`,绑定所需的 Allow 邮箱策略。
|
|
37
|
+
2. 在这条专用 Tunnel 的 Published application 中配置主机 `*.example.com`,Service URL 填 `http://127.0.0.1:24751`,Path 和 HTTP Host Header 留空。在 Access 设置中打开 **Protect with Access** 并选择前一步的应用。使用同一 Tunnel 的连接器都应能访问同一台本机路由器。
|
|
38
|
+
3. DNS 只需要每次分享对应的精确 CNAME,脚本会创建和清理。如果控制台自动新增了一条通配 DNS,请只移除本次新建的通配 DNS,保留 Tunnel 的主机路由。已有通配 DNS 用于其他服务时,使用 Cloudflare 的 Tunnel 配置 API 单独设置 ingress,保留原有 DNS。
|
|
39
|
+
|
|
40
|
+
脚本按需运行共用的 `cloudflared` 和本机 HTTP 路由器(仅回环地址,`24751` 为路由器端口、`24752` 为指标端口),把每个当前分享的域名转给对应项目的报告端口。新建地址会检查 Cloudflare Access 登录跳转。换址、`--lan` 或空闲超时会停止旧地址转发并回收 DNS。DNS 清理失败时保留记录供重试。
|
|
41
|
+
|
|
23
42
|
## 执行约束
|
|
24
43
|
|
|
25
44
|
- 成功时,把脚本的标准输出原样发给用户,每项单独占一行(不要合并到同一行),保留 Markdown 列表格式与密码两侧的反引号。各地址末尾的 `#password=…` 用于打开后自动填入密码框,转发时保留完整地址。
|
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
// One connector and one loopback router per machine. Control requests use a private Unix socket.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { parseEnv } from 'node:util';
|
|
11
|
+
|
|
12
|
+
const [command, project, portArg] = process.argv.slice(2);
|
|
13
|
+
const directory = path.join(os.homedir(), '.local/state/evidra/named-share');
|
|
14
|
+
const socket = path.join(directory, 'ctl');
|
|
15
|
+
const ledger = path.join(directory, 'records.json');
|
|
16
|
+
const configFile = path.join(os.homedir(), '.config/evidra/share.env');
|
|
17
|
+
const keys = ['DOMAIN', 'TUNNEL_TOKEN', 'ZONE_ID', 'DNS_TOKEN'];
|
|
18
|
+
const routerPort = 24751;
|
|
19
|
+
const validDomain = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/;
|
|
20
|
+
const uuid = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;
|
|
21
|
+
const variable = (key) => 'EVIDRA_SHARE_' + key;
|
|
22
|
+
const tunnelEnv = {
|
|
23
|
+
PATH: process.env.PATH,
|
|
24
|
+
HOME: os.homedir(),
|
|
25
|
+
...Object.fromEntries(
|
|
26
|
+
Object.entries(process.env).filter(([key]) => /^(http|https|all|no)_proxy$/i.test(key)),
|
|
27
|
+
),
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
function configuration() {
|
|
31
|
+
const defaults = fs.existsSync(configFile) ? parseEnv(fs.readFileSync(configFile, 'utf8')) : {};
|
|
32
|
+
return Object.fromEntries(
|
|
33
|
+
keys.map((key) => [key, process.env[variable(key)] ?? defaults[variable(key)] ?? '']),
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validate(config) {
|
|
38
|
+
const missing = keys.filter((key) => !config[key]);
|
|
39
|
+
if (missing.length) throw Error('Named Tunnel 缺少配置:' + missing.map(variable).join('、'));
|
|
40
|
+
if (!validDomain.test(config.DOMAIN) || config.DOMAIN.length > 220)
|
|
41
|
+
throw Error('EVIDRA_SHARE_DOMAIN 应为小写域名');
|
|
42
|
+
if (!/^[\da-f]{32}$/i.test(config.ZONE_ID)) throw Error('EVIDRA_SHARE_ZONE_ID 格式错误');
|
|
43
|
+
let credential;
|
|
44
|
+
try {
|
|
45
|
+
credential = JSON.parse(Buffer.from(config.TUNNEL_TOKEN, 'base64').toString());
|
|
46
|
+
} catch {}
|
|
47
|
+
if (!uuid.test(credential?.t) || !credential.s) throw Error('EVIDRA_SHARE_TUNNEL_TOKEN 格式错误');
|
|
48
|
+
return credential.t;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function dns(config, record, method, suffix, body) {
|
|
52
|
+
const response = await fetch(
|
|
53
|
+
'https://api.cloudflare.com/client/v4/zones/' + record.zone + '/dns_records' + suffix,
|
|
54
|
+
{
|
|
55
|
+
method,
|
|
56
|
+
redirect: 'error',
|
|
57
|
+
signal: AbortSignal.timeout(10000),
|
|
58
|
+
headers: { Authorization: 'Bearer ' + config.DNS_TOKEN, 'Content-Type': 'application/json' },
|
|
59
|
+
body: body && JSON.stringify(body),
|
|
60
|
+
},
|
|
61
|
+
);
|
|
62
|
+
const data = await response.json();
|
|
63
|
+
if (method === 'DELETE' && data.errors?.some((error) => error.code === 81044)) return;
|
|
64
|
+
if (!response.ok || !data.success)
|
|
65
|
+
throw Error(
|
|
66
|
+
'Cloudflare DNS ' +
|
|
67
|
+
method +
|
|
68
|
+
' 失败:HTTP ' +
|
|
69
|
+
response.status +
|
|
70
|
+
'(' +
|
|
71
|
+
(data.errors ?? []).map((error) => error.code).join(',') +
|
|
72
|
+
')',
|
|
73
|
+
);
|
|
74
|
+
return data.result;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function readBody(request) {
|
|
78
|
+
let body = '';
|
|
79
|
+
for await (const chunk of request) {
|
|
80
|
+
body += chunk;
|
|
81
|
+
if (body.length > 32768) throw Error('控制请求过大');
|
|
82
|
+
}
|
|
83
|
+
return JSON.parse(body);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function control(action, config) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const req = http.request({ socketPath: socket, path: '/', method: 'POST' }, async (res) => {
|
|
89
|
+
try {
|
|
90
|
+
const result = await readBody(res);
|
|
91
|
+
if (result.error) throw Error(result.error);
|
|
92
|
+
resolve(result.host ?? '');
|
|
93
|
+
} catch (error) {
|
|
94
|
+
reject(error);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
req.on('error', reject);
|
|
98
|
+
req.end(
|
|
99
|
+
JSON.stringify({
|
|
100
|
+
action,
|
|
101
|
+
project,
|
|
102
|
+
port: Number(portArg),
|
|
103
|
+
config,
|
|
104
|
+
idle: process.env.IDLE_MINUTES ?? '30',
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function serve() {
|
|
111
|
+
process.umask(0o077);
|
|
112
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
113
|
+
const records = fs.existsSync(ledger) ? JSON.parse(fs.readFileSync(ledger, 'utf8')) : [];
|
|
114
|
+
// After a restart, a DNS record may still need deletion. Never reactivate its old destination.
|
|
115
|
+
const active = new Map();
|
|
116
|
+
const credentials = new Map();
|
|
117
|
+
const revocations = new Map();
|
|
118
|
+
let connector;
|
|
119
|
+
let connectorToken;
|
|
120
|
+
let queue = Promise.resolve();
|
|
121
|
+
let busy = 0;
|
|
122
|
+
let controlRequests = 0;
|
|
123
|
+
const pidFile = path.join(directory, 'connector.pid');
|
|
124
|
+
function save() {
|
|
125
|
+
fs.writeFileSync(ledger + '.tmp', JSON.stringify(records), { mode: 0o600 });
|
|
126
|
+
fs.renameSync(ledger + '.tmp', ledger);
|
|
127
|
+
}
|
|
128
|
+
function revoke(record) {
|
|
129
|
+
const route = active.get(record.host);
|
|
130
|
+
active.delete(record.host);
|
|
131
|
+
for (const req of route?.clients ?? []) req.destroy();
|
|
132
|
+
}
|
|
133
|
+
async function remove(record) {
|
|
134
|
+
revoke(record);
|
|
135
|
+
const config = credentials.get(record.zone);
|
|
136
|
+
if (!config) throw Error('清理旧 DNS 需要该 Zone 的 EVIDRA_SHARE_DNS_TOKEN');
|
|
137
|
+
// A POST may have succeeded even when its response was lost. Delete only our own record.
|
|
138
|
+
if (!record.id) {
|
|
139
|
+
const found = await dns(config, record, 'GET', '?type=CNAME&name=' + record.host);
|
|
140
|
+
record.id = found.find(
|
|
141
|
+
(item) => item.comment === record.comment && item.content === record.target,
|
|
142
|
+
)?.id;
|
|
143
|
+
}
|
|
144
|
+
if (record.id) await dns(config, record, 'DELETE', '/' + record.id);
|
|
145
|
+
records.splice(records.indexOf(record), 1);
|
|
146
|
+
save();
|
|
147
|
+
}
|
|
148
|
+
const router = http.createServer((req, res) => {
|
|
149
|
+
const host = (req.headers.host ?? '').toLowerCase();
|
|
150
|
+
const route = active.get(host);
|
|
151
|
+
if (route && Date.now() - route.lastAccess >= route.idleMs) {
|
|
152
|
+
revoke(route);
|
|
153
|
+
res.writeHead(404).end();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (!route || !req.headers['cf-access-jwt-assertion']) {
|
|
157
|
+
res.writeHead(route ? 403 : 404).end();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
route.lastAccess = Date.now();
|
|
161
|
+
const upstream = http.request(
|
|
162
|
+
{
|
|
163
|
+
hostname: '127.0.0.1',
|
|
164
|
+
port: route.port,
|
|
165
|
+
method: req.method,
|
|
166
|
+
path: req.url,
|
|
167
|
+
headers: req.headers,
|
|
168
|
+
},
|
|
169
|
+
(response) => {
|
|
170
|
+
res.writeHead(response.statusCode, response.headers);
|
|
171
|
+
response.on('error', () => res.destroy());
|
|
172
|
+
response.pipe(res);
|
|
173
|
+
},
|
|
174
|
+
);
|
|
175
|
+
route.clients.add(upstream);
|
|
176
|
+
upstream.on('close', () => route.clients.delete(upstream));
|
|
177
|
+
upstream.on('error', () => {
|
|
178
|
+
if (!res.headersSent) res.writeHead(502);
|
|
179
|
+
res.end();
|
|
180
|
+
});
|
|
181
|
+
res.on('close', () => upstream.destroy());
|
|
182
|
+
req.pipe(upstream);
|
|
183
|
+
});
|
|
184
|
+
// Binding first gives a single owner the right to replace a stale control socket.
|
|
185
|
+
await new Promise((resolve, reject) =>
|
|
186
|
+
router.once('error', reject).listen(routerPort, '127.0.0.1', resolve),
|
|
187
|
+
);
|
|
188
|
+
fs.rmSync(socket, { force: true });
|
|
189
|
+
async function connect(config) {
|
|
190
|
+
if (connector && (connector.killed || config.TUNNEL_TOKEN !== connectorToken)) {
|
|
191
|
+
if (!connector.killed && active.size)
|
|
192
|
+
throw Error('已有其他 Named Tunnel 连接;请先关闭它的分享');
|
|
193
|
+
const exited = new Promise((resolve) => connector.once('close', resolve));
|
|
194
|
+
connector.kill();
|
|
195
|
+
await exited;
|
|
196
|
+
}
|
|
197
|
+
if (!connector) {
|
|
198
|
+
fs.rmSync(pidFile, { force: true });
|
|
199
|
+
connectorToken = config.TUNNEL_TOKEN;
|
|
200
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'connector'], {
|
|
201
|
+
env: { ...tunnelEnv, TUNNEL_TOKEN: connectorToken },
|
|
202
|
+
stdio: ['pipe', 'ignore', 'ignore', 'ipc'],
|
|
203
|
+
});
|
|
204
|
+
child.once('message', (pid) => {
|
|
205
|
+
child.nativePid = pid;
|
|
206
|
+
});
|
|
207
|
+
connector = child;
|
|
208
|
+
child.on('error', () => {});
|
|
209
|
+
child.on('close', () => {
|
|
210
|
+
if (connector === child) connector = undefined;
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
const deadline = Date.now() + 30000;
|
|
214
|
+
while (connector && Date.now() < deadline) {
|
|
215
|
+
if (
|
|
216
|
+
fs.existsSync(pidFile) &&
|
|
217
|
+
fs.readFileSync(pidFile, 'utf8').trim() === String(connector.nativePid)
|
|
218
|
+
) {
|
|
219
|
+
const response = await fetch('http://127.0.0.1:24752/config', {
|
|
220
|
+
signal: AbortSignal.timeout(3000),
|
|
221
|
+
});
|
|
222
|
+
const remote = await response.json();
|
|
223
|
+
if (remote.version >= 0) return remote.config.ingress;
|
|
224
|
+
}
|
|
225
|
+
await sleep(200);
|
|
226
|
+
}
|
|
227
|
+
throw Error('Named Tunnel 未能连上 Cloudflare,请检查连接 token 和网络');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function handle({ action, project, port, config, idle }, generation) {
|
|
231
|
+
if (action === 'status') {
|
|
232
|
+
const route = [...active.values()].find((route) => route.project === project);
|
|
233
|
+
return {
|
|
234
|
+
host: connector && route && Date.now() - route.lastAccess < route.idleMs ? route.host : '',
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
if (config.ZONE_ID && config.DNS_TOKEN)
|
|
238
|
+
credentials.set(config.ZONE_ID, { DNS_TOKEN: config.DNS_TOKEN });
|
|
239
|
+
const previous = records.filter((r) => r.project === project);
|
|
240
|
+
if (action === 'close') {
|
|
241
|
+
previous.forEach(revoke);
|
|
242
|
+
for (const record of previous) await remove(record);
|
|
243
|
+
return {};
|
|
244
|
+
}
|
|
245
|
+
if (action !== 'open') throw Error('未知操作');
|
|
246
|
+
const assertCurrent = () => {
|
|
247
|
+
if (generation !== revocations.get(project)) throw Error('公网分享已被 --lan 取消');
|
|
248
|
+
};
|
|
249
|
+
assertCurrent();
|
|
250
|
+
const tunnel = validate(config);
|
|
251
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || !/^\d+$/.test(idle))
|
|
252
|
+
throw Error('无效的报告端口或空闲时间');
|
|
253
|
+
const rules = await connect(config);
|
|
254
|
+
assertCurrent();
|
|
255
|
+
const host = 'preview-' + randomBytes(10).toString('hex') + '.' + config.DOMAIN;
|
|
256
|
+
const rule = rules.find(
|
|
257
|
+
({ hostname }) =>
|
|
258
|
+
!hostname ||
|
|
259
|
+
hostname === host ||
|
|
260
|
+
hostname === '*' ||
|
|
261
|
+
(hostname.startsWith('*.') && host.endsWith(hostname.slice(1))),
|
|
262
|
+
);
|
|
263
|
+
const access = rule?.originRequest?.access;
|
|
264
|
+
if (
|
|
265
|
+
rule?.service !== 'http://127.0.0.1:' + routerPort ||
|
|
266
|
+
rule.path ||
|
|
267
|
+
rule.originRequest?.httpHostHeader ||
|
|
268
|
+
!access?.required ||
|
|
269
|
+
!access.teamName ||
|
|
270
|
+
!access.audTag?.length
|
|
271
|
+
) {
|
|
272
|
+
throw Error(
|
|
273
|
+
'请先配置 Named Tunnel 路由到 http://127.0.0.1:' +
|
|
274
|
+
routerPort +
|
|
275
|
+
',保留原 Host,并在 Protect with Access 中选择报告应用',
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
const record = {
|
|
279
|
+
project,
|
|
280
|
+
host,
|
|
281
|
+
zone: config.ZONE_ID,
|
|
282
|
+
target: tunnel + '.cfargotunnel.com',
|
|
283
|
+
comment: 'Evidra ' + randomUUID(),
|
|
284
|
+
};
|
|
285
|
+
records.push(record);
|
|
286
|
+
save();
|
|
287
|
+
try {
|
|
288
|
+
const created = await dns(config, record, 'POST', '', {
|
|
289
|
+
type: 'CNAME',
|
|
290
|
+
name: host,
|
|
291
|
+
content: record.target,
|
|
292
|
+
proxied: true,
|
|
293
|
+
ttl: 1,
|
|
294
|
+
comment: record.comment,
|
|
295
|
+
});
|
|
296
|
+
record.id = created.id;
|
|
297
|
+
save();
|
|
298
|
+
// The local router stays closed until the public hostname reaches an actual Access login.
|
|
299
|
+
const deadline = Date.now() + 60000;
|
|
300
|
+
let protectedHost = false;
|
|
301
|
+
while (Date.now() < deadline) {
|
|
302
|
+
assertCurrent();
|
|
303
|
+
try {
|
|
304
|
+
const response = await fetch('https://' + host + '/api/project', {
|
|
305
|
+
redirect: 'manual',
|
|
306
|
+
signal: AbortSignal.timeout(4000),
|
|
307
|
+
headers: { 'Cache-Control': 'no-cache' },
|
|
308
|
+
});
|
|
309
|
+
const location = new URL(response.headers.get('location') ?? '/', 'https://' + host);
|
|
310
|
+
await response.body?.cancel();
|
|
311
|
+
protectedHost =
|
|
312
|
+
response.status === 302 &&
|
|
313
|
+
location.protocol === 'https:' &&
|
|
314
|
+
location.hostname === access.teamName + '.cloudflareaccess.com' &&
|
|
315
|
+
location.pathname.startsWith('/cdn-cgi/access/login/' + host);
|
|
316
|
+
if (protectedHost) break;
|
|
317
|
+
} catch {}
|
|
318
|
+
await sleep(1000);
|
|
319
|
+
}
|
|
320
|
+
if (!protectedHost)
|
|
321
|
+
throw Error('未确认公网入口已启用 Cloudflare Access,请检查域名、证书及 Allow 应用');
|
|
322
|
+
for (const old of previous) await remove(old);
|
|
323
|
+
assertCurrent();
|
|
324
|
+
active.set(host, {
|
|
325
|
+
project,
|
|
326
|
+
host,
|
|
327
|
+
port,
|
|
328
|
+
lastAccess: Date.now(),
|
|
329
|
+
idleMs: Number(idle) * 60000,
|
|
330
|
+
clients: new Set(),
|
|
331
|
+
});
|
|
332
|
+
return { host };
|
|
333
|
+
} catch (error) {
|
|
334
|
+
try {
|
|
335
|
+
await remove(record);
|
|
336
|
+
} catch (cleanup) {
|
|
337
|
+
throw Error(error.message + ';待重试清理:' + cleanup.message);
|
|
338
|
+
}
|
|
339
|
+
throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
function serial(operation) {
|
|
343
|
+
busy++;
|
|
344
|
+
const result = queue.then(operation);
|
|
345
|
+
queue = result
|
|
346
|
+
.catch(() => {})
|
|
347
|
+
.finally(() => {
|
|
348
|
+
busy--;
|
|
349
|
+
});
|
|
350
|
+
return result;
|
|
351
|
+
}
|
|
352
|
+
const admin = http.createServer(async (req, res) => {
|
|
353
|
+
controlRequests++;
|
|
354
|
+
try {
|
|
355
|
+
const message = await readBody(req);
|
|
356
|
+
if (message.action === 'close') {
|
|
357
|
+
revocations.set(message.project, (revocations.get(message.project) ?? 0) + 1);
|
|
358
|
+
for (const route of active.values()) if (route.project === message.project) revoke(route);
|
|
359
|
+
}
|
|
360
|
+
const generation = revocations.get(message.project);
|
|
361
|
+
const result =
|
|
362
|
+
message.action === 'status'
|
|
363
|
+
? await handle(message)
|
|
364
|
+
: await serial(() => handle(message, generation));
|
|
365
|
+
res.end(JSON.stringify(result));
|
|
366
|
+
} catch (error) {
|
|
367
|
+
res.end(JSON.stringify({ error: error.message }));
|
|
368
|
+
} finally {
|
|
369
|
+
controlRequests--;
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
admin.listen(socket);
|
|
373
|
+
const initial = configuration();
|
|
374
|
+
if (initial.ZONE_ID && initial.DNS_TOKEN)
|
|
375
|
+
credentials.set(initial.ZONE_ID, { DNS_TOKEN: initial.DNS_TOKEN });
|
|
376
|
+
const timer = setInterval(() => {
|
|
377
|
+
if (busy) return;
|
|
378
|
+
serial(async () => {
|
|
379
|
+
for (const record of [...records]) {
|
|
380
|
+
const route = active.get(record.host);
|
|
381
|
+
if (route && Date.now() - route.lastAccess < route.idleMs) continue;
|
|
382
|
+
if (credentials.has(record.zone)) {
|
|
383
|
+
try {
|
|
384
|
+
await remove(record);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
console.error(error.message);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (controlRequests) return;
|
|
391
|
+
if (!active.size && connector) connector.kill();
|
|
392
|
+
if (!records.length) {
|
|
393
|
+
clearInterval(timer);
|
|
394
|
+
admin.close();
|
|
395
|
+
router.close();
|
|
396
|
+
}
|
|
397
|
+
}).catch((error) => console.error(error.message));
|
|
398
|
+
}, 15000);
|
|
399
|
+
process.on('exit', () => connector?.kill());
|
|
400
|
+
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => process.exit(0));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function main() {
|
|
404
|
+
if (command === 'serve') return serve();
|
|
405
|
+
if (command === 'connector') {
|
|
406
|
+
// A broken parent pipe also stops cloudflared after a router crash.
|
|
407
|
+
const child = spawn(
|
|
408
|
+
'cloudflared',
|
|
409
|
+
[
|
|
410
|
+
'tunnel',
|
|
411
|
+
'--no-autoupdate',
|
|
412
|
+
'--metrics',
|
|
413
|
+
'127.0.0.1:24752',
|
|
414
|
+
'--pidfile',
|
|
415
|
+
path.join(directory, 'connector.pid'),
|
|
416
|
+
'run',
|
|
417
|
+
],
|
|
418
|
+
{ stdio: 'ignore' },
|
|
419
|
+
);
|
|
420
|
+
child.once('spawn', () => process.send?.(child.pid));
|
|
421
|
+
child.once('error', () => process.exit(1));
|
|
422
|
+
child.once('close', (code) => process.exit(code ?? 0));
|
|
423
|
+
process.stdin.resume().once('end', () => child.kill());
|
|
424
|
+
process.once('disconnect', () => child.kill());
|
|
425
|
+
process.once('SIGTERM', () => child.kill());
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const config = command === 'status' ? {} : configuration();
|
|
429
|
+
if (command === 'mode') {
|
|
430
|
+
if (!keys.some((key) => config[key])) return console.log('quick');
|
|
431
|
+
validate(config);
|
|
432
|
+
return console.log('named');
|
|
433
|
+
}
|
|
434
|
+
if (!['status', 'close', 'open'].includes(command)) throw Error('未知操作');
|
|
435
|
+
if (command === 'open') validate(config);
|
|
436
|
+
try {
|
|
437
|
+
return console.log(await control(command, config));
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (!['ENOENT', 'ECONNREFUSED'].includes(error.code)) throw error;
|
|
440
|
+
}
|
|
441
|
+
if (command === 'status' || (command === 'close' && !fs.existsSync(ledger))) return;
|
|
442
|
+
if (
|
|
443
|
+
command === 'close' &&
|
|
444
|
+
!JSON.parse(fs.readFileSync(ledger, 'utf8')).some((r) => r.project === project)
|
|
445
|
+
)
|
|
446
|
+
return;
|
|
447
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
448
|
+
const log = fs.openSync(path.join(directory, 'router.log'), 'a', 0o600);
|
|
449
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'serve'], {
|
|
450
|
+
detached: true,
|
|
451
|
+
stdio: ['ignore', 'ignore', log],
|
|
452
|
+
env: {
|
|
453
|
+
...tunnelEnv,
|
|
454
|
+
NODE_USE_ENV_PROXY: process.env.NODE_USE_ENV_PROXY ?? '1',
|
|
455
|
+
// 指标探测与转发到本机报告的请求始终走回环地址。
|
|
456
|
+
no_proxy: [tunnelEnv.no_proxy || tunnelEnv.NO_PROXY, '127.0.0.1'].filter(Boolean).join(','),
|
|
457
|
+
},
|
|
458
|
+
});
|
|
459
|
+
child.unref();
|
|
460
|
+
fs.closeSync(log);
|
|
461
|
+
for (let attempt = 0; attempt < 40; attempt++) {
|
|
462
|
+
await sleep(100);
|
|
463
|
+
try {
|
|
464
|
+
return console.log(await control(command, config));
|
|
465
|
+
} catch (error) {
|
|
466
|
+
if (!['ENOENT', 'ECONNREFUSED'].includes(error.code)) throw error;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
throw Error(
|
|
470
|
+
'本机路由器无法启动,请检查 127.0.0.1:' + routerPort + ' 和 ' + directory + '/router.log',
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
main().catch((error) => {
|
|
475
|
+
console.error(error.message);
|
|
476
|
+
process.exitCode = 1;
|
|
477
|
+
});
|
|
@@ -36,7 +36,13 @@ sha1() { if command -v sha1sum >/dev/null; then sha1sum; else shasum -a 1; fi; }
|
|
|
36
36
|
S="evidra-$(basename "$ROOT" | tr -cd 'A-Za-z0-9_-')-$(printf '%s' "$ROOT" | sha1 | cut -c1-6)"
|
|
37
37
|
|
|
38
38
|
# 先撤销公网分享,即使后续启动内网报告失败,公网入口也已关闭。
|
|
39
|
-
|
|
39
|
+
SKILL_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
|
40
|
+
named=(node "$SKILL_DIR/scripts/named-tunnel.mjs")
|
|
41
|
+
public_mode=
|
|
42
|
+
if [[ $mode == public ]]; then
|
|
43
|
+
public_mode=$("${named[@]}" mode)
|
|
44
|
+
fi
|
|
45
|
+
if [[ $mode == lan || $public_mode == named ]]; then
|
|
40
46
|
for win in tunnel watch; do
|
|
41
47
|
if error=$(LC_ALL=C tmux kill-window -t "=$S:=$win" 2>&1); then continue; fi
|
|
42
48
|
case $error in
|
|
@@ -46,10 +52,13 @@ if [[ $mode == lan ]]; then
|
|
|
46
52
|
done
|
|
47
53
|
fi
|
|
48
54
|
|
|
55
|
+
if [[ $mode == lan || $public_mode == quick ]]; then
|
|
56
|
+
"${named[@]}" close "$ROOT" >/dev/null
|
|
57
|
+
fi
|
|
58
|
+
|
|
49
59
|
for cmd in node curl openssl; do
|
|
50
60
|
command -v "$cmd" >/dev/null || die "未安装 $cmd"
|
|
51
61
|
done
|
|
52
|
-
SKILL_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
|
53
62
|
TMP=$(mktemp -d)
|
|
54
63
|
trap 'rm -rf "$TMP"' EXIT
|
|
55
64
|
|
|
@@ -139,15 +148,22 @@ LOCAL=http://127.0.0.1:$PORT
|
|
|
139
148
|
json() {
|
|
140
149
|
node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.stdout.write(String(JSON.parse(s)[process.argv[1]]??""))}catch{}})' "$1"
|
|
141
150
|
}
|
|
142
|
-
is_401() { [[ $(curl
|
|
151
|
+
is_401() { [[ $(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$@") == 401 ]]; }
|
|
143
152
|
|
|
144
153
|
# 窗口存在且其中进程未退出
|
|
145
154
|
alive() { [[ $(tmux display-message -p -t "=$S:=$1" '#{pane_dead}' 2>/dev/null) == 0 ]]; }
|
|
146
155
|
# 在会话 S 的窗口 $1 中运行命令:缺窗口就新建,已有窗口则替换其中的进程。
|
|
147
156
|
# 进程退出后窗口保留(remain-on-exit)便于查看报错,下次运行时重新启动。
|
|
148
157
|
run_in() {
|
|
149
|
-
local win=$1
|
|
158
|
+
local win=$1 key
|
|
159
|
+
local -a pane_env=(-e "PATH=$PATH")
|
|
150
160
|
shift
|
|
161
|
+
if [[ $win == tunnel ]]; then
|
|
162
|
+
# tmux 服务可能早已启动,把当前 shell 的代理设置传给新隧道。
|
|
163
|
+
for key in HTTP_PROXY http_proxy HTTPS_PROXY https_proxy ALL_PROXY all_proxy NO_PROXY no_proxy; do
|
|
164
|
+
if [[ -n ${!key+x} ]]; then pane_env+=(-e "$key=${!key}"); fi
|
|
165
|
+
done
|
|
166
|
+
fi
|
|
151
167
|
if ! tmux has-session -t "=$S" 2>/dev/null; then
|
|
152
168
|
tmux new-session -d -s "$S" -n "$win"
|
|
153
169
|
elif ! tmux list-panes -t "=$S:=$win" >/dev/null 2>&1; then
|
|
@@ -156,7 +172,7 @@ run_in() {
|
|
|
156
172
|
tmux set-option -w -t "=$S:=$win" remain-on-exit on
|
|
157
173
|
# 多个参数时 tmux 直接执行,不经过用户 shell(zsh 会把 =会话:=窗口 当作命令路径展开)。
|
|
158
174
|
# 传入当前 PATH:tmux 服务可能早已在别的环境中启动,找不到 nvm 的 node 或刚装的 cloudflared。
|
|
159
|
-
tmux respawn-pane -k
|
|
175
|
+
tmux respawn-pane -k "${pane_env[@]}" -t "=$S:=$win" "$@"
|
|
160
176
|
}
|
|
161
177
|
# 失败时打印窗口最后的输出并退出
|
|
162
178
|
fail_in() {
|
|
@@ -174,7 +190,7 @@ login_repo_root() {
|
|
|
174
190
|
start_report() {
|
|
175
191
|
run_in report "${BIN[@]}" start --repo "$ROOT" --port "$PORT" --password "$PASSWORD"
|
|
176
192
|
local deadline=$((SECONDS + 60))
|
|
177
|
-
until is_401 "$LOCAL/api/project"; do
|
|
193
|
+
until is_401 --noproxy '*' "$LOCAL/api/project"; do
|
|
178
194
|
alive report && ((SECONDS < deadline)) || fail_in report "Evidra 未能在 60 秒内启动"
|
|
179
195
|
sleep 0.5
|
|
180
196
|
done
|
|
@@ -283,6 +299,11 @@ try {
|
|
|
283
299
|
NODE
|
|
284
300
|
}
|
|
285
301
|
if [[ $mode == default ]]; then
|
|
302
|
+
HOST=$("${named[@]}" status "$ROOT")
|
|
303
|
+
if [[ -n $HOST ]]; then
|
|
304
|
+
print_addresses "https://$HOST/" 复用
|
|
305
|
+
exit 0
|
|
306
|
+
fi
|
|
286
307
|
if [[ -s $STATE/metrics-port ]]; then
|
|
287
308
|
MPORT=$(<"$STATE/metrics-port")
|
|
288
309
|
HOST=$(quick_host)
|
|
@@ -296,16 +317,21 @@ if [[ $mode == default ]]; then
|
|
|
296
317
|
exit 0
|
|
297
318
|
fi
|
|
298
319
|
|
|
299
|
-
#
|
|
320
|
+
# Named Tunnel 的进程由本机路由器共用,各项目独立换址和回收。
|
|
321
|
+
if [[ $public_mode == named ]]; then
|
|
322
|
+
HOST=$("${named[@]}" open "$ROOT" "$PORT")
|
|
323
|
+
print_addresses "https://$HOST/" 新地址
|
|
324
|
+
exit 0
|
|
325
|
+
fi
|
|
326
|
+
|
|
327
|
+
# 3. 临时公网隧道
|
|
300
328
|
pick_port metrics-port 20241
|
|
301
329
|
MPORT=$(<"$STATE/metrics-port")
|
|
302
330
|
HOST=$(quick_host)
|
|
303
331
|
if alive tunnel && [[ -n $HOST ]]; then
|
|
304
332
|
TAG=复用
|
|
305
333
|
else
|
|
306
|
-
|
|
307
|
-
run_in tunnel env -u HTTP_PROXY -u http_proxy -u HTTPS_PROXY -u https_proxy -u ALL_PROXY -u all_proxy \
|
|
308
|
-
cloudflared tunnel --no-autoupdate --url "$LOCAL" --metrics "127.0.0.1:$MPORT"
|
|
334
|
+
run_in tunnel cloudflared tunnel --no-autoupdate --url "$LOCAL" --metrics "127.0.0.1:$MPORT"
|
|
309
335
|
HOST= deadline=$((SECONDS + 90))
|
|
310
336
|
until [[ -n $HOST ]] && quick_ready; do
|
|
311
337
|
alive tunnel && ((SECONDS < deadline)) || fail_in tunnel "公网隧道未能在 90 秒内就绪"
|
|
@@ -71,7 +71,10 @@ case $status in
|
|
|
71
71
|
esac
|
|
72
72
|
|
|
73
73
|
public_status="未开启"
|
|
74
|
-
|
|
74
|
+
host=$(node "$(dirname "${BASH_SOURCE[0]}")/named-tunnel.mjs" status "$ROOT")
|
|
75
|
+
if [[ -n $host ]]; then
|
|
76
|
+
public_status="https://$host/"
|
|
77
|
+
elif [[ -s $STATE/metrics-port ]] && command -v tmux >/dev/null; then
|
|
75
78
|
if [[ $(tmux display-message -p -t "=$S:=tunnel" '#{pane_dead}' 2>/dev/null || true) == 0 ]]; then
|
|
76
79
|
MPORT=$(<"$STATE/metrics-port")
|
|
77
80
|
HOST=$(curl --noproxy '*' -fsS --max-time 2 "http://127.0.0.1:$MPORT/quicktunnel" 2>/dev/null | json hostname || true)
|