dsh-plugin-opencode2api 1.3.4 → 1.3.6

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 +171 -43
  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,39 @@ 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
+ try {
408
+ if (fs.existsSync(CLOUDFLARED)) {
409
+ const size = fs.statSync(CLOUDFLARED).size
410
+ logTunnel(`existing cloudflared invalid (size=${size}), re-downloading`)
411
+ fs.unlinkSync(CLOUDFLARED)
412
+ }
413
+ } catch {}
378
414
  const t = cloudflaredTarget()
379
415
  let lastFailure = null
380
416
  for (const prefix of MIRRORS) {
@@ -391,9 +427,22 @@ async function ensureCloudflared() {
391
427
  await fsp.copyFile(found, CLOUDFLARED)
392
428
  await fsp.rm(temp, { recursive: true, force: true }).catch(() => {})
393
429
  } else {
394
- await fsp.writeFile(CLOUDFLARED, body)
430
+ if (!expectedMagicOk(body)) {
431
+ throw new Error(`下载到的不是可执行文件(${body.length} 字节,多半是镜像错误页)`)
432
+ }
433
+ // 先写临时文件再改名:正在运行的旧 cloudflared 不会被写坏(Windows/Linux 都安全)
434
+ const temp = `${CLOUDFLARED}.new`
435
+ await fsp.writeFile(temp, body)
436
+ if (!IS_WIN) fs.chmodSync(temp, 0o755)
437
+ try {
438
+ fs.renameSync(temp, CLOUDFLARED)
439
+ } catch (error) {
440
+ try { fs.unlinkSync(temp) } catch {}
441
+ throw error
442
+ }
443
+ logTunnel(`cloudflared downloaded bytes=${body.length} from=${prefix || 'github'}`)
395
444
  }
396
- if (!IS_WIN) fs.chmodSync(CLOUDFLARED, 0o755)
445
+ if (!IS_WIN && t.archive) fs.chmodSync(CLOUDFLARED, 0o755)
397
446
  return
398
447
  } catch (error) {
399
448
  lastFailure = error
@@ -402,13 +451,48 @@ async function ensureCloudflared() {
402
451
  throw lastFailure || new Error('cloudflared 下载失败')
403
452
  }
404
453
 
454
+ function readTunnelPid() {
455
+ try {
456
+ return Number(fs.readFileSync(TUNNEL_PID, 'utf8').trim()) || 0
457
+ } catch {
458
+ return 0
459
+ }
460
+ }
461
+
462
+ async function processName(pid) {
463
+ if (!pid) return ''
464
+ if (IS_WIN) {
465
+ const out = await execLines('tasklist', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], 5000)
466
+ const match = /^"([^"]+)"/.exec(out.trim())
467
+ return match ? match[1].toLowerCase() : ''
468
+ }
469
+ if (process.platform === 'linux') {
470
+ try {
471
+ return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim().toLowerCase()
472
+ } catch {
473
+ // /proc 读不到就退回 ps
474
+ }
475
+ }
476
+ const out = await execLines('ps', ['-p', String(pid), '-o', 'comm='], 3000)
477
+ return out.trim().toLowerCase()
478
+ }
479
+
480
+ async function pidIsCloudflared(pid) {
481
+ if (!pid || !alive(pid)) return false
482
+ const name = await processName(pid)
483
+ return Boolean(name) && name.includes('cloudflared')
484
+ }
485
+
405
486
  function tunnelRunning() {
406
487
  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
488
+ const pid = readTunnelPid()
489
+ return Boolean(pid && alive(pid))
490
+ }
491
+
492
+ // 光看进程号会被复用骗:重启或异常退出后,pid 文件里的号可能已经属于别的程序
493
+ async function tunnelRunningVerified() {
494
+ if (tunnelChild && tunnelChild.exitCode === null) return true
495
+ return await pidIsCloudflared(readTunnelPid())
412
496
  }
413
497
 
