dsh-design-studio 0.26.0 → 0.28.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/README.en.md +1 -1
- package/README.md +1 -1
- package/lib/browser.js +19 -0
- package/lib/client.js +334 -14
- package/lib/handoff.js +4 -2
- package/lib/htmlpack.js +693 -0
- package/lib/index.js +165 -11
- package/lib/serve.js +1 -1
- package/lib/tunnel.js +598 -0
- package/package.json +1 -1
package/lib/tunnel.js
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 公网链接(#27,实验):把「整套 HTML 演示」(htmlpack.js)临时放到公网上,发到微信里对方点开就能看、能点着换屏。
|
|
3
|
+
*
|
|
4
|
+
* - 只放这一份演示:本机开一个只认一个地址的小服务(127.0.0.1,路径里带随机口令),不碰预览服务器、不列目录;
|
|
5
|
+
* 别的地址、别的请求方法一律回同一个 404
|
|
6
|
+
* - 通道用用户自己装的 cloudflared(Cloudflare 的临时通道,不用账号、不经过我们的服务器),链接形如
|
|
7
|
+
* https://xxx.trycloudflare.com/<口令>
|
|
8
|
+
* - 默认 2 小时自动关;右侧栏能随时关;关掉马上断:杀掉通道进程、关掉小服务和它的连接
|
|
9
|
+
* - 插件自己每 5 秒看一眼(有人打开时也看):到点了、这个会话换了设计 → 关;cloudflared 和 Cloudflare 断了
|
|
10
|
+
* (它自己会重连,链接不变)→ 右侧栏说「正在重连」,90 秒还没连回来 → 关
|
|
11
|
+
* - 对方每次打开都是最新的:文件改了才重新打包(按文件的修改时间和大小),没改回 304
|
|
12
|
+
* - cloudflared 不直接由插件起,而是由一个小看门进程起:插件(DSH)被强行关掉时,看门进程的 stdin 断了,
|
|
13
|
+
* 顺手把 cloudflared 也杀掉——不然公网链接会一直指着本机那个端口,端口被别的程序占了就把别的程序暴露出去
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto'
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import http from 'node:http'
|
|
19
|
+
import os from 'node:os'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import zlib from 'node:zlib'
|
|
22
|
+
import { spawn, execFile } from 'node:child_process'
|
|
23
|
+
import { pipeline } from 'node:stream/promises'
|
|
24
|
+
|
|
25
|
+
export const TTL_MS = 2 * 60 * 60 * 1000
|
|
26
|
+
const READY_MS = 60 * 1000
|
|
27
|
+
const CHECK_MS = 1500 // 两次请求之间至少隔这么久才再看一眼文件改没改
|
|
28
|
+
const FAIL_MS = 5000 // 打包失败后这么久之内直接回「暂时打不开」,不每个请求都重打一遍
|
|
29
|
+
const GUARD_MS = 5000 // 多久看一眼:到点没有、换没换设计、通道还连着没有
|
|
30
|
+
const DROP_MS = 90 * 1000 // 通道断了这么久还没连回来 → 关
|
|
31
|
+
const DL_IDLE_MS = 30 * 1000 // 下载这么久没收到一个字节 → 放弃
|
|
32
|
+
// 临时通道的地址:api.trycloudflare.com 是申请通道用的,不是给人看的
|
|
33
|
+
export const URL_RE = /https:\/\/(?!api\.)([a-z0-9-]+\.trycloudflare\.com)\b/i
|
|
34
|
+
const READY_RE = /Registered tunnel connection|Connection [0-9a-f-]+ registered/i
|
|
35
|
+
// cloudflared 自己的状态口(--metrics 127.0.0.1:0 让它挑端口,日志里说在哪);GET /ready 连着 Cloudflare 回 200
|
|
36
|
+
const METRICS_RE = /metrics server on (127\.0\.0\.1:\d+)/i
|
|
37
|
+
// 看门进程第一行报 cloudflared 的 pid:只认行首、只认第一次(别被 cloudflared 输出里碰巧有的字骗去杀别的进程)
|
|
38
|
+
const PID_RE = /^ddp-tunnel-pid (\d+)\r?\n/m
|
|
39
|
+
// 插件自己的地方:下载的 cloudflared、给它的空配置
|
|
40
|
+
export const DATA_DIR = path.join(os.homedir(), '.dsh', 'cache', 'dsh-design-studio', 'pub')
|
|
41
|
+
const RELEASE = 'https://github.com/cloudflare/cloudflared/releases/latest/download/'
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 找 cloudflared:插件自己下的 → 「手机端」插件下的 → PATH → 常见的安装位置
|
|
45
|
+
* (从访达 / 开始菜单打开的 DSH,PATH 里往往没有 Homebrew 那些目录)
|
|
46
|
+
*/
|
|
47
|
+
export function findCloudflared({ env = process.env, platform = process.platform, exists = fs.existsSync, home = os.homedir(), own = platform === process.platform && home === os.homedir() ? DATA_DIR : '' } = {}) {
|
|
48
|
+
const P = platform === 'win32' ? path.win32 : path.posix
|
|
49
|
+
const exe = platform === 'win32' ? 'cloudflared.exe' : 'cloudflared'
|
|
50
|
+
const dirs = []
|
|
51
|
+
if (own) dirs.push(P.join(own, 'bin'))
|
|
52
|
+
dirs.push(P.join(home, '.dsh', 'dsh-mobile', 'bin'))
|
|
53
|
+
dirs.push(...String(env.PATH || env.Path || '').split(platform === 'win32' ? ';' : ':').filter(Boolean))
|
|
54
|
+
if (platform === 'win32') {
|
|
55
|
+
for (const pf of [env.ProgramFiles, env['ProgramFiles(x86)'], 'C:\\Program Files', 'C:\\Program Files (x86)']) if (pf) dirs.push(P.join(pf, 'cloudflared'))
|
|
56
|
+
if (env.LOCALAPPDATA) dirs.push(P.join(env.LOCALAPPDATA, 'Microsoft', 'WinGet', 'Links'))
|
|
57
|
+
dirs.push(P.join(home, 'scoop', 'shims'))
|
|
58
|
+
} else {
|
|
59
|
+
dirs.push('/opt/homebrew/bin', '/usr/local/bin', P.join(home, '.local', 'bin'), P.join(home, 'bin'), '/usr/bin', '/snap/bin')
|
|
60
|
+
}
|
|
61
|
+
for (const d of dirs) {
|
|
62
|
+
const f = P.join(d, exe)
|
|
63
|
+
try { if (exists(f)) return f } catch { /* 读不了的目录 */ }
|
|
64
|
+
}
|
|
65
|
+
return ''
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 这台机器该下哪个文件(和「手机端」插件同一份);不支持给 null */
|
|
69
|
+
export function assetFor(platform = process.platform, arch = process.arch) {
|
|
70
|
+
const a = { x64: 'amd64', arm64: 'arm64', ia32: '386', arm: 'arm' }[arch]
|
|
71
|
+
if (!a) return null
|
|
72
|
+
if (platform === 'darwin' && (a === 'amd64' || a === 'arm64')) return { name: `cloudflared-darwin-${a}.tgz`, tgz: true }
|
|
73
|
+
if (platform === 'linux') return { name: `cloudflared-linux-${a}`, tgz: false }
|
|
74
|
+
if (platform === 'win32' && (a === 'amd64' || a === '386')) return { name: `cloudflared-windows-${a}.exe`, tgz: false }
|
|
75
|
+
// Windows on ARM 没有原生版:用 x64 的(系统自带转译)
|
|
76
|
+
if (platform === 'win32' && a === 'arm64') return { name: 'cloudflared-windows-amd64.exe', tgz: false }
|
|
77
|
+
return null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 用户点了「下载」才下:Cloudflare 官方 GitHub 发布的最新版,放进插件自己的目录(不碰系统目录、不要管理员权限)。
|
|
82
|
+
* @param onProgress ({ got, total }) => void
|
|
83
|
+
* @param signal 取消(右侧栏点了「取消」)
|
|
84
|
+
* @param idleMs 这么久一个字节都没收到就放弃(国内连 GitHub 常常卡住不动)
|
|
85
|
+
* @returns 可执行文件路径
|
|
86
|
+
*/
|
|
87
|
+
export async function downloadCloudflared({ dir = path.join(DATA_DIR, 'bin'), onProgress = () => {}, fetchImpl = globalThis.fetch, platform = process.platform, arch = process.arch, signal = null, idleMs = DL_IDLE_MS } = {}) {
|
|
88
|
+
const asset = assetFor(platform, arch)
|
|
89
|
+
if (!asset) throw Object.assign(new Error(`no cloudflared build for ${platform}/${arch}`), { code: 'unsupported' })
|
|
90
|
+
const ac = new AbortController()
|
|
91
|
+
const onAbort = () => ac.abort(Object.assign(new Error('cancelled'), { code: 'cancelled' }))
|
|
92
|
+
if (signal) { if (signal.aborted) onAbort(); else signal.addEventListener('abort', onAbort, { once: true }) }
|
|
93
|
+
let idle = null
|
|
94
|
+
const kick = () => {
|
|
95
|
+
clearTimeout(idle)
|
|
96
|
+
idle = setTimeout(() => ac.abort(Object.assign(new Error('stalled'), { code: 'stalled' })), idleMs) // 下完 / 出错都会清掉
|
|
97
|
+
}
|
|
98
|
+
// 卡住时不管 fetch 认不认 signal 都要停下:和「被取消」赛跑
|
|
99
|
+
const aborted = new Promise((_r, reject) => ac.signal.addEventListener('abort', () => reject(ac.signal.reason), { once: true }))
|
|
100
|
+
aborted.catch(() => {})
|
|
101
|
+
const race = (p) => Promise.race([p, aborted])
|
|
102
|
+
const rand = crypto.randomBytes(4).toString('hex') // 取消后马上重下:两次的临时文件别撞上
|
|
103
|
+
const tmp = path.join(dir, `.${asset.name}.${process.pid}.${rand}.part`)
|
|
104
|
+
const unpack = path.join(dir, `.unpack.${process.pid}.${rand}`)
|
|
105
|
+
let out = null
|
|
106
|
+
try {
|
|
107
|
+
kick()
|
|
108
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
109
|
+
const res = await race(fetchImpl(RELEASE + asset.name, { redirect: 'follow', signal: ac.signal }))
|
|
110
|
+
if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`)
|
|
111
|
+
const total = Number(res.headers.get('content-length')) || 0
|
|
112
|
+
let got = 0
|
|
113
|
+
out = fs.createWriteStream(tmp, { mode: 0o755 })
|
|
114
|
+
// pipeline:写盘出错、正文中途断了、卡住、取消都走到 catch(不会冒成没人接的 error 事件)
|
|
115
|
+
await race(pipeline(async function* () {
|
|
116
|
+
for await (const chunk of res.body) {
|
|
117
|
+
if (ac.signal.aborted) throw ac.signal.reason
|
|
118
|
+
kick()
|
|
119
|
+
got += chunk.length
|
|
120
|
+
onProgress({ got, total })
|
|
121
|
+
yield chunk
|
|
122
|
+
}
|
|
123
|
+
}, out, { signal: ac.signal }))
|
|
124
|
+
} catch (e) {
|
|
125
|
+
if (!ac.signal.aborted) ac.abort(e) // 让还在读的正文也停下
|
|
126
|
+
if (out && !out.closed) { out.destroy(); await new Promise((r) => out.once('close', r)) }
|
|
127
|
+
try { fs.unlinkSync(tmp) } catch { /* 没写出来 */ }
|
|
128
|
+
clearTimeout(idle)
|
|
129
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
130
|
+
throw ac.signal.reason && ac.signal.reason.code ? ac.signal.reason : e
|
|
131
|
+
}
|
|
132
|
+
clearTimeout(idle)
|
|
133
|
+
const target = path.join(dir, platform === 'win32' ? 'cloudflared.exe' : 'cloudflared')
|
|
134
|
+
try {
|
|
135
|
+
// 先解到旁边的临时目录:解包时点了「取消」就不装上
|
|
136
|
+
let file = tmp
|
|
137
|
+
if (asset.tgz) {
|
|
138
|
+
fs.mkdirSync(unpack, { recursive: true, mode: 0o700 })
|
|
139
|
+
await new Promise((resolve, reject) => execFile('tar', ['-xzf', tmp, '-C', unpack, 'cloudflared'], (e) => (e ? reject(e) : resolve())))
|
|
140
|
+
file = path.join(unpack, 'cloudflared')
|
|
141
|
+
}
|
|
142
|
+
if (ac.signal.aborted) throw ac.signal.reason
|
|
143
|
+
fs.chmodSync(file, 0o755)
|
|
144
|
+
fs.renameSync(file, target)
|
|
145
|
+
} finally {
|
|
146
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
147
|
+
try { fs.unlinkSync(tmp) } catch { /* 已经挪走了 */ }
|
|
148
|
+
try { fs.rmSync(unpack, { recursive: true, force: true }) } catch { /* 没解 */ }
|
|
149
|
+
}
|
|
150
|
+
return target
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 给 cloudflared 一个空配置:用户自己的 ~/.cloudflared/config.yml 不该影响临时通道。放插件自己的目录(不放共享的临时目录) */
|
|
154
|
+
function emptyConfig(dir = DATA_DIR) {
|
|
155
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
156
|
+
const f = path.join(dir, 'cloudflared.yml')
|
|
157
|
+
fs.writeFileSync(f, '{}\n', { mode: 0o600 })
|
|
158
|
+
return f
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// 看门进程:起 cloudflared,告诉插件它的 pid;自己的 stdin 一断(插件没了、或者插件让关)就把它杀掉再退出
|
|
162
|
+
const WATCHDOG = `
|
|
163
|
+
const { spawn } = require('child_process')
|
|
164
|
+
const [bin, ...args] = JSON.parse(process.argv[1])
|
|
165
|
+
let c
|
|
166
|
+
try { c = spawn(bin, args, { stdio: ['ignore', 'inherit', 'inherit'], windowsHide: true }) } catch (e) { console.error('ddp-watchdog-error ' + e.message); process.exit(127) }
|
|
167
|
+
c.on('error', (e) => { console.error('ddp-watchdog-error ' + e.message); process.exit(127) })
|
|
168
|
+
if (c.pid) console.error('ddp-tunnel-pid ' + c.pid)
|
|
169
|
+
let ending = false
|
|
170
|
+
const end = () => {
|
|
171
|
+
if (ending) return
|
|
172
|
+
ending = true
|
|
173
|
+
try { c.kill() } catch {}
|
|
174
|
+
setTimeout(() => { try { c.kill('SIGKILL') } catch {} process.exit(0) }, 2000).unref()
|
|
175
|
+
}
|
|
176
|
+
c.on('exit', (code) => process.exit(ending ? 0 : code == null ? 1 : code))
|
|
177
|
+
process.stdin.on('end', end)
|
|
178
|
+
process.stdin.on('close', end)
|
|
179
|
+
process.stdin.on('error', end)
|
|
180
|
+
process.on('SIGTERM', end)
|
|
181
|
+
process.on('SIGINT', end)
|
|
182
|
+
process.stdin.resume()
|
|
183
|
+
`
|
|
184
|
+
|
|
185
|
+
/** 起看门进程(DSH 里 process.execPath 是 Electron:要按 Node 跑) */
|
|
186
|
+
export function launchWatched(bin, args, { execPath = process.execPath, env = process.env } = {}) {
|
|
187
|
+
return spawn(execPath, ['-e', WATCHDOG, JSON.stringify([bin, ...args])], {
|
|
188
|
+
env: { ...env, ELECTRON_RUN_AS_NODE: '1' },
|
|
189
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
190
|
+
windowsHide: true,
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const PAGE = (title, text) => `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${title}</title>
|
|
195
|
+
<style>body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font:16px/1.6 -apple-system,system-ui,sans-serif;color:#555;background:#f5f5f7;text-align:center;padding:24px;box-sizing:border-box}b{display:block;color:#111;font-size:18px;margin-bottom:6px}</style>
|
|
196
|
+
</head><body><div><b>${title}</b>${text}</div></body></html>`
|
|
197
|
+
const NOT_FOUND = PAGE('链接失效了 / Link expired', '这个链接已经关了,或者地址不对。<br>This link has been closed or is wrong.')
|
|
198
|
+
const BUSY = PAGE('暂时打不开 / Not available', '过一会儿再刷新试试。<br>Please refresh in a moment.')
|
|
199
|
+
|
|
200
|
+
const SAFE_HEADERS = {
|
|
201
|
+
'Referrer-Policy': 'no-referrer', // 页面里的外网字体、链接不带上通道地址(口令在路径里)
|
|
202
|
+
'X-Robots-Tag': 'noindex, nofollow, noarchive',
|
|
203
|
+
'X-Content-Type-Options': 'nosniff',
|
|
204
|
+
'X-Frame-Options': 'DENY',
|
|
205
|
+
// 不加 CSP:每屏是 srcdoc 的 iframe,会继承外层的 CSP,页面里的内联脚本就全跑不了了
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 问 cloudflared 自己的状态口:还连着 Cloudflare 吗(连不上状态口也算没连着) */
|
|
209
|
+
function probeReady(addr, timeoutMs = 3000) {
|
|
210
|
+
const [host, port] = String(addr).split(':')
|
|
211
|
+
return new Promise((resolve) => {
|
|
212
|
+
const req = http.get({ host, port: Number(port), path: '/ready', timeout: timeoutMs, agent: false }, (res) => {
|
|
213
|
+
res.resume()
|
|
214
|
+
resolve(res.statusCode === 200)
|
|
215
|
+
})
|
|
216
|
+
req.on('timeout', () => { req.destroy(); resolve(false) })
|
|
217
|
+
req.on('error', () => resolve(false))
|
|
218
|
+
})
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* @param opts.build (params) → { html, deps: [绝对路径…] },打不出来就抛错
|
|
223
|
+
* @param opts.find () → cloudflared 的路径,没有给 ''
|
|
224
|
+
* @param opts.launch (bin, args) → 子进程(默认带看门进程)
|
|
225
|
+
* @param opts.alive (session, params) → 这个会话现在看的还是不是这个设计;不是了就关
|
|
226
|
+
* @param opts.probe (127.0.0.1:端口) → Promise<bool> 通道还连着 Cloudflare 没有
|
|
227
|
+
*/
|
|
228
|
+
export function createPublicShare({ build, find = () => findCloudflared(), launch = launchWatched, config = emptyConfig, download = downloadCloudflared, alive = () => true, probe = probeReady, log = () => {}, now = Date.now, ttlMs = TTL_MS, readyMs = READY_MS, guardMs = GUARD_MS, dropMs = DROP_MS } = {}) {
|
|
229
|
+
const shares = new Map() // session → share
|
|
230
|
+
const ended = new Map() // session → 上一次是怎么关的(到点 / 断了 / 起不来 / 换了设计),给右侧栏说一声
|
|
231
|
+
let dl = null // 正在下 / 下完的 cloudflared:{ got, total, done, error }
|
|
232
|
+
let dlAbort = null
|
|
233
|
+
|
|
234
|
+
/** 下载 cloudflared(已经在下就不重复下);状态在 status().dl 里 */
|
|
235
|
+
function fetchTool() {
|
|
236
|
+
if (dl && !dl.done) return dl
|
|
237
|
+
dl = { got: 0, total: 0, done: false, error: '' }
|
|
238
|
+
const me = dl
|
|
239
|
+
const ac = new AbortController()
|
|
240
|
+
dlAbort = ac
|
|
241
|
+
Promise.resolve().then(() => download({ signal: ac.signal, onProgress: ({ got, total }) => { me.got = got; me.total = total } }))
|
|
242
|
+
.then(() => { me.done = true })
|
|
243
|
+
.catch((e) => {
|
|
244
|
+
log(e)
|
|
245
|
+
me.done = true
|
|
246
|
+
me.error = e.code === 'unsupported' || e.code === 'stalled' || e.code === 'cancelled' ? e.code : String(e.message || e).slice(0, 160)
|
|
247
|
+
})
|
|
248
|
+
.finally(() => { if (dlAbort === ac) dlAbort = null })
|
|
249
|
+
return me
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** 右侧栏点了「取消下载」 */
|
|
253
|
+
function cancelTool() {
|
|
254
|
+
if (dlAbort) dlAbort.abort()
|
|
255
|
+
dlAbort = null
|
|
256
|
+
dl = null
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** 到点了、换了设计:给关掉的原因;还好好的给 null */
|
|
260
|
+
function gone(s) {
|
|
261
|
+
if (now() >= s.expires) return { ended: 'expired' }
|
|
262
|
+
let ok = true
|
|
263
|
+
try { ok = alive(s.session, s.params) !== false } catch (e) { log(e) }
|
|
264
|
+
return ok ? null : { ended: 'moved' }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** @param brief 只给开没开、什么状态(右侧栏每次刷新都带,别让次数、地址一变就重画) */
|
|
268
|
+
function status(session, { brief = false } = {}) {
|
|
269
|
+
let s = shares.get(session)
|
|
270
|
+
if (s) {
|
|
271
|
+
const why = gone(s)
|
|
272
|
+
if (why) { finish(session, why, s); s = null }
|
|
273
|
+
}
|
|
274
|
+
if (!s) {
|
|
275
|
+
let e = ended.get(session)
|
|
276
|
+
if (e && e.root !== undefined) {
|
|
277
|
+
// 打包失败记下的原因:只对那个设计说(插件本机路径不往外给)
|
|
278
|
+
let same = false
|
|
279
|
+
try { same = alive(session, { root: e.root }) !== false } catch (err) { log(err) }
|
|
280
|
+
if (!same) { ended.delete(session); e = null } else { const { root: _r, ...rest } = e; e = rest }
|
|
281
|
+
}
|
|
282
|
+
if (brief) return { on: false, ...(e && e.ended ? { ended: e.ended } : {}), ...(e && e.error ? { error: e.error } : {}) }
|
|
283
|
+
const d = dl ? { dl: { ...dl } } : {}
|
|
284
|
+
return e ? { on: false, ...e, ...d } : { on: false, ...d }
|
|
285
|
+
}
|
|
286
|
+
if (brief) return { on: true, state: s.state }
|
|
287
|
+
return {
|
|
288
|
+
on: true,
|
|
289
|
+
state: s.state, // starting | ready | reconnecting(cloudflared 和 Cloudflare 断了,在重连,链接不变)
|
|
290
|
+
url: s.state === 'starting' ? '' : s.url,
|
|
291
|
+
// 开着以后重新打包失败了(比如又加了很多图,超了上限):对方现在看到「暂时打不开」,右侧栏要说(打包成功了才清掉)
|
|
292
|
+
broken: s.broken,
|
|
293
|
+
screens: s.labels, // 放出去的是哪几屏(生成时那几屏,新加的屏不自动放出去)
|
|
294
|
+
expires: s.expires,
|
|
295
|
+
views: s.views,
|
|
296
|
+
name: s.name,
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** 每 5 秒:到点 / 换了设计 → 关;问 cloudflared 还连着没有,断了 90 秒 → 关 */
|
|
301
|
+
async function guard(s) {
|
|
302
|
+
if (shares.get(s.session) !== s) return
|
|
303
|
+
const why = gone(s)
|
|
304
|
+
if (why) return finish(s.session, why, s)
|
|
305
|
+
if (!s.metrics || s.probing || (s.state === 'starting' && !s.url)) return
|
|
306
|
+
s.probing = true
|
|
307
|
+
let ok = false
|
|
308
|
+
try { ok = await probe(s.metrics) } catch { ok = false } finally { s.probing = false }
|
|
309
|
+
if (shares.get(s.session) !== s) return
|
|
310
|
+
if (ok) {
|
|
311
|
+
// 还在「正在连」但状态口说连上了:也算连上(以后新版 cloudflared 改了日志措辞也不会一直卡在「正在连」)
|
|
312
|
+
if (s.state === 'starting') clearTimeout(s.readyTimer)
|
|
313
|
+
s.state = 'ready'
|
|
314
|
+
s.downSince = 0
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
if (s.state === 'starting') return // 还没连上过:交给 60 秒的超时
|
|
318
|
+
if (!s.downSince) s.downSince = now()
|
|
319
|
+
s.state = 'reconnecting'
|
|
320
|
+
if (now() - s.downSince >= dropMs) finish(s.session, { ended: 'dropped' }, s)
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* 开(已经开着就只换参数:屏、画幅、深浅色这些按右侧栏现在的)。
|
|
325
|
+
* @returns status;没装 cloudflared → { on: false, error: 'no-cloudflared' }
|
|
326
|
+
*/
|
|
327
|
+
async function start(session, params, { name = '' } = {}) {
|
|
328
|
+
const have = shares.get(session)
|
|
329
|
+
const why = have && gone(have)
|
|
330
|
+
if (why) finish(session, why, have) // 开着的早该关了(到点 / 换了设计):关掉重开
|
|
331
|
+
else if (have) {
|
|
332
|
+
update(session, params)
|
|
333
|
+
return status(session)
|
|
334
|
+
}
|
|
335
|
+
ended.delete(session)
|
|
336
|
+
const bin = find()
|
|
337
|
+
if (!bin) return { on: false, error: 'no-cloudflared' }
|
|
338
|
+
// 先打一次包:打不出来(屏都没了、太大)就别开通道
|
|
339
|
+
let first
|
|
340
|
+
try { first = pack(params) } catch (e) {
|
|
341
|
+
// 记着原因(右侧栏轮询别把它冲掉),换了设计就不提了
|
|
342
|
+
const why = { error: e.code || 'pack', message: e.message, root: params && params.root }
|
|
343
|
+
ended.set(session, why)
|
|
344
|
+
return status(session)
|
|
345
|
+
}
|
|
346
|
+
const s = {
|
|
347
|
+
session,
|
|
348
|
+
params,
|
|
349
|
+
name: String(name || '').slice(0, 80),
|
|
350
|
+
token: crypto.randomBytes(18).toString('base64url'),
|
|
351
|
+
state: 'starting',
|
|
352
|
+
url: '',
|
|
353
|
+
host: '',
|
|
354
|
+
port: 0,
|
|
355
|
+
views: 0,
|
|
356
|
+
started: now(),
|
|
357
|
+
expires: now() + ttlMs,
|
|
358
|
+
cache: first,
|
|
359
|
+
checkedAt: now(),
|
|
360
|
+
failAt: 0,
|
|
361
|
+
failErr: null,
|
|
362
|
+
broken: '',
|
|
363
|
+
// 只放生成时那几屏:之后同目录里新出现的网页(比如刚下载的别的文件)不自动加进链接
|
|
364
|
+
keys: Array.isArray(params && params.screens) ? new Set(params.screens.map((x) => x && x.key)) : null,
|
|
365
|
+
labels: Array.isArray(params && params.screens) ? params.screens.map((x) => String((x && (x.label || x.key)) || '').slice(0, 80)) : [],
|
|
366
|
+
sockets: new Set(),
|
|
367
|
+
out: '',
|
|
368
|
+
pid: 0,
|
|
369
|
+
metrics: '',
|
|
370
|
+
downSince: 0,
|
|
371
|
+
probing: false,
|
|
372
|
+
}
|
|
373
|
+
const server = http.createServer((req, res) => {
|
|
374
|
+
try { handle(s, req, res) } catch (e) {
|
|
375
|
+
log(e)
|
|
376
|
+
try { if (!res.headersSent) send(res, 500, BUSY); else res.destroy() } catch { /* 连接已经没了 */ }
|
|
377
|
+
}
|
|
378
|
+
})
|
|
379
|
+
server.on('connection', (c) => { s.sockets.add(c); c.on('close', () => s.sockets.delete(c)) })
|
|
380
|
+
server.on('clientError', (_e, c) => c.destroy())
|
|
381
|
+
server.on('error', (e) => log(e))
|
|
382
|
+
s.server = server
|
|
383
|
+
shares.set(session, s)
|
|
384
|
+
try {
|
|
385
|
+
await new Promise((resolve, reject) => {
|
|
386
|
+
server.once('error', reject)
|
|
387
|
+
server.listen(0, '127.0.0.1', () => resolve())
|
|
388
|
+
})
|
|
389
|
+
} catch (e) {
|
|
390
|
+
log(e)
|
|
391
|
+
finish(session, { error: 'listen', message: e.message })
|
|
392
|
+
return status(session)
|
|
393
|
+
}
|
|
394
|
+
if (shares.get(session) !== s) return status(session) // 等端口的时候被关了
|
|
395
|
+
s.port = server.address().port
|
|
396
|
+
let child
|
|
397
|
+
try {
|
|
398
|
+
// --protocol http2:默认的 QUIC 走 UDP,碰上代理 / 公司网络常常连不上
|
|
399
|
+
// --metrics 127.0.0.1:0:只在本机开它的状态口、端口它自己挑,插件靠它知道通道断没断
|
|
400
|
+
child = launch(bin, ['tunnel', '--no-autoupdate', '--protocol', 'http2', '--config', config(), '--metrics', '127.0.0.1:0', '--url', `http://127.0.0.1:${s.port}`])
|
|
401
|
+
} catch (e) {
|
|
402
|
+
finish(session, { error: 'tunnel', message: e.message })
|
|
403
|
+
return status(session)
|
|
404
|
+
}
|
|
405
|
+
s.child = child
|
|
406
|
+
const onOut = (buf) => {
|
|
407
|
+
s.out = (s.out + buf.toString('utf8')).slice(-8000)
|
|
408
|
+
if (!s.pid) {
|
|
409
|
+
const pid = PID_RE.exec(s.out)
|
|
410
|
+
if (pid) s.pid = Number(pid[1])
|
|
411
|
+
}
|
|
412
|
+
if (!s.metrics) {
|
|
413
|
+
const m = METRICS_RE.exec(s.out)
|
|
414
|
+
if (m) s.metrics = m[1]
|
|
415
|
+
}
|
|
416
|
+
if (!s.url) {
|
|
417
|
+
const m = URL_RE.exec(s.out)
|
|
418
|
+
if (m) { s.host = m[1].toLowerCase(); s.url = `https://${s.host}/${s.token}` }
|
|
419
|
+
}
|
|
420
|
+
if (s.url && s.state === 'starting' && READY_RE.test(s.out)) {
|
|
421
|
+
s.state = 'ready'
|
|
422
|
+
clearTimeout(s.readyTimer)
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
// 子进程、它的输出流出了错都接住:没人接的 error 事件会让整个 DSH 退出
|
|
426
|
+
if (child.stdout) { child.stdout.on('data', onOut); child.stdout.on('error', () => {}) }
|
|
427
|
+
if (child.stderr) { child.stderr.on('data', onOut); child.stderr.on('error', () => {}) }
|
|
428
|
+
if (child.stdin) child.stdin.on('error', () => {})
|
|
429
|
+
child.on('error', (e) => { log(e); if (shares.get(session) === s) finish(session, { error: 'tunnel', message: e.message }, s) })
|
|
430
|
+
child.on('exit', (code) => {
|
|
431
|
+
s.child = null
|
|
432
|
+
if (shares.get(session) !== s) return
|
|
433
|
+
// 看门进程自己没了(被系统、安全软件单独结束):cloudflared 没人管了,直接杀掉,别让它一直指着本机端口
|
|
434
|
+
if (s.pid) { try { process.kill(s.pid) } catch { /* 已经退了 */ } }
|
|
435
|
+
// 还没连上就退了:起不来(多半是网络连不上 Cloudflare,或者本机的 cloudflared 配置文件不对);连上以后退了:断了
|
|
436
|
+
finish(session, s.state === 'starting' ? { error: 'tunnel', message: lastError(s.out) || `exit ${code}` } : { ended: 'dropped' }, s)
|
|
437
|
+
})
|
|
438
|
+
s.readyTimer = setTimeout(() => {
|
|
439
|
+
if (shares.get(session) === s && s.state === 'starting') finish(session, { error: 'timeout', message: lastError(s.out) }, s)
|
|
440
|
+
}, readyMs)
|
|
441
|
+
s.ttlTimer = setTimeout(() => { if (shares.get(session) === s) finish(session, { ended: 'expired' }, s) }, ttlMs)
|
|
442
|
+
// 电脑睡着时定时器不走:醒来靠这个每 5 秒的检查补上(到点、换了设计、通道断了)
|
|
443
|
+
s.guardTimer = setInterval(() => { guard(s).catch((e) => log(e)) }, guardMs)
|
|
444
|
+
for (const tm of [s.readyTimer, s.ttlTimer, s.guardTimer]) if (tm.unref) tm.unref()
|
|
445
|
+
return status(session)
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** 右侧栏换了屏、画幅、深浅色:下次有人打开按新的打包 */
|
|
449
|
+
function update(session, params) {
|
|
450
|
+
const s = shares.get(session)
|
|
451
|
+
if (!s || !params) return false
|
|
452
|
+
if (s.params && params.root !== s.params.root) return false // 换了设计不跟着换:那是关掉(guard),不是悄悄换一份放出去
|
|
453
|
+
if (s.keys && Array.isArray(params.screens)) {
|
|
454
|
+
// 只认生成时那几屏(删掉的去掉,新加的不放);都没了就不换
|
|
455
|
+
const screens = params.screens.filter((x) => x && s.keys.has(x.key))
|
|
456
|
+
if (!screens.length) return false
|
|
457
|
+
params = { ...params, screens }
|
|
458
|
+
}
|
|
459
|
+
if (JSON.stringify(params) === JSON.stringify(s.params)) return true
|
|
460
|
+
s.params = params
|
|
461
|
+
s.labels = params.screens ? params.screens.map((x) => String(x.label || x.key || '').slice(0, 80)) : s.labels
|
|
462
|
+
s.cache = null
|
|
463
|
+
s.failAt = 0 // 参数变了马上重打;失败提示(broken)等打包成功才清
|
|
464
|
+
return true
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* 关:杀通道进程、关小服务、断开所有连接,旧链接马上失效
|
|
469
|
+
* @param only 只关这一个(迟到的定时器、退出事件别把同一会话新开的那个关了)
|
|
470
|
+
*/
|
|
471
|
+
function finish(session, why = {}, only = null) {
|
|
472
|
+
const s = shares.get(session)
|
|
473
|
+
if (!s || (only && s !== only)) return
|
|
474
|
+
shares.delete(session)
|
|
475
|
+
if (why.error || why.ended) ended.set(session, why)
|
|
476
|
+
clearTimeout(s.readyTimer)
|
|
477
|
+
clearTimeout(s.ttlTimer)
|
|
478
|
+
clearInterval(s.guardTimer)
|
|
479
|
+
const c = s.child
|
|
480
|
+
if (c) {
|
|
481
|
+
try { if (c.stdin) c.stdin.end() } catch { /* 已经断了 */ }
|
|
482
|
+
if (s.pid) { try { process.kill(s.pid) } catch { /* 已经退了 */ } }
|
|
483
|
+
// 看门进程收到 stdin 断了会自己收尾;万一它卡住,过一会儿再杀它(cloudflared 上面已经直接杀过)
|
|
484
|
+
const tm = setTimeout(() => { try { c.kill() } catch { /* 已经退了 */ } }, 5000)
|
|
485
|
+
if (tm.unref) tm.unref()
|
|
486
|
+
}
|
|
487
|
+
for (const sock of s.sockets) sock.destroy()
|
|
488
|
+
try { s.server.close() } catch { /* 没开起来 */ }
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function stop(session) {
|
|
492
|
+
ended.delete(session)
|
|
493
|
+
finish(session)
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
function stopAll() {
|
|
497
|
+
for (const k of [...shares.keys()]) finish(k)
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** 本机找不找得到 cloudflared(右侧栏开面板时问一下:没有就先说要下载) */
|
|
501
|
+
function hasTool() {
|
|
502
|
+
return !!find()
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ── 小服务 ──────────────────────────────────────────────────────────────
|
|
506
|
+
|
|
507
|
+
function pack(params) {
|
|
508
|
+
const r = build(params)
|
|
509
|
+
const html = Buffer.from(r.html, 'utf8')
|
|
510
|
+
return {
|
|
511
|
+
html,
|
|
512
|
+
gz: zlib.gzipSync(html, { level: 6 }),
|
|
513
|
+
etag: '"' + crypto.createHash('sha1').update(html).digest('base64url').slice(0, 22) + '"',
|
|
514
|
+
deps: (r.deps || []).map((f) => [f, sigOf(f)]),
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** 文件改了(或者新加 / 删了)就重新打包;两次请求挨得很近就不每次都去看文件;打不出来的一会儿之内不再重打 */
|
|
519
|
+
function current(s) {
|
|
520
|
+
if (!s.cache && s.failAt && now() - s.failAt < FAIL_MS) throw s.failErr
|
|
521
|
+
if (s.cache && now() - s.checkedAt < CHECK_MS) return s.cache
|
|
522
|
+
s.checkedAt = now()
|
|
523
|
+
if (s.cache && s.cache.deps.every(([f, sig]) => sigOf(f) === sig)) return s.cache
|
|
524
|
+
try {
|
|
525
|
+
s.cache = pack(s.params)
|
|
526
|
+
s.failAt = 0
|
|
527
|
+
s.broken = ''
|
|
528
|
+
} catch (e) {
|
|
529
|
+
s.cache = null
|
|
530
|
+
s.failAt = now()
|
|
531
|
+
s.failErr = e
|
|
532
|
+
s.broken = e.code || 'pack'
|
|
533
|
+
throw e
|
|
534
|
+
}
|
|
535
|
+
return s.cache
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function handle(s, req, res) {
|
|
539
|
+
const p = String(req.url || '').split('?')[0]
|
|
540
|
+
// 已经关了(迟到的请求)、到点了、这个会话换了设计:回 404,顺手关掉
|
|
541
|
+
const why = shares.get(s.session) === s ? gone(s) : { ended: '' }
|
|
542
|
+
if (why) {
|
|
543
|
+
if (why.ended) {
|
|
544
|
+
const end = () => finish(s.session, why, s)
|
|
545
|
+
res.once('finish', end)
|
|
546
|
+
res.once('close', end)
|
|
547
|
+
}
|
|
548
|
+
return send(res, 404, NOT_FOUND)
|
|
549
|
+
}
|
|
550
|
+
// 只认这一个地址(带不带结尾的 /),别的一律同一个 404
|
|
551
|
+
if ((req.method !== 'GET' && req.method !== 'HEAD') || (p !== '/' + s.token && p !== '/' + s.token + '/')) return send(res, 404, NOT_FOUND)
|
|
552
|
+
let c
|
|
553
|
+
try { c = current(s) } catch (e) {
|
|
554
|
+
log(e)
|
|
555
|
+
return send(res, 503, BUSY)
|
|
556
|
+
}
|
|
557
|
+
const headers = { ...SAFE_HEADERS, 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', ETag: c.etag, Vary: 'Accept-Encoding' }
|
|
558
|
+
if (String(req.headers['if-none-match'] || '') === c.etag) {
|
|
559
|
+
res.writeHead(304, headers)
|
|
560
|
+
return res.end()
|
|
561
|
+
}
|
|
562
|
+
if (req.method === 'GET') s.views++
|
|
563
|
+
const gz = /\bgzip\b/i.test(String(req.headers['accept-encoding'] || ''))
|
|
564
|
+
const body = gz ? c.gz : c.html
|
|
565
|
+
res.writeHead(200, { ...headers, ...(gz ? { 'Content-Encoding': 'gzip' } : {}), 'Content-Length': body.length })
|
|
566
|
+
res.end(req.method === 'HEAD' ? undefined : body)
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** 测试用:本机小服务的端口、口令、通道进程 */
|
|
570
|
+
function _inspect(session) {
|
|
571
|
+
const s = shares.get(session)
|
|
572
|
+
return s ? { port: s.port, token: s.token, pid: s.pid || 0, watchdog: s.child ? s.child.pid : 0, metrics: s.metrics } : null
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
return { start, update, stop, stopAll, status, fetchTool, cancelTool, hasTool, _inspect }
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function send(res, code, html) {
|
|
579
|
+
const body = Buffer.from(html, 'utf8')
|
|
580
|
+
res.writeHead(code, { ...SAFE_HEADERS, 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Length': body.length })
|
|
581
|
+
res.end(body)
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function sigOf(f) {
|
|
585
|
+
try {
|
|
586
|
+
const st = fs.statSync(f)
|
|
587
|
+
return `${st.size}:${Math.round(st.mtimeMs)}`
|
|
588
|
+
} catch {
|
|
589
|
+
return 'none'
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/** cloudflared 输出里最后一条报错(ERR / failed),给右侧栏看;不带本机路径 */
|
|
594
|
+
function lastError(out) {
|
|
595
|
+
const lines = String(out || '').split(/\r?\n/).filter((l) => /\bERR\b|error|failed|unable|cannot/i.test(l) && !/ddp-tunnel-pid/.test(l))
|
|
596
|
+
const l = lines.length ? lines[lines.length - 1] : ''
|
|
597
|
+
return l.replace(/^\S+\s+(ERR|WRN|INF)\s+/, '').replace(/(\/Users\/|\/home\/|[A-Z]:\\Users\\)[^\s"']+/g, '…').slice(0, 200)
|
|
598
|
+
}
|