dsh-plugin-opencode2api 1.3.4 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +8 -0
  2. package/lib/index.js +146 -38
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -61,6 +61,14 @@ Windows / macOS / Linux 装好后,打开 DSH Web UI(默认 `http://127.0.0.1
61
61
 
62
62
  管理端看到设备「在线」后就会把请求分配过来。心跳超过 3 分钟没到会自动标记离线,重新上线自动恢复;长期不用时在管理端点「删除」会同时清理隧道和 DNS。
63
63
 
64
+ ### 隧道连不上怎么查(Windows 尤其看这里)
65
+
66
+ 1. 看日志:`<DSH_HOME>\dsh-go\opencode2api\cloudflared.log`(默认 `C:\Users\你的用户名\.dsh\...`),搜索 `ERR`、`exit`、`[plugin]`。出现 `下载到的不是可执行文件` 说明镜像返回了网页,删掉同目录的 `cloudflared.exe` 让插件重下即可。
67
+ 2. Windows Defender 有时会拦 cloudflared:在「病毒和威胁防护 → 排除项」里把插件数据目录加进去,再重新接入。
68
+ 3. 1.3.5 起,插件启动 cloudflared 后等 1.5 秒确认进程还活着;秒退会直接显示「隧道启动失败」,不再假装在线。
69
+ 4. 旧版留下的 `cloudflared.pid` 可能被别的程序复用,导致插件误以为隧道在跑。1.3.5 会核对进程名(Windows 用 `tasklist`,Linux 读 `/proc/<pid>/comm`,macOS 用 `ps`),不是 cloudflared 就忽略并重新启动。
70
+ 5. 回源地址统一用 `http://127.0.0.1:8080`,避免 Windows 上 `localhost` 先解析到 `::1` 而本地服务只监听 IPv4。
71
+
64
72
  退出:面板里点「退出设备池」,会同时从中转站删除这台设备。
65
73
 
66
74
  ## 使用
package/lib/index.js CHANGED
@@ -333,6 +333,7 @@ let heartbeatFails = 0
333
333
  let tunnelDownStreak = 0
334
334
  let tunnelNextTry = 0
335
335
  let tunnelExits = 0
336
+ let tunnelState = { ok: false, at: 0, reason: '' }
336
337
 
337
338
  function readPool() {
338
339
  try {
@@ -359,6 +360,10 @@ function poolSnapshot() {
359
360
  if (pool.lastError) return { status: '心跳失败', tone: 'warn', hostname: pool.hostname || '', lastError: pool.lastError }
360
361
  if (age === null) return { status: '等待心跳', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
361
362
  if (age < 180000) {
363
+ const fresh = tunnelState.at > 0 && Date.now() - tunnelState.at < 150000
364
+ if (fresh && !tunnelState.ok) {
365
+ return { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: tunnelState.reason || '' }
366
+ }
362
367
  if (!tunnelRunning()) return { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
363
368
  return { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
364
369
  }
@@ -373,8 +378,36 @@ function cloudflaredTarget() {
373
378
  return { file: `cloudflared-linux-${arch}`, archive: false }
374
379
  }
375
380
 
381
+ function expectedMagicOk(buf) {
382
+ if (!buf || buf.length < 1024) return false
383
+ if (process.platform === 'win32') return buf[0] === 0x4d && buf[1] === 0x5a
384
+ if (process.platform === 'darwin') return true
385
+ return buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46
386
+ }
387
+
388
+ function existingBinaryOk(file) {
389
+ try {
390
+ if (!fs.existsSync(file)) return false
391
+ if (fs.statSync(file).size < 1024 * 1024) return false
392
+ const fd = fs.openSync(file, 'r')
393
+ const head = Buffer.alloc(4)
394
+ try {
395
+ fs.readSync(fd, head, 0, 4, 0)
396
+ } finally {
397
+ fs.closeSync(fd)
398
+ }
399
+ return expectedMagicOk(head)
400
+ } catch {
401
+ return false
402
+ }
403
+ }
404
+
376
405
  async function ensureCloudflared() {
377
- if (fs.existsSync(CLOUDFLARED)) return
406
+ if (existingBinaryOk(CLOUDFLARED)) return
407
+ // 之前下到的可能是镜像的错误网页,留着只会每次启动都失败
408
+ try {
409
+ if (fs.existsSync(CLOUDFLARED)) fs.unlinkSync(CLOUDFLARED)
410
+ } catch {}
378
411
  const t = cloudflaredTarget()
379
412
  let lastFailure = null
380
413
  for (const prefix of MIRRORS) {
@@ -391,7 +424,11 @@ async function ensureCloudflared() {
391
424
  await fsp.copyFile(found, CLOUDFLARED)
392
425
  await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
393
426
  } else {
427
+ if (!expectedMagicOk(body)) {
428
+ throw new Error(`下载到的不是可执行文件(${body.length} 字节,多半是镜像错误页)`)
429
+ }
394
430
  await fsp.writeFile(CLOUDFLARED, body)
431
+ logTunnel(`cloudflared downloaded bytes=${body.length} from=${prefix || 'github'}`)
395
432
  }
396
433
  if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
397
434
  return
@@ -402,13 +439,48 @@ async function ensureCloudflared() {
402
439
  throw lastFailure || new Error('cloudflared 下载失败')
403
440
  }
404
441
 
442
+ function readTunnelPid() {
443
+ try {
444
+ return Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim()) || 0
445
+ } catch {
446
+ return 0
447
+ }
448
+ }
449
+
450
+ async function processName(pid) {
451
+ if (!pid) return ''
452
+ if (IS_WIN) {
453
+ const out = await execLines('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], 5000)
454
+ const match = /^"([^"]+)"/.exec(out.trim())
455
+ return match ? match[1].toLowerCase() : ''
456
+ }
457
+ if (process.platform === 'linux') {
458
+ try {
459
+ return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim().toLowerCase()
460
+ } catch {
461
+ // /proc 读不到就退回 ps
462
+ }
463
+ }
464
+ const out = await execLines('ps', ['-p', String(pid), '-o', 'comm='], 3000)
465
+ return out.trim().toLowerCase()
466
+ }
467
+
468
+ async function pidIsCloudflared(pid) {
469
+ if (!pid || !alive(pid)) return false
470
+ const name = await processName(pid)
471
+ return Boolean(name) && name.includes('cloudflared')
472
+ }
473
+
405
474
  function tunnelRunning() {
406
475
  if (tunnelChild && tunnelChild.exitCode === null) return true
407
- try {
408
- const pid = Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim())
409
- if (pid && alive(pid)) return true
410
- } catch {}
411
- return false
476
+ const pid = readTunnelPid()
477
+ return Boolean(pid && alive(pid))
478
+ }
479
+
480
+ // 光看进程号会被复用骗:重启或异常退出后,pid 文件里的号可能已经属于别的程序
481
+ async function tunnelRunningVerified() {
482
+ if (tunnelChild && tunnelChild.exitCode === null) return true
483
+ return await pidIsCloudflared(readTunnelPid())
412
484
  }
413
485
 
414
486
  async function tunnelReady() {
@@ -433,7 +505,7 @@ function logTunnel(message) {
433
505
 
434
506
  function tunnelArgs(token) {
435
507
  const args = ['tunnel', '--no-autoupdate']
436
- // 手机网络对 UDP 7844 很不友好,强制走 TCP/http2,省得 QUIC 一直握手失败
508
+ // 手机/办公网经常把 UDP 7844 掐掉,强制走 TCP/http2,省得 QUIC 一直握手超时
437
509
  args.push('--protocol', 'http2', '--edge-ip-version', '4')
438
510
  args.push('--metrics', `127.0.0.1:${METRICS_PORT}`)
439
511
  args.push('run', '--token', token)
@@ -443,38 +515,54 @@ function tunnelArgs(token) {
443
515
  async function startTunnel() {
444
516
  const pool = readPool()
445
517
  if (!pool?.tunnelToken) return false
446
- if (tunnelRunning()) return true
518
+ if (await tunnelRunningVerified()) return true
519
+ if (tunnelRunning()) {
520
+ logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
521
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
522
+ }
447
523
  if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
448
524
  const fd = fs.openSync(TUNNEL_LOG, 'a')
525
+ let child
449
526
  try {
450
- tunnelChild = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
527
+ child = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
451
528
  stdio: ['ignore', fd, fd],
452
529
  detached: false,
530
+ windowsHide: true,
453
531
  })
532
+ tunnelChild = child
454
533
  } finally {
455
534
  fs.closeSync(fd)
456
535
  }
457
- tunnelChild.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
458
- tunnelChild.once('exit', (code, signal) => {
536
+ child.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
537
+ child.once('exit', (code, signal) => {
459
538
  tunnelExits += 1
460
539
  logTunnel(`cloudflared exit code=${code} signal=${signal || ''} total=${tunnelExits}`)
461
540
  })
462
- tunnelChild.unref()
541
+ child.unref()
463
542
  try {
464
- fs.writeFileSync(TUNNEL_PID, String(tunnelChild.pid))
543
+ fs.writeFileSync(TUNNEL_PID, String(child.pid))
465
544
  } catch {}
466
- logTunnel(`cloudflared started pid=${tunnelChild.pid} protocol=http2 edge=4 metrics=${METRICS_PORT}`)
545
+ logTunnel(`cloudflared started pid=${child.pid} protocol=http2 edge=4 metrics=${METRICS_PORT}`)
546
+ // 下载到的是网页、缺 DLL、被杀软拦下时进程会立刻退,别把这种当成启动成功
547
+ await sleep(1500)
548
+ if (tunnelChild && tunnelChild.exitCode !== null) {
549
+ logTunnel(`cloudflared died right after start code=${tunnelChild.exitCode}`)
550
+ tunnelChild = null
551
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
552
+ return false
553
+ }
467
554
  return true
468
555
  }
469
556
 
470
- function stopTunnel() {
471
- const pids = new Set()
472
- if (tunnelChild?.pid) pids.add(tunnelChild.pid)
473
- try {
474
- const filePid = Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim())
475
- if (filePid) pids.add(filePid)
476
- } catch {}
477
- for (const pid of pids) {
557
+ async function stopTunnel() {
558
+ const targets = new Set()
559
+ if (tunnelChild?.pid) targets.add(tunnelChild.pid)
560
+ const filePid = readTunnelPid()
561
+ if (filePid && filePid !== tunnelChild?.pid) {
562
+ if (await pidIsCloudflared(filePid)) targets.add(filePid)
563
+ else logTunnel(`skip killing stale pid=${filePid} (not cloudflared)`)
564
+ }
565
+ for (const pid of targets) {
478
566
  try {
479
567
  process.kill(pid)
480
568
  } catch {}
@@ -490,6 +578,11 @@ export async function heartbeat() {
490
578
  const pool = readPool()
491
579
  if (!pool?.deviceId || !pool?.deviceSecret) return
492
580
  const tunnel = await tunnelReady()
581
+ tunnelState = {
582
+ ok: tunnel.ok,
583
+ at: Date.now(),
584
+ reason: tunnel.known ? (tunnel.ok ? '' : '隧道没连上') : '隧道状态未知',
585
+ }
493
586
  try {
494
587
  const res = await fetch(`${pool.url}/api/device/heartbeat`, {
495
588
  method: 'POST',
@@ -516,11 +609,13 @@ export async function heartbeat() {
516
609
  pool.lastError = ''
517
610
  writePool(pool)
518
611
  if (data.enabled === false) {
519
- stopTunnel()
612
+ void stopTunnel()
520
613
  poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
521
614
  } else {
522
- void startTunnel()
523
- if (tunnel.known && !tunnel.ok) {
615
+ const started = await startTunnel()
616
+ if (!started) {
617
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
618
+ } else if (tunnel.known && !tunnel.ok) {
524
619
  poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
525
620
  } else {
526
621
  poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
@@ -556,9 +651,14 @@ async function checkTunnel() {
556
651
  const pool = readPool()
557
652
  if (!pool?.tunnelToken) return
558
653
  if (Date.now() < tunnelNextTry) return
559
- const alive = tunnelRunning()
560
- if (alive) {
654
+ const running = await tunnelRunningVerified()
655
+ if (running) {
561
656
  const ready = await tunnelReady()
657
+ tunnelState = {
658
+ ok: ready.ok,
659
+ at: Date.now(),
660
+ reason: ready.known ? (ready.ok ? '' : '隧道没连上') : '隧道状态未知',
661
+ }
562
662
  if (ready.ok) {
563
663
  tunnelDownStreak = 0
564
664
  return
@@ -567,15 +667,18 @@ async function checkTunnel() {
567
667
  tunnelDownStreak += 1
568
668
  if (tunnelDownStreak < 2) return
569
669
  logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
570
- stopTunnel()
670
+ await stopTunnel()
671
+ } else if (tunnelRunning()) {
672
+ logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
673
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
571
674
  }
572
675
  // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
573
676
  tunnelDownStreak = 0
574
- try {
575
- await startTunnel()
576
- } catch (error) {
677
+ const started = await startTunnel().catch((error) => {
577
678
  logTunnel(`restart failed: ${error?.message || error}`)
578
- }
679
+ return false
680
+ })
681
+ if (!started) tunnelState = { ok: false, at: Date.now(), reason: 'cloudflared 启动失败' }
579
682
  tunnelNextTry = Date.now() + Math.min(5000 * 2 ** Math.min(tunnelExits, 5), 180000)
580
683
  }
581
684
 
@@ -626,9 +729,13 @@ export async function joinPool(input = {}) {
626
729
  lastError: '',
627
730
  })
628
731
  await ensureCloudflared()
629
- await startTunnel()
732
+ const started = await startTunnel()
630
733
  startPoolTimers()
631
734
  await heartbeat()
735
+ if (!started) {
736
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: data.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
737
+ return `设备已登记,但隧道没启动:${data.hostname || data.device_id}`
738
+ }
632
739
  poolInfo = { status: '在线', tone: 'good', hostname: data.hostname || '', lastError: '' }
633
740
  return `已接入设备池:${data.hostname || data.device_id}`
634
741
  })()
@@ -641,7 +748,7 @@ export async function joinPool(input = {}) {
641
748
 
642
749
  export function resetPoolLocally(reason) {
643
750
  stopPoolTimers()
644
- stopTunnel()
751
+ void stopTunnel()
645
752
  try {
646
753
  fs.unlinkSync(POOL)
647
754
  } catch {}
@@ -651,7 +758,7 @@ export function resetPoolLocally(reason) {
651
758
  async function leavePool() {
652
759
  const pool = readPool()
653
760
  stopPoolTimers()
654
- stopTunnel()
761
+ await stopTunnel()
655
762
  if (pool?.deviceId && pool?.deviceSecret && pool?.url) {
656
763
  await fetch(`${pool.url}/api/device/leave`, {
657
764
  method: 'POST',
@@ -706,6 +813,7 @@ async function buildState() {
706
813
  poolTone: pool.tone,
707
814
  poolHost: pool.hostname,
708
815
  poolError: pool.lastError,
816
+ poolTunnel: tunnelState.at ? { ok: tunnelState.ok, reason: tunnelState.reason, at: tunnelState.at } : null,
709
817
  }
710
818
  }
711
819
 
@@ -842,7 +950,7 @@ function findFile(dir, filename) {
842
950
 
843
951
  async function runCommand(command, args) {
844
952
  return new Promise((resolve, reject) => {
845
- const child = spawn(command, args, { stdio: 'ignore' })
953
+ const child = spawn(command, args, { stdio: 'ignore', windowsHide: true })
846
954
  child.once('error', reject)
847
955
  child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`${command} exit ${code}`))))
848
956
  })
@@ -964,7 +1072,7 @@ function alive(pid) {
964
1072
 
965
1073
  function execLines(command, args, timeout = 3000) {
966
1074
  return new Promise((resolve) => {
967
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'] })
1075
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
968
1076
  let out = ''
969
1077
  let done = false
970
1078
  let timer
@@ -1104,7 +1212,7 @@ async function start() {
1104
1212
  const fd = fs.openSync(LOG, 'a')
1105
1213
  let child
1106
1214
  try {
1107
- child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd] })
1215
+ child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd], windowsHide: true })
1108
1216
  } finally {
1109
1217
  fs.closeSync(fd)
1110
1218
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-opencode2api",
3
- "version": "1.3.4",
3
+ "version": "1.3.5",
4
4
  "description": "Unofficial one-click installer and auto-runner for opencode2api — a local free OpenAI-compatible API gateway — inside DSH, with a desktop settings UI and a dsh-go native panel (Windows, macOS, Linux, Android).",
5
5
  "repository": {
6
6
  "type": "git",