414
498
  async function tunnelReady() {
@@ -433,7 +517,7 @@ function logTunnel(message) {
433
517
 
434
518
  function tunnelArgs(token) {
435
519
  const args = ['tunnel', '--no-autoupdate']
436
- // 手机网络对 UDP 7844 很不友好,强制走 TCP/http2,省得 QUIC 一直握手失败
520
+ // 手机/办公网经常把 UDP 7844 掐掉,强制走 TCP/http2,省得 QUIC 一直握手超时
437
521
  args.push('--protocol', 'http2', '--edge-ip-version', '4')
438
522
  args.push('--metrics', `127.0.0.1:${METRICS_PORT}`)
439
523
  args.push('run', '--token', token)
@@ -443,38 +527,62 @@ function tunnelArgs(token) {
443
527
  async function startTunnel() {
444
528
  const pool = readPool()
445
529
  if (!pool?.tunnelToken) return false
446
- if (tunnelRunning()) return true
530
+ if (await tunnelRunningVerified()) return true
531
+ if (tunnelRunning()) {
532
+ logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
533
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
534
+ }
447
535
  if (!fs.existsSync(CLOUDFLARED)) await ensureCloudflared()
448
- const fd = fs.openSync(TUNNEL_LOG, 'a')
536
+ let fd = null
449
537
  try {
450
- tunnelChild = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
451
- stdio: ['ignore', fd, fd],
538
+ fd = fs.openSync(TUNNEL_LOG, 'a')
539
+ } catch {
540
+ // Windows 上日志被杀软临时占用时也要能启动,不能因为打不开日志就整条隧道不跑
541
+ fd = null
542
+ }
543
+ let child
544
+ try {
545
+ child = spawn(CLOUDFLARED, tunnelArgs(pool.tunnelToken), {
546
+ stdio: fd === null ? 'ignore' : ['ignore', fd, fd],
452
547
  detached: false,
548
+ windowsHide: true,
453
549
  })
550
+ tunnelChild = child
454
551
  } finally {
455
- fs.closeSync(fd)
552
+ if (fd !== null) {
553
+ try { fs.closeSync(fd) } catch {}
554
+ }
456
555
  }
457
- tunnelChild.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
458
- tunnelChild.once('exit', (code, signal) => {
556
+ child.once('error', (error) => logTunnel(`spawn error: ${error?.message || error}`))
557
+ child.once('exit', (code, signal) => {
459
558
  tunnelExits += 1
460
559
  logTunnel(`cloudflared exit code=${code} signal=${signal || ''} total=${tunnelExits}`)
461
560
  })
462
- tunnelChild.unref()
561
+ child.unref()
463
562
  try {
464
- fs.writeFileSync(TUNNEL_PID, String(tunnelChild.pid))
563
+ fs.writeFileSync(TUNNEL_PID, String(child.pid))
465
564
  } catch {}
466
- logTunnel(`cloudflared started pid=${tunnelChild.pid} protocol=http2 edge=4 metrics=${METRICS_PORT}`)
565
+ logTunnel(`cloudflared started pid=${child.pid} protocol=http2 edge=4 metrics=${METRICS_PORT}`)
566
+ // 下载到的是网页、缺 DLL、被杀软拦下时进程会立刻退,别把这种当成启动成功
567
+ await sleep(1500)
568
+ if (tunnelChild && tunnelChild.exitCode !== null) {
569
+ logTunnel(`cloudflared died right after start code=${tunnelChild.exitCode}`)
570
+ tunnelChild = null
571
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
572
+ return false
573
+ }
467
574
  return true
468
575
  }
469
576
 
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) {
577
+ async function stopTunnel() {
578
+ const targets = new Set()
579
+ if (tunnelChild?.pid) targets.add(tunnelChild.pid)
580
+ const filePid = readTunnelPid()
581
+ if (filePid && filePid !== tunnelChild?.pid) {
582
+ if (await pidIsCloudflared(filePid)) targets.add(filePid)
583
+ else logTunnel(`skip killing stale pid=${filePid} (not cloudflared)`)
584
+ }
585
+ for (const pid of targets) {
478
586
  try {
479
587
  process.kill(pid)
480
588
  } catch {}
@@ -490,6 +598,11 @@ export async function heartbeat() {
490
598
  const pool = readPool()
491
599
  if (!pool?.deviceId || !pool?.deviceSecret) return
492
600
  const tunnel = await tunnelReady()
601
+ tunnelState = {
602
+ ok: tunnel.ok,
603
+ at: Date.now(),
604
+ reason: tunnel.known ? (tunnel.ok ? '' : '隧道没连上') : '隧道状态未知',
605
+ }
493
606
  try {
494
607
  const res = await fetch(`${pool.url}/api/device/heartbeat`, {
495
608
  method: 'POST',
@@ -516,11 +629,13 @@ export async function heartbeat() {
516
629
  pool.lastError = ''
517
630
  writePool(pool)
518
631
  if (data.enabled === false) {
519
- stopTunnel()
632
+ void stopTunnel()
520
633
  poolInfo = { status: '已被管理端停用', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
521
634
  } else {
522
- void startTunnel()
523
- if (tunnel.known && !tunnel.ok) {
635
+ const started = await startTunnel()
636
+ if (!started) {
637
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: pool.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
638
+ } else if (tunnel.known && !tunnel.ok) {
524
639
  poolInfo = { status: '隧道重连中', tone: 'warn', hostname: pool.hostname || '', lastError: '' }
525
640
  } else {
526
641
  poolInfo = { status: '在线', tone: 'good', hostname: pool.hostname || '', lastError: '' }
@@ -556,9 +671,14 @@ async function checkTunnel() {
556
671
  const pool = readPool()
557
672
  if (!pool?.tunnelToken) return
558
673
  if (Date.now() < tunnelNextTry) return
559
- const alive = tunnelRunning()
560
- if (alive) {
674
+ const running = await tunnelRunningVerified()
675
+ if (running) {
561
676
  const ready = await tunnelReady()
677
+ tunnelState = {
678
+ ok: ready.ok,
679
+ at: Date.now(),
680
+ reason: ready.known ? (ready.ok ? '' : '隧道没连上') : '隧道状态未知',
681
+ }
562
682
  if (ready.ok) {
563
683
  tunnelDownStreak = 0
564
684
  return
@@ -567,15 +687,18 @@ async function checkTunnel() {
567
687
  tunnelDownStreak += 1
568
688
  if (tunnelDownStreak < 2) return
569
689
  logTunnel(`tunnel unhealthy (connections=${ready.connections} known=${ready.known}), restarting`)
570
- stopTunnel()
690
+ await stopTunnel()
691
+ } else if (tunnelRunning()) {
692
+ logTunnel(`stale pid=${readTunnelPid()} is not cloudflared, clearing it`)
693
+ try { fs.unlinkSync(TUNNEL_PID) } catch {}
571
694
  }
572
695
  // 进程没了或确认不健康:重启并做指数退避,避免秒退秒起
573
696
  tunnelDownStreak = 0
574
- try {
575
- await startTunnel()
576
- } catch (error) {
697
+ const started = await startTunnel().catch((error) => {
577
698
  logTunnel(`restart failed: ${error?.message || error}`)
578
- }
699
+ return false
700
+ })
701
+ if (!started) tunnelState = { ok: false, at: Date.now(), reason: 'cloudflared 启动失败' }
579
702
  tunnelNextTry = Date.now() + Math.min(5000 * 2 ** Math.min(tunnelExits, 5), 180000)
580
703
  }
581
704
 
@@ -626,9 +749,13 @@ export async function joinPool(input = {}) {
626
749
  lastError: '',
627
750
  })
628
751
  await ensureCloudflared()
629
- await startTunnel()
752
+ const started = await startTunnel()
630
753
  startPoolTimers()
631
754
  await heartbeat()
755
+ if (!started) {
756
+ poolInfo = { status: '隧道启动失败', tone: 'bad', hostname: data.hostname || '', lastError: 'cloudflared 没能启动,看 cloudflared.log' }
757
+ return `设备已登记,但隧道没启动:${data.hostname || data.device_id}`
758
+ }
632
759
  poolInfo = { status: '在线', tone: 'good', hostname: data.hostname || '', lastError: '' }
633
760
  return `已接入设备池:${data.hostname || data.device_id}`
634
761
  })()
@@ -641,7 +768,7 @@ export async function joinPool(input = {}) {
641
768
 
642
769
  export function resetPoolLocally(reason) {
643
770
  stopPoolTimers()
644
- stopTunnel()
771
+ void stopTunnel()
645
772
  try {
646
773
  fs.unlinkSync(POOL)
647
774
  } catch {}
@@ -651,7 +778,7 @@ export function resetPoolLocally(reason) {
651
778
  async function leavePool() {
652
779
  const pool = readPool()
653
780
  stopPoolTimers()
654
- stopTunnel()
781
+ await stopTunnel()
655
782
  if (pool?.deviceId && pool?.deviceSecret && pool?.url) {
656
783
  await fetch(`${pool.url}/api/device/leave`, {
657
784
  method: 'POST',
@@ -706,6 +833,7 @@ async function buildState() {
706
833
  poolTone: pool.tone,
707
834
  poolHost: pool.hostname,
708
835
  poolError: pool.lastError,
836
+ poolTunnel: tunnelState.at ? { ok: tunnelState.ok, reason: tunnelState.reason, at: tunnelState.at } : null,
709
837
  }
710
838
  }
711
839
 
@@ -842,7 +970,7 @@ function findFile(dir, filename) {
842
970
 
843
971
  async function runCommand(command, args) {
844
972
  return new Promise((resolve, reject) => {
845
- const child = spawn(command, args, { stdio: 'ignore' })
973
+ const child = spawn(command, args, { stdio: 'ignore', windowsHide: true })
846
974
  child.once('error', reject)
847
975
  child.once('close', (code) => (code === 0 ? resolve() : reject(new Error(`${command} exit ${code}`))))
848
976
  })
@@ -964,7 +1092,7 @@ function alive(pid) {
964
1092
 
965
1093
  function execLines(command, args, timeout = 3000) {
966
1094
  return new Promise((resolve) => {
967
- const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'] })
1095
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true })
968
1096
  let out = ''
969
1097
  let done = false
970
1098
  let timer
@@ -1104,7 +1232,7 @@ async function start() {
1104
1232
  const fd = fs.openSync(LOG, 'a')
1105
1233
  let child
1106
1234
  try {
1107
- child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd] })
1235
+ child = spawn(BIN, ['-config', CFG], { cwd: DATA, detached: true, stdio: ['ignore', fd, fd], windowsHide: true })
1108
1236
  } finally {
1109
1237
  fs.closeSync(fd)
1110
1238
  }
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.6",
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",