dsh-chrome-bridge 1.20.0 → 2.0.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/README.en.md +6 -2
- package/README.md +6 -2
- package/client.js +110 -29
- package/core/ext.js +119 -0
- package/core/hosts.js +277 -0
- package/core/locale.js +8 -0
- package/core/receipt.js +56 -0
- package/core/session.js +157 -0
- package/core/shots.js +56 -0
- package/core/tooldef.js +142 -0
- package/core/transport.js +212 -0
- package/core/upload.js +59 -0
- package/devtools.js +18 -8
- package/download.js +879 -60
- package/drag.js +38 -20
- package/features/frames.js +58 -0
- package/features/gif.js +203 -0
- package/features/index.js +1 -0
- package/features/mock-har.js +85 -0
- package/features/record.js +225 -0
- package/i18n/en.js +168 -16
- package/i18n/ru.js +168 -16
- package/i18n/zh.js +168 -16
- package/image-guard.js +13 -6
- package/index.js +17 -1155
- package/locale/ru.json +7 -0
- package/nav.js +43 -5
- package/package.json +8 -1
- package/panel.js +10 -1
- package/refs.js +275 -230
- package/setup.js +214 -46
- package/tools/click.js +58 -0
- package/tools/devtools.js +61 -0
- package/tools/dialog.js +22 -0
- package/tools/download.js +50 -0
- package/tools/drag.js +61 -0
- package/tools/eval.js +22 -0
- package/tools/fill.js +77 -0
- package/tools/handoff.js +40 -0
- package/tools/index.js +38 -0
- package/tools/input.js +147 -0
- package/tools/nav.js +57 -0
- package/tools/read.js +87 -0
- package/tools/record.js +120 -0
- package/tools/screenshot.js +231 -0
- package/tools/tabs.js +131 -0
- package/tools/wait.js +56 -0
- package/vendor/cb +616 -35
- package/vendor/extension/_locales/en/messages.json +3 -0
- package/vendor/extension/_locales/ru/messages.json +3 -0
- package/vendor/extension/_locales/zh_CN/messages.json +3 -0
- package/vendor/extension/_locales/zh_TW/messages.json +3 -0
- package/vendor/extension/background.js +2 -1969
- package/vendor/extension/confirm.css +148 -0
- package/vendor/extension/confirm.html +49 -0
- package/vendor/extension/confirm.js +188 -0
- package/vendor/extension/in-page-cursor.js +599 -0
- package/vendor/extension/manifest.json +11 -2
- package/vendor/extension/popup.css +99 -5
- package/vendor/extension/popup.html +28 -2
- package/vendor/extension/popup.js +430 -45
- package/vendor/extension/sw/boot.js +111 -0
- package/vendor/extension/sw/cdp.js +411 -0
- package/vendor/extension/sw/chooser.js +192 -0
- package/vendor/extension/sw/confirm.js +608 -0
- package/vendor/extension/sw/cursor.js +241 -0
- package/vendor/extension/sw/dispatch.js +129 -0
- package/vendor/extension/sw/download.js +279 -0
- package/vendor/extension/sw/fetch-hub.js +224 -0
- package/vendor/extension/sw/frames.js +651 -0
- package/vendor/extension/sw/imaging.js +439 -0
- package/vendor/extension/sw/native.js +111 -0
- package/vendor/extension/sw/net-tools.js +525 -0
- package/vendor/extension/sw/ops.js +829 -0
- package/vendor/extension/sw/popup-api.js +303 -0
- package/vendor/extension/sw/profile.js +166 -0
- package/vendor/extension/sw/record.js +494 -0
- package/vendor/extension/sw/state.js +161 -0
- package/vendor/extension/sw/tabui.js +219 -0
- package/vendor/extension/sw/util.js +166 -0
- package/vendor/extension/sw/welcome.js +26 -0
- package/vendor/extension/sw/windows.js +94 -0
- package/vendor/extension/welcome.css +189 -0
- package/vendor/extension/welcome.html +70 -0
- package/vendor/extension/welcome.js +157 -0
- package/vendor/host/host.js +476 -71
- package/vendor/in-page-cursor.js +309 -37
- package/vendor/skill/SKILL.md +34 -16
package/vendor/host/host.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* 调试时可以手动跑:node host.js --standalone
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
14
15
|
import net from 'node:net'
|
|
15
16
|
import fs from 'node:fs'
|
|
16
17
|
import os from 'node:os'
|
|
@@ -22,15 +23,49 @@ import crypto from 'node:crypto'
|
|
|
22
23
|
// Windows 上 %TEMP% 本来就是每个用户自己的目录
|
|
23
24
|
const WIN = process.platform === 'win32'
|
|
24
25
|
const DIR = process.env.DSH_BRIDGE_DIR || (WIN ? path.join(os.tmpdir(), 'dsh-bridge') : `/tmp/dsh-bridge-${process.getuid()}`)
|
|
26
|
+
const HOSTS_DIR = path.join(DIR, 'hosts')
|
|
25
27
|
const TOKEN_FILE = process.env.DSH_BRIDGE_TOKEN || path.join(DIR, 'dsh-bridge.token')
|
|
26
28
|
const UNIX_SOCK = process.env.DSH_BRIDGE_SOCK || path.join(DIR, 'dsh-bridge.sock')
|
|
27
29
|
const LOG_FILE = process.env.DSH_BRIDGE_LOG || path.join(DIR, 'dsh-bridge.log')
|
|
28
30
|
const TIMEOUT_MS = Number(process.env.DSH_BRIDGE_TIMEOUT_MS || 45000)
|
|
29
31
|
const MAX_TIMEOUT_MS = 10 * 60_000
|
|
32
|
+
const HEARTBEAT_MS = Number(process.env.DSH_BRIDGE_HEARTBEAT_MS || 30_000)
|
|
33
|
+
const STALE_MS = 120_000
|
|
30
34
|
const STANDALONE = process.argv.includes('--standalone') || process.stdin.isTTY
|
|
31
35
|
const { O_WRONLY, O_CREAT, O_EXCL, O_TRUNC, O_NOFOLLOW } = fs.constants
|
|
32
36
|
|
|
37
|
+
const hostFile = fileURLToPath(import.meta.url)
|
|
38
|
+
const hostHash = () => crypto.createHash('sha256').update(fs.readFileSync(hostFile)).digest('hex').slice(0, 16)
|
|
39
|
+
const HOST_HASH = hostHash()
|
|
40
|
+
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
33
41
|
const TOKEN = crypto.randomBytes(24).toString('hex')
|
|
42
|
+
const REGISTRY_FILE = path.join(HOSTS_DIR, `${process.pid}.json`)
|
|
43
|
+
|
|
44
|
+
function isPidAlive(pid) {
|
|
45
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
46
|
+
try {
|
|
47
|
+
process.kill(pid, 0)
|
|
48
|
+
return true
|
|
49
|
+
} catch (e) {
|
|
50
|
+
return e.code === 'EPERM'
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isUnixSocket(sockPath) {
|
|
55
|
+
if (WIN) return true
|
|
56
|
+
if (typeof sockPath !== 'string' || !sockPath) return false
|
|
57
|
+
try { return fs.lstatSync(sockPath).isSocket() } catch { return false }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function isEntryAlive(data, now = Date.now()) {
|
|
61
|
+
if (!data || typeof data !== 'object') return false
|
|
62
|
+
if (!isPidAlive(data.pid)) return false
|
|
63
|
+
const ts = Number(data.lastSeenAt || data.startedAt || 0)
|
|
64
|
+
if (!Number.isFinite(ts) || ts <= 0 || now - ts > STALE_MS || ts - now > STALE_MS) return false
|
|
65
|
+
if (typeof data.socket !== 'string' || !data.socket) return false
|
|
66
|
+
if (!isUnixSocket(data.socket)) return false
|
|
67
|
+
return true
|
|
68
|
+
}
|
|
34
69
|
|
|
35
70
|
/** 没有就建(0700);有的话必须是自己的真目录(不是软链接),权限多了就收回 0700 */
|
|
36
71
|
function privateDir(dir) {
|
|
@@ -41,7 +76,7 @@ function privateDir(dir) {
|
|
|
41
76
|
}
|
|
42
77
|
|
|
43
78
|
try {
|
|
44
|
-
for (const d of new Set([...(WIN ? [] : [UNIX_SOCK]), TOKEN_FILE, LOG_FILE].map((f) => path.dirname(f)))) privateDir(d)
|
|
79
|
+
for (const d of new Set([DIR, HOSTS_DIR, ...(WIN ? [] : [UNIX_SOCK]), TOKEN_FILE, LOG_FILE].map((f) => (f === DIR || f === HOSTS_DIR ? f : path.dirname(f))))) privateDir(d)
|
|
45
80
|
} catch (e) {
|
|
46
81
|
process.stderr.write(`dsh-bridge: ${e.message}\n`) // Chrome 会把宿主的 stderr 记进它自己的日志
|
|
47
82
|
process.exit(1)
|
|
@@ -56,13 +91,21 @@ const PIPE_RE = new RegExp(`^dsh-bridge-${PIPE_SCOPE}-\\d{17}-[0-9a-f]+$`)
|
|
|
56
91
|
const SOCK = WIN
|
|
57
92
|
? process.env.DSH_BRIDGE_SOCK || `\\\\.\\pipe\\dsh-bridge-${PIPE_SCOPE}-${String(Math.round((performance.timeOrigin + performance.now()) * 1000)).padStart(17, '0')}-${crypto.randomBytes(12).toString('hex')}`
|
|
58
93
|
: UNIX_SOCK
|
|
94
|
+
const HOST_SOCK = WIN ? SOCK : path.join(DIR, `h-${process.pid}.sock`)
|
|
59
95
|
// Unix:先在同目录一个只属于自己的临时名字上监听、记下 inode,再原子改名成公开路径。
|
|
60
96
|
// 直接在公开路径上监听的话,监听完、记 inode 之前要是另一个宿主刚好接管,就会把人家的 inode 记成自己的
|
|
61
97
|
const BIND_PATH = WIN ? SOCK : path.join(path.dirname(SOCK), `.s${process.pid}`)
|
|
98
|
+
const HOST_BIND_PATH = WIN ? HOST_SOCK : path.join(DIR, `.h${process.pid}`)
|
|
62
99
|
|
|
63
100
|
// 日志:开一次、不跟软链接(O_NOFOLLOW),之后一直往这个 fd 写
|
|
64
101
|
let logFd = null
|
|
65
|
-
try {
|
|
102
|
+
try {
|
|
103
|
+
const old = fs.lstatSync(LOG_FILE, { throwIfNoEntry: false })
|
|
104
|
+
if (old && !old.isFile()) throw new Error('日志路径不是普通文件')
|
|
105
|
+
if (old?.size) fs.renameSync(LOG_FILE, LOG_FILE + '.1')
|
|
106
|
+
logFd = fs.openSync(LOG_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0o600)
|
|
107
|
+
fs.fchmodSync(logFd, 0o600)
|
|
108
|
+
} catch {}
|
|
66
109
|
|
|
67
110
|
function log(...args) {
|
|
68
111
|
const line = new Date().toISOString() + ' ' + args.map(a => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')
|
|
@@ -75,10 +118,17 @@ function writeToken() {
|
|
|
75
118
|
try { fs.unlinkSync(tmp) } catch {}
|
|
76
119
|
const fd = fs.openSync(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
|
|
77
120
|
try { fs.writeSync(fd, TOKEN + '\n' + (WIN ? SOCK + '\n' : '')) } finally { fs.closeSync(fd) }
|
|
78
|
-
|
|
121
|
+
try {
|
|
122
|
+
for (let retries = 0; ; retries++) {
|
|
123
|
+
try { fs.renameSync(tmp, TOKEN_FILE); break } catch (e) {
|
|
124
|
+
if (!WIN || retries >= 3 || !['EPERM', 'EBUSY'].includes(e.code)) throw e
|
|
125
|
+
pause(50)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
} finally { fs.rmSync(tmp, { force: true }) }
|
|
79
129
|
}
|
|
80
130
|
|
|
81
|
-
// ──
|
|
131
|
+
// ── 宿主注册表与元数据 ──────────────────────────────────────────────────────
|
|
82
132
|
|
|
83
133
|
let extReady = false
|
|
84
134
|
let lastExtMsg = 0
|
|
@@ -86,40 +136,208 @@ const STARTED_AT = Date.now()
|
|
|
86
136
|
let served = 0 // 处理过多少次 socket 请求(给扩展弹窗看)
|
|
87
137
|
let lastClientAt = 0
|
|
88
138
|
let listening = false
|
|
139
|
+
let isPrimary = false
|
|
140
|
+
let instanceId = `pid-${process.pid}`
|
|
141
|
+
const meta = { extId: '', extVersion: '', browser: '', label: '', focusedAt: 0 }
|
|
142
|
+
|
|
143
|
+
function updateMeta(msg) {
|
|
144
|
+
let changed = false
|
|
145
|
+
if (typeof msg.instanceId === 'string' && /^[A-Za-z0-9_-]{1,48}$/.test(msg.instanceId) && msg.instanceId !== instanceId) {
|
|
146
|
+
instanceId = msg.instanceId
|
|
147
|
+
changed = true
|
|
148
|
+
}
|
|
149
|
+
for (const k of ['extId', 'extVersion', 'browser', 'label']) {
|
|
150
|
+
if (typeof msg[k] === 'string' && msg[k] !== meta[k]) {
|
|
151
|
+
meta[k] = msg[k].slice(0, 128)
|
|
152
|
+
changed = true
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (typeof msg.focusedAt === 'number' && Number.isFinite(msg.focusedAt) && msg.focusedAt !== meta.focusedAt) {
|
|
156
|
+
meta.focusedAt = msg.focusedAt
|
|
157
|
+
changed = true
|
|
158
|
+
}
|
|
159
|
+
return changed
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 原子写入本宿主在 DIR/hosts/<pid>.json 的注册记录(0600,防软链接) */
|
|
163
|
+
function writeRegistry() {
|
|
164
|
+
if (!listening) return
|
|
165
|
+
try {
|
|
166
|
+
privateDir(HOSTS_DIR)
|
|
167
|
+
const now = Date.now()
|
|
168
|
+
const payload = {
|
|
169
|
+
id: instanceId,
|
|
170
|
+
pid: process.pid,
|
|
171
|
+
socket: HOST_SOCK,
|
|
172
|
+
token: TOKEN,
|
|
173
|
+
extId: meta.extId,
|
|
174
|
+
extVersion: meta.extVersion,
|
|
175
|
+
browser: meta.browser,
|
|
176
|
+
label: meta.label,
|
|
177
|
+
hostHash: HOST_HASH,
|
|
178
|
+
startedAt: STARTED_AT,
|
|
179
|
+
lastSeenAt: now,
|
|
180
|
+
focusedAt: meta.focusedAt,
|
|
181
|
+
extConnected: extReady,
|
|
182
|
+
isPrimary,
|
|
183
|
+
}
|
|
184
|
+
const tmp = `${REGISTRY_FILE}.${process.pid}.tmp`
|
|
185
|
+
try { fs.unlinkSync(tmp) } catch {}
|
|
186
|
+
const fd = fs.openSync(tmp, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
|
|
187
|
+
try { fs.writeSync(fd, JSON.stringify(payload, null, 2) + '\n') } finally { fs.closeSync(fd) }
|
|
188
|
+
try {
|
|
189
|
+
for (let retries = 0; ; retries++) {
|
|
190
|
+
try { fs.renameSync(tmp, REGISTRY_FILE); break } catch (e) {
|
|
191
|
+
if (!WIN || retries >= 3 || !['EPERM', 'EBUSY'].includes(e.code)) throw e
|
|
192
|
+
pause(50)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
} finally { fs.rmSync(tmp, { force: true }) }
|
|
196
|
+
} catch (e) {
|
|
197
|
+
log('写注册文件失败:', String(e))
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 清理 DIR/hosts/ 里已死 PID、过期心跳或缺 socket 的死注册文件,以及残留的 h-<deadPid>.sock */
|
|
202
|
+
function cleanupDeadHosts() {
|
|
203
|
+
const now = Date.now()
|
|
204
|
+
try {
|
|
205
|
+
const entries = fs.readdirSync(HOSTS_DIR)
|
|
206
|
+
for (const name of entries) {
|
|
207
|
+
if (!name.endsWith('.json')) continue
|
|
208
|
+
const full = path.join(HOSTS_DIR, name)
|
|
209
|
+
let pid = Number(name.slice(0, -5))
|
|
210
|
+
let data = null
|
|
211
|
+
try {
|
|
212
|
+
const st = fs.lstatSync(full)
|
|
213
|
+
if (!st.isFile()) continue
|
|
214
|
+
data = JSON.parse(fs.readFileSync(full, 'utf8'))
|
|
215
|
+
if (Number.isInteger(data?.pid) && data.pid > 0) pid = data.pid
|
|
216
|
+
} catch {}
|
|
217
|
+
if (pid === process.pid) continue
|
|
218
|
+
if (!isEntryAlive(data, now)) {
|
|
219
|
+
try { fs.rmSync(full, { force: true }) } catch {}
|
|
220
|
+
if (!WIN && Number.isInteger(pid) && pid > 0) {
|
|
221
|
+
try { fs.rmSync(path.join(DIR, `h-${pid}.sock`), { force: true }) } catch {}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
} catch {}
|
|
226
|
+
if (!WIN) {
|
|
227
|
+
try {
|
|
228
|
+
for (const name of fs.readdirSync(DIR)) {
|
|
229
|
+
const m = /^h-(\d+)\.sock$/.exec(name)
|
|
230
|
+
if (!m) continue
|
|
231
|
+
const pid = Number(m[1])
|
|
232
|
+
if (pid !== process.pid && !isPidAlive(pid)) {
|
|
233
|
+
try { fs.rmSync(path.join(DIR, name), { force: true }) } catch {}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
} catch {}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** 扫描 DIR/hosts/ 检查是否有活着的兄弟宿主占着主入口 */
|
|
241
|
+
function hasAliveSiblingPrimary(matchSocket = null) {
|
|
242
|
+
const now = Date.now()
|
|
243
|
+
try {
|
|
244
|
+
for (const name of fs.readdirSync(HOSTS_DIR)) {
|
|
245
|
+
if (!name.endsWith('.json')) continue
|
|
246
|
+
const full = path.join(HOSTS_DIR, name)
|
|
247
|
+
try {
|
|
248
|
+
const st = fs.lstatSync(full)
|
|
249
|
+
if (!st.isFile()) continue
|
|
250
|
+
const data = JSON.parse(fs.readFileSync(full, 'utf8'))
|
|
251
|
+
if (!data || data.pid === process.pid || !isEntryAlive(data, now)) continue
|
|
252
|
+
if (matchSocket && data.socket === matchSocket) return true
|
|
253
|
+
if (data.isPrimary) return true
|
|
254
|
+
} catch {}
|
|
255
|
+
}
|
|
256
|
+
} catch {}
|
|
257
|
+
return false
|
|
258
|
+
}
|
|
89
259
|
|
|
90
260
|
function toExtension(obj) {
|
|
91
261
|
const payload = Buffer.from(JSON.stringify(obj), 'utf8')
|
|
92
|
-
if (payload.length > 900 * 1024) throw new Error(
|
|
262
|
+
if (payload.length > 900 * 1024) throw new Error(`发给扩展的消息为 ${payload.length} 字节(${(payload.length / 1024).toFixed(1)} KB),超过 900 KB,请拆小参数或分段处理`)
|
|
93
263
|
const head = Buffer.alloc(4)
|
|
94
264
|
head.writeUInt32LE(payload.length, 0)
|
|
95
|
-
|
|
265
|
+
const frame = Buffer.concat([head, payload])
|
|
266
|
+
const deadline = Date.now() + 1000
|
|
267
|
+
for (let offset = 0; offset < frame.length;) {
|
|
268
|
+
try {
|
|
269
|
+
const written = fs.writeSync(1, frame, offset, frame.length - offset)
|
|
270
|
+
if (!written) throw new Error('扩展管道关闭')
|
|
271
|
+
offset += written
|
|
272
|
+
} catch (e) {
|
|
273
|
+
if (['EAGAIN', 'EINTR', 'EWOULDBLOCK'].includes(e.code) && Date.now() < deadline) { pause(2); continue }
|
|
274
|
+
if (offset) { log('扩展管道写入中断', String(e)); shutdown(1) }
|
|
275
|
+
throw e
|
|
276
|
+
}
|
|
277
|
+
}
|
|
96
278
|
}
|
|
97
279
|
|
|
98
|
-
/** extension → host 的分片重组:id → string[] */
|
|
99
280
|
const inbox = new Map()
|
|
281
|
+
function failChunk(id, error) {
|
|
282
|
+
inbox.delete(id)
|
|
283
|
+
const pending = waiting.get(id)
|
|
284
|
+
if (!pending) return
|
|
285
|
+
clearTimeout(pending.timer)
|
|
286
|
+
waiting.delete(id)
|
|
287
|
+
reply(pending.sock, { id: pending.cid, ok: false, error })
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
setInterval(() => {
|
|
291
|
+
for (const [id, entry] of inbox) {
|
|
292
|
+
if (Date.now() - entry.at >= 30_000) failChunk(id, '扩展分片重组超时')
|
|
293
|
+
}
|
|
294
|
+
}, 1000).unref()
|
|
100
295
|
|
|
101
296
|
function onExtensionMessage(raw) {
|
|
102
297
|
let msg
|
|
103
298
|
try { msg = JSON.parse(raw) } catch (e) { log('扩展消息不是 JSON:', String(e)); return }
|
|
299
|
+
if (!msg || typeof msg !== 'object') return
|
|
300
|
+
const wasReady = extReady
|
|
104
301
|
extReady = true
|
|
105
302
|
lastExtMsg = Date.now()
|
|
303
|
+
let metaChanged = false
|
|
304
|
+
if (msg.hostMeta || msg.hello || msg.hostHello) {
|
|
305
|
+
metaChanged = updateMeta(msg)
|
|
306
|
+
}
|
|
307
|
+
if (!wasReady || metaChanged) writeRegistry()
|
|
106
308
|
|
|
107
309
|
if (msg.chunk) {
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
inbox.
|
|
111
|
-
if (
|
|
112
|
-
|
|
113
|
-
|
|
310
|
+
const { id, data, chunk: { seq, total } } = msg
|
|
311
|
+
if (!waiting.has(id)) return
|
|
312
|
+
let entry = inbox.get(id)
|
|
313
|
+
if (!Number.isInteger(seq) || !Number.isInteger(total) || seq < 0 || seq >= total ||
|
|
314
|
+
total > 65536 || typeof data !== 'string' || (entry && entry.total !== total)) {
|
|
315
|
+
return failChunk(id, '扩展分片格式错误')
|
|
114
316
|
}
|
|
115
|
-
|
|
317
|
+
if (!entry) {
|
|
318
|
+
if (inbox.size >= 64) return failChunk(id, '并发分片请求超过 64 个')
|
|
319
|
+
entry = { parts: new Map(), bytes: 0, at: Date.now(), total }
|
|
320
|
+
inbox.set(id, entry)
|
|
321
|
+
}
|
|
322
|
+
if (entry.parts.has(seq)) return
|
|
323
|
+
entry.bytes += Buffer.byteLength(data)
|
|
324
|
+
if (entry.bytes > 64 * 1024 * 1024) return failChunk(id, '扩展分片超过 64 MB')
|
|
325
|
+
entry.parts.set(seq, data)
|
|
326
|
+
if (entry.parts.size >= total) {
|
|
327
|
+
inbox.delete(id)
|
|
328
|
+
try {
|
|
329
|
+
msg = JSON.parse(Array.from({ length: total }, (_, i) => entry.parts.get(i)).join(''))
|
|
330
|
+
if (msg.id !== id || msg.chunk) throw new Error()
|
|
331
|
+
} catch { return failChunk(id, '扩展分片重组失败') }
|
|
332
|
+
} else return
|
|
116
333
|
}
|
|
117
|
-
if (msg.keepalive) return
|
|
334
|
+
if (msg.keepalive || msg.hostMeta || msg.hostHello) return
|
|
118
335
|
if (msg.hostPing) {
|
|
119
336
|
// 扩展弹窗要看的:宿主活着没、socket 在不在听、最近一次被调用是什么时候
|
|
120
337
|
try {
|
|
121
338
|
toExtension({ hostPong: true, pid: process.pid, startedAt: STARTED_AT, node: process.version,
|
|
122
|
-
socket: SOCK
|
|
339
|
+
socket: isPrimary ? SOCK : HOST_SOCK, hostSocket: HOST_SOCK, instanceId, hostHash: HOST_HASH,
|
|
340
|
+
socketOk: listening && (WIN || fs.existsSync(HOST_SOCK)), served, lastClientAt, pending: waiting.size })
|
|
123
341
|
} catch (e) { log('回 hostPong 失败:', String(e)) }
|
|
124
342
|
return
|
|
125
343
|
}
|
|
@@ -127,6 +345,7 @@ function onExtensionMessage(raw) {
|
|
|
127
345
|
const pending = waiting.get(msg.id)
|
|
128
346
|
if (!pending) return
|
|
129
347
|
waiting.delete(msg.id)
|
|
348
|
+
inbox.delete(msg.id)
|
|
130
349
|
clearTimeout(pending.timer)
|
|
131
350
|
reply(pending.sock, { id: pending.cid, ok: msg.ok !== false, result: msg.result, error: msg.error })
|
|
132
351
|
}
|
|
@@ -177,17 +396,22 @@ function forwardToExtension(sock, req) {
|
|
|
177
396
|
}
|
|
178
397
|
// 客户端带了自己的超时(等元素、截图这类慢操作)就按它来,比它早一点点回话,免得客户端先放弃、只看到「超时」
|
|
179
398
|
const asked = Number(req.timeoutMs)
|
|
180
|
-
|
|
399
|
+
let ms = TIMEOUT_MS
|
|
400
|
+
if (asked > 0) {
|
|
401
|
+
ms = asked <= 2500 ? Math.max(asked - 200, 200) : Math.min(asked - 1500, MAX_TIMEOUT_MS)
|
|
402
|
+
}
|
|
181
403
|
const timer = setTimeout(() => {
|
|
182
404
|
waiting.delete(id)
|
|
405
|
+
inbox.delete(id)
|
|
183
406
|
reply(sock, { id: cid, ok: false, error: `扩展 ${ms}ms 没回(操作太慢,或者标签页已关闭;做没做成不确定)` })
|
|
184
407
|
}, ms)
|
|
185
408
|
waiting.set(id, { sock, timer, cid })
|
|
186
409
|
try {
|
|
187
|
-
toExtension({ id, op: req.op, args: req.args || {}, ...(req.client ? { client: req.client } : {}) })
|
|
410
|
+
toExtension({ id, timeoutMs: ms, op: req.op, args: req.args || {}, ...(req.client ? { client: req.client } : {}) })
|
|
188
411
|
} catch (e) {
|
|
189
412
|
clearTimeout(timer)
|
|
190
413
|
waiting.delete(id)
|
|
414
|
+
inbox.delete(id)
|
|
191
415
|
reply(sock, { id: cid, ok: false, error: String(e && e.message || e) })
|
|
192
416
|
}
|
|
193
417
|
}
|
|
@@ -200,57 +424,212 @@ function handleLine(sock, line) {
|
|
|
200
424
|
log('token 不匹配,拒绝')
|
|
201
425
|
return reply(sock, { id: req.id, ok: false, error: 'token 不匹配' })
|
|
202
426
|
}
|
|
427
|
+
sock.authenticated = true
|
|
203
428
|
served++
|
|
204
429
|
lastClientAt = Date.now()
|
|
205
430
|
if (draining && req.op !== 'status') {
|
|
206
|
-
return reply(sock, { id: req.id, ok: false, error: '
|
|
431
|
+
return reply(sock, { id: req.id, ok: false, error: '宿主正要重启,这次操作没执行:过几秒再试' })
|
|
207
432
|
}
|
|
208
433
|
if (req.op === 'status') {
|
|
209
434
|
return reply(sock, {
|
|
210
435
|
id: req.id, ok: true,
|
|
211
|
-
result: {
|
|
212
|
-
|
|
436
|
+
result: {
|
|
437
|
+
pid: process.pid, hostHash: HOST_HASH, extConnected: extReady, lastExtMsg,
|
|
438
|
+
socket: isPrimary ? SOCK : HOST_SOCK, hostSocket: HOST_SOCK, registryFile: REGISTRY_FILE,
|
|
439
|
+
instanceId, label: meta.label, browser: meta.browser, focusedAt: meta.focusedAt,
|
|
440
|
+
standalone: STANDALONE, pending: waiting.size,
|
|
441
|
+
},
|
|
213
442
|
})
|
|
214
443
|
}
|
|
215
444
|
forwardToExtension(sock, req)
|
|
216
445
|
}
|
|
217
446
|
|
|
218
|
-
function
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
447
|
+
function onClientConnection(sock) {
|
|
448
|
+
const authLimit = 64 * 1024
|
|
449
|
+
const lineLimit = 32 * 1024 * 1024
|
|
450
|
+
let buffer = Buffer.alloc(0)
|
|
451
|
+
let bytes = 0
|
|
452
|
+
sock.on('data', (data) => {
|
|
453
|
+
let start = 0
|
|
454
|
+
while (start < data.length) {
|
|
455
|
+
const end = data.indexOf(10, start)
|
|
456
|
+
const part = data.subarray(start, end < 0 ? data.length : end)
|
|
457
|
+
const size = bytes + part.length
|
|
458
|
+
if (size > lineLimit) return sock.destroy()
|
|
459
|
+
if (!sock.authenticated && size > authLimit) {
|
|
460
|
+
// cb 和插件把 token 放在第一个字段。先验证有界前缀,大请求也能沿用单行协议。
|
|
461
|
+
const prefix = Buffer.concat([buffer.subarray(0, bytes), part], authLimit).toString('utf8')
|
|
462
|
+
if (/^\s*\{\s*"token"\s*:\s*"([a-f0-9]+)"\s*[,}]/.exec(prefix)?.[1] !== TOKEN) return sock.destroy()
|
|
463
|
+
sock.authenticated = true
|
|
231
464
|
}
|
|
465
|
+
if (size > buffer.length) {
|
|
466
|
+
const next = Buffer.allocUnsafe(Math.min(lineLimit, Math.max(size, buffer.length * 2)))
|
|
467
|
+
buffer.copy(next, 0, 0, bytes)
|
|
468
|
+
buffer = next
|
|
469
|
+
}
|
|
470
|
+
part.copy(buffer, bytes)
|
|
471
|
+
bytes = size
|
|
472
|
+
if (end < 0) return
|
|
473
|
+
const line = buffer.toString('utf8', 0, size).trim()
|
|
474
|
+
if (line) handleLine(sock, line)
|
|
475
|
+
bytes = 0
|
|
476
|
+
buffer = Buffer.alloc(0)
|
|
477
|
+
start = end + 1
|
|
478
|
+
}
|
|
479
|
+
})
|
|
480
|
+
sock.on('error', () => {})
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function probeUnixSocket(sockPath) {
|
|
484
|
+
return new Promise((resolve) => {
|
|
485
|
+
const s = net.connect(sockPath)
|
|
486
|
+
let settled = false
|
|
487
|
+
const done = (alive) => {
|
|
488
|
+
if (settled) return
|
|
489
|
+
settled = true
|
|
490
|
+
try { s.destroy() } catch {}
|
|
491
|
+
resolve(alive)
|
|
492
|
+
}
|
|
493
|
+
s.setTimeout(500, () => done(false))
|
|
494
|
+
s.on('connect', () => done(true))
|
|
495
|
+
s.on('error', () => done(false))
|
|
496
|
+
})
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
let primaryServer = null
|
|
500
|
+
let ownHostSock = null
|
|
501
|
+
let hostPublished = false
|
|
502
|
+
let claimingPrimary = false
|
|
503
|
+
|
|
504
|
+
async function maybeReconcilePrimary() {
|
|
505
|
+
if (draining || claimingPrimary) return
|
|
506
|
+
if (isPrimary) {
|
|
507
|
+
if (!WIN && !isCurrentHost()) {
|
|
508
|
+
isPrimary = false
|
|
509
|
+
ownsToken = false
|
|
510
|
+
published = false
|
|
511
|
+
log('主入口已被其他宿主接管,降级为非主宿主')
|
|
512
|
+
}
|
|
513
|
+
return
|
|
514
|
+
}
|
|
515
|
+
if (hasAliveSiblingPrimary()) return
|
|
516
|
+
if (!WIN) {
|
|
517
|
+
const existing = fs.lstatSync(SOCK, { throwIfNoEntry: false })
|
|
518
|
+
if (existing && existing.isSocket() && await probeUnixSocket(SOCK)) return
|
|
519
|
+
claimingPrimary = true
|
|
520
|
+
claimPrimaryUnix(false)
|
|
521
|
+
return
|
|
522
|
+
}
|
|
523
|
+
let curPipe = null
|
|
524
|
+
try { curPipe = fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1]?.trim() || null } catch {}
|
|
525
|
+
if (hasAliveSiblingPrimary(curPipe)) return
|
|
526
|
+
try {
|
|
527
|
+
isPrimary = true
|
|
528
|
+
ownsToken = true
|
|
529
|
+
writeToken()
|
|
530
|
+
writeRegistry()
|
|
531
|
+
log('主宿主已退出,自动补位接管主入口')
|
|
532
|
+
} catch (e) {
|
|
533
|
+
isPrimary = false
|
|
534
|
+
ownsToken = false
|
|
535
|
+
log('补位写 token 失败:', String(e))
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function finishStartup() {
|
|
540
|
+
writeRegistry()
|
|
541
|
+
cleanupDeadHosts()
|
|
542
|
+
log(`监听 ${HOST_SOCK}${isPrimary && !WIN ? ` + 主入口 ${SOCK}` : ''}(pid ${process.pid}, primary=${isPrimary}, standalone=${STANDALONE})`)
|
|
543
|
+
setInterval(healFiles, HEAL_MS).unref()
|
|
544
|
+
setInterval(() => {
|
|
545
|
+
if (draining) return
|
|
546
|
+
cleanupDeadHosts()
|
|
547
|
+
maybeReconcilePrimary().finally(() => {
|
|
548
|
+
if (!draining) writeRegistry()
|
|
232
549
|
})
|
|
233
|
-
|
|
550
|
+
}, HEARTBEAT_MS).unref()
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function claimPrimaryUnix(initial = true) {
|
|
554
|
+
try { fs.unlinkSync(BIND_PATH) } catch {}
|
|
555
|
+
const srv = net.createServer(onClientConnection)
|
|
556
|
+
srv.on('error', (e) => {
|
|
557
|
+
claimingPrimary = false
|
|
558
|
+
log('主入口 socket 服务出错:', String(e))
|
|
559
|
+
if (initial) shutdown(1)
|
|
234
560
|
})
|
|
561
|
+
srv.listen(BIND_PATH, () => {
|
|
562
|
+
try {
|
|
563
|
+
fs.chmodSync(BIND_PATH, 0o600)
|
|
564
|
+
const st = fs.lstatSync(BIND_PATH)
|
|
565
|
+
ownSock = { dev: st.dev, ino: st.ino }
|
|
566
|
+
fs.renameSync(BIND_PATH, SOCK)
|
|
567
|
+
published = true
|
|
568
|
+
isPrimary = true
|
|
569
|
+
ownsToken = true
|
|
570
|
+
writeToken()
|
|
571
|
+
} catch (e) {
|
|
572
|
+
claimingPrimary = false
|
|
573
|
+
log('放主入口 socket 失败:', String(e))
|
|
574
|
+
try { srv.close() } catch {}
|
|
575
|
+
if (initial) return shutdown(1)
|
|
576
|
+
return
|
|
577
|
+
}
|
|
578
|
+
claimingPrimary = false
|
|
579
|
+
primaryServer = srv
|
|
580
|
+
if (initial) finishStartup()
|
|
581
|
+
else {
|
|
582
|
+
writeRegistry()
|
|
583
|
+
log(`主宿主已退出,自动补位接管主入口 ${SOCK}`)
|
|
584
|
+
}
|
|
585
|
+
})
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function startServer() {
|
|
589
|
+
if (!WIN) { try { fs.unlinkSync(HOST_BIND_PATH) } catch {} }
|
|
235
590
|
|
|
236
|
-
|
|
237
|
-
|
|
591
|
+
const srv = net.createServer(onClientConnection)
|
|
592
|
+
srv.on('error', (e) => { log('socket 服务出错:', String(e)); shutdown(1) })
|
|
593
|
+
srv.listen(HOST_BIND_PATH, async () => {
|
|
238
594
|
if (!WIN) {
|
|
239
595
|
try {
|
|
240
|
-
fs.chmodSync(
|
|
241
|
-
const st = fs.lstatSync(
|
|
242
|
-
|
|
243
|
-
fs.renameSync(
|
|
244
|
-
|
|
245
|
-
} catch (e) { log('
|
|
596
|
+
fs.chmodSync(HOST_BIND_PATH, 0o600)
|
|
597
|
+
const st = fs.lstatSync(HOST_BIND_PATH)
|
|
598
|
+
ownHostSock = { dev: st.dev, ino: st.ino }
|
|
599
|
+
fs.renameSync(HOST_BIND_PATH, HOST_SOCK)
|
|
600
|
+
hostPublished = true
|
|
601
|
+
} catch (e) { log('放独立 socket 失败:', String(e)); return shutdown(1) }
|
|
602
|
+
listening = true
|
|
603
|
+
if (hasAliveSiblingPrimary()) {
|
|
604
|
+
isPrimary = false
|
|
605
|
+
ownsToken = false
|
|
606
|
+
return finishStartup()
|
|
607
|
+
}
|
|
608
|
+
const existing = fs.lstatSync(SOCK, { throwIfNoEntry: false })
|
|
609
|
+
if (!existing || !existing.isSocket()) return claimPrimaryUnix()
|
|
610
|
+
const alive = await probeUnixSocket(SOCK)
|
|
611
|
+
if (alive) {
|
|
612
|
+
isPrimary = false
|
|
613
|
+
ownsToken = false
|
|
614
|
+
return finishStartup()
|
|
615
|
+
}
|
|
616
|
+
return claimPrimaryUnix()
|
|
246
617
|
}
|
|
247
618
|
listening = true
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
619
|
+
let curPipe = null
|
|
620
|
+
try { curPipe = fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1]?.trim() || null } catch {}
|
|
621
|
+
if (hasAliveSiblingPrimary(curPipe)) {
|
|
622
|
+
isPrimary = false
|
|
623
|
+
ownsToken = false
|
|
624
|
+
} else {
|
|
625
|
+
isPrimary = true
|
|
626
|
+
ownsToken = true
|
|
627
|
+
try { writeToken() } catch (e) { log('写 token 失败:', String(e)); return shutdown(1) }
|
|
628
|
+
}
|
|
629
|
+
finishStartup()
|
|
251
630
|
})
|
|
252
631
|
|
|
253
|
-
return
|
|
632
|
+
return srv
|
|
254
633
|
}
|
|
255
634
|
|
|
256
635
|
/**
|
|
@@ -271,38 +650,41 @@ let draining = false
|
|
|
271
650
|
* 管道名里带着启动时刻,列一下 \\.\pipe\ 就知道。
|
|
272
651
|
*/
|
|
273
652
|
function isCurrentHost() {
|
|
653
|
+
if (!isPrimary) return false
|
|
274
654
|
if (!WIN) {
|
|
275
655
|
try {
|
|
276
656
|
const st = fs.lstatSync(SOCK)
|
|
277
657
|
return !!ownSock && st.dev === ownSock.dev && st.ino === ownSock.ino
|
|
278
658
|
} catch { return false }
|
|
279
659
|
}
|
|
280
|
-
|
|
281
|
-
if (!PIPE_RE.test(me)) return ownsToken // 自己指定的管道名,比不了先后:只在上次见到的 token 是自己的时候补
|
|
282
|
-
try {
|
|
283
|
-
return !fs.readdirSync('\\\\.\\pipe\\').some((n) => PIPE_RE.test(n) && n > me)
|
|
284
|
-
} catch (e) {
|
|
285
|
-
if (!pipeListFailed) log('列不出命名管道,退回看上次见到的 token 是不是自己的:', String(e))
|
|
286
|
-
pipeListFailed = true
|
|
287
|
-
return ownsToken
|
|
288
|
-
}
|
|
660
|
+
return true
|
|
289
661
|
}
|
|
290
|
-
let pipeListFailed = false
|
|
291
662
|
|
|
292
663
|
let sockGone = false
|
|
293
664
|
function healFiles() {
|
|
294
665
|
if (draining || sockGone) return
|
|
295
|
-
if (!
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
sockGone = false
|
|
300
|
-
if (fs.existsSync(SOCK)) return
|
|
301
|
-
log('socket 文件被删了(系统清理临时目录?)')
|
|
302
|
-
if (!STANDALONE) drainThenExit() // 扩展那边断开就会重连、拉起新宿主
|
|
303
|
-
}, 1000).unref()
|
|
304
|
-
return
|
|
666
|
+
if (!STANDALONE) {
|
|
667
|
+
try {
|
|
668
|
+
if (hostHash() !== HOST_HASH) { log('宿主文件已升级,排空后退出'); return drainThenExit() }
|
|
669
|
+
} catch (e) { log('读取宿主文件失败:', String(e)) }
|
|
305
670
|
}
|
|
671
|
+
if (!WIN) {
|
|
672
|
+
const missingHost = hostPublished && !fs.existsSync(HOST_SOCK)
|
|
673
|
+
const missingPrimary = isPrimary && published && !fs.existsSync(SOCK)
|
|
674
|
+
if (missingHost || missingPrimary) {
|
|
675
|
+
// 隔一秒再看一眼:别的宿主退出时会把 socket 挪开一瞬间(见 shutdown),别被这一下骗了
|
|
676
|
+
sockGone = true
|
|
677
|
+
setTimeout(() => {
|
|
678
|
+
sockGone = false
|
|
679
|
+
if ((!missingHost || fs.existsSync(HOST_SOCK)) && (!missingPrimary || fs.existsSync(SOCK))) return
|
|
680
|
+
log('socket 文件被删了(系统清理临时目录?)')
|
|
681
|
+
if (!STANDALONE) drainThenExit() // 扩展那边断开就会重连、拉起新宿主
|
|
682
|
+
}, 1000).unref()
|
|
683
|
+
return
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (!fs.existsSync(REGISTRY_FILE)) writeRegistry()
|
|
687
|
+
if (!isPrimary) return
|
|
306
688
|
let cur = null
|
|
307
689
|
try {
|
|
308
690
|
cur = fs.readFileSync(TOKEN_FILE, 'utf8')
|
|
@@ -337,7 +719,7 @@ function drainThenExit() {
|
|
|
337
719
|
if ((waiting.size || writing) && Date.now() < until) return setTimeout(tick, 200)
|
|
338
720
|
for (const w of waiting.values()) {
|
|
339
721
|
clearTimeout(w.timer)
|
|
340
|
-
reply(w.sock, { id: w.cid, ok: false, error: '
|
|
722
|
+
reply(w.sock, { id: w.cid, ok: false, error: '宿主要重启,这次操作做没做成不确定:先看看页面现在的样子,再决定要不要重做' })
|
|
341
723
|
}
|
|
342
724
|
waiting.clear()
|
|
343
725
|
const flushBy = Date.now() + 5000
|
|
@@ -351,14 +733,26 @@ let server = null
|
|
|
351
733
|
/** 自己建的那个 socket 文件(dev+inode):退出时只删它,别把后来接管的新宿主的 socket 删了 */
|
|
352
734
|
let ownSock = null
|
|
353
735
|
let published = false // 已经改名成公开路径了(没成功的话公开路径上的东西跟自己无关,退出时别碰)
|
|
354
|
-
|
|
736
|
+
let cleanedUp = false
|
|
737
|
+
|
|
738
|
+
function cleanupOwnFiles() {
|
|
739
|
+
if (cleanedUp) return
|
|
740
|
+
cleanedUp = true
|
|
355
741
|
// 不调 server.close():Node 关 Unix socket 服务时会按路径无条件 unlink(实测),
|
|
356
742
|
// 正好会删掉后来接管的新宿主的 socket。反正马上退出,fd 由系统回收。
|
|
743
|
+
try { fs.rmSync(REGISTRY_FILE, { force: true }) } catch {}
|
|
357
744
|
try {
|
|
358
745
|
if (WIN) {
|
|
359
746
|
// 命名管道随进程消失;token 文件还指着自己的管道就删掉,免得客户端连一个不存在的管道
|
|
360
|
-
if (fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1] === SOCK) fs.unlinkSync(TOKEN_FILE)
|
|
747
|
+
if (isPrimary && fs.readFileSync(TOKEN_FILE, 'utf8').split('\n')[1]?.trim() === SOCK) fs.unlinkSync(TOKEN_FILE)
|
|
361
748
|
} else {
|
|
749
|
+
try { fs.unlinkSync(HOST_BIND_PATH) } catch {}
|
|
750
|
+
if (hostPublished) {
|
|
751
|
+
try {
|
|
752
|
+
const hst = fs.lstatSync(HOST_SOCK)
|
|
753
|
+
if (ownHostSock && hst.dev === ownHostSock.dev && hst.ino === ownHostSock.ino) fs.unlinkSync(HOST_SOCK)
|
|
754
|
+
} catch {}
|
|
755
|
+
}
|
|
362
756
|
try { fs.unlinkSync(BIND_PATH) } catch {} // 还没来得及改名就退了
|
|
363
757
|
// 只删自己的 socket 文件:先原子挪到自己的临时名再看是谁的(先看再删的话,中间新宿主刚好换上来就会删错)。
|
|
364
758
|
// 挪下来的是新宿主的就放回去(link 不覆盖:放回之前又来了更新的,就不用放了)
|
|
@@ -370,17 +764,28 @@ function shutdown(code) {
|
|
|
370
764
|
fs.linkSync(BIND_PATH, SOCK)
|
|
371
765
|
} catch (e) {
|
|
372
766
|
// 放不回去(不是因为已经有更新的了):改名挪回去,挪不回也别删,那是别人的
|
|
373
|
-
if (e.code !== 'EEXIST') { try { fs.renameSync(BIND_PATH, SOCK) } catch {} ;
|
|
767
|
+
if (e.code !== 'EEXIST') { try { fs.renameSync(BIND_PATH, SOCK) } catch {} ; return }
|
|
374
768
|
}
|
|
375
769
|
}
|
|
376
770
|
fs.unlinkSync(BIND_PATH)
|
|
377
771
|
}
|
|
378
772
|
}
|
|
379
773
|
} catch {}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
function shutdown(code) {
|
|
777
|
+
cleanupOwnFiles()
|
|
380
778
|
process.exit(code)
|
|
381
779
|
}
|
|
382
780
|
|
|
781
|
+
const socketLimit = process.platform === 'darwin' ? 103 : 107
|
|
782
|
+
if (!WIN && [BIND_PATH, SOCK, HOST_BIND_PATH, HOST_SOCK].some((p) => Buffer.byteLength(p) > socketLimit)) {
|
|
783
|
+
process.stderr.write(`Unix socket 路径超过 ${socketLimit} 字节,请缩短 DSH_BRIDGE_DIR 或 DSH_BRIDGE_SOCK\n`)
|
|
784
|
+
process.exit(1)
|
|
785
|
+
}
|
|
383
786
|
server = startServer()
|
|
384
787
|
process.on('SIGTERM', () => shutdown(0))
|
|
385
788
|
process.on('SIGINT', () => shutdown(0))
|
|
789
|
+
process.on('SIGHUP', () => shutdown(0))
|
|
790
|
+
process.on('exit', cleanupOwnFiles)
|
|
386
791
|
log('宿主启动', { STANDALONE, node: process.version })
|