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.
Files changed (70) hide show
  1. package/CHANGELOG.md +700 -0
  2. package/CONTRIBUTING.md +358 -0
  3. package/KNOWN-ISSUES.md +601 -0
  4. package/LICENSE +21 -0
  5. package/README.en.md +353 -0
  6. package/README.md +317 -2
  7. package/SECURITY.md +348 -0
  8. package/bin/dsh-remote-relay.js +257 -0
  9. package/bin/dsh-remote-setup.js +440 -0
  10. 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
  11. package/cordis.patch.yml +87 -0
  12. package/deploy/relay-vps/Caddyfile +24 -0
  13. package/deploy/relay-vps/README.md +132 -0
  14. package/deploy/relay-vps/dsh-remote-relay.service +47 -0
  15. package/deploy/relay-vps/nginx.conf +49 -0
  16. package/deploy/relay-vps/relay.env.example +20 -0
  17. package/docs/dispatch-automation-eval.md +140 -0
  18. package/docs/screenshots/panel-main.png +0 -0
  19. package/docs/screenshots/panel-task-detail.png +0 -0
  20. package/docs/verification-agent-e2e.md +425 -0
  21. package/docs/verification-repos-routing-real.md +521 -0
  22. package/docs/verification-resume-real.md +254 -0
  23. package/docs/worker-setup-pitfalls.md +266 -0
  24. package/lib/artifacts.js +451 -0
  25. package/lib/client.js +1752 -0
  26. package/lib/e2e.js +304 -0
  27. package/lib/glob.js +225 -0
  28. package/lib/hub/audit-log.js +161 -0
  29. package/lib/hub/hub-util.js +114 -0
  30. package/lib/hub/index.js +500 -0
  31. package/lib/hub/node-registry.js +943 -0
  32. package/lib/hub/pull-manager.js +781 -0
  33. package/lib/hub/registry-handshake.js +403 -0
  34. package/lib/hub/registry-ingest.js +346 -0
  35. package/lib/hub/relay-link.js +228 -0
  36. package/lib/hub/subagent-provider.js +424 -0
  37. package/lib/hub/templates.js +693 -0
  38. package/lib/hub/tools.js +1059 -0
  39. package/lib/hub/ui-routes.js +856 -0
  40. package/lib/hub/views.js +351 -0
  41. package/lib/identity.js +271 -0
  42. package/lib/index.js +272 -0
  43. package/lib/node/artifact-service.js +231 -0
  44. package/lib/node/diff.js +124 -0
  45. package/lib/node/exec.js +536 -0
  46. package/lib/node/hub-pin.js +71 -0
  47. package/lib/node/index.js +1022 -0
  48. package/lib/node/repos.js +134 -0
  49. package/lib/node/resource.js +63 -0
  50. package/lib/node/runner.js +792 -0
  51. package/lib/node/task-engine.js +712 -0
  52. package/lib/node/task-store.js +273 -0
  53. package/lib/node/transport.js +763 -0
  54. package/lib/pairing.js +186 -0
  55. package/lib/protocol.js +414 -0
  56. package/lib/relay-config.js +317 -0
  57. package/lib/relay.js +732 -0
  58. package/lib/setup-routes.js +313 -0
  59. package/lib/setup.js +522 -0
  60. package/lib/ws.js +466 -0
  61. package/package.json +103 -4
  62. package/profiles/README.md +573 -0
  63. package/profiles/hub.cordis.yml +84 -0
  64. package/profiles/worker.cordis.yml +60 -0
  65. package/scripts/check-doc-drift.mjs +785 -0
  66. package/scripts/check-packaging.mjs +130 -0
  67. package/scripts/diag-inject.mjs +243 -0
  68. package/scripts/e2e-live-check.mjs +181 -0
  69. package/scripts/relay-init.ps1 +286 -0
  70. package/scripts/relay-init.sh +199 -0
