dsh-remote-peers 0.3.63 → 0.3.165

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/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  /** DeepSeek Harness 局域网互联 —— Host 面。 本插件在自己的监听器上暴露一个「带共享密钥的 HTTP 网关」,收到的请求以本机 操作者 Peer 的身份进入 DSH 自己的 `/api` 通道(`ctx.connection.createSharedFetchHandler`), 因此对端看... */
2
2
 
3
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
3
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
4
4
  import { spawn } from 'node:child_process'
5
5
  import { once } from 'node:events'
6
- import { appendFileSync, createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
6
+ import { appendFileSync, chmodSync, createWriteStream, existsSync, mkdirSync, promises as fsp, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
7
7
  import { createServer } from 'node:http'
8
- import { networkInterfaces } from 'node:os'
9
- import { basename, join } from 'node:path'
8
+ import { createServer as createTcpServer } from 'node:net'
9
+ import { hostname, homedir, networkInterfaces } from 'node:os'
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
10
11
  import { Readable } from 'node:stream'
11
12
  import { pipeline } from 'node:stream/promises'
12
13
  import { pathToFileURL } from 'node:url'
@@ -21,11 +22,51 @@ const DEFAULTS = Object.freeze({
21
22
  listenHost: '0.0.0.0',
22
23
  listenPort: 0,
23
24
  allowedCidrs: ['127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '::1/128'],
25
+ sshServerPort: 36400,
24
26
  })
25
27
 
26
28
  /** 单请求体上限,与 DSH 自己的 HTTP 载体一致(聚合图片 200 MiB 的 base64 余量)。 */
27
29
  const MAX_REQUEST_BODY_BYTES = 300 * 1024 * 1024
28
30
 
31
+ /** 跨域网关(EasyTier)的固定口径:内核版本、默认中继、虚拟网段与本地端口池。 */
32
+ const GATEWAY = Object.freeze({
33
+ version: '2.6.4',
34
+ relay: 'tcp://easytier.weiai.org.cn:11010',
35
+ ipv4Prefix: '10.126.126.',
36
+ listenPort: 11010,
37
+ rpcPort: 25890,
38
+ /** 插件端口 = 37000 + 虚拟地址末段(.1 → 37001,.166 → 37166)。 */
39
+ portBase: 37000,
40
+ /** 到某节点的本地转发口 = 37500 + 末段(.166 → 37666)。 */
41
+ forwardPortBase: 37500,
42
+ /** 到对端节点 SSH 的本地口 = 37700 + 末段(.166 → 37866)。 */
43
+ sshPortBase: 37700,
44
+ /** 网关口令的派生参数:同网同 secret 必然算出同一把,所以不需要交换。 */
45
+ tokenMessage: 'dsh-remote-peers/v1/gateway-token',
46
+ })
47
+
48
+ /** 虚拟地址末段:端口约定的索引。`.166` → 166;不合法就按 0(落到基址上)。 */
49
+ export function vipIndex(vip) {
50
+ // 内核表里是 `10.126.126.1/24` 这种带掩码的写法,先切掉掩码再取末段。
51
+ const value = Number(String(vip).trim().split('/')[0].split('.').pop())
52
+ return Number.isInteger(value) && value >= 0 && value <= 254 ? value : 0
53
+ }
54
+
55
+ /** 网关模式的插件端口:别人按你的虚拟地址算出这个数来连你,所以不能临时改。 */
56
+ export function gatewayPortOf(vip) {
57
+ return GATEWAY.portBase + vipIndex(vip)
58
+ }
59
+
60
+ /** 到某节点的本地转发口:只在本机有意义,同样按虚拟地址算,重启后不变。 */
61
+ export function forwardPortOf(vip) {
62
+ return GATEWAY.forwardPortBase + vipIndex(vip)
63
+ }
64
+
65
+ /** 网关口令:由网络 secret 派生,同网所有节点收敛到同一把,无需任何交换。 */
66
+ export function gatewayTokenOf(secret) {
67
+ return createHmac('sha256', secret).update(GATEWAY.tokenMessage).digest('base64url')
68
+ }
69
+
29
70
  /** 空的 Client→Host 上行:普通 Remote 流不读它,只有 Gateway 自有端点才会消费。 */
30
71
  const EMPTY_UPLINK = Object.freeze({
31
72
  async *[Symbol.asyncIterator]() {
@@ -55,9 +96,25 @@ export function apply(ctx, config = {}) {
55
96
  }
56
97
  mark(`apply start typertGateway=${ctx.get('typertGateway') !== undefined} connection=${ctx.get('connection') !== undefined}`)
57
98
  const state = loadState(settings.stateDir)
99
+ /** 连接方式(局域网 / 跨域网关)的落盘位置:同一时刻只启用一个,未启用时不监听。 */
100
+ const modesFile = join(settings.stateDir, 'modes.json')
101
+ const readMode = () => {
102
+ try {
103
+ const parsed = safeParse(readFileSync(modesFile, 'utf8'))
104
+ return parsed !== undefined && parsed !== null && (parsed.active === 'lan' || parsed.active === 'gateway') ? parsed.active : ''
105
+ } catch {
106
+ return ''
107
+ }
108
+ }
109
+ let activeMode = readMode()
58
110
  const connection = ctx.connection
59
111
  /** 当前共享密钥;重置时轮换,已连接的对端须重新填写。 */
60
112
  let currentToken = state.token
113
+ /**
114
+ * 网关模式的口令不是实例私钥,而是全网从 secret 派生的一把:
115
+ * 谁都在本地算得出来,所以节点之间不需要交换口令就能互相验证。
116
+ */
117
+ const effectiveToken = () => (activeMode === 'gateway' && gateway.network.secret !== '' ? gatewayTokenOf(gateway.network.secret) : currentToken)
61
118
 
62
119
  if (connection === undefined) {
63
120
  logger.error('remote-peers: 缺少 connection 服务,网关未启动')
@@ -120,11 +177,33 @@ export function apply(ctx, config = {}) {
120
177
  if (settings.allowedCidrs.length === 0) logger.warn('remote-peers: allowedCidrs 为空,只接受 127.0.0.1')
121
178
  })
122
179
  }
123
- try {
124
- listen(preferredPort)
125
- } catch (error) {
126
- mark(`listen throw ${error?.stack ?? error}`)
180
+ /** 某一种连接方式启用时才监听:没有启用任何方式的本机不对外开放端口。 */
181
+ /** 网关模式的监听口由虚拟地址决定;配置读出来之前先按旧口径,之后由 applyGatewayIdentity() 对齐。 */
182
+ let gatewayPortHint = 0
183
+ const listenerPort = () => {
184
+ if (activeMode === 'gateway' && gatewayPortHint !== 0) return gatewayPortHint
185
+ return settings.listenPort !== 0 ? settings.listenPort : state.port
127
186
  }
187
+ const startListener = () => {
188
+ if (server.listening) return
189
+ try {
190
+ listen(listenerPort())
191
+ } catch (error) {
192
+ mark(`listen throw ${error?.stack ?? error}`)
193
+ }
194
+ }
195
+ const stopListener = () => {
196
+ if (!server.listening) return
197
+ try { server.closeAllConnections() } catch { /* 老 Node 没有这个方法,close 之后连接也会自己断 */ }
198
+ server.close()
199
+ }
200
+ const waitListening = async (timeoutMs) => {
201
+ const deadline = Date.now() + timeoutMs
202
+ while (Date.now() < deadline && !server.listening) await new Promise((resolve) => setTimeout(resolve, 100))
203
+ return server.listening
204
+ }
205
+ if (activeMode !== '') startListener()
206
+ mark(`active mode ${activeMode === '' ? 'none' : activeMode}`)
128
207
 
129
208
  try {
130
209
  ctx.effect(() => () => {
@@ -174,24 +253,59 @@ export function apply(ctx, config = {}) {
174
253
  case 'peers/remove': {
175
254
  const id = typeof payload?.id === 'string' ? payload.id : undefined
176
255
  if (id === undefined) return fail('remote-peers/bad-request', '需要 id')
256
+ const removed = peers.find((item) => item.id === id)
177
257
  peers = peers.filter((item) => item.id !== id)
178
258
  writePeers(peersFile, peers)
259
+ // 网关节点由内核表推导:只记一笔「不要再加回来」,下一轮同步自然跳过。
260
+ if (removed?.via === 'gateway' && removed.gateway !== undefined) hiddenVips.add(removed.gateway.vip)
179
261
  return ok({ peers })
180
262
  }
181
263
  case 'peers/ping':
182
264
  return ok(await pingPeer(payload?.id, signal))
265
+ case 'ssh/status':
266
+ return ok(sshSnapshot())
267
+ case 'ssh/enable': {
268
+ try {
269
+ return ok(await sshToggle(true))
270
+ } catch (error) {
271
+ return fail(error?.code ?? 'ssh/enable-failed', error instanceof Error ? error.message : String(error))
272
+ }
273
+ }
274
+ case 'ssh/disable':
275
+ return ok(await sshToggle(false))
276
+ case 'ssh/access':
277
+ return ok(sshSetAccess(payload?.mode))
278
+ case 'ssh/peerStatus':
279
+ return ok(await sshPeerStatus(payload?.id))
280
+ case 'ssh/connect': {
281
+ try {
282
+ return ok(await sshConnect(payload))
283
+ } catch (error) {
284
+ return fail(error?.code ?? 'ssh/connect-failed', error instanceof Error ? error.message : String(error))
285
+ }
286
+ }
287
+ case 'ssh/exec': {
288
+ try {
289
+ return ok(await sshExec(payload))
290
+ } catch (error) {
291
+ return fail(error?.code ?? 'ssh/exec-failed', error instanceof Error ? error.message : String(error))
292
+ }
293
+ }
294
+ case 'ssh/close':
295
+ return ok(sshClose(payload?.sessionId))
183
296
  case 'proxy':
184
297
  return ok({ result: await forward(payload, signal) })
185
298
  case 'file/size': {
186
299
  const id = typeof payload?.id === 'string' ? payload.id : ''
187
300
  const peerEntry = peerById(id)
188
- if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知他端 ${JSON.stringify(id)}`)
301
+ if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
189
302
  const source = typeof payload?.path === 'string' ? payload.path : ''
190
303
  if (!isAbsoluteFsPath(source)) return fail('remote-peers/bad-path', '需要绝对文件路径')
191
304
  const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
192
- const size = await remoteSizeOf(peerEntry, source, sessionId, signal)
193
- // TEMP-DIAG:Host 侧也留一行,确认跑的到底是哪条取大小路径(stat / 响应头 / 拿不到)。
305
+ const probe = await remoteProbeOf(peerEntry, source, sessionId, signal)
306
+ const size = typeof probe.size === 'number' && probe.size > 0 ? probe.size : undefined
194
307
  hostDiag(`size host ${source} session=${sessionId === '' ? '-' : sessionId} -> ${String(size ?? 'unknown')}`)
308
+ if (probe.missing === true) return fail('remote-peers/file-missing', '对端上没有这份文件(可能已被清理或移动)')
195
309
  if (size === undefined) return fail('remote-peers/size-unknown', '对端没有给出文件大小')
196
310
  return ok({ size })
197
311
  }
@@ -200,15 +314,16 @@ export function apply(ctx, config = {}) {
200
314
  // 不让一个坏路径拖垮整批(前端把 null 记成 error 占位,不再重问)。
201
315
  const id = typeof payload?.id === 'string' ? payload.id : ''
202
316
  const peerEntry = peerById(id)
203
- if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知他端 ${JSON.stringify(id)}`)
317
+ if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
204
318
  const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
205
319
  const wanted = Array.isArray(payload?.paths) ? payload.paths : []
206
320
  const paths = wanted
207
321
  .filter((item) => typeof item === 'string' && item !== '' && !item.includes('\0') && isAbsoluteFsPath(item))
208
322
  .slice(0, 200)
209
- if (paths.length === 0) return ok({ sizes: {}, locals: {} })
323
+ if (paths.length === 0) return ok({ sizes: {}, locals: {}, missing: {} })
210
324
  const sizes = {}
211
325
  const locals = {}
326
+ const missing = {}
212
327
  await runPool(paths, 4, async (source) => {
213
328
  // 「本机是否已有副本」是纯本地 stat,顺路带回给前端,卡片据此显示「已下载」。
214
329
  locals[source] = hasLocalCopy(localCopyPathOf(peerEntry.id, source))
@@ -221,7 +336,7 @@ export function apply(ctx, config = {}) {
221
336
  }
222
337
  })
223
338
  hostDiag(`size batch ${paths.length} -> ${paths.filter((item) => typeof sizes[item] === 'number').length} hit, ${paths.filter((item) => locals[item] === true).length} local`)
224
- return ok({ sizes, locals })
339
+ return ok({ sizes, locals, missing })
225
340
  }
226
341
  case 'open-local':
227
342
  return ok(await openLocal(payload, signal))
@@ -229,7 +344,7 @@ export function apply(ctx, config = {}) {
229
344
  // 「显示文件位置」用的探针:只回答本机有没有这份副本,绝不顺手去下载。
230
345
  const id = typeof payload?.id === 'string' ? payload.id : ''
231
346
  const peerEntry = peerById(id)
232
- if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知他端 ${JSON.stringify(id)}`)
347
+ if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
233
348
  const source = typeof payload?.path === 'string' ? payload.path : ''
234
349
  if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) {
235
350
  return fail('remote-peers/bad-path', '需要绝对文件路径')
@@ -258,12 +373,17 @@ export function apply(ctx, config = {}) {
258
373
  // 不再弹「另存为」:直接落到本机副本目录。已有副本就当场返回 `reused`,一次字节都不取。
259
374
  const id = typeof payload?.id === 'string' ? payload.id : ''
260
375
  const peerEntry = peerById(id)
261
- if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知他端 ${JSON.stringify(id)}`)
376
+ if (peerEntry === undefined) return fail('remote-peers/unknown-peer', `未知节点 ${JSON.stringify(id)}`)
262
377
  const source = typeof payload?.path === 'string' ? payload.path : ''
263
378
  if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) {
264
379
  return fail('remote-peers/bad-path', '需要绝对文件路径')
265
380
  }
266
381
  const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
382
+ // 点下载先确认这份文件还在:对端已清理掉就直接回「不存在」,不建任务、不进 loading。
383
+ const localPath = localCopyPathOf(peerEntry.id, source)
384
+ if (!hasLocalCopy(localPath) && (await remoteProbeOf(peerEntry, source, sessionId, signal)).missing === true) {
385
+ return fail('remote-peers/file-missing', '对端上没有这份文件(可能已被清理或移动)')
386
+ }
267
387
  const started = startCopy(peerEntry, source, sessionId, '下载')
268
388
  return ok({
269
389
  key: started.key,
@@ -273,111 +393,1555 @@ export function apply(ctx, config = {}) {
273
393
  reused: started.reused,
274
394
  })
275
395
  }
276
- case 'download/cancel': {
277
- const key = typeof payload?.key === 'string' ? payload.key : ''
278
- const entry = liveTransfers.get(key)
279
- if (entry === undefined) return fail('remote-peers/unknown-transfer', '没有这个下载任务')
280
- entry.abort?.()
281
- liveTransfers.delete(key)
282
- return ok({ cancelled: key })
396
+ case 'download/cancel': {
397
+ // 取消允许两种寻址:精确 key,或 id + path(分隔符/大小写对不上时按路径找)。
398
+ const key = typeof payload?.key === 'string' ? payload.key : ''
399
+ const byId = typeof payload?.id === 'string' ? payload.id : ''
400
+ const byPath = typeof payload?.path === 'string' ? payload.path : ''
401
+ const samePath = (value) => String(value).replace(/[/\\]+/gu, '\\').toLowerCase()
402
+ const target = liveTransfers.get(key)
403
+ ?? (byPath === ''
404
+ ? undefined
405
+ : [...liveTransfers.values()].find((entry) => (byId === '' || entry.peerId === byId) && samePath(entry.path) === samePath(byPath)))
406
+ // 已经没有这条任务也算取消成功:前端只需要一个「停掉它」的回答,不该再弹失败。
407
+ if (target === undefined) return ok({ cancelled: key, missing: true })
408
+ target.abort?.()
409
+ liveTransfers.delete(target.key)
410
+ return ok({ cancelled: target.key })
411
+ }
412
+ case 'gateway/status':
413
+ return ok(await gatewayStatusOf())
414
+ case 'gateway/download':
415
+ return ok(await downloadGateway())
416
+ case 'gateway/enable':
417
+ return ok(await enableGateway())
418
+ case 'gateway/disable':
419
+ return ok(await disableGateway())
420
+ case 'gateway/join':
421
+ return ok(await joinGateway(payload?.code))
422
+ case 'lan/enable':
423
+ return ok(await enableLan())
424
+ case 'lan/disable':
425
+ return ok(await disableLan())
426
+ case 'diag': {
427
+ // TEMP-DIAG:把渲染器一侧探测到的结果落到 stateDir/diag.log(渲染器 console 无处可看)。
428
+ const line = `${new Date().toISOString()} ${JSON.stringify(payload)}\n`
429
+ mkdirSync(settings.stateDir, { recursive: true })
430
+ appendFileSync(join(settings.stateDir, 'diag.log'), line)
431
+ return ok({})
432
+ }
433
+ default:
434
+ return fail('remote-peers/unknown-endpoint', `未知端点 ${JSON.stringify(endpoint)}`)
435
+ }
436
+ } catch (error) {
437
+ logger.warn('remote-peers: /remote-peers %s 失败 %s', endpoint, String(error))
438
+ return fail('remote-peers/internal', String(error instanceof Error ? error.message : error))
439
+ }
440
+ }
441
+
442
+ // 热重载时上一个实例可能还占着通道,注册会在同一毫秒失败;退避重试而不是让 apply 半途死掉。
443
+ const registerChannel = (attempt = 0) => {
444
+ try {
445
+ connection.rpc.handle('/remote-peers', handleRemotePeers)
446
+ mark(`rpc channel ready (attempt ${attempt})`)
447
+ } catch (error) {
448
+ if (attempt < 12) {
449
+ mark(`rpc retry ${attempt}: ${String(error)}`)
450
+ setTimeout(() => registerChannel(attempt + 1), 250)
451
+ return
452
+ }
453
+ mark(`rpc throw ${error?.stack ?? error}`)
454
+ }
455
+ }
456
+ registerChannel()
457
+
458
+ // ── 跨域网关(EasyTier,免管理员)────────────────────────────────────
459
+ // 内核以 `--no-tun` 运行:不建虚拟网卡、不请求提权,节点之间仍可用虚拟 IP 互相访问;
460
+ // 本机再用 `--port-forward` 把每个网关节点的网关端口提到 127.0.0.1,既有 RPC 只认 host:port。
461
+ const gatewayFile = join(settings.stateDir, 'gateway.json')
462
+ const gatewayBin = join(settings.stateDir, 'easytier', GATEWAY.version)
463
+ const gatewayLog = join(settings.stateDir, 'easytier-core.log')
464
+ let gateway = loadGateway(gatewayFile)
465
+ // 旧版只把开关存在 gateway.json 里:读到了就当成「跨域网关」已启用。
466
+ if (gateway.enabled && activeMode !== 'gateway') activeMode = 'gateway'
467
+ let gatewayChild = undefined
468
+ let gatewayPhase = 'off'
469
+ let gatewayError = ''
470
+ let gatewayDownloading = false
471
+
472
+ /**
473
+ * 网关身份变了(启用、加入、换网)就重算监听口。
474
+ * 端口是约定的:别人按你的虚拟地址算出这个数来连你,临时换端口等于谁也找不到你。
475
+ */
476
+ async function applyGatewayIdentity() {
477
+ gatewayPortHint = gateway.vip === '' ? 0 : gatewayPortOf(gateway.vip)
478
+ if (activeMode !== 'gateway') return
479
+ const want = listenerPort()
480
+ const bound = server.address()
481
+ const current = typeof bound === 'object' && bound !== null ? bound.port : 0
482
+ if (server.listening && current === want) return
483
+ stopListener()
484
+ startListener()
485
+ await waitListening(2000)
486
+ }
487
+
488
+ // 启动时先按 modes.json 在旧端口上监听了一次,读到网关身份后立刻对齐到约定端口。
489
+ void applyGatewayIdentity()
490
+
491
+ /** 切换连接方式的唯一入口:两种方式互斥,顺带把网关开关写回自己的文件。 */
492
+ function settleMode(mode) {
493
+ activeMode = mode
494
+ gateway.enabled = mode === 'gateway'
495
+ try {
496
+ writeFileSync(modesFile, `${JSON.stringify({ active: mode }, null, 2)}\n`)
497
+ } catch (error) {
498
+ hostDiag(`write modes ${String(error)}`)
499
+ }
500
+ saveGateway()
501
+ }
502
+
503
+ const gatewayExeName = () => (process.platform === 'win32' ? 'easytier-core.exe' : 'easytier-core')
504
+ const gatewayCliName = () => (process.platform === 'win32' ? 'easytier-cli.exe' : 'easytier-cli')
505
+
506
+ /** 内核可执行文件:用户指定的路径优先,其次是自己解压的那份。 */
507
+ const corePathOf = () => {
508
+ if (gateway.corePath !== '' && existsSync(gateway.corePath)) return gateway.corePath
509
+ const local = join(gatewayBin, gatewayExeName())
510
+ return existsSync(local) ? local : undefined
511
+ }
512
+
513
+ const cliPathOf = () => {
514
+ const core = corePathOf()
515
+ return core === undefined ? undefined : join(dirname(core), gatewayCliName())
516
+ }
517
+
518
+ function loadGateway(file) {
519
+ const base = {
520
+ enabled: false,
521
+ role: 'host',
522
+ network: { name: '', secret: '' },
523
+ relay: [GATEWAY.relay],
524
+ vip: '',
525
+ listenPort: GATEWAY.listenPort,
526
+ rpcPort: GATEWAY.rpcPort,
527
+ corePath: '',
528
+ pid: 0,
529
+ }
530
+ const parsed = existsSync(file) ? safeParse(readFileSync(file, 'utf8')) : undefined
531
+ if (parsed === null || typeof parsed !== 'object') return base
532
+ return {
533
+ ...base,
534
+ enabled: parsed.enabled === true,
535
+ role: parsed.role === 'joiner' ? 'joiner' : 'host',
536
+ network: { name: String(parsed.network?.name ?? ''), secret: String(parsed.network?.secret ?? '') },
537
+ relay: Array.isArray(parsed.relay) && parsed.relay.length > 0 ? parsed.relay.map(String) : base.relay,
538
+ vip: typeof parsed.vip === 'string' ? parsed.vip : '',
539
+ listenPort: Number(parsed.listenPort) || GATEWAY.listenPort,
540
+ rpcPort: Number(parsed.rpcPort) || GATEWAY.rpcPort,
541
+ corePath: typeof parsed.corePath === 'string' ? parsed.corePath : '',
542
+ pid: Number(parsed.pid) || 0,
543
+ }
544
+ }
545
+
546
+ function saveGateway() {
547
+ writeFileSync(gatewayFile, `${JSON.stringify(gateway, null, 2)}\n`)
548
+ }
549
+
550
+ /** 本机在这个虚拟网里的地址:建网一方固定 .1,加入方按实例 id 散列到 .20–.219。 */
551
+ function pickVip() {
552
+ const digest = createHash('sha1').update(state.instanceId).digest('hex')
553
+ return `${GATEWAY.ipv4Prefix}${(parseInt(digest.slice(0, 6), 16) % 200) + 20}`
554
+ }
555
+
556
+ function coreArgs() {
557
+ const args = [
558
+ '--no-tun',
559
+ '-i', gateway.vip,
560
+ '--network-name', gateway.network.name,
561
+ '--network-secret', gateway.network.secret,
562
+ '-l', String(gateway.listenPort),
563
+ '--rpc-portal', `127.0.0.1:${gateway.rpcPort}`,
564
+ ]
565
+ for (const relay of gateway.relay) if (relay.trim() !== '') args.push('-p', relay.trim())
566
+ // 转发口一律在运行中按约定动态加:内核重启后由同步循环补回来,不必写进启动参数。
567
+ return args
568
+ }
569
+
570
+ /** 跑一条命令并收齐输出(超时直接杀掉,不让状态查询挂住面板)。 */
571
+ function runCommand(command, args, timeoutMs) {
572
+ return new Promise((resolve) => {
573
+ const child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
574
+ let stdout = ''
575
+ let stderr = ''
576
+ const timer = setTimeout(() => { try { child.kill() } catch { /* 已退出 */ } }, timeoutMs)
577
+ child.stdout?.on('data', (chunk) => { stdout += String(chunk) })
578
+ child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
579
+ child.on('error', (error) => { clearTimeout(timer); resolve({ code: -1, stdout, stderr: String(error) }) })
580
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code: code ?? -1, stdout, stderr }) })
581
+ })
582
+ }
583
+
584
+ function releaseAssetOf() {
585
+ const os = process.platform === 'win32' ? 'windows' : process.platform === 'linux' ? 'linux' : process.platform === 'darwin' ? 'macos' : undefined
586
+ const arch = process.arch === 'arm64' ? 'arm64' : process.arch === 'x64' ? 'x86_64' : undefined
587
+ if (os === undefined || arch === undefined) return undefined
588
+ const tag = `v${GATEWAY.version}`
589
+ return `https://github.com/EasyTier/EasyTier/releases/download/${tag}/easytier-${os}-${arch}-${tag}.zip`
590
+ }
591
+
592
+ /** 内核缺失时就地下载并摊平解压(首次 33MB,之后直接用)。 */
593
+ async function ensureCore() {
594
+ const ready = corePathOf()
595
+ if (ready !== undefined) return ready
596
+ const asset = releaseAssetOf()
597
+ if (asset === undefined) throw new Error(`本平台(${process.platform}/${process.arch})没有可自动下载的 EasyTier 内核,请手动放一份 easytier-core 到 ${gatewayBin}`)
598
+ logger.info('remote-peers: 首次启用跨域网关,下载 EasyTier 内核 %s', asset)
599
+ mkdirSync(gatewayBin, { recursive: true })
600
+ const zip = join(gatewayBin, 'easytier.zip')
601
+ const response = await fetch(asset, { redirect: 'follow' })
602
+ if (!response.ok) throw new Error(`下载 EasyTier 内核失败 HTTP ${response.status}`)
603
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(zip))
604
+ const unpacked = join(gatewayBin, 'unpack')
605
+ rmSync(unpacked, { recursive: true, force: true })
606
+ mkdirSync(unpacked, { recursive: true })
607
+ const untar = await runCommand('tar', ['-xf', zip, '-C', unpacked], 180000)
608
+ if (untar.code !== 0) throw new Error(`解压 EasyTier 内核失败:${untar.stderr.trim() === '' ? untar.code : untar.stderr.trim()}`)
609
+ for (const name of safeReaddir(unpacked)) {
610
+ const inner = join(unpacked, name)
611
+ if (!statSync(inner).isDirectory()) continue
612
+ for (const file of safeReaddir(inner)) {
613
+ const target = join(gatewayBin, file)
614
+ if (existsSync(target)) continue
615
+ try { renameSync(join(inner, file), target) } catch { /* 个别文件(如驱动)可能被占用,跳过 */ }
616
+ }
617
+ }
618
+ rmSync(zip, { force: true })
619
+ rmSync(unpacked, { recursive: true, force: true })
620
+ const exe = join(gatewayBin, gatewayExeName())
621
+ if (!existsSync(exe)) throw new Error('解压后没有找到 easytier-core')
622
+ if (process.platform !== 'win32') {
623
+ try { chmodSync(exe, 0o755) } catch { /* 拿不到执行位就交给用户手动 chmod */ }
624
+ }
625
+ return exe
626
+ }
627
+
628
+ function pidAlive(pid) {
629
+ if (!Number.isInteger(pid) || pid <= 0) return false
630
+ try { process.kill(pid, 0); return true } catch { return false }
631
+ }
632
+
633
+ /** 等内核的 RPC 门户能答出本机虚拟 IP。 */
634
+ async function waitCoreReady(timeoutMs) {
635
+ const cli = cliPathOf()
636
+ if (cli === undefined) return false
637
+ const deadline = Date.now() + timeoutMs
638
+ while (Date.now() < deadline) {
639
+ const probe = await runCommand(cli, ['--rpc-portal', `127.0.0.1:${gateway.rpcPort}`, 'node'], 4000)
640
+ if (probe.code === 0 && probe.stdout.includes(gateway.vip)) return true
641
+ await new Promise((resolve) => setTimeout(resolve, 400))
642
+ }
643
+ return false
644
+ }
645
+
646
+ /** 本机是否还空着这个端口:同一台机器跑两个网关(例如本机既建网又加入别的网)时不撞车。
647
+ 探测必须绑在本工具真实使用的地址上:EasyTier 监听 0.0.0.0,RPC 门户只绑回环。 */
648
+ function freePort(preferred, span, host) {
649
+ return new Promise((resolve) => {
650
+ const probe = (port, left) => {
651
+ const server = createTcpServer()
652
+ server.once('error', () => {
653
+ if (left <= 0) resolve(preferred)
654
+ else probe(port + 1, left - 1)
655
+ })
656
+ server.once('listening', () => server.close(() => resolve(port)))
657
+ server.listen(port, host)
658
+ }
659
+ probe(preferred, span)
660
+ })
661
+ }
662
+
663
+ async function startCore() {
664
+ // 转发规则挂在运行中的内核上:换一次进程就清一次账,由同步循环按约定补回来。
665
+ forwardedVips.clear()
666
+ if (gateway.network.name === '') {
667
+ gateway.network = { name: `dsh-${randomBytes(4).toString('hex')}`, secret: randomBytes(24).toString('base64url') }
668
+ }
669
+ if (gateway.vip === '') gateway.vip = gateway.role === 'joiner' ? pickVip() : `${GATEWAY.ipv4Prefix}1`
670
+ // 上次 apply 起的内核还活着:接管它,不起第二个进程。
671
+ if (gatewayChild === undefined && pidAlive(gateway.pid)) {
672
+ gatewayPhase = 'starting'
673
+ if (await waitCoreReady(3000)) { gatewayPhase = 'running'; gatewayError = ''; return }
674
+ await stopCore()
675
+ }
676
+ // 端口只有在自己起进程时挑:接管时沿用内核实际占用的那个。
677
+ gateway.listenPort = await freePort(gateway.listenPort, 8, '0.0.0.0')
678
+ gateway.rpcPort = await freePort(gateway.rpcPort, 8, '127.0.0.1')
679
+ saveGateway()
680
+ gatewayPhase = 'starting'
681
+ gatewayError = ''
682
+ const core = await ensureCore()
683
+ mkdirSync(settings.stateDir, { recursive: true })
684
+ const sink = createWriteStream(gatewayLog, { flags: 'a' })
685
+ // spawn 需要已经打开的文件描述符:等流 open 之后再交给它。
686
+ await new Promise((resolve) => { sink.once('open', resolve); sink.once('error', resolve) })
687
+ const child = spawn(core, coreArgs(), { windowsHide: true, stdio: ['ignore', sink, sink] })
688
+ gatewayChild = child
689
+ gateway.pid = child.pid ?? 0
690
+ saveGateway()
691
+ child.on('exit', (code) => {
692
+ if (gatewayChild !== child) return
693
+ gatewayChild = undefined
694
+ hostDiag(`easytier-core exit ${String(code)}`)
695
+ if (!gateway.enabled) { gatewayPhase = 'off'; return }
696
+ gatewayPhase = 'starting'
697
+ // 崩了就拉一次;这次还起不来就把错误留在状态里等用户点。
698
+ setTimeout(() => {
699
+ if (!gateway.enabled || gatewayChild !== undefined) return
700
+ void startCore().catch((error) => { gatewayPhase = 'error'; gatewayError = String(error?.message ?? error) })
701
+ }, 2000)
702
+ })
703
+ if (!(await waitCoreReady(15000))) throw new Error('EasyTier 内核 15 秒内没有就绪(详见 easytier-core.log)')
704
+ gatewayPhase = 'running'
705
+ }
706
+
707
+ async function stopCore() {
708
+ const pid = gatewayChild?.pid ?? gateway.pid
709
+ gatewayChild = undefined
710
+ if (pidAlive(pid)) {
711
+ try { process.kill(pid) } catch { /* 已退出 */ }
712
+ const deadline = Date.now() + 3000
713
+ while (Date.now() < deadline && pidAlive(pid)) await new Promise((resolve) => setTimeout(resolve, 200))
714
+ }
715
+ gateway.pid = 0
716
+ saveGateway()
717
+ }
718
+
719
+ /**
720
+ * 隧道刚建好的第一跳会空一次(转发口先接受连接、路由还没通,连接当场被关)。
721
+ * 这里先用一次 hello 把路径焐热,免得住户第一次点开节点就吃到一个假故障。
722
+ */
723
+ async function warmGatewayPeers(timeoutMs) {
724
+ const targets = peers.filter((item) => item.via === 'gateway')
725
+ if (targets.length === 0) return
726
+ const deadline = Date.now() + timeoutMs
727
+ for (const peerEntry of targets) {
728
+ // 连续两次成功才算焐热:隧道重建后的第一条连接仍可能被掐掉。
729
+ let streak = 0
730
+ while (Date.now() < deadline && streak < 2) {
731
+ try {
732
+ const response = await fetch(`http://127.0.0.1:${peerEntry.port}/remote-peers/hello`, {
733
+ headers: peerHeaders(peerEntry),
734
+ signal: AbortSignal.timeout(4000),
735
+ })
736
+ await response.text().catch(() => '')
737
+ streak = response.ok ? streak + 1 : 0
738
+ if (streak > 0) await new Promise((resolve) => setTimeout(resolve, 150))
739
+ } catch {
740
+ // 路由还没通,等一拍再来。
741
+ streak = 0
742
+ }
743
+ if (streak < 2) await new Promise((resolve) => setTimeout(resolve, 400))
744
+ }
745
+ }
746
+ }
747
+
748
+ function parseCliTable(text) {
749
+ const lines = String(text).split('\n').map((line) => line.trim()).filter((line) => line.startsWith('|'))
750
+ if (lines.length < 3) return []
751
+ const header = lines[0].split('|').slice(1, -1).map((cell) => cell.trim())
752
+ return lines.slice(2).map((line) => {
753
+ const cells = line.split('|').slice(1, -1).map((cell) => cell.trim())
754
+ const row = {}
755
+ for (const [index, key] of header.entries()) row[key] = cells[index] ?? ''
756
+ return row
757
+ })
758
+ }
759
+
760
+ /**
761
+ * 连接码只带「怎么进这张网」:网名、secret、中继、以及本机的虚拟地址。
762
+ * 端口由虚拟地址约定、口令由 secret 派生,都不必写进码里。
763
+ */
764
+ function buildCode() {
765
+ const payload = {
766
+ v: 1,
767
+ net: gateway.network.name,
768
+ secret: gateway.network.secret,
769
+ relay: gateway.relay,
770
+ me: {
771
+ id: state.instanceId,
772
+ name: hostname(),
773
+ vip: gateway.vip,
774
+ },
775
+ }
776
+ return `DSHG1-${Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')}`
777
+ }
778
+
779
+ function parseCode(text) {
780
+ const body = String(text ?? '').replace(/\s+/gu, '')
781
+ if (!body.startsWith('DSHG1-')) return undefined
782
+ let parsed
783
+ try { parsed = JSON.parse(Buffer.from(body.slice('DSHG1-'.length), 'base64url').toString('utf8')) } catch { return undefined }
784
+ if (parsed === null || typeof parsed !== 'object') return undefined
785
+ const net = typeof parsed.net === 'string' ? parsed.net : ''
786
+ const secret = typeof parsed.secret === 'string' ? parsed.secret : ''
787
+ const vip = typeof parsed.me?.vip === 'string' ? parsed.me.vip : ''
788
+ if (net === '' || secret === '' || vip === '') return undefined
789
+ return {
790
+ net,
791
+ secret,
792
+ vip,
793
+ relay: Array.isArray(parsed.relay) ? parsed.relay.map(String) : [],
794
+ me: { id: String(parsed.me?.id ?? ''), name: String(parsed.me?.name ?? '') },
795
+ }
796
+ }
797
+
798
+ /** 内核 peer 表:节点发现的唯一来源,面板与同步循环共用。 */
799
+ async function peerRows() {
800
+ const cli = cliPathOf()
801
+ if (cli === undefined || gatewayPhase !== 'running') return []
802
+ const result = await runCommand(cli, ['--rpc-portal', `127.0.0.1:${gateway.rpcPort}`, 'peer'], 6000)
803
+ return parseCliTable(result.stdout)
804
+ }
805
+
806
+ async function gatewayStatusOf() {
807
+ const rows = await peerRows()
808
+ const online = rows
809
+ .filter((row) => String(row.cost ?? '').toLowerCase() !== 'local' && String(row.ipv4 ?? '').trim() !== '')
810
+ .map((row) => ({ vip: String(row.ipv4 ?? '').trim().split('/')[0], host: String(row.hostname ?? ''), latency: String(row['lat(ms)'] ?? ''), tunnel: String(row.tunnel ?? '') }))
811
+ return {
812
+ enabled: gateway.enabled,
813
+ active: activeMode === 'gateway',
814
+ downloaded: corePathOf() !== undefined,
815
+ downloading: gatewayDownloading,
816
+ listening: server.listening,
817
+ phase: gatewayPhase,
818
+ error: gatewayError,
819
+ vip: gateway.vip,
820
+ networkName: gateway.network.name,
821
+ relay: gateway.relay,
822
+ coreReady: corePathOf() !== undefined,
823
+ coreVersion: GATEWAY.version,
824
+ online,
825
+ code: gateway.enabled ? buildCode() : '',
826
+ }
827
+ }
828
+
829
+ /** 内核是独立的一步:没点「下载内核」之前,启用/加入都先拒绝,避免让人对着一个卡死的按钮等 33MB。 */
830
+ function requireCore() {
831
+ if (corePathOf() === undefined) {
832
+ const error = new Error('EasyTier 内核还没下载,请先点「下载内核」')
833
+ error.code = 'remote-peers/kernel-missing'
834
+ throw error
835
+ }
836
+ }
837
+
838
+ async function downloadGateway() {
839
+ if (gatewayDownloading) return await gatewayStatusOf()
840
+ gatewayDownloading = true
841
+ try {
842
+ await ensureCore()
843
+ gatewayError = ''
844
+ } catch (error) {
845
+ gatewayError = String(error?.message ?? error)
846
+ throw error
847
+ } finally {
848
+ gatewayDownloading = false
849
+ }
850
+ return await gatewayStatusOf()
851
+ }
852
+
853
+ async function enableGateway() {
854
+ requireCore()
855
+ // 隧道要把对端的请求落到本机这个监听口上,所以网关模式也要监听;只是局域网那一侧不再算作启用。
856
+ settleMode('gateway')
857
+ await applyGatewayIdentity()
858
+ if (gatewayPhase !== 'running') await startCore()
859
+ await syncGatewayNodes()
860
+ await warmGatewayPeers(6000)
861
+ return await gatewayStatusOf()
862
+ }
863
+
864
+ async function disableGateway() {
865
+ settleMode(activeMode === 'gateway' ? '' : activeMode)
866
+ await stopCore()
867
+ gatewayPhase = 'off'
868
+ gatewayPortHint = 0
869
+ if (activeMode === '') stopListener()
870
+ return await gatewayStatusOf()
871
+ }
872
+
873
+ /** 局域网连接方式:启用才监听,关闭就真的关掉端口。 */
874
+ async function enableLan() {
875
+ if (gateway.enabled) await disableGateway()
876
+ settleMode('lan')
877
+ gatewayPortHint = 0
878
+ startListener()
879
+ await waitListening(3000)
880
+ return statusOf()
881
+ }
882
+
883
+ async function disableLan() {
884
+ if (activeMode === 'lan') {
885
+ settleMode('')
886
+ gatewayPortHint = 0
887
+ stopListener()
888
+ }
889
+ return statusOf()
890
+ }
891
+
892
+ /** 把一条连接码接进来:换了网络就连内核一起换凭证重启,同一张网只补一次节点表。 */
893
+ async function joinGateway(text) {
894
+ requireCore()
895
+ const code = parseCode(text)
896
+ if (code === undefined) throw new Error('连接码无法识别,请整段复制对方「跨域网关」里的连接码')
897
+ const sameNetwork = code.net === gateway.network.name && code.secret === gateway.network.secret
898
+ settleMode('gateway')
899
+ if (!sameNetwork) {
900
+ await stopCore()
901
+ gatewayPhase = 'off'
902
+ gateway.network = { name: code.net, secret: code.secret }
903
+ gateway.role = 'joiner'
904
+ if (gateway.relay.length === 0 && code.relay.length > 0) gateway.relay = code.relay
905
+ // 本机虚拟 IP 不能和对方撞:撞了就重新散列一个。
906
+ if (gateway.vip === '' || gateway.vip === code.vip) gateway.vip = pickVip()
907
+ hiddenVips.clear()
908
+ }
909
+ await applyGatewayIdentity()
910
+ if (gatewayPhase !== 'running') await startCore()
911
+ // 节点由内核 peer 表推导,先跑一次,省得第一次打开面板是空的。
912
+ await syncGatewayNodes()
913
+ await warmGatewayPeers(8000)
914
+ logger.info('remote-peers: 跨域网关接入 %s(本机 %s)', code.me.name === '' ? code.vip : code.me.name, gateway.vip)
915
+ return await gatewayStatusOf()
916
+ }
917
+
918
+ /** 本会话已经加过的转发口:内核不接受重复规则,按虚拟地址去重。 */
919
+ const forwardedVips = new Set()
920
+ /** 手动删掉的节点:留住这个意图,别在下一轮又被加回来。 */
921
+ const hiddenVips = new Set()
922
+
923
+ /** 动态加一条内核转发口:不重启内核,已连的节点不受影响。 */
924
+ async function addForwardRule(local, vip, remote) {
925
+ const cli = cliPathOf()
926
+ if (cli === undefined) return false
927
+ const result = await runCommand(cli, ['--rpc-portal', `127.0.0.1:${gateway.rpcPort}`, 'port-forward', 'add', 'tcp', `127.0.0.1:${local}`, `${vip}:${remote}`], 6000)
928
+ if (result.code === 0 || /exist|already/iu.test(`${result.stdout}${result.stderr}`)) return true
929
+ mark(`forward add failed ${local}->${vip}:${remote} ${result.stderr.trim()}`)
930
+ return false
931
+ }
932
+
933
+ /**
934
+ * 唯一的节点发现:读内核 peer 表,按约定算出端口,给每个节点开一条本地转发口。
935
+ * 零消息——谁在线只有内核知道,端口由虚拟地址算出、口令由 secret 派生,不需要彼此打招呼。
936
+ * 内核以 `--no-tun` 运行,虚拟地址在本机不可路由,所以一律落在 `127.0.0.1:<转发口>`。
937
+ */
938
+ async function syncGatewayNodes() {
939
+ if (activeMode !== 'gateway' || gatewayPhase !== 'running') return
940
+ const rows = await peerRows()
941
+ const nodes = []
942
+ for (const row of rows) {
943
+ const vip = String(row.ipv4 ?? '').trim().split('/')[0]
944
+ // 没有虚拟地址的是中转服务器;等于本机地址的是自己;手动删掉的先不加回来。
945
+ if (vip === '' || vip === gateway.vip || hiddenVips.has(vip)) continue
946
+ nodes.push({ vip, name: String(row.hostname ?? '').trim() || vip })
947
+ }
948
+ for (const node of nodes) {
949
+ if (forwardedVips.has(node.vip)) continue
950
+ if (await addForwardRule(forwardPortOf(node.vip), node.vip, gatewayPortOf(node.vip))) forwardedVips.add(node.vip)
951
+ }
952
+ const token = effectiveToken()
953
+ const built = nodes.map((node) => ({
954
+ id: `gateway-${node.vip}`,
955
+ name: node.name,
956
+ host: '127.0.0.1',
957
+ port: forwardPortOf(node.vip),
958
+ token,
959
+ via: 'gateway',
960
+ gateway: { vip: node.vip, port: gatewayPortOf(node.vip) },
961
+ }))
962
+ // 局域网那批原样保留;网关这批整块由内核表推导,节点消失即从列表消失。
963
+ const next = [...peers.filter((item) => item.via !== 'gateway'), ...built]
964
+ if (JSON.stringify(next) !== JSON.stringify(peers)) peers = next
965
+ }
966
+
967
+ if (activeMode === 'gateway') {
968
+ void startCore().catch((error) => { gatewayPhase = 'error'; gatewayError = String(error?.message ?? error) })
969
+ }
970
+
971
+ /** 每 3 秒读一次内核 peer 表:节点进出、对方重启都会自己对齐,不必手动刷新,也不互相发消息。 */
972
+ try {
973
+ ctx.effect(() => {
974
+ const timer = setInterval(() => { void syncGatewayNodes() }, 3000)
975
+ void syncGatewayNodes()
976
+ return () => clearInterval(timer)
977
+ }, 'remote-peers: gateway nodes')
978
+ } catch (error) {
979
+ mark(`gateway nodes effect throw ${error?.stack ?? error}`)
980
+ }
981
+
982
+ try {
983
+ ctx.effect(() => () => {
984
+ // 热更新会重新 apply:只停本进程起的那一个,接管来的内核留给下一轮继续用。
985
+ if (gatewayChild === undefined) return
986
+ try { gatewayChild.kill() } catch { /* 已退出 */ }
987
+ gatewayChild = undefined
988
+ }, 'remote-peers: easytier core')
989
+ } catch (error) {
990
+ mark(`gateway effect throw ${error?.stack ?? error}`)
991
+ }
992
+
993
+ function statusOf() {
994
+ const address = server.address()
995
+ return {
996
+ instanceId: state.instanceId,
997
+ active: activeMode,
998
+ listening: server.listening,
999
+ host: settings.listenHost,
1000
+ port: typeof address === 'object' && address !== null ? address.port : Number(state.port) || settings.listenPort,
1001
+ addresses: lanAddresses(),
1002
+ allowedCidrs: settings.allowedCidrs,
1003
+ token: effectiveToken(),
1004
+ peers: peers.length,
1005
+ }
1006
+ }
1007
+
1008
+ /** 轮换密钥:写盘并让运行中的监听器立刻只用新密钥。 */
1009
+ function rotateToken() {
1010
+ currentToken = randomBytes(32).toString('base64url')
1011
+ writeFileSync(tokenPath(settings.stateDir), `${currentToken}\n`, { mode: 0o600 })
1012
+ logger.warn('remote-peers: 共享密钥已重置,已连接的对端需要重新填写')
1013
+ return statusOf()
1014
+ }
1015
+
1016
+ /** 两种连接方式互斥:不属于当前启用方式的对端一律不发起请求。 */
1017
+ const modeOfPeer = (peerEntry) => (peerEntry.via === 'gateway' ? 'gateway' : 'lan')
1018
+ const peerModeOff = (peerEntry) => modeOfPeer(peerEntry) !== activeMode
1019
+
1020
+ async function pingPeer(id, signal) {
1021
+ const peerEntry = peerById(id)
1022
+ if (peerEntry === undefined) return { ok: false, reason: 'peer-not-found' }
1023
+ if (peerModeOff(peerEntry)) {
1024
+ return { ok: false, reason: modeOfPeer(peerEntry) === 'gateway' ? 'gateway-off' : 'lan-off' }
1025
+ }
1026
+ const url = `http://${peerEntry.host}:${peerEntry.port}/remote-peers/hello`
1027
+ try {
1028
+ const response = await fetch(url, {
1029
+ headers: peerHeaders(peerEntry),
1030
+ signal: AbortSignal.timeout(5000),
1031
+ })
1032
+ if (response.status === 401) return { ok: false, reason: 'token-rejected' }
1033
+ if (!response.ok) return { ok: false, reason: `status-${response.status}` }
1034
+ const body = await response.json()
1035
+ return { ok: true, instanceId: body.instanceId, port: body.port, version: body.version }
1036
+ } catch (error) {
1037
+ return { ok: false, reason: String(error instanceof Error ? error.message : error) }
1038
+ }
1039
+ }
1040
+
1041
+ /** 把一次端点调用转发到对端网关,返回对端原始的 server-response.result。 */
1042
+ async function forward(payload, signal) {
1043
+ const id = typeof payload?.id === 'string' ? payload.id : undefined
1044
+ const method = typeof payload?.method === 'string' ? payload.method : undefined
1045
+ if (id === undefined || method === undefined) throw new Error('proxy 需要 id 与 method')
1046
+ const peerEntry = peerById(id)
1047
+ if (peerEntry === undefined) throw new Error(`未登记的对端 ${id}`)
1048
+ if (peerModeOff(peerEntry)) {
1049
+ throw new Error(modeOfPeer(peerEntry) === 'gateway' ? '跨域网关未启用,这个节点暂不可访问' : '局域网连接方式未启用,这个节点暂不可访问')
1050
+ }
1051
+ if (!/^[A-Za-z0-9_$.-]+\/[A-Za-z0-9_$.-]+$/.test(method)) throw new Error(`非法端点 ${method}`)
1052
+
1053
+ const url = `http://${peerEntry.host}:${peerEntry.port}/api/${method}`
1054
+ const init = {
1055
+ method: 'POST',
1056
+ headers: { 'content-type': 'application/json', [TOKEN_HEADER]: peerEntry.token },
1057
+ body: JSON.stringify({
1058
+ type: 'client-request',
1059
+ rpcId: `lan-${randomUUID()}`,
1060
+ method,
1061
+ payload: payload?.payload ?? { args: {} },
1062
+ }),
1063
+ signal,
1064
+ }
1065
+ // 网关节点走的是本机转发口:隧道刚重建时第一条连接会被当场掐掉(首跳必空),重试一次即可。
1066
+ const attempts = peerEntry.via === 'gateway' ? 2 : 1
1067
+ let response
1068
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1069
+ try {
1070
+ response = await fetch(url, init)
1071
+ break
1072
+ } catch (error) {
1073
+ const last = attempt === attempts - 1
1074
+ if (last || signal?.aborted === true) throw error
1075
+ await new Promise((resolve) => setTimeout(resolve, 350))
1076
+ }
1077
+ }
1078
+ if (response.status === 401) throw new Error('对端拒绝了共享密钥')
1079
+ if (!response.ok) throw new Error(`对端返回 ${response.status}`)
1080
+ const envelope = await response.json()
1081
+ if (envelope?.type !== 'server-response') throw new Error('对端响应不是 server-response')
1082
+ return envelope.result
1083
+ }
1084
+
1085
+ // ── 节点 SSH:插件内置服务端,只有一条通道 ──────────────────────────────
1086
+ // 系统 sshd 在 Windows 上要求管理员密钥文件走 administrators_authorized_keys(要提权写、ACL 只许
1087
+ // SYSTEM/Administrators),免密做不到。所以节点之间只走这条内置通道:本插件自己监听一个 SSH
1088
+ // 服务端,口令就是两端本来就共享的局域网密钥。对端打开开关后,这边点「连接」直接进入,无需凭据。
1089
+ const sshDir = join(settings.stateDir, 'ssh')
1090
+ const sshEnabledPath = () => join(sshDir, 'enabled.json')
1091
+ /** 运行中的 SSH 会话:sessionId → { client, peerId, startedAt, fingerprint }。 */
1092
+ const sshSessions = new Map()
1093
+
1094
+ /** 带错误码的失败:RPC 用例据此回 `ssh/*` 而不是笼统的内部错误。 */
1095
+ const sshError = (code, message) => Object.assign(new Error(message), { code })
1096
+
1097
+ /** 内置通道的运行态;`enabled` 是用户开关(会落盘,重载后自动恢复)。 */
1098
+ const sshServer = { running: false, enabled: false, port: 0, error: '', server: null }
1099
+ /** 文件访问范围:`readonly` / `workspace` / `full`,启动时由 `ssh/access.json` 填入。 */
1100
+ let sshAccess = 'workspace'
1101
+ const sshHostKeyFile = () => join(sshDir, 'server_host_key')
1102
+ let sshHostKeyPromise = null
1103
+
1104
+ // ssh2 是 CJS:动态 import 拿到的命名导出不一定全,统一从 default 取一次。
1105
+ let ssh2Module = null
1106
+ async function loadSsh2() {
1107
+ if (ssh2Module === null) {
1108
+ const mod = await import('ssh2')
1109
+ ssh2Module = mod.default ?? mod
1110
+ }
1111
+ return ssh2Module
1112
+ }
1113
+
1114
+ function readSshEnabled() {
1115
+ try {
1116
+ return parseJsonObject(readFileSync(sshEnabledPath(), 'utf8'))?.enabled === true
1117
+ } catch {
1118
+ // 没有开关文件:默认关着,第一次点「开启」会写出来。
1119
+ return false
1120
+ }
1121
+ }
1122
+
1123
+ function writeSshEnabled(enabled) {
1124
+ mkdirSync(sshDir, { recursive: true })
1125
+ writeFileSync(sshEnabledPath(), `${JSON.stringify({ enabled })}\n`)
1126
+ }
1127
+
1128
+ /** 面板与对端共用的一份状态:开关、是否在监听、端口、失败原因、文件权限。 */
1129
+ function sshSnapshot() {
1130
+ return {
1131
+ enabled: sshServer.enabled,
1132
+ running: sshServer.running,
1133
+ port: sshServer.port > 0 ? sshServer.port : settings.sshServerPort,
1134
+ error: sshServer.error,
1135
+ access: sshAccess,
1136
+ root: sshHomeDir(),
1137
+ addresses: lanAddresses(),
1138
+ }
1139
+ }
1140
+
1141
+ /** 主机密钥只生成一次,重载后指纹不变。 */
1142
+ async function ensureSshHostKey() {
1143
+ if (sshHostKeyPromise === null) {
1144
+ sshHostKeyPromise = (async () => {
1145
+ mkdirSync(sshDir, { recursive: true })
1146
+ const file = sshHostKeyFile()
1147
+ if (existsSync(file)) {
1148
+ const existing = readFileSync(file, 'utf8')
1149
+ if (existing.includes('PRIVATE KEY')) return existing
1150
+ }
1151
+ const { utils } = await loadSsh2()
1152
+ const pair = utils.generateKeyPairSync('ed25519')
1153
+ writeFileSync(file, pair.private, { encoding: 'utf8', mode: 0o600 })
1154
+ return pair.private
1155
+ })()
1156
+ }
1157
+ return sshHostKeyPromise
1158
+ }
1159
+
1160
+ /** 命令与交互 shell 的起始目录:和 SFTP 的 `/` 同一个(DSH 默认工作区)。 */
1161
+ function sshShellCwd() {
1162
+ const dir = sshHomeDir()
1163
+ try {
1164
+ mkdirSync(dir, { recursive: true })
1165
+ return dir
1166
+ } catch {
1167
+ // 工作区不可用(盘未挂载、权限不足)时退回状态目录,登录本身不受影响。
1168
+ return settings.stateDir
1169
+ }
1170
+ }
1171
+
1172
+ /** 一条 exec:Windows 走 powershell,其它平台走 sh,stdout/stderr 与退出码原样回给客户端。 */
1173
+ function runSshServerCommand(command, stream) {
1174
+ // 子进程的 stdout 是重定向管道:先把 PowerShell 的输出编码钉到 UTF-8,中文路径才不会变成 OEM 乱码。
1175
+ const wrapped = process.platform === 'win32'
1176
+ ? `[Console]::OutputEncoding = [Text.Encoding]::UTF8; ${command}`
1177
+ : command
1178
+ const child = process.platform === 'win32'
1179
+ ? spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', wrapped], { cwd: sshShellCwd(), windowsHide: true })
1180
+ : spawn('/bin/sh', ['-lc', wrapped], { cwd: sshShellCwd() })
1181
+ child.stdout.on('data', (chunk) => { stream.write(chunk) })
1182
+ child.stderr.on('data', (chunk) => { stream.stderr.write(chunk) })
1183
+ child.on('error', (error) => {
1184
+ stream.stderr.write(`${error.message}\n`)
1185
+ stream.exit(127)
1186
+ stream.end()
1187
+ })
1188
+ child.on('close', (code) => {
1189
+ stream.exit(code ?? 0)
1190
+ stream.end()
1191
+ })
1192
+ stream.on('close', () => {
1193
+ if (!child.killed) child.kill()
1194
+ })
1195
+ }
1196
+
1197
+ /**
1198
+ * 一条交互 shell。PowerShell 在 stdin 模式下既不打印提示符也不回显输入,
1199
+ * 直接桥接会让客户端看着像卡死,所以在 Windows 上自己回显字符、补 `PS path>`,
1200
+ * 并用一行哨兵判断一条命令执行结束。非 Windows 仍按原样直连。
1201
+ */
1202
+ function runSshServerShell(stream) {
1203
+ const spawnShell = () => process.platform === 'win32'
1204
+ ? spawn('powershell.exe', ['-NoProfile', '-NoLogo', '-NonInteractive', '-Command', '-'], { cwd: sshShellCwd(), windowsHide: true })
1205
+ : spawn('/bin/sh', [], { cwd: sshShellCwd() })
1206
+ let child = spawnShell()
1207
+ if (process.platform !== 'win32') {
1208
+ child.stdout.on('data', (chunk) => { stream.write(chunk) })
1209
+ child.stderr.on('data', (chunk) => { stream.stderr.write(chunk) })
1210
+ stream.on('data', (chunk) => { child.stdin.write(chunk) })
1211
+ child.on('error', (error) => { stream.stderr.write(`${error.message}\n`); stream.exit(127); stream.end() })
1212
+ child.on('close', (code) => { stream.exit(code ?? 0); stream.end() })
1213
+ stream.on('close', () => { if (!child.killed) child.kill() })
1214
+ return
1215
+ }
1216
+
1217
+ const sentinel = '__dsh-shell-done__'
1218
+ let cwd = sshShellCwd()
1219
+ let pending = '' // 已送到子进程、还没等到哨兵的输出
1220
+ let line = '' // 当前正在输入的一行
1221
+ let busy = false // 上一条是否还在跑
1222
+ let closed = false
1223
+
1224
+ const prompt = () => { if (!closed) stream.write(`\r\nPS ${cwd}> `) }
1225
+
1226
+ /** 每条命令末尾补一行哨兵:从哨兵后面的文字能拿到命令跑完时的 cwd,也用来判断「跑完了」。 */
1227
+ const consume = (chunk) => {
1228
+ pending += chunk
1229
+ for (;;) {
1230
+ const at = pending.indexOf(sentinel)
1231
+ if (at === -1) {
1232
+ if (pending.length > 64) {
1233
+ stream.write(pending.slice(0, pending.length - 40))
1234
+ pending = pending.slice(-40)
1235
+ }
1236
+ return
1237
+ }
1238
+ if (at > 0) stream.write(pending.slice(0, at))
1239
+ const rest = pending.slice(at + sentinel.length)
1240
+ const eol = rest.indexOf('\n')
1241
+ if (eol === -1) { pending = pending.slice(at); return }
1242
+ cwd = rest.slice(0, eol).trim().replace(/\r$/, '') || cwd
1243
+ pending = ''
1244
+ busy = false
1245
+ prompt()
1246
+ }
1247
+ }
1248
+
1249
+ /** 挂上一个 PowerShell;它退出(含被 Ctrl+C 杀掉)时整个会话结束。 */
1250
+ const wire = (next) => {
1251
+ next.stdout.on('data', consume)
1252
+ next.stderr.on('data', (chunk) => { stream.stderr.write(chunk) })
1253
+ next.on('error', (error) => {
1254
+ stream.stderr.write(`${error.message}\n`)
1255
+ stream.exit(127)
1256
+ stream.end()
1257
+ })
1258
+ next.on('close', (code) => {
1259
+ if (closed) return
1260
+ closed = true
1261
+ stream.exit(code ?? 0)
1262
+ stream.end()
1263
+ })
1264
+ }
1265
+
1266
+ /** 中断:Windows 的 PowerShell 不认管道里塞来的 ^C,只能把子进程杀掉再起一个,状态(当前目录)保留。 */
1267
+ const interrupt = () => {
1268
+ line = ''
1269
+ pending = ''
1270
+ child.removeAllListeners('close')
1271
+ child.kill()
1272
+ child = spawnShell()
1273
+ wire(child)
1274
+ busy = false
1275
+ stream.write('^C\r\n')
1276
+ prompt()
1277
+ }
1278
+
1279
+ wire(child)
1280
+
1281
+ stream.on('data', (chunk) => {
1282
+ for (const raw of chunk.toString('utf8')) {
1283
+ if (raw === '\x03') {
1284
+ interrupt()
1285
+ continue
1286
+ }
1287
+ if (busy) continue
1288
+ if (raw === '\r' || raw === '\n') {
1289
+ if (line === '') continue
1290
+ if (line.trim() === 'exit') {
1291
+ closed = true
1292
+ stream.exit(0)
1293
+ stream.end()
1294
+ child.kill()
1295
+ return
1296
+ }
1297
+ stream.write('\r\n')
1298
+ busy = true
1299
+ child.stdin.write(`${line}\n[Console]::Out.WriteLine('${sentinel}' + $PWD.Path)\n`)
1300
+ line = ''
1301
+ } else if (raw === '\x7f' || raw === '\b') {
1302
+ if (line !== '') {
1303
+ line = line.slice(0, -1)
1304
+ stream.write('\b \b')
1305
+ }
1306
+ } else if (raw >= ' ' || raw === '\t') {
1307
+ line += raw
1308
+ stream.write(raw)
1309
+ }
1310
+ }
1311
+ })
1312
+
1313
+ stream.on('close', () => {
1314
+ closed = true
1315
+ if (!child.killed) child.kill()
1316
+ })
1317
+ prompt()
1318
+ }
1319
+ // ── SFTP:文件通道,范围由「权限」决定 ──────────────────────────────────
1320
+ // 三档与 DSH 会话权限同口径:仅可查看 / 工作区内修改 / 完全权限。
1321
+ // 前两档把访问锁在 DSH 的默认工作区(只读 vs 可写),只有完全权限才放开整台机器。
1322
+ const sshAccessPath = () => join(sshDir, 'access.json')
1323
+ const SSH_ACCESS_ORDER = ['readonly', 'workspace', 'full']
1324
+ const normalizeSshAccess = (mode) => (SSH_ACCESS_ORDER.includes(mode) ? mode : 'workspace')
1325
+
1326
+ /** DSH 的应用数据主目录;SFTP 只借它找注册表,不作为访问根。 */
1327
+ function dshHomeDir() {
1328
+ const explicit = process.env.DSH_HOME ?? ''
1329
+ return explicit !== '' ? resolve(explicit) : join(homedir(), '.dsh')
1330
+ }
1331
+
1332
+ /**
1333
+ * 工作区 = DSH 注册表里的默认工作区(会话 cwd 就是它)。
1334
+ * 顺序:config `sshWorkspace` → `defaultWorkspaceId` → 注册表第一个工作区 → `$DSH_HOME/default-workspace`。
1335
+ */
1336
+ function sshHomeDir() {
1337
+ if (settings.sshWorkspace !== undefined) return settings.sshWorkspace
1338
+ try {
1339
+ const state = parseJsonObject(readFileSync(join(dshHomeDir(), 'storages', 'workspace.json'), 'utf8'))
1340
+ const table = state?.tables?.workspaces ?? {}
1341
+ const order = Array.isArray(state?.global?.workspaceIds) ? state.global.workspaceIds : []
1342
+ for (const id of [state?.global?.defaultWorkspaceId, ...order]) {
1343
+ const path = typeof id === 'string' ? table[id]?.path : undefined
1344
+ if (typeof path === 'string' && path !== '') return resolve(path)
1345
+ }
1346
+ } catch {
1347
+ // 注册表还没写出来(首次启动或已被清空):退回 DSH 自己用的默认目录名。
1348
+ }
1349
+ return join(dshHomeDir(), 'default-workspace')
1350
+ }
1351
+
1352
+ function readSshAccess() {
1353
+ try {
1354
+ const stored = parseJsonObject(readFileSync(sshAccessPath(), 'utf8'))?.mode
1355
+ // 旧默认是 readonly;没被人主动改过就按新默认升到「工作区内修改」并落盘,免得面板还停在旧档。
1356
+ if (stored === 'readonly') {
1357
+ writeSshAccess('workspace')
1358
+ return 'workspace'
1359
+ }
1360
+ return normalizeSshAccess(stored)
1361
+ } catch {
1362
+ // 没有权限文件:默认「工作区内修改」。
1363
+ return 'workspace'
1364
+ }
1365
+ }
1366
+
1367
+ function writeSshAccess(mode) {
1368
+ mkdirSync(sshDir, { recursive: true })
1369
+ writeFileSync(sshAccessPath(), `${JSON.stringify({ mode })}\n`)
1370
+ }
1371
+
1372
+ /** 正在连着的 SFTP 会话在下一次请求时就按新一档走,不需要断开重连。 */
1373
+ sshAccess = readSshAccess()
1374
+
1375
+ function sshSetAccess(mode) {
1376
+ sshAccess = normalizeSshAccess(typeof mode === 'string' ? mode : '')
1377
+ writeSshAccess(sshAccess)
1378
+ return sshSnapshot()
1379
+ }
1380
+
1381
+ /** 客户端给的路径 → 真实路径,并在前两档挡住越界(含 `..` 绕出主目录)。 */
1382
+ function sftpRealPath(raw) {
1383
+ const text = String(raw ?? '').replace(/\\/gu, '/')
1384
+ let full
1385
+ if (/^[A-Za-z]:\//u.test(text)) full = text
1386
+ else if (text.startsWith('/')) {
1387
+ const rest = text.replace(/^\/+/u, '')
1388
+ full = /^[A-Za-z]:/u.test(rest) ? rest : join(sshHomeDir(), rest)
1389
+ } else full = join(sshHomeDir(), text)
1390
+ const target = resolve(full)
1391
+ if (sshAccess !== 'full') {
1392
+ const home = resolve(sshHomeDir())
1393
+ const lowered = target.toLowerCase()
1394
+ const homeLowered = home.toLowerCase()
1395
+ if (lowered !== homeLowered && !lowered.startsWith(`${homeLowered}${sep}`)) {
1396
+ throw sshError('sftp/denied', '这个路径不在允许范围内')
1397
+ }
1398
+ }
1399
+ return target
1400
+ }
1401
+
1402
+ /** 回给客户端的路径:主目录显示成 `/`,边界外才给完整路径。 */
1403
+ function sftpVirtualPath(real) {
1404
+ const home = resolve(sshHomeDir())
1405
+ const rel = relative(home, real)
1406
+ if (rel === '') return '/'
1407
+ if (!rel.startsWith('..') && !isAbsolute(rel)) return `/${rel.split(sep).join('/')}`
1408
+ return real.split(sep).join('/')
1409
+ }
1410
+
1411
+ const SFTP_ATTRS = (stats) => ({
1412
+ mode: stats.mode,
1413
+ uid: stats.uid ?? 0,
1414
+ gid: stats.gid ?? 0,
1415
+ size: stats.size,
1416
+ atime: Math.floor(stats.atimeMs / 1000),
1417
+ mtime: Math.floor(stats.mtimeMs / 1000),
1418
+ })
1419
+
1420
+ /** 一条 SFTP 会话:句柄表留在插件进程里,每个请求都落到真实 fs。 */
1421
+ function startSftpSession(sftp) {
1422
+ const handles = new Map()
1423
+ let seq = 0
1424
+ const writable = () => sshAccess !== 'readonly'
1425
+ const DENIED = 3
1426
+ const FAILURE = 4
1427
+ const MISSING = 2
1428
+ const EOF = 1
1429
+
1430
+ /** 打开标志:远端 pflags → node fs 的 flag 字符串。`CREAT` 不带 `TRUNC` 时要保留原内容,用 `r+` 而不是 `a`(`a` 会忽略 offset 一路追加)。 */
1431
+ const openFlag = (pflags) => {
1432
+ const WRITE = 0x02
1433
+ const APPEND = 0x04
1434
+ const CREAT = 0x08
1435
+ const TRUNC = 0x10
1436
+ const EXCL = 0x20
1437
+ if ((pflags & TRUNC) !== 0) return 'w'
1438
+ if ((pflags & APPEND) !== 0) return 'a'
1439
+ if ((pflags & CREAT) !== 0) return (pflags & EXCL) !== 0 ? 'wx' : 'r+'
1440
+ if ((pflags & WRITE) !== 0) return 'r+'
1441
+ return 'r'
1442
+ }
1443
+ const wantsWrite = (pflags) => (pflags & (0x02 | 0x04 | 0x08 | 0x10)) !== 0
1444
+
1445
+ const entryOf = (handle) => handles.get(handle.toString())
1446
+
1447
+ sftp.on('OPEN', (reqid, filename, pflags) => {
1448
+ if (wantsWrite(pflags) && !writable()) { sftp.status(reqid, DENIED); return }
1449
+ let path
1450
+ try {
1451
+ path = sftpRealPath(filename)
1452
+ } catch {
1453
+ sftp.status(reqid, DENIED)
1454
+ return
1455
+ }
1456
+ fsp.open(path, openFlag(pflags)).catch((error) => {
1457
+ // `r+` 只在文件已存在时成立;OpenSSH 的 scp 先 `CREAT` 打开,新文件要退回 `w` 建出来。
1458
+ if (error?.code === 'ENOENT' && openFlag(pflags) === 'r+') return fsp.open(path, 'w')
1459
+ throw error
1460
+ }).then((handle) => {
1461
+ seq += 1
1462
+ handles.set(String(seq), { kind: 'file', handle, path })
1463
+ sftp.handle(reqid, Buffer.from(String(seq)))
1464
+ }).catch(() => sftp.status(reqid, MISSING))
1465
+ })
1466
+
1467
+ sftp.on('READ', (reqid, handle, offset, length) => {
1468
+ const entry = entryOf(handle)
1469
+ if (entry === undefined || entry.kind !== 'file') { sftp.status(reqid, FAILURE); return }
1470
+ const buffer = Buffer.alloc(length)
1471
+ entry.handle.read(buffer, 0, length, offset).then(({ bytesRead }) => {
1472
+ if (bytesRead === 0) sftp.status(reqid, EOF)
1473
+ else sftp.data(reqid, buffer.subarray(0, bytesRead))
1474
+ }).catch(() => sftp.status(reqid, FAILURE))
1475
+ })
1476
+
1477
+ sftp.on('WRITE', (reqid, handle, offset, data) => {
1478
+ const entry = entryOf(handle)
1479
+ if (entry === undefined || entry.kind !== 'file') { sftp.status(reqid, FAILURE); return }
1480
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1481
+ entry.handle.write(data, 0, data.length, offset).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1482
+ })
1483
+
1484
+ sftp.on('CLOSE', (reqid, handle) => {
1485
+ const entry = entryOf(handle)
1486
+ if (entry === undefined) { sftp.status(reqid, FAILURE); return }
1487
+ handles.delete(handle.toString())
1488
+ if (entry.kind === 'file') entry.handle.close().then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1489
+ else sftp.status(reqid, 0)
1490
+ })
1491
+
1492
+ // 客户端发 EOF 表示它不再发请求了;这里必须把通道收掉,否则 OpenSSH 的 scp/sftp 会一直挂着等我们关闭。
1493
+ sftp.on('end', () => {
1494
+ for (const entry of handles.values()) {
1495
+ if (entry.kind === 'file') entry.handle.close().catch(() => undefined)
1496
+ }
1497
+ handles.clear()
1498
+ try { sftp.end() } catch { /* 通道已经关了 */ }
1499
+ })
1500
+
1501
+ sftp.on('OPENDIR', (reqid, filename) => {
1502
+ let path
1503
+ try {
1504
+ path = sftpRealPath(filename)
1505
+ } catch {
1506
+ sftp.status(reqid, DENIED)
1507
+ return
1508
+ }
1509
+ fsp.readdir(path, { withFileTypes: true }).then((list) => {
1510
+ seq += 1
1511
+ handles.set(String(seq), { kind: 'dir', path, names: list.map((item) => item.name), at: 0 })
1512
+ sftp.handle(reqid, Buffer.from(String(seq)))
1513
+ }).catch((error) => sftp.status(reqid, error?.code === 'ENOENT' ? MISSING : FAILURE))
1514
+ })
1515
+
1516
+ sftp.on('READDIR', async (reqid, handle) => {
1517
+ const entry = entryOf(handle)
1518
+ if (entry === undefined || entry.kind !== 'dir') { sftp.status(reqid, FAILURE); return }
1519
+ const batch = entry.names.slice(entry.at, entry.at + 32)
1520
+ entry.at += batch.length
1521
+ if (batch.length === 0) { sftp.status(reqid, EOF); return }
1522
+ const names = []
1523
+ for (const name of batch) {
1524
+ try {
1525
+ const stats = await fsp.lstat(join(entry.path, name))
1526
+ names.push({ filename: name, longname: `${stats.mode.toString(8).slice(-4)} ${stats.size} ${name}`, attrs: SFTP_ATTRS(stats) })
1527
+ } catch {
1528
+ names.push({ filename: name, longname: name, attrs: undefined })
1529
+ }
1530
+ }
1531
+ sftp.name(reqid, names)
1532
+ })
1533
+
1534
+ const statOf = (method) => (reqid, filename) => {
1535
+ let path
1536
+ try {
1537
+ path = sftpRealPath(filename)
1538
+ } catch {
1539
+ sftp.status(reqid, DENIED)
1540
+ return
1541
+ }
1542
+ fsp[method](path).then((stats) => sftp.attrs(reqid, SFTP_ATTRS(stats))
1543
+ ).catch((error) => sftp.status(reqid, error?.code === 'ENOENT' ? MISSING : FAILURE))
1544
+ }
1545
+ sftp.on('STAT', statOf('stat'))
1546
+ sftp.on('LSTAT', statOf('lstat'))
1547
+
1548
+ sftp.on('FSTAT', (reqid, handle) => {
1549
+ const entry = entryOf(handle)
1550
+ if (entry === undefined) { sftp.status(reqid, FAILURE); return }
1551
+ const target = entry.kind === 'file' ? entry.handle.stat() : fsp.lstat(entry.path)
1552
+ target.then((stats) => sftp.attrs(reqid, SFTP_ATTRS(stats))).catch(() => sftp.status(reqid, FAILURE))
1553
+ })
1554
+
1555
+ sftp.on('REALPATH', (reqid, filename) => {
1556
+ let path
1557
+ try {
1558
+ path = sftpRealPath(filename)
1559
+ } catch {
1560
+ sftp.status(reqid, DENIED)
1561
+ return
1562
+ }
1563
+ const virtual = sftpVirtualPath(path)
1564
+ sftp.name(reqid, [{ filename: virtual, longname: virtual, attrs: {} }])
1565
+ })
1566
+
1567
+ sftp.on('REMOVE', (reqid, filename) => {
1568
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1569
+ try {
1570
+ fsp.unlink(sftpRealPath(filename)).then(() => sftp.status(reqid, 0)).catch((error) => sftp.status(reqid, error?.code === 'ENOENT' ? MISSING : FAILURE))
1571
+ } catch {
1572
+ sftp.status(reqid, DENIED)
1573
+ }
1574
+ })
1575
+
1576
+ sftp.on('RMDIR', (reqid, filename) => {
1577
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1578
+ try {
1579
+ fsp.rmdir(sftpRealPath(filename)).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1580
+ } catch {
1581
+ sftp.status(reqid, DENIED)
1582
+ }
1583
+ })
1584
+
1585
+ sftp.on('MKDIR', (reqid, filename) => {
1586
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1587
+ try {
1588
+ fsp.mkdir(sftpRealPath(filename)).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1589
+ } catch {
1590
+ sftp.status(reqid, DENIED)
1591
+ }
1592
+ })
1593
+
1594
+ sftp.on('RENAME', (reqid, from, to) => {
1595
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1596
+ try {
1597
+ const source = sftpRealPath(from)
1598
+ const target = sftpRealPath(to)
1599
+ fsp.rename(source, target).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1600
+ } catch {
1601
+ sftp.status(reqid, DENIED)
1602
+ }
1603
+ })
1604
+
1605
+ sftp.on('SETSTAT', (reqid, filename, attrs) => {
1606
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1607
+ let path
1608
+ try {
1609
+ path = sftpRealPath(filename)
1610
+ } catch {
1611
+ sftp.status(reqid, DENIED)
1612
+ return
1613
+ }
1614
+ const steps = []
1615
+ if (attrs?.mode !== undefined) steps.push(fsp.chmod(path, attrs.mode))
1616
+ if (attrs?.size !== undefined) steps.push(fsp.truncate(path, attrs.size))
1617
+ if (attrs?.atime !== undefined || attrs?.mtime !== undefined) {
1618
+ steps.push(fsp.utimes(path, attrs.atime ?? attrs.mtime ?? 0, attrs.mtime ?? attrs.atime ?? 0))
1619
+ }
1620
+ Promise.all(steps).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1621
+ })
1622
+
1623
+ sftp.on('FSETSTAT', (reqid, handle, attrs) => {
1624
+ const entry = entryOf(handle)
1625
+ if (entry === undefined || entry.kind !== 'file') { sftp.status(reqid, FAILURE); return }
1626
+ if (!writable()) { sftp.status(reqid, DENIED); return }
1627
+ // OpenSSH 的 scp 用 `FSETSTAT size` 来截断目标文件,忽略它就会把旧内容留在前面。
1628
+ const steps = []
1629
+ if (attrs?.size !== undefined) steps.push(entry.handle.truncate(attrs.size))
1630
+ if (attrs?.atime !== undefined || attrs?.mtime !== undefined) {
1631
+ steps.push(entry.handle.utimes(attrs.atime ?? attrs.mtime ?? 0, attrs.mtime ?? attrs.atime ?? 0))
1632
+ }
1633
+ Promise.all(steps).then(() => sftp.status(reqid, 0)).catch(() => sftp.status(reqid, FAILURE))
1634
+ })
1635
+ }
1636
+
1637
+ /** 起内置 SSH 服务端;认证只认共享密钥(用户名随意,口令 = 本机 token)。 */
1638
+ /** 授权公钥文件:一行一个 OpenSSH 公钥,改完即生效(每次认证都重读)。 */
1639
+ const sshAuthorizedKeysFile = () => join(sshDir, 'authorized_keys')
1640
+
1641
+ /** 在这份授权公钥里找与客户端出示的公钥 blob 相同的那个,找到才返回可用于验签的 Key。 */
1642
+ async function authorizedKeyFor(key) {
1643
+ let text
1644
+ try {
1645
+ text = readFileSync(sshAuthorizedKeysFile(), 'utf8')
1646
+ } catch {
1647
+ return undefined
1648
+ }
1649
+ const { utils } = await loadSsh2()
1650
+ for (const entry of text.split(/\r?\n/u)) {
1651
+ const trimmed = entry.trim()
1652
+ if (trimmed === '' || trimmed.startsWith('#')) continue
1653
+ let parsed
1654
+ try {
1655
+ parsed = utils.parseKey(trimmed)
1656
+ } catch {
1657
+ continue
1658
+ }
1659
+ const candidate = Array.isArray(parsed) ? parsed[0] : parsed
1660
+ if (candidate === undefined || candidate === null || typeof candidate.getPublicSSH !== 'function') continue
1661
+ const blob = candidate.getPublicSSH()
1662
+ if (candidate.type !== key.algo || blob.length !== key.data.length) continue
1663
+ if (timingSafeEqual(blob, key.data)) return candidate
1664
+ }
1665
+ return undefined
1666
+ }
1667
+
1668
+ async function startSshServer() {
1669
+ if (sshServer.server !== null) return
1670
+ const { Server } = await loadSsh2()
1671
+ const hostKey = await ensureSshHostKey()
1672
+ const server = new Server({ hostKeys: [hostKey] }, (client) => {
1673
+ let attempts = 0
1674
+ client.on('authentication', (auth) => {
1675
+ attempts += 1
1676
+ if (attempts > 6) {
1677
+ client.end()
1678
+ return
1679
+ }
1680
+ // 口令 = 本机共享密钥;也认 `ssh/authorized_keys` 里的公钥(免输口令,避开终端不回显的坑)。
1681
+ const accepted = auth.method === 'password' && secretEquals(String(auth.password ?? ''), effectiveToken())
1682
+ if (accepted) {
1683
+ auth.accept()
1684
+ return
283
1685
  }
284
- case 'diag': {
285
- // TEMP-DIAG:把渲染器一侧探测到的结果落到 stateDir/diag.log(渲染器 console 无处可看)。
286
- const line = `${new Date().toISOString()} ${JSON.stringify(payload)}\n`
287
- mkdirSync(settings.stateDir, { recursive: true })
288
- appendFileSync(join(settings.stateDir, 'diag.log'), line)
289
- return ok({})
1686
+ if (auth.method === 'publickey') {
1687
+ void authorizedKeyFor(auth.key).then((key) => {
1688
+ let ok = false
1689
+ if (key !== undefined) {
1690
+ if (auth.signature === undefined) ok = true
1691
+ else {
1692
+ try {
1693
+ ok = key.verify(auth.blob, auth.signature, auth.hashAlgo) === true
1694
+ } catch {
1695
+ ok = false
1696
+ }
1697
+ }
1698
+ }
1699
+ if (ok) auth.accept()
1700
+ else auth.reject(['password', 'publickey'])
1701
+ }).catch(() => { auth.reject(['password', 'publickey']) })
1702
+ return
290
1703
  }
291
- default:
292
- return fail('remote-peers/unknown-endpoint', `未知端点 ${JSON.stringify(endpoint)}`)
293
- }
1704
+ auth.reject(['password', 'publickey'])
1705
+ })
1706
+ client.on('ready', () => {
1707
+ client.on('session', (accept) => {
1708
+ const session = accept()
1709
+ session.on('pty', (acceptPty) => { if (typeof acceptPty === 'function') acceptPty() })
1710
+ session.on('exec', (acceptExec, _rejectExec, info) => {
1711
+ const stream = typeof acceptExec === 'function' ? acceptExec() : null
1712
+ if (stream === null) return
1713
+ runSshServerCommand(String(info?.command ?? ''), stream)
1714
+ })
1715
+ session.on('shell', (acceptShell) => {
1716
+ const stream = typeof acceptShell === 'function' ? acceptShell() : null
1717
+ if (stream === null) return
1718
+ runSshServerShell(stream)
1719
+ })
1720
+ session.on('sftp', (acceptSftp) => {
1721
+ const sftp = typeof acceptSftp === 'function' ? acceptSftp() : null
1722
+ if (sftp === null) return
1723
+ startSftpSession(sftp)
1724
+ })
1725
+ })
1726
+ })
1727
+ client.on('error', () => {
1728
+ // 握手/半开连接的错误不需要上报,客户端那边会看到失败。
1729
+ })
1730
+ })
1731
+ server.on('error', (error) => {
1732
+ sshServer.error = error instanceof Error ? error.message : String(error)
1733
+ })
1734
+ try {
1735
+ server.listen(settings.sshServerPort, '0.0.0.0')
1736
+ await once(server, 'listening')
294
1737
  } catch (error) {
295
- logger.warn('remote-peers: /remote-peers %s 失败 %s', endpoint, String(error))
296
- return fail('remote-peers/internal', String(error instanceof Error ? error.message : error))
1738
+ sshServer.error = error instanceof Error ? error.message : String(error)
1739
+ try { server.close() } catch { /* 没起来就没有要关的 */ }
1740
+ throw error
297
1741
  }
1742
+ sshServer.server = server
1743
+ sshServer.port = settings.sshServerPort
1744
+ sshServer.running = true
1745
+ sshServer.error = ''
1746
+ logger.info('remote-peers: 节点 SSH 已监听 %d', sshServer.port)
298
1747
  }
299
1748
 
300
- // 热重载时上一个实例可能还占着通道,注册会在同一毫秒失败;退避重试而不是让 apply 半途死掉。
301
- const registerChannel = (attempt = 0) => {
1749
+ /** 关掉监听并落盘开关;已经关着也照常返回。 */
1750
+ function stopSshServer() {
1751
+ for (const session of sshSessions.values()) {
1752
+ try { session.client.end() } catch { /* 已断开 */ }
1753
+ }
1754
+ sshSessions.clear()
1755
+ if (sshServer.server !== null) {
1756
+ try { sshServer.server.close() } catch { /* 已经关了 */ }
1757
+ sshServer.server = null
1758
+ }
1759
+ sshServer.running = false
1760
+ }
1761
+
1762
+ /** 开关:开 = 立刻监听(不需要提权),关 = 立刻断开所有节点会话。 */
1763
+ async function sshToggle(enabled) {
1764
+ if (enabled === true) {
1765
+ await startSshServer()
1766
+ sshServer.enabled = true
1767
+ writeSshEnabled(true)
1768
+ } else {
1769
+ stopSshServer()
1770
+ sshServer.enabled = false
1771
+ writeSshEnabled(false)
1772
+ }
1773
+ return sshSnapshot()
1774
+ }
1775
+
1776
+ /** 问对端要一份状态:走同一把共享密钥,插件端口而不是 sshd 端口。 */
1777
+ async function sshPeerStatus(id) {
1778
+ const peerEntry = typeof id === 'string' ? peerById(id) : undefined
1779
+ if (peerEntry === undefined) return { reachable: false, reason: '对端记录不存在' }
1780
+ if (peerModeOff(peerEntry)) {
1781
+ return { reachable: false, reason: modeOfPeer(peerEntry) === 'gateway' ? '跨域网关未启用,这个节点暂不可访问' : '局域网连接方式未启用,这个节点暂不可访问' }
1782
+ }
1783
+ const url = upstreamUrl(peerEntry, '/remote-peers/ssh/status')
302
1784
  try {
303
- connection.rpc.handle('/remote-peers', handleRemotePeers)
304
- mark(`rpc channel ready (attempt ${attempt})`)
305
- } catch (error) {
306
- if (attempt < 12) {
307
- mark(`rpc retry ${attempt}: ${String(error)}`)
308
- setTimeout(() => registerChannel(attempt + 1), 250)
309
- return
1785
+ const response = await fetch(url, { headers: peerHeaders(peerEntry), signal: AbortSignal.timeout(6000) })
1786
+ if (response.status === 401) return { reachable: false, reason: '对端拒绝了共享密钥' }
1787
+ if (response.status === 404) return { reachable: true, outdated: true, running: false, reason: '对端插件版本较旧,没有节点 SSH 接口' }
1788
+ if (!response.ok) return { reachable: false, reason: `对端返回 ${response.status}` }
1789
+ const body = await response.json()
1790
+ return {
1791
+ reachable: true,
1792
+ outdated: false,
1793
+ running: body?.running === true,
1794
+ port: Number(body?.port) > 0 ? Number(body.port) : settings.sshServerPort,
1795
+ access: SSH_ACCESS_ORDER.includes(body?.access) ? body.access : 'workspace',
310
1796
  }
311
- mark(`rpc throw ${error?.stack ?? error}`)
1797
+ } catch (error) {
1798
+ return { reachable: false, reason: String(error instanceof Error ? error.message : error) }
312
1799
  }
313
1800
  }
314
- registerChannel()
315
1801
 
316
- function statusOf() {
317
- const address = server.address()
318
- return {
319
- instanceId: state.instanceId,
320
- host: settings.listenHost,
321
- port: typeof address === 'object' && address !== null ? address.port : settings.listenPort,
322
- addresses: lanAddresses(),
323
- allowedCidrs: settings.allowedCidrs,
324
- token: currentToken,
325
- peers: peers.length,
1802
+ /**
1803
+ * 网关节点没有直达路由(内核以 `--no-tun` 运行):按虚拟地址末段算一个固定本地口,
1804
+ * 动态加一条 `127.0.0.1:<本地口> → <对端 vip>:<sshd 口>` 转发,不重启内核。
1805
+ */
1806
+ async function ensurePortForward(peerEntry, remotePort) {
1807
+ const vip = peerEntry.gateway?.vip
1808
+ if (typeof vip !== 'string' || vip === '') throw sshError('ssh/gateway-no-forward', '这个网关节点没有虚拟地址,无法建立通道')
1809
+ const local = GATEWAY.sshPortBase + vipIndex(vip)
1810
+ if (!(await addForwardRule(local, vip, Number(remotePort)))) {
1811
+ throw sshError('ssh/gateway-forward-failed', `到 ${vip}:${remotePort} 的转发口建不起来,详见网关日志`)
326
1812
  }
1813
+ return { host: '127.0.0.1', port: local }
327
1814
  }
328
1815
 
329
- /** 轮换密钥:写盘并让运行中的监听器立刻只用新密钥。 */
330
- function rotateToken() {
331
- currentToken = randomBytes(32).toString('base64url')
332
- writeFileSync(tokenPath(settings.stateDir), `${currentToken}\n`, { mode: 0o600 })
333
- logger.warn('remote-peers: 共享密钥已重置,已连接的对端需要重新填写')
334
- return statusOf()
1816
+ /** 建立一条 SSH 会话,成功后由 Host 常驻持有(面板随后用它发保活命令)。 */
1817
+ async function sshConnect(payload) {
1818
+ const peerEntry = typeof payload?.id === 'string' ? peerById(payload.id) : undefined
1819
+ if (peerEntry === undefined) throw sshError('ssh/unknown-peer', '对端记录不存在')
1820
+ if (peerModeOff(peerEntry)) {
1821
+ throw sshError('ssh/mode-off', modeOfPeer(peerEntry) === 'gateway' ? '跨域网关未启用,这个节点暂不可访问' : '局域网连接方式未启用,这个节点暂不可访问')
1822
+ }
1823
+ const reported = await sshPeerStatus(peerEntry.id)
1824
+ if (reported.reachable !== true) throw sshError('ssh/peer-unreachable', String(reported.reason ?? '对端不可达'))
1825
+ if (reported.outdated === true) throw sshError('ssh/peer-outdated', '对端插件版本较旧,请升级后再连')
1826
+ if (reported.running !== true) throw sshError('ssh/peer-off', '对端没有开启节点 SSH:请在那边打开开关,这边就能直接连上')
1827
+
1828
+ const target = peerEntry.via === 'gateway'
1829
+ ? await ensurePortForward(peerEntry, reported.port)
1830
+ : { host: peerEntry.host, port: reported.port }
1831
+
1832
+ // 口令就是对端的局域网密钥:它本来就在节点记录里,不需要用户复制或填写。
1833
+ const authSecret = String(peerEntry.token ?? '')
1834
+ const { Client } = await loadSsh2()
1835
+ const client = new Client()
1836
+ let fingerprint = ''
1837
+ const ready = new Promise((resolve, reject) => {
1838
+ client.once('ready', resolve)
1839
+ client.once('error', reject)
1840
+ client.on('keyboard-interactive', (_name, _instructions, _lang, _prompts, finish) => finish([authSecret]))
1841
+ client.connect({
1842
+ host: target.host,
1843
+ port: target.port,
1844
+ username: 'dsh',
1845
+ password: authSecret,
1846
+ tryKeyboard: true,
1847
+ readyTimeout: 20000,
1848
+ keepaliveInterval: 15000,
1849
+ keepaliveCountMax: 3,
1850
+ hostVerifier: (key) => {
1851
+ fingerprint = `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/u, '')}`
1852
+ return true
1853
+ },
1854
+ })
1855
+ })
1856
+ try {
1857
+ await ready
1858
+ } catch (error) {
1859
+ try { client.end() } catch { /* 握手阶段就断了 */ }
1860
+ throw sshError('ssh/connect-failed', error instanceof Error ? error.message : String(error))
1861
+ }
1862
+ const sessionId = `ssh-${randomBytes(6).toString('hex')}`
1863
+ sshSessions.set(sessionId, { client, peerId: peerEntry.id, startedAt: Date.now(), fingerprint })
1864
+ client.on('close', () => sshSessions.delete(sessionId))
1865
+ logger.info('remote-peers: SSH 会话已建立 %s → %s:%d', peerEntry.id, target.host, target.port)
1866
+ return {
1867
+ sessionId,
1868
+ peerId: peerEntry.id,
1869
+ host: target.host,
1870
+ port: target.port,
1871
+ fingerprint,
1872
+ startedAt: Date.now(),
1873
+ }
335
1874
  }
336
1875
 
337
- async function pingPeer(id, signal) {
338
- const peerEntry = peerById(id)
339
- if (peerEntry === undefined) return { ok: false, reason: 'peer-not-found' }
340
- const url = `http://${peerEntry.host}:${peerEntry.port}/remote-peers/hello`
341
- try {
342
- const response = await fetch(url, {
343
- headers: peerHeaders(peerEntry),
344
- signal: AbortSignal.timeout(5000),
1876
+ /** 保活命令:默认 `echo dsh-alive`,走 exec 通道,带回输出与耗时。 */
1877
+ async function sshExec(payload) {
1878
+ const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
1879
+ const session = sshSessions.get(sessionId)
1880
+ if (session === undefined) throw sshError('ssh/no-session', '这个 SSH 会话已经断开,请重新连接')
1881
+ const command = typeof payload?.command === 'string' && payload.command.trim() !== '' ? payload.command.trim() : 'echo dsh-alive'
1882
+ const started = Date.now()
1883
+ return await new Promise((resolve, reject) => {
1884
+ let settled = false
1885
+ let timer
1886
+ const finish = (value, failure) => {
1887
+ if (settled) return
1888
+ settled = true
1889
+ clearTimeout(timer)
1890
+ if (failure !== undefined) reject(failure)
1891
+ else resolve(value)
1892
+ }
1893
+ timer = setTimeout(() => finish(undefined, sshError('ssh/exec-timeout', '命令 10 秒内没有返回')), 10000)
1894
+ session.client.exec(command, (error, stream) => {
1895
+ if (error !== undefined && error !== null) {
1896
+ finish(undefined, sshError('ssh/exec-failed', error.message))
1897
+ return
1898
+ }
1899
+ let stdout = ''
1900
+ let stderr = ''
1901
+ stream.on('data', (chunk) => { stdout += String(chunk) })
1902
+ stream.stderr?.on('data', (chunk) => { stderr += String(chunk) })
1903
+ stream.on('close', (code) => {
1904
+ finish({
1905
+ ok: (code ?? 1) === 0,
1906
+ code: code ?? 0,
1907
+ command,
1908
+ stdout: stdout.trim(),
1909
+ stderr: stderr.trim(),
1910
+ elapsedMs: Date.now() - started,
1911
+ })
1912
+ })
345
1913
  })
346
- if (response.status === 401) return { ok: false, reason: 'token-rejected' }
347
- if (!response.ok) return { ok: false, reason: `status-${response.status}` }
348
- const body = await response.json()
349
- return { ok: true, instanceId: body.instanceId, port: body.port, version: body.version }
350
- } catch (error) {
351
- return { ok: false, reason: String(error instanceof Error ? error.message : error) }
1914
+ })
1915
+ }
1916
+
1917
+ /** 断开一条会话;已经断开也回 `closed:false`,前端不必为此报错。 */
1918
+ function sshClose(sessionId) {
1919
+ const session = typeof sessionId === 'string' ? sshSessions.get(sessionId) : undefined
1920
+ if (session === undefined) return { closed: false }
1921
+ sshSessions.delete(sessionId)
1922
+ try { session.client.end() } catch {
1923
+ try { session.client.destroy() } catch {
1924
+ // 已经断开。
1925
+ }
352
1926
  }
1927
+ return { closed: true }
353
1928
  }
354
1929
 
355
- /** 把一次端点调用转发到对端网关,返回对端原始的 server-response.result。 */
356
- async function forward(payload, signal) {
357
- const id = typeof payload?.id === 'string' ? payload.id : undefined
358
- const method = typeof payload?.method === 'string' ? payload.method : undefined
359
- if (id === undefined || method === undefined) throw new Error('proxy 需要 id 与 method')
360
- const peerEntry = peerById(id)
361
- if (peerEntry === undefined) throw new Error(`未登记的对端 ${id}`)
362
- if (!/^[A-Za-z0-9_$.-]+\/[A-Za-z0-9_$.-]+$/.test(method)) throw new Error(`非法端点 ${method}`)
1930
+ try {
1931
+ ctx.effect(() => () => {
1932
+ // 插件热重载/卸载时把监听收干净:端口不释放的话下一次 start 会撞车。
1933
+ stopSshServer()
1934
+ }, 'remote-peers: ssh server')
1935
+ } catch (error) {
1936
+ mark(`ssh effect throw ${error?.stack ?? error}`)
1937
+ }
363
1938
 
364
- const url = `http://${peerEntry.host}:${peerEntry.port}/api/${method}`
365
- const response = await fetch(url, {
366
- method: 'POST',
367
- headers: { 'content-type': 'application/json', [TOKEN_HEADER]: peerEntry.token },
368
- body: JSON.stringify({
369
- type: 'client-request',
370
- rpcId: `lan-${randomUUID()}`,
371
- method,
372
- payload: payload?.payload ?? { args: {} },
373
- }),
374
- signal,
1939
+ sshServer.enabled = readSshEnabled()
1940
+ if (sshServer.enabled) {
1941
+ void startSshServer().catch((error) => {
1942
+ sshServer.error = `节点 SSH 启动失败:${error instanceof Error ? error.message : String(error)}`
1943
+ logger.warn('remote-peers: %s', sshServer.error)
375
1944
  })
376
- if (response.status === 401) throw new Error('对端拒绝了共享密钥')
377
- if (!response.ok) throw new Error(`对端返回 ${response.status}`)
378
- const envelope = await response.json()
379
- if (envelope?.type !== 'server-response') throw new Error('对端响应不是 server-response')
380
- return envelope.result
381
1945
  }
382
1946
 
383
1947
  // 打开与下载共用同一份本机副本:对端文件只取一次,落在 `<stateDir>/files/<peerId>/<路径摘要>/<原名>`,
@@ -480,6 +2044,16 @@ export function apply(ctx, config = {}) {
480
2044
  * 有 `v` 取版本串第三段(`<inode>:<…>:<size>:…`),否则用 `content-length`。
481
2045
  */
482
2046
  async function remoteSizeOf(peerEntry, source, sessionId, signal) {
2047
+ const probe = await remoteProbeOf(peerEntry, source, sessionId, signal)
2048
+ return probe.size
2049
+ }
2050
+
2051
+ /**
2052
+ * 对端这份文件的「大小 / 是否已经不在了」。只有 `workspaceFiles/stat` 或 `/api/file`
2053
+ * 明确回 not-found / 404 才判 missing,超时、旧版本端点缺失一律不下结论(免得误伤可下载的文件)。
2054
+ * @returns `{ size?: number, missing?: true }`
2055
+ */
2056
+ async function remoteProbeOf(peerEntry, source, sessionId, signal) {
483
2057
  if (typeof sessionId === 'string' && sessionId !== '') {
484
2058
  const statUrl = upstreamUrl(peerEntry, '/api/workspaceFiles/stat')
485
2059
  const stat = await fetch(statUrl, {
@@ -495,22 +2069,26 @@ export function apply(ctx, config = {}) {
495
2069
  })
496
2070
  if (stat.ok) {
497
2071
  const body = await stat.json().catch(() => undefined)
498
- const value = body?.result?.value
499
- if (body?.result?.ok === true && typeof value?.bytes === 'number' && value.bytes > 0) return value.bytes
2072
+ const result = body?.result
2073
+ if (String(result?.error?.code ?? '').includes('not-found')) return { missing: true }
2074
+ const value = result?.value
2075
+ if (result?.ok === true && typeof value?.bytes === 'number' && value.bytes > 0) return { size: value.bytes }
2076
+ // stat 成功但没有字节数(0 字节/目录):交给 /api/file 兜底,别在这里猜。
500
2077
  }
501
2078
  }
502
2079
  const upstream = upstreamUrl(peerEntry, '/api/file')
503
2080
  upstream.searchParams.set('path', source)
504
2081
  const response = await fetch(upstream, { headers: peerHeaders(peerEntry), redirect: 'manual', signal })
505
2082
  await response.body?.cancel().catch(() => {})
2083
+ if (response.status === 404) return { missing: true }
506
2084
  const token = /[?&]v=([^&]+)/u.exec(response.headers.get('location') ?? '')
507
2085
  if (token !== null) {
508
2086
  const fields = decodeURIComponent(token[1]).split(':')
509
2087
  const size = Number(fields[2] ?? Number.NaN)
510
- if (Number.isFinite(size) && size > 0) return size
2088
+ if (Number.isFinite(size) && size > 0) return { size }
511
2089
  }
512
2090
  const length = Number(response.headers.get('content-length') ?? Number.NaN)
513
- return Number.isFinite(length) && length > 0 ? length : undefined
2091
+ return Number.isFinite(length) && length > 0 ? { size: length } : {}
514
2092
  }
515
2093
 
516
2094
  /** 原名做目录里的文件名:去掉 Windows 不允许的字符,保留中文。 */
@@ -589,7 +2167,7 @@ export function apply(ctx, config = {}) {
589
2167
  async function openLocal(payload, signal) {
590
2168
  const startedAt = Date.now()
591
2169
  const peerEntry = peerById(typeof payload?.id === 'string' ? payload.id : undefined)
592
- if (peerEntry === undefined) throw new Error('未找到该他端,请先在列表里登记')
2170
+ if (peerEntry === undefined) throw new Error('未找到该节点,请先在列表里登记')
593
2171
  const source = typeof payload?.path === 'string' ? payload.path : ''
594
2172
  if (source === '' || source.includes('\0') || !isAbsoluteFsPath(source)) throw new Error('需要绝对文件路径')
595
2173
  const action = payload?.action === 'reveal' ? 'reveal' : 'open'
@@ -695,32 +2273,14 @@ export function apply(ctx, config = {}) {
695
2273
  })
696
2274
  },
697
2275
  }
698
- const streamRoute = {
699
- path: '/api/remote-peers/stream',
700
- methods: ['GET'],
701
- requestBody: 'buffered',
702
- fetch: async (request) => {
703
- const url = new URL(request.url)
704
- const id = url.searchParams.get('id')
705
- const peerEntry = peerById(id)
706
- if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
2276
+ const streamRoute = peerPassRoute('/api/remote-peers/stream', '/remote-peers/stream',
2277
+ (url) => {
707
2278
  const endpoint = url.searchParams.get('endpoint')
708
2279
  const payload = url.searchParams.get('payload')
709
- if (endpoint === null || payload === null) return new Response('missing endpoint or payload', { status: 400 })
710
- const upstream = upstreamUrl(peerEntry, `/remote-peers/stream`)
711
- upstream.searchParams.set('endpoint', endpoint)
712
- upstream.searchParams.set('payload', payload)
713
- const response = await fetch(upstream, {
714
- headers: peerHeaders(peerEntry),
715
- signal: request.signal,
716
- })
717
- if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
718
- return new Response(response.body, {
719
- status: 200,
720
- headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' },
721
- })
2280
+ if (endpoint === null || payload === null) return 'missing endpoint or payload'
2281
+ return { endpoint, payload }
722
2282
  },
723
- }
2283
+ () => ({ 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' }))
724
2284
  // 会话导出:把对端的 `GET /api/session.export` 原样转成本机的一条下载路由,
725
2285
  // 浏览器只与本机通信,对端令牌不出 Host。
726
2286
 
@@ -757,67 +2317,61 @@ function peerHeaders(peerEntry) {
757
2317
  return { [TOKEN_HEADER]: peerEntry.token }
758
2318
  }
759
2319
 
760
- const exportRoute = {
761
- path: '/api/remote-peers/export',
2320
+ /**
2321
+ * 对端 `GET <upstreamPath>?…` 的直通路由:查 peer → 组查询串 → 带令牌转发 → 回写指定响应头。
2322
+ * `paramsOf(url)` 返回要转发的查询参数,或返回一段文案表示参数不合法(回 400)。
2323
+ * 404/400/502 的口径与原各条路由一致。
2324
+ * @param path - 本机暴露的路由路径
2325
+ * @param upstreamPath - 对端路径(`/api/…`)
2326
+ * @param paramsOf - `(url) => Record<string,string> | string`
2327
+ * @param headersOf - `(response, params) => Record<string,string>`,写回浏览器的响应头
2328
+ * @returns 路由定义
2329
+ */
2330
+ function peerPassRoute(path, upstreamPath, paramsOf, headersOf) {
2331
+ return {
2332
+ path,
762
2333
  methods: ['GET'],
763
2334
  requestBody: 'buffered',
764
2335
  fetch: async (request) => {
765
2336
  const url = new URL(request.url)
766
- const id = url.searchParams.get('id')
767
- const peerEntry = peerById(id)
2337
+ const peerEntry = peerById(url.searchParams.get('id'))
768
2338
  if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
769
- const sessionId = url.searchParams.get('sessionId')
770
- if (sessionId === null || sessionId === '') return new Response('missing sessionId', { status: 400 })
771
- const upstream = upstreamUrl(peerEntry, `/api/session.export`)
772
- upstream.searchParams.set('sessionId', sessionId)
773
- upstream.searchParams.set('includeDescendants', url.searchParams.get('includeDescendants') ?? 'true')
774
- const response = await fetch(upstream, {
775
- headers: peerHeaders(peerEntry),
776
- signal: request.signal,
777
- })
2339
+ const params = paramsOf(url)
2340
+ if (typeof params === 'string') return new Response(params, { status: 400 })
2341
+ const upstream = upstreamUrl(peerEntry, upstreamPath)
2342
+ for (const [name, value] of Object.entries(params)) upstream.searchParams.set(name, value)
2343
+ const response = await fetch(upstream, { headers: peerHeaders(peerEntry), signal: request.signal })
778
2344
  if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
779
- const disposition = response.headers.get('content-disposition')
780
- ?? `attachment; filename="dsh-session-${sessionId}.zip"`
781
- return new Response(response.body, {
782
- status: 200,
783
- headers: {
784
- 'content-type': response.headers.get('content-type') ?? 'application/zip',
785
- 'content-disposition': disposition,
786
- 'cache-control': 'no-store',
787
- },
788
- })
2345
+ return new Response(response.body, { status: 200, headers: headersOf(response, params) })
789
2346
  },
790
2347
  }
2348
+ }
2349
+
2350
+ const exportRoute = peerPassRoute('/api/remote-peers/export', '/api/session.export',
2351
+ (url) => {
2352
+ const sessionId = url.searchParams.get('sessionId')
2353
+ if (sessionId === null || sessionId === '') return 'missing sessionId'
2354
+ return { sessionId, includeDescendants: url.searchParams.get('includeDescendants') ?? 'true' }
2355
+ },
2356
+ (response, params) => ({
2357
+ 'content-type': response.headers.get('content-type') ?? 'application/zip',
2358
+ 'content-disposition': response.headers.get('content-disposition')
2359
+ ?? `attachment; filename="dsh-session-${params.sessionId}.zip"`,
2360
+ 'cache-control': 'no-store',
2361
+ }))
791
2362
 
792
2363
  // 复制会话为 Markdown:把对端的 `GET /api/session.markdown` 转成本机一条路由,
793
2364
  // 对端 Host 自己按会话日志生成 Markdown(原生同一实现),令牌不出 Host。
794
- const markdownRoute = {
795
- path: '/api/remote-peers/markdown',
796
- methods: ['GET'],
797
- requestBody: 'buffered',
798
- fetch: async (request) => {
799
- const url = new URL(request.url)
800
- const id = url.searchParams.get('id')
801
- const peerEntry = peerById(id)
802
- if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
2365
+ const markdownRoute = peerPassRoute('/api/remote-peers/markdown', '/api/session.markdown',
2366
+ (url) => {
803
2367
  const sessionId = url.searchParams.get('sessionId')
804
- if (sessionId === null || sessionId === '') return new Response('missing sessionId', { status: 400 })
805
- const upstream = upstreamUrl(peerEntry, `/api/session.markdown`)
806
- upstream.searchParams.set('sessionId', sessionId)
807
- const response = await fetch(upstream, {
808
- headers: peerHeaders(peerEntry),
809
- signal: request.signal,
810
- })
811
- if (!response.ok) return new Response(`upstream ${response.status}`, { status: 502 })
812
- return new Response(response.body, {
813
- status: 200,
814
- headers: {
815
- 'content-type': response.headers.get('content-type') ?? 'text/markdown; charset=utf-8',
816
- 'cache-control': 'no-store',
817
- },
818
- })
2368
+ if (sessionId === null || sessionId === '') return 'missing sessionId'
2369
+ return { sessionId }
819
2370
  },
820
- }
2371
+ (response) => ({
2372
+ 'content-type': response.headers.get('content-type') ?? 'text/markdown; charset=utf-8',
2373
+ 'cache-control': 'no-store',
2374
+ }))
821
2375
 
822
2376
  // 预览 / 下载:把对端的 `GET|HEAD /api/file?path=` 转成本机一条路由。
823
2377
  // 对端在缺 `v` 时 302 到带版本号的 URL;这里把重定向改写成指回本路由(保留 id),
@@ -911,6 +2465,7 @@ function peerHeaders(peerEntry) {
911
2465
  upstream.searchParams.set('path', source)
912
2466
  upstream.searchParams.set('download', '1')
913
2467
  const response = await fetch(upstream, { headers: peerHeaders(peerEntry), signal })
2468
+ if (response.status === 404) throw new Error('对端上没有这份文件(可能已被清理或移动)')
914
2469
  if (!response.ok) throw new Error(`对端返回 HTTP ${response.status}`)
915
2470
  let written = 0
916
2471
  await pipeline(Readable.fromWeb(response.body), async function* (chunks) {
@@ -1101,7 +2656,14 @@ function peerHeaders(peerEntry) {
1101
2656
  })
1102
2657
  if (!response.ok) throw new Error(`upstream ${response.status}`)
1103
2658
  const boundary = /boundary=([^;]+)/u.exec(response.headers.get('content-type') ?? '')
1104
- if (boundary === null) return undefined
2659
+ if (boundary === null) {
2660
+ // 对端没给分区数据就是信封错误:`not-found` 说明文件已被清理,换成能读懂的文案。
2661
+ const body = await response.json().catch(() => undefined)
2662
+ const error = body?.result?.error
2663
+ if (String(error?.code ?? '').includes('not-found')) throw new Error('对端上没有这份文件(可能已被清理或移动)')
2664
+ if (typeof error?.message === 'string' && error.message !== '') throw new Error(error.message)
2665
+ return undefined
2666
+ }
1105
2667
  const buffer = Buffer.from(await response.arrayBuffer())
1106
2668
  return extractMultipartPart(buffer, boundary[1].trim().replace(/^"|"$/gu, ''))
1107
2669
  }
@@ -1238,6 +2800,44 @@ function peerHeaders(peerEntry) {
1238
2800
  },
1239
2801
  }
1240
2802
 
2803
+ // 附件上行:浏览器把 `File` 的字节直接投给本机网关,网关原样流给节点自己的
2804
+ // `/api/session/uploadFileBinary`(原生 Client 同一条路由),不经过 JSON-RPC 的 base64 展开。
2805
+ const uploadRoute = {
2806
+ path: '/api/remote-peers/upload',
2807
+ methods: ['POST'],
2808
+ requestBody: 'streaming',
2809
+ fetch: async (request) => {
2810
+ const url = new URL(request.url)
2811
+ const peerEntry = peerById(url.searchParams.get('id'))
2812
+ if (peerEntry === undefined) return new Response('unknown peer', { status: 404 })
2813
+ const sessionId = url.searchParams.get('sessionId')
2814
+ if (sessionId === null || sessionId === '') return new Response('missing sessionId', { status: 400 })
2815
+ const query = new URLSearchParams({ sessionId })
2816
+ // 带 `mediaType` 的按提示词图片存放;名字用于节点侧保留原始文件名。
2817
+ const name = url.searchParams.get('name')
2818
+ if (name !== null && name !== '') query.set('name', name)
2819
+ const mediaType = url.searchParams.get('mediaType')
2820
+ if (mediaType !== null && mediaType !== '') query.set('mediaType', mediaType)
2821
+ const response = await fetch(
2822
+ `http://${peerEntry.host}:${peerEntry.port}/api/session/uploadFileBinary?${query.toString()}`,
2823
+ {
2824
+ method: 'POST',
2825
+ headers: { 'content-type': 'application/octet-stream', [TOKEN_HEADER]: peerEntry.token },
2826
+ body: request.body,
2827
+ duplex: 'half',
2828
+ signal: request.signal,
2829
+ },
2830
+ )
2831
+ return new Response(response.body, {
2832
+ status: response.status,
2833
+ headers: {
2834
+ 'content-type': response.headers.get('content-type') ?? 'application/json; charset=utf-8',
2835
+ 'cache-control': 'no-store',
2836
+ },
2837
+ })
2838
+ },
2839
+ }
2840
+
1241
2841
  // 本轮改动摘要/对比:把对端的 `GET /api/changes.summary|changes.diff` 转成本机一条路由。
1242
2842
  const changesRoute = {
1243
2843
  path: '/api/remote-peers/changes',
@@ -1279,7 +2879,7 @@ function peerHeaders(peerEntry) {
1279
2879
  }
1280
2880
 
1281
2881
  // 与通道注册同理:重载瞬间旧实例可能还没释放这条精确路由。
1282
- const fetchRoutes = [streamRoute, exportRoute, markdownRoute, fileRoute, downloadRoute, vendorRoute, diagRoute, officeRoute, presentOpenRoute, changesRoute, callRoute]
2882
+ const fetchRoutes = [streamRoute, exportRoute, markdownRoute, fileRoute, downloadRoute, vendorRoute, diagRoute, officeRoute, presentOpenRoute, changesRoute, uploadRoute, callRoute]
1283
2883
  const registerFetchRoute = (attempt = 0) => {
1284
2884
  try {
1285
2885
  for (const route of fetchRoutes) connection.fetch.register(route)
@@ -1307,7 +2907,7 @@ function peerHeaders(peerEntry) {
1307
2907
  req.destroy()
1308
2908
  return
1309
2909
  }
1310
- if (!tokenMatches(req.headers, currentToken)) {
2910
+ if (!tokenMatches(req.headers, effectiveToken())) {
1311
2911
  res.writeHead(401, {
1312
2912
  'content-type': 'text/plain; charset=utf-8',
1313
2913
  'www-authenticate': 'Bearer realm="dsh-remote-peers"',
@@ -1329,6 +2929,13 @@ function peerHeaders(peerEntry) {
1329
2929
  return
1330
2930
  }
1331
2931
 
2932
+ if (url.pathname === '/remote-peers/ssh/status' && method === 'GET') {
2933
+ const snapshot = sshSnapshot()
2934
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
2935
+ res.end(JSON.stringify({ type: 'remote-peers/ssh-status', ...snapshot }))
2936
+ return
2937
+ }
2938
+
1332
2939
  if (url.pathname.startsWith('/api/')) {
1333
2940
  await bridge(req, res)
1334
2941
  return
@@ -1427,16 +3034,33 @@ function peerHeaders(peerEntry) {
1427
3034
  }
1428
3035
  }
1429
3036
 
3037
+
3038
+ function parseJsonObject(text) {
3039
+ if (typeof text !== 'string') return undefined
3040
+ const start = text.indexOf('{')
3041
+ const end = text.lastIndexOf('}')
3042
+ if (start === -1 || end === -1 || end <= start) return undefined
3043
+ try {
3044
+ return JSON.parse(text.slice(start, end + 1))
3045
+ } catch {
3046
+ return undefined
3047
+ }
3048
+ }
3049
+
1430
3050
  /** 归一化配置;缺省值只在这里出现,调用方永远拿到完整的一份。 */
1431
3051
  function resolveSettings(config) {
1432
3052
  const listenHost = typeof config.listenHost === 'string' && config.listenHost !== '' ? config.listenHost : DEFAULTS.listenHost
1433
3053
  const listenPort = Number.isInteger(config.listenPort) ? config.listenPort : DEFAULTS.listenPort
1434
3054
  const allowedCidrs = Array.isArray(config.allowedCidrs) ? config.allowedCidrs.map(String) : DEFAULTS.allowedCidrs
1435
3055
  const configuredDir = typeof config.stateDir === 'string' && config.stateDir !== '' ? config.stateDir : undefined
3056
+ const sshServerPort = Number.isInteger(config.sshServerPort) && config.sshServerPort > 0 ? config.sshServerPort : DEFAULTS.sshServerPort
3057
+ const sshWorkspace = typeof config.sshWorkspace === 'string' && config.sshWorkspace !== '' ? resolve(config.sshWorkspace) : undefined
1436
3058
  return {
1437
3059
  listenHost,
1438
3060
  listenPort,
1439
3061
  allowedCidrs,
3062
+ sshServerPort,
3063
+ sshWorkspace,
1440
3064
  stateDir: configuredDir ?? defaultStateDir(),
1441
3065
  }
1442
3066
  }
@@ -1511,6 +3135,16 @@ function basenameOf(path) {
1511
3135
  return at === -1 ? path : path.slice(at + 1)
1512
3136
  }
1513
3137
 
3138
+ /** 两个字符串等值比较(固定时间,用于口令/密钥);空值一律不等。 */
3139
+ function secretEquals(supplied, expected) {
3140
+ if (typeof supplied !== 'string' || typeof expected !== 'string') return false
3141
+ if (supplied === '' || expected === '') return false
3142
+ const left = Buffer.from(supplied)
3143
+ const right = Buffer.from(expected)
3144
+ if (left.length !== right.length) return false
3145
+ return timingSafeEqual(left, right)
3146
+ }
3147
+
1514
3148
  /** 固定时间比较,避免按字节提前返回。 */
1515
3149
  function tokenMatches(headers, token) {
1516
3150
  const supplied = headerToken(headers)
@@ -1641,5 +3275,17 @@ function normalizePeer(payload) {
1641
3275
  if (token.length < 16) return undefined
1642
3276
  const name = typeof payload.name === 'string' && payload.name.trim() !== '' ? payload.name.trim() : `${host}:${port}`
1643
3277
  const id = typeof payload.id === 'string' && payload.id !== '' ? payload.id : randomUUID()
1644
- return { id, name, host, port, token }
3278
+ // 跨域网关接入的节点多带两个标记:来源(列表角标)与它在虚拟网里的真实地址(列表展示用)。
3279
+ if (payload.via !== 'gateway') return { id, name, host, port, token }
3280
+ const vip = typeof payload.gateway?.vip === 'string' ? payload.gateway.vip : ''
3281
+ const remotePort = Number(payload.gateway?.port)
3282
+ return {
3283
+ id,
3284
+ name,
3285
+ host,
3286
+ port,
3287
+ token,
3288
+ via: 'gateway',
3289
+ gateway: { vip, port: Number.isInteger(remotePort) ? remotePort : 0 },
3290
+ }
1645
3291
  }