dsh-remote-agent 0.0.0-stage → 0.4.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/CHANGELOG.md +700 -0
- package/CONTRIBUTING.md +358 -0
- package/KNOWN-ISSUES.md +601 -0
- package/LICENSE +21 -0
- package/README.en.md +353 -0
- package/README.md +317 -2
- package/SECURITY.md +348 -0
- package/bin/dsh-remote-relay.js +257 -0
- package/bin/dsh-remote-setup.js +440 -0
- package/bin//345/217/214/345/207/273/350/277/220/350/241/214-/351/205/215/347/275/256/345/220/221/345/257/274.cmd +28 -0
- package/cordis.patch.yml +87 -0
- package/deploy/relay-vps/Caddyfile +24 -0
- package/deploy/relay-vps/README.md +132 -0
- package/deploy/relay-vps/dsh-remote-relay.service +47 -0
- package/deploy/relay-vps/nginx.conf +49 -0
- package/deploy/relay-vps/relay.env.example +20 -0
- package/docs/dispatch-automation-eval.md +140 -0
- package/docs/screenshots/panel-main.png +0 -0
- package/docs/screenshots/panel-task-detail.png +0 -0
- package/docs/verification-agent-e2e.md +425 -0
- package/docs/verification-repos-routing-real.md +521 -0
- package/docs/verification-resume-real.md +254 -0
- package/docs/worker-setup-pitfalls.md +266 -0
- package/lib/artifacts.js +451 -0
- package/lib/client.js +1752 -0
- package/lib/e2e.js +304 -0
- package/lib/glob.js +225 -0
- package/lib/hub/audit-log.js +161 -0
- package/lib/hub/hub-util.js +114 -0
- package/lib/hub/index.js +500 -0
- package/lib/hub/node-registry.js +943 -0
- package/lib/hub/pull-manager.js +781 -0
- package/lib/hub/registry-handshake.js +403 -0
- package/lib/hub/registry-ingest.js +346 -0
- package/lib/hub/relay-link.js +228 -0
- package/lib/hub/subagent-provider.js +424 -0
- package/lib/hub/templates.js +693 -0
- package/lib/hub/tools.js +1059 -0
- package/lib/hub/ui-routes.js +856 -0
- package/lib/hub/views.js +351 -0
- package/lib/identity.js +271 -0
- package/lib/index.js +272 -0
- package/lib/node/artifact-service.js +231 -0
- package/lib/node/diff.js +124 -0
- package/lib/node/exec.js +536 -0
- package/lib/node/hub-pin.js +71 -0
- package/lib/node/index.js +1022 -0
- package/lib/node/repos.js +134 -0
- package/lib/node/resource.js +63 -0
- package/lib/node/runner.js +792 -0
- package/lib/node/task-engine.js +712 -0
- package/lib/node/task-store.js +273 -0
- package/lib/node/transport.js +763 -0
- package/lib/pairing.js +186 -0
- package/lib/protocol.js +414 -0
- package/lib/relay-config.js +317 -0
- package/lib/relay.js +732 -0
- package/lib/setup-routes.js +313 -0
- package/lib/setup.js +522 -0
- package/lib/ws.js +466 -0
- package/package.json +103 -4
- package/profiles/README.md +573 -0
- package/profiles/hub.cordis.yml +84 -0
- package/profiles/worker.cordis.yml +60 -0
- package/scripts/check-doc-drift.mjs +785 -0
- package/scripts/check-packaging.mjs +130 -0
- package/scripts/diag-inject.mjs +243 -0
- package/scripts/e2e-live-check.mjs +181 -0
- package/scripts/relay-init.ps1 +286 -0
- package/scripts/relay-init.sh +199 -0
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 副机侧的传输层:把"连到 hub"这件事抽象成两种后端。
|
|
3
|
+
*
|
|
4
|
+
* direct —— 直连 hub 的 WebSocket 端点(双方至少一方有公网地址 / cloudflared)
|
|
5
|
+
* relay —— 经中继 VPS 会合(双方都在 NAT 后)
|
|
6
|
+
*
|
|
7
|
+
* 对上层(worker)暴露同一个接口:send / sendBinary / on('frame') / on('binary')。
|
|
8
|
+
* 任务逻辑完全不需要知道自己在走哪条管子 —— 这是 transportMode 能成为纯配置项的前提。
|
|
9
|
+
*
|
|
10
|
+
* 重连策略:指数退避 + 抖动,封顶 30s。断连期间任务**不中断**(核心不变式),
|
|
11
|
+
* 重连成功后由 worker 主动 task/sync 上报状态,hub 侧由此重建视图。
|
|
12
|
+
*/
|
|
13
|
+
import { EventEmitter } from 'node:events'
|
|
14
|
+
import {
|
|
15
|
+
ERROR_CODE,
|
|
16
|
+
HUB_TO_NODE,
|
|
17
|
+
NODE_TO_HUB,
|
|
18
|
+
PROTOCOL_VERSION,
|
|
19
|
+
RELAY_FRAME,
|
|
20
|
+
decodeBinaryFrame,
|
|
21
|
+
decodeFrame,
|
|
22
|
+
encodeBinaryFrame,
|
|
23
|
+
encodeFrame,
|
|
24
|
+
envelope,
|
|
25
|
+
} from '../protocol.js'
|
|
26
|
+
import { connect } from '../ws.js'
|
|
27
|
+
// P2-11:hub 身份验证。transport 不碰 fs —— pin 落盘经构造注入(pinStore)。
|
|
28
|
+
import { fingerprintOf, newNonce, normalizeFingerprint, verifyIdentity } from '../identity.js'
|
|
29
|
+
// 提案 #1:E2E 会话加密(中继不可见业务帧内容)。
|
|
30
|
+
import { E2E_MARKER, generateEphemeral, verifyExchange, createSession, normalizeE2EPub } from '../e2e.js'
|
|
31
|
+
|
|
32
|
+
export const TRANSPORT_MODE = Object.freeze({ DIRECT: 'direct', RELAY: 'relay' })
|
|
33
|
+
|
|
34
|
+
const BACKOFF_BASE_MS = 1000
|
|
35
|
+
const BACKOFF_MAX_MS = 30_000
|
|
36
|
+
const HEARTBEAT_MS = 15_000
|
|
37
|
+
const HEARTBEAT_TIMEOUT_MS = 45_000
|
|
38
|
+
/**
|
|
39
|
+
* 握手超时:upgrade 成功后,hub 必须在这个时间内回 welcome(direct)或
|
|
40
|
+
* 中继回 accepted(relay)。此前 heartbeat 只在 markOnline 之后启动,
|
|
41
|
+
* 服务端若 upgrade 后不发帧,连接会**永久挂起且不重连** —— 小白看到的就是
|
|
42
|
+
* "副机没反应",而日志里连一条错误都没有。
|
|
43
|
+
*
|
|
44
|
+
* 取值与 hub 侧 helloTimeoutMs(10s)对齐:两边给同一次握手各 10s 预算。
|
|
45
|
+
*/
|
|
46
|
+
const HANDSHAKE_TIMEOUT_MS = 10_000
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* P2-11:relay 模式下等 hub 追发身份帧的宽限窗口。
|
|
50
|
+
* direct 模式不需要它 —— 身份就在 welcome 里,随握手一起到。
|
|
51
|
+
*/
|
|
52
|
+
export const IDENTITY_GRACE_MS = 15_000
|
|
53
|
+
/** hub 身份帧时间戳容差:双方时钟各让 5 分钟。 */
|
|
54
|
+
export const IDENTITY_MAX_SKEW_MS = 5 * 60 * 1000
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 提案 #1:会话建立后**必须加密**的下行业务帧类型。
|
|
58
|
+
* 明文形态出现在这里 = 伪造(中继运营者持有 enrollToken 可冒充 hub)或
|
|
59
|
+
* hub 丢失会话 —— 一律拒绝执行并回 e2e-required。
|
|
60
|
+
* welcome / hub/identity / error / ping / hub/e2e 是握手与控制面,永远明文豁免。
|
|
61
|
+
*/
|
|
62
|
+
const E2E_REQUIRED_TYPES = new Set([
|
|
63
|
+
HUB_TO_NODE.TASK_START,
|
|
64
|
+
HUB_TO_NODE.TASK_CANCEL,
|
|
65
|
+
HUB_TO_NODE.TASK_QUERY,
|
|
66
|
+
HUB_TO_NODE.ARTIFACT_LIST,
|
|
67
|
+
HUB_TO_NODE.ARTIFACT_PULL,
|
|
68
|
+
HUB_TO_NODE.ARTIFACT_CANCEL,
|
|
69
|
+
])
|
|
70
|
+
|
|
71
|
+
/** 副机侧永远明文的帧类型(握手/心跳/交换本身)。 */
|
|
72
|
+
const E2E_CLEAR_TYPES = new Set([
|
|
73
|
+
'hello',
|
|
74
|
+
RELAY_FRAME.HELLO_NODE,
|
|
75
|
+
'ping',
|
|
76
|
+
'pong',
|
|
77
|
+
NODE_TO_HUB.E2E_OFFER,
|
|
78
|
+
])
|
|
79
|
+
|
|
80
|
+
/** 把各种写法收敛成 ws:// 或 wss:// 的 URL。 */
|
|
81
|
+
export function normalizeWsUrl(raw, fallbackPath = '/') {
|
|
82
|
+
if (typeof raw !== 'string' || raw.trim() === '') return ''
|
|
83
|
+
let s = raw.trim()
|
|
84
|
+
if (!/^wss?:\/\//i.test(s)) {
|
|
85
|
+
if (/^https:\/\//i.test(s)) s = `wss://${s.slice(8)}`
|
|
86
|
+
else if (/^http:\/\//i.test(s)) s = `ws://${s.slice(7)}`
|
|
87
|
+
else s = `ws://${s}`
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const u = new URL(s)
|
|
91
|
+
if (u.pathname === '/' || u.pathname === '') u.pathname = fallbackPath
|
|
92
|
+
return u.toString()
|
|
93
|
+
} catch {
|
|
94
|
+
return ''
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* 一个可重连的节点连接。
|
|
100
|
+
* 事件:'online'(ack) / 'offline'(reason) / 'reconnecting'({attempt,delayMs}) /
|
|
101
|
+
* 'frame'(frame) / 'binary'(header,payload) / 'error'(err)
|
|
102
|
+
*/
|
|
103
|
+
export class NodeTransport extends EventEmitter {
|
|
104
|
+
constructor(o) {
|
|
105
|
+
super()
|
|
106
|
+
this.mode = o.mode === TRANSPORT_MODE.RELAY ? TRANSPORT_MODE.RELAY : TRANSPORT_MODE.DIRECT
|
|
107
|
+
this.rawUrl = o.url
|
|
108
|
+
this.token = o.token ?? ''
|
|
109
|
+
this.hello = o.hello
|
|
110
|
+
this.heartbeatMs = o.heartbeatMs ?? HEARTBEAT_MS
|
|
111
|
+
this.conn = undefined
|
|
112
|
+
this.online = false
|
|
113
|
+
this.attempt = 0
|
|
114
|
+
this.stopped = false
|
|
115
|
+
this.lastPongAt = 0
|
|
116
|
+
this.timer = undefined
|
|
117
|
+
this.hbTimer = undefined
|
|
118
|
+
this.hsTimer = undefined
|
|
119
|
+
// ── P2-11:hub 身份验证 ──
|
|
120
|
+
// pinnedFingerprint 来自显式配置(最高优先级);pinStore 是 TOFU 落盘的
|
|
121
|
+
// 三件套 { get/set/clear },由 worker 用 <stateDir>/hub-pin.json 实现 ——
|
|
122
|
+
// transport 自身不碰 fs,测试可以注入内存实现。
|
|
123
|
+
this.pinnedFingerprint = normalizeFingerprint(o.pinnedFingerprint ?? '')
|
|
124
|
+
this.pinStore = o.pinStore ?? null
|
|
125
|
+
this.identityGraceMs = Number.isFinite(o.identityGraceMs) ? o.identityGraceMs : IDENTITY_GRACE_MS
|
|
126
|
+
/** hub 身份状态:'pending'(未验证)| 'ok'(已验过)| 'absent'(hub 未提供,旧版兼容)。 */
|
|
127
|
+
this.hubIdentity = 'pending'
|
|
128
|
+
this.identityTimer = undefined
|
|
129
|
+
// ── 提案 #1:E2E 会话加密 ──
|
|
130
|
+
// e2e:false 可关(默认开)。会话/提议随连接生死:close 一律清零。
|
|
131
|
+
this.e2eEnabled = o.e2e !== false
|
|
132
|
+
/** 已协商的 E2ESession(null = 明文)。 */
|
|
133
|
+
this.e2e = null
|
|
134
|
+
/** 在途的握手提议 { privateKeyB64, publicKeyB64, nonce, timer }。 */
|
|
135
|
+
this.e2eOffer = null
|
|
136
|
+
/** 已验证的 hub 身份 { fp, pub }(E2E 确认帧的验签锚)。 */
|
|
137
|
+
this.identityPeer = null
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
resolveUrl() {
|
|
141
|
+
if (this.mode === TRANSPORT_MODE.RELAY) {
|
|
142
|
+
const base = normalizeWsUrl(this.rawUrl, '/relay')
|
|
143
|
+
if (base === '') return ''
|
|
144
|
+
const u = new URL(base)
|
|
145
|
+
u.searchParams.set('role', 'node')
|
|
146
|
+
// ⚠ token **不再**放进 URL query。
|
|
147
|
+
//
|
|
148
|
+
// 原来这里是 `u.searchParams.set('token', this.token)` —— 而 URL 会进
|
|
149
|
+
// 各级访问日志(中继自己的 access log、反向代理、CDN、浏览器历史、
|
|
150
|
+
// Referer)。凭证写进 URL 等于把密钥抄在很多地方。
|
|
151
|
+
//
|
|
152
|
+
// 中继侧本来就支持 header 优先:
|
|
153
|
+
// `url.searchParams.get('token') ?? req.headers['x-relay-token']`
|
|
154
|
+
// 所以改成走 header(见 connectOnce 里的 headers)。
|
|
155
|
+
//
|
|
156
|
+
// direct 模式早就是这个做法(`x-dsh-token` header),relay 模式此前与它
|
|
157
|
+
// 不对称 —— 这是评审指出的不一致。
|
|
158
|
+
u.searchParams.set('nodeId', this.hello.nodeId)
|
|
159
|
+
return u.toString()
|
|
160
|
+
}
|
|
161
|
+
return normalizeWsUrl(this.rawUrl, '/api/remote-agent/node')
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
start() {
|
|
165
|
+
this.stopped = false
|
|
166
|
+
void this.connectOnce()
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async connectOnce() {
|
|
170
|
+
if (this.stopped) return
|
|
171
|
+
const url = this.resolveUrl()
|
|
172
|
+
if (url === '') {
|
|
173
|
+
this.emit('error', new Error(`transport: invalid url "${this.rawUrl}"`))
|
|
174
|
+
this.scheduleReconnect()
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// 凭证一律走 header,不走 URL query(URL 会进各级日志)。
|
|
179
|
+
// 两种模式用不同的 header 名,因为两端是不同组件:
|
|
180
|
+
// direct → 主机 DSH 的直连 upgrade 端点,认 `x-dsh-token`
|
|
181
|
+
// relay → 中继服务,认 `x-relay-token`
|
|
182
|
+
const headers = {}
|
|
183
|
+
if (this.token) {
|
|
184
|
+
if (this.mode === TRANSPORT_MODE.DIRECT) headers['x-dsh-token'] = this.token
|
|
185
|
+
else headers['x-relay-token'] = this.token
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
const conn = await connect(url, { headers, name: `node:${this.hello.nodeId}` })
|
|
190
|
+
if (this.stopped) {
|
|
191
|
+
conn.close(1000, 'stopped')
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
this.conn = conn
|
|
195
|
+
this.attach(conn)
|
|
196
|
+
// P2-11:新连接 → hub 身份重新进入待验证态(上一条连接的结论对新连接无效,
|
|
197
|
+
// 也可能连到了另一个 hub)。worker 侧凭这个状态拦宽限窗口内的任务。
|
|
198
|
+
this.setHubIdentity('pending')
|
|
199
|
+
// 提案 #1:新连接 = 旧会话密钥作废(ECDH 临时钥不复用),从头协商。
|
|
200
|
+
this.resetE2E()
|
|
201
|
+
this.handshake()
|
|
202
|
+
this.armHandshakeTimeout(conn)
|
|
203
|
+
} catch (err) {
|
|
204
|
+
this.emit('error', err)
|
|
205
|
+
this.scheduleReconnect()
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 握手超时守卫。upgrade 成功、hello 发出之后,`markOnline`(welcome /
|
|
211
|
+
* accepted)必须在预算内到达;不到就毁掉这条连接 —— close 处理器会照常
|
|
212
|
+
* 走重连退避,避免"TCP 连着但永远上不了线"的哑状态。
|
|
213
|
+
*
|
|
214
|
+
* 必须校验 `this.conn === conn`:超时触发时连接可能已被更新的连接顶替
|
|
215
|
+
* (与 RelayLink 的陈旧连接问题同源),此时不能动新连接。
|
|
216
|
+
*/
|
|
217
|
+
armHandshakeTimeout(conn) {
|
|
218
|
+
this.stopHandshakeTimeout()
|
|
219
|
+
this.hsTimer = setTimeout(() => {
|
|
220
|
+
this.hsTimer = undefined
|
|
221
|
+
if (this.online || this.conn !== conn || conn.closed) return
|
|
222
|
+
this.emit('error', new Error(`handshake timeout: no welcome/accepted within ${HANDSHAKE_TIMEOUT_MS}ms`))
|
|
223
|
+
try {
|
|
224
|
+
conn.destroy(new Error('handshake timeout'))
|
|
225
|
+
} catch {
|
|
226
|
+
/* 已销毁,close 处理器接手 */
|
|
227
|
+
}
|
|
228
|
+
}, HANDSHAKE_TIMEOUT_MS)
|
|
229
|
+
if (this.hsTimer.unref) this.hsTimer.unref()
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
stopHandshakeTimeout() {
|
|
233
|
+
if (this.hsTimer) {
|
|
234
|
+
clearTimeout(this.hsTimer)
|
|
235
|
+
this.hsTimer = undefined
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
attach(conn) {
|
|
240
|
+
conn.on('message', (payload, isBinary) => {
|
|
241
|
+
if (isBinary) {
|
|
242
|
+
const dec = decodeBinaryFrame(payload)
|
|
243
|
+
if (!dec.ok) {
|
|
244
|
+
this.emit('error', new Error(`transport: bad binary frame (${dec.error})`))
|
|
245
|
+
return
|
|
246
|
+
}
|
|
247
|
+
// E2E 解密(提案 #1):带标记的先拆密,把内层 header/payload 交上层。
|
|
248
|
+
let hdr = dec.header
|
|
249
|
+
let pl = dec.payload
|
|
250
|
+
if (hdr && hdr.e2e === E2E_MARKER) {
|
|
251
|
+
if (!this.e2e) {
|
|
252
|
+
this.emit('error', new Error('收到加密二进制帧但 E2E 会话未建立,已丢弃'))
|
|
253
|
+
return
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const opened = this.e2e.openBinary(hdr.t, hdr, pl)
|
|
257
|
+
hdr = opened.header
|
|
258
|
+
pl = opened.payload
|
|
259
|
+
} catch (err) {
|
|
260
|
+
this.emit('error', new Error(`E2E 二进制解密失败,已丢弃:${err?.message ?? err}`))
|
|
261
|
+
return
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
this.emit('binary', hdr, pl)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
const dec = decodeFrame(payload)
|
|
268
|
+
if (!dec.ok) {
|
|
269
|
+
this.emit('error', new Error(`transport: bad frame (${dec.error})`))
|
|
270
|
+
return
|
|
271
|
+
}
|
|
272
|
+
this.handleFrame(dec.frame)
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
conn.on('pong', () => {
|
|
276
|
+
this.lastPongAt = Date.now()
|
|
277
|
+
})
|
|
278
|
+
|
|
279
|
+
conn.on('close', (code, reason) => {
|
|
280
|
+
const wasOnline = this.online
|
|
281
|
+
this.online = false
|
|
282
|
+
this.conn = undefined
|
|
283
|
+
this.stopHandshakeTimeout()
|
|
284
|
+
this.stopHeartbeat()
|
|
285
|
+
this.stopIdentityGrace()
|
|
286
|
+
// 提案 #1:会话随连接生死 —— 密钥材料销毁,下条连接重新协商。
|
|
287
|
+
this.resetE2E()
|
|
288
|
+
if (wasOnline) this.emit('offline', `closed ${code}${reason ? `: ${reason}` : ''}`)
|
|
289
|
+
if (!this.stopped) this.scheduleReconnect()
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
conn.on('error', (err) => this.emit('error', err))
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
handshake() {
|
|
296
|
+
// P2-11:每次连接换 nonce,hub 把它签进身份证明 —— 录一帧旧 welcome
|
|
297
|
+
// 重放给新连接会因 nonce 对不上被拒。hello 冻结等异常时静默退化
|
|
298
|
+
// (hub 自拟 nonce + ±5min 时间窗兜底)。
|
|
299
|
+
try {
|
|
300
|
+
this.hello.nonce = newNonce()
|
|
301
|
+
} catch {
|
|
302
|
+
/* hello 只读:走退化路径 */
|
|
303
|
+
}
|
|
304
|
+
if (this.mode === TRANSPORT_MODE.RELAY) {
|
|
305
|
+
this.sendRaw(RELAY_FRAME.HELLO_NODE, { ...this.hello, protocol: PROTOCOL_VERSION })
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
this.sendRaw('hello', { ...this.hello, protocol: PROTOCOL_VERSION })
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
handleFrame(frame) {
|
|
312
|
+
// E2E 解密(提案 #1):带标记的帧先拆密再走分发。会话不存在时丢帧 ——
|
|
313
|
+
// 正常时序里 ack 先于任何密文到达(WS FIFO),除非被中间人插队。
|
|
314
|
+
let wasEncrypted = false
|
|
315
|
+
if (frame.d && frame.d.e2e === E2E_MARKER) {
|
|
316
|
+
if (!this.e2e) {
|
|
317
|
+
this.emit('error', new Error('收到加密帧但 E2E 会话未建立,已丢弃(疑似伪造或时序错乱)'))
|
|
318
|
+
return
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
frame = { ...frame, d: this.e2e.openFrame(frame.t, frame.id, frame.d) }
|
|
322
|
+
wasEncrypted = true
|
|
323
|
+
} catch (err) {
|
|
324
|
+
this.emit('error', new Error(`E2E 解密失败,已丢弃该帧:${err?.message ?? err}`))
|
|
325
|
+
return
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (frame.t === 'welcome') {
|
|
329
|
+
if (this.mode === TRANSPORT_MODE.DIRECT) {
|
|
330
|
+
// P2-11:先验 hub 身份,验过才上线 —— 假 hub 回一帧 welcome 让副机
|
|
331
|
+
// 上线的路,在这里被钉住的指纹挡死。
|
|
332
|
+
const v = this.verifyHubIdentity(frame.d?.identity)
|
|
333
|
+
if (!v.ok) {
|
|
334
|
+
this.failHubIdentity(v.reason)
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
this.setHubIdentity(v.status)
|
|
338
|
+
this.markOnline(frame.d)
|
|
339
|
+
}
|
|
340
|
+
return
|
|
341
|
+
}
|
|
342
|
+
if (frame.t === HUB_TO_NODE.IDENTITY) {
|
|
343
|
+
// P2-11:relay 模式 hub 在上线后追发的身份帧(direct 模式重发也照收,
|
|
344
|
+
// 幂等 —— 验证逻辑无副作用,只有 TOFU 首次落盘)。
|
|
345
|
+
this.stopIdentityGrace()
|
|
346
|
+
const v = this.verifyHubIdentity(frame.d)
|
|
347
|
+
if (!v.ok) {
|
|
348
|
+
this.failHubIdentity(v.reason)
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
this.setHubIdentity(v.status)
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
if (frame.t === HUB_TO_NODE.E2E_ACK) {
|
|
355
|
+
// 提案 #1:密钥交换确认。明文帧(此时还没有共享密钥)。
|
|
356
|
+
this.handleE2EAck(frame.d)
|
|
357
|
+
return
|
|
358
|
+
}
|
|
359
|
+
if (frame.t === RELAY_FRAME.HELLO_HUB) {
|
|
360
|
+
// relay 自身的握手回执,节点继续等 hello/node 的 accepted
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
if (frame.t === RELAY_FRAME.HELLO_NODE) {
|
|
364
|
+
if (this.mode === TRANSPORT_MODE.RELAY) {
|
|
365
|
+
if (frame.d?.accepted === true) {
|
|
366
|
+
this.markOnline({ relay: true, nodeId: frame.d.nodeId })
|
|
367
|
+
// P2-11:relay 模式的"在线"信号来自中继,hub 身份还没验 —— 开一个
|
|
368
|
+
// 宽限窗口等追发的 hub/identity;窗口内到达的任务由 worker 拦下。
|
|
369
|
+
this.armIdentityGrace()
|
|
370
|
+
} else this.emit('error', new Error(`relay rejected hello: ${JSON.stringify(frame.d)}`))
|
|
371
|
+
}
|
|
372
|
+
return
|
|
373
|
+
}
|
|
374
|
+
// 中继级错误与 hub 错误帧共用 t='error'(RELAY_FRAME.ERROR === HUB_TO_NODE.ERROR)。
|
|
375
|
+
if (frame.t === RELAY_FRAME.ERROR) {
|
|
376
|
+
const code = frame.d?.code ?? 'relay-error'
|
|
377
|
+
if (code === ERROR_CODE.E2E_RESET) {
|
|
378
|
+
// 提案 #1:hub 侧丢了会话(典型:hub 重启而中继连接还在)。清掉本地
|
|
379
|
+
// 会话重新握手 —— 提议已在途时跳过(避免 reset 风暴下反复重发)。
|
|
380
|
+
if (this.e2e) {
|
|
381
|
+
this.e2e.destroy()
|
|
382
|
+
this.e2e = null
|
|
383
|
+
}
|
|
384
|
+
this.emit('e2e', 'reset')
|
|
385
|
+
if (!this.e2eOffer) this.beginE2EOffer()
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
this.emit('error', new Error(`relay error: ${code} ${frame.d?.message ?? ''}`.trim()))
|
|
389
|
+
if (code === 'duplicate-node' || code === 'node-id-invalid' || code === 'unauthorized' || code === 'revoked') {
|
|
390
|
+
// 这类错误重连不会自愈,停下来等人工处理,避免把中继刷爆
|
|
391
|
+
this.stop()
|
|
392
|
+
}
|
|
393
|
+
return
|
|
394
|
+
}
|
|
395
|
+
if (frame.t === 'ping') {
|
|
396
|
+
this.sendRaw('pong', { echo: frame.id })
|
|
397
|
+
return
|
|
398
|
+
}
|
|
399
|
+
// 会话已建立后,未加密的业务帧一律拒绝(fail-closed)—— 中继运营者
|
|
400
|
+
// 持有 enrollToken、可以伪造"hub"发任意 task/start;加密层是唯一能挡住
|
|
401
|
+
// 它的防线。明文 task 帧在此处死,绝不执行。带标记的帧在顶部已解开,
|
|
402
|
+
// wasEncrypted 为真不会进这里。
|
|
403
|
+
if (this.e2e && !wasEncrypted && E2E_REQUIRED_TYPES.has(frame.t)) {
|
|
404
|
+
this.emit('error', new Error(`收到明文 ${frame.t} 帧(E2E 已启用)—— 已拒绝执行,疑似伪造或 hub 丢失会话`))
|
|
405
|
+
this.sendRaw(NODE_TO_HUB.ERROR, { code: ERROR_CODE.E2E_REQUIRED, message: `unencrypted ${frame.t} rejected while e2e session active` })
|
|
406
|
+
return
|
|
407
|
+
}
|
|
408
|
+
this.emit('frame', frame)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/* ───────────────── P2-11:hub 身份验证 ───────────────── */
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* 验证 hub 身份帧。返回 {ok:true,status:'ok'|'absent'} 或 {ok:false,reason}。
|
|
415
|
+
*
|
|
416
|
+
* 验证链(任何一环失败即整体失败,fail-closed):
|
|
417
|
+
* 1. 指纹自洽 —— sha256(报上来的公钥) 必须等于报上来的指纹,
|
|
418
|
+
* 防"报真指纹、递假钥匙"的糊弄;
|
|
419
|
+
* 2. 指纹匹配 pin —— 显式配置或 TOFU 落盘的值,这是主防线;
|
|
420
|
+
* 3. ed25519 验签;
|
|
421
|
+
* 4. nonce 回显 —— 必须等于本次 hello 发出的(防重放旧帧);
|
|
422
|
+
* 5. 时间窗 —— |now - at| ≤ 5min(nonce 缺失时的兜底)。
|
|
423
|
+
*
|
|
424
|
+
* 'absent' = hub 没提供身份(旧版 hub)。只在**没有任何 pin 期望**时放行:
|
|
425
|
+
* 已钉住指纹的副机遇到不报身份的 hub 一律视为红线(身份帧可能被中间人
|
|
426
|
+
* 剥掉),绝不静默降级。
|
|
427
|
+
*/
|
|
428
|
+
verifyHubIdentity(idFrame) {
|
|
429
|
+
const endpoint = this.resolveUrl()
|
|
430
|
+
const expected = this.expectedPin(endpoint)
|
|
431
|
+
if (!idFrame || typeof idFrame !== 'object') {
|
|
432
|
+
if (expected) return { ok: false, reason: `pinned hub (${expected.fingerprint}) presented no identity frame` }
|
|
433
|
+
return { ok: true, status: 'absent' }
|
|
434
|
+
}
|
|
435
|
+
const { fp, pub, sig, at, nonce } = idFrame
|
|
436
|
+
if (typeof fp !== 'string' || typeof pub !== 'string' || pub === '' || typeof sig !== 'string') {
|
|
437
|
+
return { ok: false, reason: 'malformed identity frame' }
|
|
438
|
+
}
|
|
439
|
+
const fpNorm = normalizeFingerprint(fp)
|
|
440
|
+
if (!fpNorm || fingerprintOf(Buffer.from(pub, 'base64url')) !== fpNorm) {
|
|
441
|
+
return { ok: false, reason: 'fingerprint does not match presented public key' }
|
|
442
|
+
}
|
|
443
|
+
if (expected && fpNorm !== expected.fingerprint) {
|
|
444
|
+
return { ok: false, reason: `hub fingerprint mismatch: pinned ${expected.fingerprint}, got ${fpNorm}` }
|
|
445
|
+
}
|
|
446
|
+
if (!verifyIdentity(pub, { fingerprint: fpNorm, nodeId: this.hello.nodeId, nonce: typeof nonce === 'string' ? nonce : '', at: typeof at === 'number' ? at : 0 }, sig)) {
|
|
447
|
+
return { ok: false, reason: 'hub identity signature invalid' }
|
|
448
|
+
}
|
|
449
|
+
const sentNonce = typeof this.hello.nonce === 'string' ? this.hello.nonce : ''
|
|
450
|
+
if (sentNonce !== '' && nonce !== sentNonce) {
|
|
451
|
+
return { ok: false, reason: 'identity nonce does not match this connection (replayed frame?)' }
|
|
452
|
+
}
|
|
453
|
+
if (Math.abs(Date.now() - (typeof at === 'number' ? at : 0)) > IDENTITY_MAX_SKEW_MS) {
|
|
454
|
+
return { ok: false, reason: 'identity timestamp outside ±5min window' }
|
|
455
|
+
}
|
|
456
|
+
// TOFU:没有任何 pin 期望时,把这次验证过的指纹钉住(endpoint 一并记录,
|
|
457
|
+
// 供"用户换了拨入地址 → 重新 TOFU"的判定)。
|
|
458
|
+
if (!expected && this.pinStore) {
|
|
459
|
+
const saved = this.pinStore.set({ fingerprint: fpNorm, endpoint })
|
|
460
|
+
if (!saved) this.emit('error', new Error('hub pin 落盘失败 —— 下次连接将重新首连钉住'))
|
|
461
|
+
}
|
|
462
|
+
// 提案 #1:记录已验证的 hub 身份 —— E2E 确认帧(hub/e2e)的验签锚。
|
|
463
|
+
this.identityPeer = { fp: fpNorm, pub }
|
|
464
|
+
return { ok: true, status: 'ok', fingerprint: fpNorm }
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* 当前生效的指纹期望:显式配置 > pin 文件。
|
|
469
|
+
*
|
|
470
|
+
* pin 文件记录的 endpoint 与本次拨入地址不同 → 视为"用户自己换了 hub"
|
|
471
|
+
* (本地配置行为,远程攻击者改不了副机的配置),发 re-pin 提示并返回
|
|
472
|
+
* null 重新 TOFU。endpoint 缺省(旧格式)时不比较,从严处理。
|
|
473
|
+
*/
|
|
474
|
+
expectedPin(endpoint) {
|
|
475
|
+
if (this.pinnedFingerprint) return { fingerprint: this.pinnedFingerprint, source: 'config' }
|
|
476
|
+
const stored = this.pinStore?.get?.() ?? null
|
|
477
|
+
if (!stored?.fingerprint) return null
|
|
478
|
+
if (stored.endpoint && endpoint && stored.endpoint !== endpoint) {
|
|
479
|
+
this.emit('re-pin', { from: stored.endpoint, to: endpoint, fingerprint: stored.fingerprint })
|
|
480
|
+
return null
|
|
481
|
+
}
|
|
482
|
+
return { fingerprint: stored.fingerprint, source: 'file' }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
setHubIdentity(status) {
|
|
486
|
+
if (this.hubIdentity === status) return
|
|
487
|
+
this.hubIdentity = status
|
|
488
|
+
this.emit('hubIdentity', status)
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* 身份验证失败:大声报错并**停止重连**。
|
|
493
|
+
*
|
|
494
|
+
* 这不是瞬时网络问题 —— 指纹不匹配意味着假 hub / 中间人 / hub 身份被重建,
|
|
495
|
+
* 盲目重连只会无限循环刷错误。钉住的指纹**不**清除:失败持续可见,修法
|
|
496
|
+
* 只有两条 —— 确认是主动换 hub 后删 <stateDir>/hub-pin.json(或更新
|
|
497
|
+
* pinnedHubFingerprint),或者去查为什么有人站在中间。
|
|
498
|
+
*/
|
|
499
|
+
failHubIdentity(reason) {
|
|
500
|
+
this.stopIdentityGrace()
|
|
501
|
+
this.emit('error', new Error(
|
|
502
|
+
`hub 身份验证失败,已停止重连:${reason}`
|
|
503
|
+
+ ' —— 若你确实更换了 hub,删除副机 stateDir 下的 hub-pin.json(或更新 pinnedHubFingerprint)后重启副机;'
|
|
504
|
+
+ '否则请排查是否被中间人劫持。',
|
|
505
|
+
))
|
|
506
|
+
this.stop()
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* relay 模式的身份宽限窗口:上线后 hub/identity 必须在窗口内到达。
|
|
511
|
+
* 超时分支按"有没有 pin 期望"分两种结局 —— 有 pin = 拒绝(我们钉住的
|
|
512
|
+
* hub 没证明自己,可能被剥帧);无 pin = absent 放行(旧版 hub 兼容)。
|
|
513
|
+
*/
|
|
514
|
+
armIdentityGrace() {
|
|
515
|
+
this.stopIdentityGrace()
|
|
516
|
+
this.identityTimer = setTimeout(() => {
|
|
517
|
+
this.identityTimer = undefined
|
|
518
|
+
if (this.hubIdentity !== 'pending' || !this.online) return
|
|
519
|
+
const expected = this.expectedPin(this.resolveUrl())
|
|
520
|
+
if (expected) {
|
|
521
|
+
this.failHubIdentity(`pinned hub sent no identity frame within ${this.identityGraceMs}ms`)
|
|
522
|
+
return
|
|
523
|
+
}
|
|
524
|
+
this.setHubIdentity('absent')
|
|
525
|
+
this.emit('error', new Error('提示:hub 未提供身份帧(可能是旧版 hub)—— 按无身份认证模式继续,建议两端都升级到同一版本'))
|
|
526
|
+
}, this.identityGraceMs)
|
|
527
|
+
if (this.identityTimer.unref) this.identityTimer.unref()
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
stopIdentityGrace() {
|
|
531
|
+
if (this.identityTimer) {
|
|
532
|
+
clearTimeout(this.identityTimer)
|
|
533
|
+
this.identityTimer = undefined
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
markOnline(ack) {
|
|
538
|
+
this.online = true
|
|
539
|
+
this.attempt = 0
|
|
540
|
+
this.lastPongAt = Date.now()
|
|
541
|
+
this.stopHandshakeTimeout()
|
|
542
|
+
this.startHeartbeat()
|
|
543
|
+
// 提案 #1:上线即提议 E2E 握手(direct/relay 通吃 —— direct 的 ws:// 同样
|
|
544
|
+
// 可能是明文链路)。放在 emit('online') **之前**:worker 收到 online 后立刻
|
|
545
|
+
// 发的 task/sync 已排在提议之后,保证 hub 先看到 offer。
|
|
546
|
+
if (this.e2eEnabled) this.beginE2EOffer()
|
|
547
|
+
this.emit('online', ack ?? {})
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/* ───────────────── 提案 #1:E2E 会话加密 ───────────────── */
|
|
551
|
+
|
|
552
|
+
/** 每次连接/重连清一次 E2E 状态(密钥材料销毁,绝不跨连接复用)。 */
|
|
553
|
+
resetE2E() {
|
|
554
|
+
if (this.e2e) {
|
|
555
|
+
this.e2e.destroy()
|
|
556
|
+
this.e2e = null
|
|
557
|
+
}
|
|
558
|
+
this.clearE2EOfferTimer()
|
|
559
|
+
this.e2eOffer = null
|
|
560
|
+
this.identityPeer = null
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
clearE2EOfferTimer() {
|
|
564
|
+
if (this.e2eOffer?.timer) {
|
|
565
|
+
clearTimeout(this.e2eOffer.timer)
|
|
566
|
+
this.e2eOffer.timer = undefined
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** E2E_ACK 等待窗口:超时只是"没握成",按明文继续(旧版 hub 兼容),只提示不报错。 */
|
|
571
|
+
E2E_ACK_TIMEOUT_MS = 5_000
|
|
572
|
+
/** 重置风暴去抖:连续 e2e-reset 时最多每 250ms 重发一次提议。 */
|
|
573
|
+
E2E_REOFFER_DEBOUNCE_MS = 250
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* 发出 node/e2e 提议:一次性 X25519 公钥 + 连接 nonce。
|
|
577
|
+
* hub 的确认帧(hub/e2e)签名绑定这两个值 —— 中继偷换/重放都会在副机
|
|
578
|
+
* 验签处失败。会话就绪前业务帧继续明文(hub 两侧都接受)。
|
|
579
|
+
*/
|
|
580
|
+
beginE2EOffer() {
|
|
581
|
+
this.clearE2EOfferTimer()
|
|
582
|
+
if (!this.online || !this.conn || this.conn.closed) return
|
|
583
|
+
const eph = generateEphemeral()
|
|
584
|
+
const nonce = newNonce()
|
|
585
|
+
this.e2eOffer = { ...eph, nonce }
|
|
586
|
+
this.e2eOffer.timer = setTimeout(() => {
|
|
587
|
+
if (!this.e2eOffer) return
|
|
588
|
+
this.e2eOffer.timer = undefined
|
|
589
|
+
this.e2eOffer = null
|
|
590
|
+
// 不是错误 —— 旧版 hub 不认识 node/e2e,按未知帧忽略。降级可见即可。
|
|
591
|
+
this.emit('e2e', 'timeout')
|
|
592
|
+
}, this.E2E_ACK_TIMEOUT_MS)
|
|
593
|
+
if (this.e2eOffer.timer.unref) this.e2eOffer.timer.unref()
|
|
594
|
+
this.sendRaw(NODE_TO_HUB.E2E_OFFER, { pub: eph.publicKeyB64, nonce })
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* 处理 hub/e2e 确认帧。验证链(fail-closed):
|
|
599
|
+
* 1. 必须有在途提议(没提议过就收到 ack = 伪造);
|
|
600
|
+
* 2. 必须已验证 hub 身份(P2-11 链)—— 没有验签锚就不该有 ack;
|
|
601
|
+
* 3. ed25519 验签(绑定双方临时公钥 + 本连接 nonce + 时间窗)。
|
|
602
|
+
* 任一失败:伪造 = 中间人,大声报错并停止重连(与身份失败同待遇);
|
|
603
|
+
* 形态不对 = 版本错乱,丢帧按明文继续。
|
|
604
|
+
*/
|
|
605
|
+
handleE2EAck(d) {
|
|
606
|
+
if (!this.e2eOffer) {
|
|
607
|
+
// 没有在途提议:会话已建立(同一提议的重复 ack,reset 风暴下 hub 会话
|
|
608
|
+
// 被后到的 offer 覆盖时会出现)或提议已超时清理 —— 两种都静默忽略,
|
|
609
|
+
// 绝不杀连接。伪造的 ack 本身过不了验签,走到这里的不构成威胁。
|
|
610
|
+
return
|
|
611
|
+
}
|
|
612
|
+
if (!this.identityPeer) {
|
|
613
|
+
this.emit('error', new Error('收到 hub/e2e 但 hub 身份未验证 —— 拒绝建立 E2E 会话'))
|
|
614
|
+
this.stop()
|
|
615
|
+
return
|
|
616
|
+
}
|
|
617
|
+
const peerPub = normalizeE2EPub(d?.pub)
|
|
618
|
+
if (peerPub === '' || typeof d?.sig !== 'string' || typeof d?.at !== 'number') {
|
|
619
|
+
this.emit('error', new Error('hub/e2e 帧形态不对,已丢弃(链路按明文继续)'))
|
|
620
|
+
return
|
|
621
|
+
}
|
|
622
|
+
if (Math.abs(Date.now() - d.at) > IDENTITY_MAX_SKEW_MS) {
|
|
623
|
+
this.emit('error', new Error('hub/e2e 时间戳超出 ±5min 窗口,已丢弃(链路按明文继续)'))
|
|
624
|
+
return
|
|
625
|
+
}
|
|
626
|
+
const ok = verifyExchange(this.identityPeer.pub, {
|
|
627
|
+
fingerprint: this.identityPeer.fp,
|
|
628
|
+
nodeId: this.hello.nodeId,
|
|
629
|
+
nonce: this.e2eOffer.nonce,
|
|
630
|
+
pub: peerPub,
|
|
631
|
+
peerPub: this.e2eOffer.publicKeyB64,
|
|
632
|
+
at: d.at,
|
|
633
|
+
}, d.sig)
|
|
634
|
+
if (!ok) {
|
|
635
|
+
this.failHubIdentity('hub/e2e 签名验证失败 —— 公钥被偷换或 hub 身份不符(疑似中间人)')
|
|
636
|
+
return
|
|
637
|
+
}
|
|
638
|
+
try {
|
|
639
|
+
this.e2e = createSession({
|
|
640
|
+
role: 'node',
|
|
641
|
+
ownPrivB64: this.e2eOffer.privateKeyB64,
|
|
642
|
+
peerPubB64: peerPub,
|
|
643
|
+
nodePubB64: this.e2eOffer.publicKeyB64,
|
|
644
|
+
hubPubB64: peerPub,
|
|
645
|
+
})
|
|
646
|
+
} catch (err) {
|
|
647
|
+
this.emit('error', new Error(`E2E 会话建立失败,链路按明文继续:${err?.message ?? err}`))
|
|
648
|
+
this.e2eOffer = null
|
|
649
|
+
return
|
|
650
|
+
}
|
|
651
|
+
this.clearE2EOfferTimer()
|
|
652
|
+
this.e2eOffer = null
|
|
653
|
+
this.emit('e2e', 'ok')
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
startHeartbeat() {
|
|
657
|
+
this.stopHeartbeat()
|
|
658
|
+
this.hbTimer = setInterval(() => {
|
|
659
|
+
if (!this.conn || this.conn.closed) return
|
|
660
|
+
if (Date.now() - this.lastPongAt > HEARTBEAT_TIMEOUT_MS) {
|
|
661
|
+
this.emit('error', new Error('heartbeat timeout, forcing reconnect'))
|
|
662
|
+
this.conn.destroy(new Error('heartbeat timeout'))
|
|
663
|
+
return
|
|
664
|
+
}
|
|
665
|
+
this.conn.ping()
|
|
666
|
+
this.sendRaw('ping', { time: Date.now() })
|
|
667
|
+
}, this.heartbeatMs)
|
|
668
|
+
if (this.hbTimer.unref) this.hbTimer.unref()
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
stopHeartbeat() {
|
|
672
|
+
if (this.hbTimer) {
|
|
673
|
+
clearInterval(this.hbTimer)
|
|
674
|
+
this.hbTimer = undefined
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
scheduleReconnect() {
|
|
679
|
+
if (this.stopped || this.timer) return
|
|
680
|
+
this.attempt += 1
|
|
681
|
+
const base = Math.min(BACKOFF_BASE_MS * 2 ** (this.attempt - 1), BACKOFF_MAX_MS)
|
|
682
|
+
const jitter = Math.floor(base * 0.2 * Math.random())
|
|
683
|
+
const delay = base + jitter
|
|
684
|
+
this.emit('reconnecting', { attempt: this.attempt, delayMs: delay })
|
|
685
|
+
this.timer = setTimeout(() => {
|
|
686
|
+
this.timer = undefined
|
|
687
|
+
void this.connectOnce()
|
|
688
|
+
}, delay)
|
|
689
|
+
if (this.timer.unref) this.timer.unref()
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/**
|
|
693
|
+
* 发送一个协议信封。
|
|
694
|
+
*
|
|
695
|
+
* 注意 `encodeFrame` 的契约是"收一个完整 frame 对象",不是 (type, data, opts)。
|
|
696
|
+
* 早期版本这里误按三参调用,导致首帧实际发出裸字符串 `"hello/node"`,
|
|
697
|
+
* 对端 decodeFrame 报 missing-type,副机永远上不了线。
|
|
698
|
+
* 统一用 envelope() 构造,与 relay.js / hub/node-registry.js 保持同一形式。
|
|
699
|
+
*/
|
|
700
|
+
sendRaw(type, data, opts) {
|
|
701
|
+
if (!this.conn || this.conn.closed) return false
|
|
702
|
+
const env = envelope(type, data, opts)
|
|
703
|
+
// E2E 封密(提案 #1):握手/心跳/交换帧保持明文,业务帧在会话就绪后自动加密。
|
|
704
|
+
if (this.e2e && !E2E_CLEAR_TYPES.has(type)) {
|
|
705
|
+
try {
|
|
706
|
+
env.d = this.e2e.sealFrame(type, env.id, env.d)
|
|
707
|
+
} catch (err) {
|
|
708
|
+
this.emit('error', new Error(`E2E 封密失败,帧已丢弃:${err?.message ?? err}`))
|
|
709
|
+
return false
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return this.conn.send(encodeFrame(env))
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
send(type, data, opts) {
|
|
716
|
+
return this.sendRaw(type, data, opts)
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
sendBinary(header, payload) {
|
|
720
|
+
if (!this.conn || this.conn.closed) return false
|
|
721
|
+
let hdr = header ?? {}
|
|
722
|
+
let pl = payload ?? Buffer.alloc(0)
|
|
723
|
+
// E2E 封密(提案 #1):内层完整帧(含 pullId/offset/sha256)进密文,
|
|
724
|
+
// 外层只留 t/seq/iv —— 中继看不到文件名与完整性字段。
|
|
725
|
+
if (this.e2e) {
|
|
726
|
+
try {
|
|
727
|
+
const sealed = this.e2e.sealBinary(hdr.t, hdr, pl)
|
|
728
|
+
hdr = sealed.header
|
|
729
|
+
pl = sealed.payload
|
|
730
|
+
} catch (err) {
|
|
731
|
+
this.emit('error', new Error(`E2E 二进制封密失败,帧已丢弃:${err?.message ?? err}`))
|
|
732
|
+
return false
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return this.conn.sendBinary(encodeBinaryFrame(hdr, pl))
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** 写缓冲字节数(产物分块背压用)。 */
|
|
739
|
+
get bufferedBytes() {
|
|
740
|
+
return this.conn?.bufferedBytes ?? 0
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** 等待写缓冲降到阈值以下。 */
|
|
744
|
+
drain(threshold, timeoutMs) {
|
|
745
|
+
if (!this.conn) return Promise.resolve(false)
|
|
746
|
+
return this.conn.drain(threshold, timeoutMs)
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
stop() {
|
|
750
|
+
this.stopped = true
|
|
751
|
+
this.stopHandshakeTimeout()
|
|
752
|
+
this.stopHeartbeat()
|
|
753
|
+
this.stopIdentityGrace()
|
|
754
|
+
this.resetE2E()
|
|
755
|
+
if (this.timer) {
|
|
756
|
+
clearTimeout(this.timer)
|
|
757
|
+
this.timer = undefined
|
|
758
|
+
}
|
|
759
|
+
if (this.conn && !this.conn.closed) this.conn.close(1000, 'node stopping')
|
|
760
|
+
this.conn = undefined
|
|
761
|
+
this.online = false
|
|
762
|
+
}
|
|
763
|
+
}
|