@@ -0,0 +1,403 @@
1
+ /**
2
+ * NodeRegistry 的「连接接入 + 握手 + hub 身份」职责(P1-4 自 node-registry.js
3
+ * 拆出)。
4
+ *
5
+ * 以 mixin 形式合入:`class NodeRegistry extends withHandshake(withIngest(...))`。
6
+ * 纯搬移 —— 方法体与拆分前一字不差。搬出动机:接入/握手是「连接生命周期」,
7
+ * 身份证明(P2-11)是「安全协议」,两者与注册表的视图查询/任务下发是不同
8
+ * 变更节奏,此前挤在同一个千行文件里。
9
+ *
10
+ * this.* 依赖面(全部由 NodeRegistryCore 提供):
11
+ * nodes / pending / limits / log / send / markOffline
12
+ * (finishPending / sendWelcome / buildIdentityPayload / sendIdentityFrame /
13
+ * rejectConn 在本 mixin 内自洽。)
14
+ */
15
+ import {
16
+ ERROR_CODE,
17
+ HUB_TO_NODE,
18
+ NODE_TO_HUB,
19
+ PROTOCOL_VERSION,
20
+ RELAY_FRAME,
21
+ decodeBinaryFrame,
22
+ decodeFrame,
23
+ encodeFrame,
24
+ envelope,
25
+ validateHello,
26
+ } from '../protocol.js'
27
+ import { newNonce, signIdentity } from '../identity.js'
28
+ import { generateEphemeral, normalizeE2EPub, signExchange, createSession } from '../e2e.js'
29
+ import { errText } from './hub-util.js'
30
+
31
+ export function withHandshake(Base) {
32
+ return class extends Base {
33
+ // ─────────────────────────── 连接接入 ───────────────────────────
34
+
35
+ /**
36
+ * 接管一条刚 upgrade 完的直连 socket。
37
+ * 第一帧必须是 hello;超时未收到就拒绝并关闭。
38
+ */
39
+ attachDirect(conn, meta = {}) {
40
+ const pending = { conn, remote: meta.remote ?? '', nodeId: '', timer: undefined, done: false }
41
+ this.pending.add(pending)
42
+ pending.timer = setTimeout(() => {
43
+ if (pending.done) return
44
+ pending.done = true
45
+ this.pending.delete(pending)
46
+ this.log('warn', 'hello timeout', { remote: pending.remote })
47
+ this.rejectConn(conn, 'hello-timeout', 'hello frame required as the first frame')
48
+ }, this.limits.helloTimeoutMs)
49
+ if (pending.timer.unref) pending.timer.unref()
50
+
51
+ conn.on('message', (payload, isBinary) => {
52
+ try {
53
+ if (isBinary) {
54
+ this.onDirectBinary(pending, payload)
55
+ return
56
+ }
57
+ const dec = decodeFrame(payload)
58
+ if (!dec.ok) {
59
+ this.log('warn', 'node frame undecodable', { error: dec.error, remote: pending.remote })
60
+ return
61
+ }
62
+ this.onDirectFrame(pending, dec.frame)
63
+ } catch (err) {
64
+ this.log('error', 'node frame handler failed', { error: errText(err) })
65
+ }
66
+ })
67
+
68
+ const onGone = (reason) => {
69
+ pending.done = true
70
+ if (pending.timer) clearTimeout(pending.timer)
71
+ this.pending.delete(pending)
72
+ const nodeId = pending.nodeId
73
+ if (nodeId) {
74
+ const rec = this.nodes.get(nodeId)
75
+ // 只有"当前生效的那条连接"断开才算掉线(重复实例被拒后断开不算)
76
+ if (rec && rec.conn === conn) this.markOffline(nodeId, reason)
77
+ }
78
+ this.log('info', 'node socket closed', { nodeId: nodeId || undefined, reason })
79
+ }
80
+
81
+ conn.on('close', (code, reason) => onGone(`socket closed ${code}${reason ? `: ${reason}` : ''}`))
82
+
83
+ // 对端硬断(FIN 无 close 帧)由冻结层统一处理:ws.js 的 WSConnection 构造时
84
+ // 就挂了 `socket.on('end')` → finish(1006) + destroy,所以这里只监听 conn 的
85
+ // 'close' 即可,半关闭不会漏掉下线、fd 也已释放。
86
+ // **不要**再补一层 conn.socket.on('end') 兜底 —— 对端干净 FIN 时同一个事件会
87
+ // 走两遍 onGone,日志里 'node socket closed' 打两条。
88
+
89
+ conn.on('error', (err) => this.log('warn', 'node socket error', { error: errText(err) }))
90
+ }
91
+
92
+ /** 绑定中继链路:上行帧由中继转发,下行帧靠 header.to / frame.to 路由。 */
93
+ attachRelay(link) {
94
+ this.relay = link
95
+ }
96
+
97
+ onDirectFrame(pending, frame) {
98
+ if (!pending.nodeId) {
99
+ if (frame.t !== NODE_TO_HUB.HELLO) {
100
+ this.rejectConn(pending.conn, 'hello-required', `expected hello, got ${frame.t}`)
101
+ return
102
+ }
103
+ this.ingestHello({
104
+ helloData: frame.d,
105
+ conn: pending.conn,
106
+ transport: 'direct',
107
+ pending,
108
+ })
109
+ return
110
+ }
111
+ this.handleFrameFor(pending.nodeId, frame, { conn: pending.conn, transport: 'direct' })
112
+ }
113
+
114
+ onDirectBinary(pending, payload) {
115
+ if (!pending.nodeId) {
116
+ this.log('warn', 'binary frame before hello, dropped', { remote: pending.remote })
117
+ return
118
+ }
119
+ const dec = decodeBinaryFrame(payload)
120
+ if (!dec.ok) {
121
+ this.log('warn', 'binary frame undecodable', { error: dec.error })
122
+ return
123
+ }
124
+ this.handleBinaryFor(pending.nodeId, dec.header, dec.payload, { conn: pending.conn })
125
+ }
126
+
127
+ /** 中继上行文本帧:中继已把来源写在 frame.from。 */
128
+ handleRelayFrame(frame) {
129
+ try {
130
+ if (frame.t === RELAY_FRAME.HELLO_HUB || frame.t === RELAY_FRAME.NODE_LIST) {
131
+ const list = Array.isArray(frame.d?.nodes) ? frame.d.nodes : []
132
+ for (const summary of list) this.adoptRelaySummary(summary)
133
+ this.log('info', 'relay node directory received', { count: list.length })
134
+ return
135
+ }
136
+ if (frame.t === RELAY_FRAME.NODE_ONLINE) {
137
+ this.adoptRelaySummary(frame.d?.node)
138
+ return
139
+ }
140
+ if (frame.t === RELAY_FRAME.NODE_OFFLINE) {
141
+ const nodeId = frame.d?.nodeId
142
+ if (typeof nodeId === 'string') this.markOffline(nodeId, `relay: ${frame.d?.reason ?? 'offline'}`)
143
+ return
144
+ }
145
+ if (frame.t === RELAY_FRAME.ERROR) {
146
+ this.log('warn', 'relay reported error', { code: frame.d?.code, nodeId: frame.d?.nodeId })
147
+ return
148
+ }
149
+ const from = typeof frame.from === 'string' ? frame.from : ''
150
+ if (from === '') {
151
+ this.log('warn', 'relay frame without source node', { type: frame.t })
152
+ return
153
+ }
154
+ this.handleFrameFor(from, frame, { transport: 'relay' })
155
+ } catch (err) {
156
+ this.log('error', 'relay frame handler failed', { error: errText(err) })
157
+ }
158
+ }
159
+
160
+ /** 中继上行二进制帧:来源在 header.from。 */
161
+ handleRelayBinary(header, payload) {
162
+ try {
163
+ const from = typeof header?.from === 'string' ? header.from : ''
164
+ if (from === '') {
165
+ this.log('warn', 'relay binary frame without source node')
166
+ return
167
+ }
168
+ this.handleBinaryFor(from, header, payload, { transport: 'relay' })
169
+ } catch (err) {
170
+ this.log('error', 'relay binary handler failed', { error: errText(err) })
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 中继模式下 hub 看不到副机的 hello 帧(中继自己消费了 hello/node),
176
+ * 只广播节点摘要。这里用摘要补一个等价 hello,让上层视图保持一致。
177
+ */
178
+ adoptRelaySummary(summary) {
179
+ if (!summary || typeof summary !== 'object') return
180
+ if (typeof summary.nodeId !== 'string') return
181
+ this.ingestHello({
182
+ helloData: { ...summary, protocol: summary.protocol ?? PROTOCOL_VERSION },
183
+ conn: undefined,
184
+ transport: 'relay',
185
+ pending: undefined,
186
+ })
187
+ }
188
+
189
+ /**
190
+ * 处理 hello:校验 → 同 id 冲突判定 → 登记 / 回 welcome。
191
+ */
192
+ ingestHello({ helloData, conn, transport, pending }) {
193
+ const v = validateHello(helloData)
194
+ if (!v.ok) {
195
+ const code = v.error === ERROR_CODE.PROTOCOL_MISMATCH ? ERROR_CODE.PROTOCOL_MISMATCH : 'hello-invalid'
196
+ this.log('warn', 'hello rejected', { reason: v.error, transport })
197
+ if (transport === 'direct') this.rejectConn(conn, code, `invalid hello: ${v.error}`)
198
+ else this.send(helloData?.nodeId, HUB_TO_NODE.ERROR, { code, message: `invalid hello: ${v.error}` })
199
+ this.finishPending(pending)
200
+ return undefined
201
+ }
202
+
203
+ const hello = v.hello
204
+ const existing = this.nodes.get(hello.nodeId)
205
+ // 同 id 第二实例:拒掉新连接,保住已经在跑的那个(任务不能被打断)
206
+ if (existing && existing.online && existing.conn && existing.conn !== conn && !existing.conn.closed) {
207
+ this.log('warn', 'duplicate node rejected', { nodeId: hello.nodeId, transport })
208
+ if (transport === 'direct') {
209
+ this.rejectConn(conn, ERROR_CODE.DUPLICATE_NODE, 'another live connection owns this nodeId', hello.nodeId)
210
+ } else {
211
+ this.send(hello.nodeId, HUB_TO_NODE.ERROR, {
212
+ code: ERROR_CODE.DUPLICATE_NODE,
213
+ message: 'another live connection owns this nodeId',
214
+ nodeId: hello.nodeId,
215
+ })
216
+ }
217
+ this.finishPending(pending)
218
+ return undefined
219
+ }
220
+
221
+ const rec = existing ?? {
222
+ nodeId: hello.nodeId,
223
+ hello,
224
+ online: false,
225
+ transport,
226
+ since: Date.now(),
227
+ lastSeen: Date.now(),
228
+ conn: undefined,
229
+ tasks: new Map(),
230
+ pendingPulls: new Map(),
231
+ }
232
+ if (!existing) {
233
+ rec.since = Date.now()
234
+ this.nodes.set(hello.nodeId, rec)
235
+ }
236
+ rec.hello = hello
237
+ rec.transport = transport
238
+ rec.online = true
239
+ rec.lastSeen = Date.now()
240
+ rec.conn = transport === 'direct' ? conn : undefined
241
+ this.finishPending(pending, hello.nodeId)
242
+
243
+ if (transport === 'direct') this.sendWelcome(rec)
244
+ else this.sendIdentityFrame(rec) // relay:hub 在握手期对副机静默,身份帧必须在上线后追发
245
+ this.log('info', 'node online', { nodeId: hello.nodeId, os: hello.os, transport })
246
+ return rec
247
+ }
248
+
249
+ finishPending(pending, nodeId) {
250
+ if (!pending || pending.done) return
251
+ pending.done = true
252
+ if (pending.timer) clearTimeout(pending.timer)
253
+ this.pending.delete(pending)
254
+ if (nodeId) pending.nodeId = nodeId
255
+ }
256
+
257
+ /** welcome 里带 config 限制,让副机知道自己该守什么;P2-11 起再带一帧身份证明。 */
258
+ sendWelcome(rec) {
259
+ const data = {
260
+ protocol: PROTOCOL_VERSION,
261
+ nodeId: rec.nodeId,
262
+ limits: {
263
+ heartbeatMs: this.limits.heartbeatMs,
264
+ ackTimeoutMs: this.limits.ackTimeoutMs,
265
+ pullTimeoutMs: this.limits.pullTimeoutMs,
266
+ maxPullBytes: this.limits.maxPullBytes,
267
+ maxTasksPerNode: this.limits.maxTasksPerNode,
268
+ },
269
+ serverTime: Date.now(),
270
+ }
271
+ // 身份证明放在 welcome 里:副机在 markOnline **之前**先验 hub,
272
+ // 验不过连上线资格都没有(副机侧 transport.js 负责拒绝)。
273
+ const identity = this.buildIdentityPayload(rec)
274
+ if (identity) data.identity = identity
275
+ this.send(rec.nodeId, HUB_TO_NODE.WELCOME, data)
276
+ }
277
+
278
+ /**
279
+ * 构造 hub 身份证明载荷(P2-11)。
280
+ *
281
+ * nonce 优先用副机 hello 里带来的 —— hub 对"本次连接"签名,副机核对一致
282
+ * 即可确认这不是重放的旧帧。旧版副机 / 中继摘要不带 nonce 时自拟一个,
283
+ * 副机退化为只靠 ±5min 时间窗(主防线仍是 pin 匹配)。
284
+ *
285
+ * 签名失败(私钥坏)返回 undefined:welcome 不带 identity,绝不抛 ——
286
+ * 身份子系统故障不能拖垮接入路径。
287
+ */
288
+ buildIdentityPayload(rec) {
289
+ if (!this.identity) return undefined
290
+ const nonce = typeof rec?.hello?.nonce === 'string' && rec.hello.nonce !== '' ? rec.hello.nonce : newNonce()
291
+ const at = Date.now()
292
+ let sig
293
+ try {
294
+ sig = signIdentity(this.identity.privateKeyB64, {
295
+ fingerprint: this.identity.fingerprint,
296
+ nodeId: rec.nodeId,
297
+ nonce,
298
+ at,
299
+ })
300
+ } catch (err) {
301
+ this.log('warn', 'hub identity sign failed', { error: errText(err) })
302
+ return undefined
303
+ }
304
+ return { fp: this.identity.fingerprint, pub: this.identity.publicKeyB64, sig, at, nonce }
305
+ }
306
+
307
+ /**
308
+ * relay 模式追发身份帧(P2-11)。
309
+ *
310
+ * relay 模式下副机的"在线"信号是中继的 hello/node accepted,hub 在握手期
311
+ * 对副机**完全静默** —— 假中继正是利用这个空窗冒充 hub 下发任务。所以
312
+ * 节点一经登记,hub 立刻经中继补一帧 hub/identity。链路未就绪时帧会丢,
313
+ * 靠两条既有路径自愈:hub 与中继重连后 requestNodeList 会重播节点目录
314
+ * (adoptRelaySummary → 本方法),中继的 node/online 通知同理。
315
+ */
316
+ sendIdentityFrame(rec) {
317
+ const payload = this.buildIdentityPayload(rec)
318
+ if (!payload) return false
319
+ return this.send(rec.nodeId, HUB_TO_NODE.IDENTITY, payload)
320
+ }
321
+
322
+ /**
323
+ * E2E 密钥交换(提案 #1):处理副机的 node/e2e 提议。
324
+ *
325
+ * 流程:校验副机的一次性 X25519 公钥 → 生成本方一次性 X25519 →
326
+ * ECDH 派生 AES-256-GCM 会话密钥(存 rec.e2e,此后本节点的收发自动
327
+ * 加解密)→ 用持久 ed25519 身份签 hub/e2e 确认帧回给副机。签名绑定
328
+ * 双方公钥 + 副机提议里的连接 nonce —— 中继既伪造不了签名,也偷换不了
329
+ * 任何一侧公钥(偷换后另一端验签必败)。
330
+ *
331
+ * hub 身份不可用(identity=null)时直接跳过:E2E 的认证锚就是这把身份,
332
+ * 没有它签出的确认帧一文不值 —— 副机等不到 ack 自然按明文继续(兼容旧版)。
333
+ *
334
+ * 会话随 rec 生存:重连 → 新 offer → 新会话覆盖旧会话(旧密钥销毁)。
335
+ */
336
+ handleE2EOffer(nodeId, d) {
337
+ const rec = this.nodes.get(nodeId)
338
+ if (!rec) {
339
+ this.log('warn', 'e2e offer from unknown node', { nodeId })
340
+ return false
341
+ }
342
+ const pub = normalizeE2EPub(d?.pub)
343
+ const nonce = typeof d?.nonce === 'string' && /^[0-9a-f]{16,128}$/.test(d.nonce) ? d.nonce : ''
344
+ if (pub === '' || nonce === '') {
345
+ this.log('warn', 'e2e offer rejected: malformed', { nodeId })
346
+ return false
347
+ }
348
+ if (!this.identity) {
349
+ this.log('info', 'e2e skipped: hub identity unavailable, link stays plaintext', { nodeId })
350
+ return false
351
+ }
352
+ let session
353
+ let ackSig
354
+ let ackPub
355
+ // 签名与传输必须是**同一个** at —— 两次 Date.now() 会让副机验签必败
356
+ // (实测踩过:签名载荷里的 at 和帧里的 at 差几毫秒,验签 false)。
357
+ const now = Date.now()
358
+ try {
359
+ const eph = generateEphemeral()
360
+ session = createSession({
361
+ role: 'hub',
362
+ ownPrivB64: eph.privateKeyB64,
363
+ peerPubB64: pub,
364
+ nodePubB64: pub,
365
+ hubPubB64: eph.publicKeyB64,
366
+ })
367
+ ackSig = signExchange(this.identity.privateKeyB64, {
368
+ fingerprint: this.identity.fingerprint,
369
+ nodeId,
370
+ nonce,
371
+ pub: eph.publicKeyB64,
372
+ peerPub: pub,
373
+ at: now,
374
+ })
375
+ ackPub = eph.publicKeyB64
376
+ } catch (err) {
377
+ this.log('warn', 'e2e session setup failed, link stays plaintext', { nodeId, error: errText(err) })
378
+ return false
379
+ }
380
+ // 旧会话(若有)销毁密钥材料后再覆盖 —— 重连重协商是常态路径。
381
+ if (rec.e2e && typeof rec.e2e.destroy === 'function') rec.e2e.destroy()
382
+ rec.e2e = session
383
+ rec.e2eAt = now
384
+ this.send(nodeId, HUB_TO_NODE.E2E_ACK, { pub: ackPub, sig: ackSig, at: now })
385
+ this.log('info', 'e2e session established (relay traffic encrypted)', { nodeId })
386
+ return true
387
+ }
388
+
389
+ /** 在指定连接上回 error 帧然后关闭。 */
390
+ rejectConn(conn, code, message, nodeId) {
391
+ try {
392
+ conn.send(encodeFrame(envelope(HUB_TO_NODE.ERROR, { code, message, nodeId })))
393
+ } catch {
394
+ /* 连接可能已断 */
395
+ }
396
+ try {
397
+ conn.close(1008, code)
398
+ } catch {
399
+ /* 已关闭 */
400
+ }
401
+ }
402
+ }
403
+ }