@andy.ian/dsh-homing 2.0.0 → 2.0.2

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/bin/watchdog.mjs CHANGED
@@ -1,158 +1,144 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * 看门狗 / 重启脚本的安装器。
3
+ * 守护进程的安装 / 状态 / 卸载命令(纯 Node,无 PowerShell、无计划任务)。
4
4
  *
5
- * 为什么需要它:
6
- * 重启脚本必须跑在 DSH 之外(它要杀掉承载插件的进程),所以不能由插件自己在运行时执行。
7
- * 换电脑后,插件包装好了,但 ~/.dsh/watchdog 下的脚本和计划任务都不会自动跟过来。
8
- * 这个命令把这件事变成一条:
9
- *
10
- * dsh-homing-watchdog install # 装脚本 + 注册看门狗计划任务
11
- * dsh-homing-watchdog status # 看状态(等价 restart-now.ps1 -Check)
12
- * dsh-homing-watchdog remove # 卸载计划任务(保留脚本)
13
- * dsh-homing-watchdog restart # 立刻重启 DSH(默认等空闲)
14
- * dsh-homing-watchdog restart --immediate # 一空闲就重启
15
- *
16
- * 只支持 Windows(脚本是 PowerShell + 计划任务)。
5
+ * 守护逻辑在 bin/supervisor.mjs:常驻、监视 DSH、崩溃自动拉起、升级期间等待。
6
+ * 本命令只负责入口管理:
7
+ * install 写入「登录时启动守护进程」(Win 启动文件夹 / macOS LaunchAgent / Linux systemd user unit)
8
+ * status 向守护进程控制接口取状态
9
+ * remove 删除启动项
10
+ * restart 请求重启(默认等空闲,--immediate 立即)
11
+ * stop 让守护进程退出(不再拉起 DSH)
17
12
  */
18
13
  import fs from 'node:fs'
19
14
  import path from 'node:path'
20
- import { spawnSync } from 'node:child_process'
15
+ import os from 'node:os'
16
+ import http from 'node:http'
21
17
  import { fileURLToPath } from 'node:url'
22
18
 
23
19
  const here = path.dirname(fileURLToPath(import.meta.url))
24
20
  const pkgRoot = path.resolve(here, '..')
25
- const sourceDir = path.join(pkgRoot, 'ops', 'watchdog')
26
- const dshHome = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? '', '.dsh')
27
- const targetDir = path.join(dshHome, 'watchdog')
21
+ const supervisor = path.join(pkgRoot, 'bin', 'supervisor.mjs')
22
+ const controlPort = Number(process.env.DSH_HOMING_CONTROL ?? 8790)
28
23
 
29
- const TASK_WATCHDOG = 'DSH-Watchdog'
30
- const TASK_RESTART = 'DSH-Restart-Now'
31
- const EXE = 'powershell.exe'
24
+ const has = (name) => process.argv.includes('--' + name)
25
+ const [command] = process.argv.slice(2)
32
26
 
33
- const run = (args, opts = {}) => spawnSync(EXE, args, { encoding: 'utf8', windowsHide: true, ...opts })
34
- const ps = (script) => run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script])
35
- const psFile = (file, extra = []) => {
36
- // 中文 Windows 的 PowerShell 默认按 GBK 输出,Node 按 utf8 读会乱码;
37
- // 这里先设 [Console]::OutputEncoding 再执行脚本,保证能读懂结果。
38
- const quoted = "'" + file.replaceAll("'", "''") + "'"
39
- // 开关参数必须原样传(加引号会变成位置参数,被 ValidateSet 拒绝)
40
- const args = extra.join(' ')
41
- return run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
42
- `[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; & ${quoted} ${args}`])
27
+ function call(pathname, method = 'POST') {
28
+ return new Promise((resolve, reject) => {
29
+ const req = http.request({ host: '127.0.0.1', port: controlPort, path: pathname, method, timeout: 8000 }, (res) => {
30
+ const chunks = []
31
+ res.on('data', (chunk) => chunks.push(chunk))
32
+ res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }))
33
+ })
34
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')) })
35
+ req.on('error', reject)
36
+ req.end()
37
+ })
43
38
  }
44
39
 
45
- function requireWindows() {
46
- if (process.platform !== 'win32') {
47
- console.error('这个命令只支持 Windows(用 PowerShell + 计划任务实现)。')
48
- process.exit(1)
40
+ function startupPath() {
41
+ if (process.platform === 'win32') {
42
+ return path.join(process.env.APPDATA ?? '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'dsh-homing-supervisor.vbs')
49
43
  }
44
+ if (process.platform === 'darwin') {
45
+ return path.join(os.homedir(), 'Library', 'LaunchAgents', 'online.gitsrc.dsh-homing.plist')
46
+ }
47
+ return path.join(os.homedir(), '.config', 'systemd', 'user', 'dsh-homing-supervisor.service')
50
48
  }
51
49
 
52
50
  function install() {
53
- requireWindows()
54
- if (!fs.existsSync(sourceDir)) {
55
- console.error(`找不到脚本目录:${sourceDir}`)
56
- process.exit(1)
57
- }
58
- fs.mkdirSync(targetDir, { recursive: true })
59
- for (const name of fs.readdirSync(sourceDir)) {
60
- if (!name.endsWith('.ps1')) continue
61
- fs.copyFileSync(path.join(sourceDir, name), path.join(targetDir, name))
62
- console.log(` ✓ 已复制 ${name}`)
63
- }
51
+ const file = startupPath()
52
+ fs.mkdirSync(path.dirname(file), { recursive: true })
53
+ if (process.platform === 'win32') {
54
+ // 用 wscript 启动,登录时才不会闪控制台窗口
55
+ const vbs = `' 由 dsh-homing 生成:登录时以隐藏窗口启动守护进程\r\nSet sh = CreateObject("WScript.Shell")\r\nsh.Run """${process.execPath}"" ""${supervisor}"" --detach", 0, False\r\n`
56
+ fs.writeFileSync(file, vbs, 'ascii')
57
+ } else if (process.platform === 'darwin') {
58
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
59
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
60
+ <plist version="1.0"><dict>
61
+ <key>Label</key><string>online.gitsrc.dsh-homing</string>
62
+ <key>ProgramArguments</key><array><string>${process.execPath}</string><string>${supervisor}</string><string>--detach</string></array>
63
+ <key>RunAtLoad</key><true/>
64
+ </dict></plist>
65
+ `
66
+ fs.writeFileSync(file, xml, 'utf8')
67
+ } else {
68
+ const text = `[Unit]
69
+ Description=DSH Homing supervisor
64
70
 
65
- const watchdog = path.join(targetDir, 'dsh-watchdog.ps1')
66
- const register = `
67
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${watchdog}"'
68
- $trigger1 = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2) -RepetitionInterval (New-TimeSpan -Minutes 5)
69
- $trigger2 = New-ScheduledTaskTrigger -AtLogOn
70
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
71
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
72
- Register-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Action $action -Trigger $trigger1,$trigger2 -Settings $settings -Principal $principal -Force | Out-Null
73
- Write-Output 'registered'
74
- `
75
- const registered = ps(register)
76
- if (!String(registered.stdout).includes('registered')) {
77
- console.error('注册看门狗计划任务失败:' + (registered.stderr || registered.stdout || '').slice(0, 400))
78
- process.exit(1)
71
+ [Service]
72
+ ExecStart=${process.execPath} ${supervisor} --detach
73
+
74
+ [Install]
75
+ WantedBy=default.target
76
+ `
77
+ fs.writeFileSync(file, text, 'utf8')
79
78
  }
80
- console.log(` ✓ 已注册计划任务 ${TASK_WATCHDOG}(每 5 分钟体检)`)
81
- console.log('\n装好了。常用命令:')
82
- console.log(' dsh-homing-watchdog status 查看状态与能否重启')
83
- console.log(' dsh-homing-watchdog restart 重启 DSH(等空闲)')
84
- console.log(' dsh-homing-watchdog restart --immediate 一空闲就重启')
79
+ console.log(` ✓ 已写入启动项:${file}`)
80
+ if (process.platform === 'linux') console.log(' 启用:systemctl --user enable --now dsh-homing-supervisor')
81
+ console.log('\n常用命令:')
82
+ console.log(' dsh-homing-watchdog status')
83
+ console.log(' dsh-homing-watchdog restart [--immediate]')
84
+ console.log(' dsh-homing-watchdog stop')
85
85
  }
86
86
 
87
- function status() {
88
- requireWindows()
89
- const restart = path.join(targetDir, 'restart-now.ps1')
90
- if (!fs.existsSync(restart)) {
91
- console.error('还没安装:先跑 dsh-homing-watchdog install')
87
+ async function status() {
88
+ try {
89
+ const res = await call('/status', 'GET')
90
+ console.log(res.body.trim())
91
+ } catch {
92
+ console.error('守护进程没在运行(控制端口连不上)。先 dsh-homing-watchdog install,或手动运行 supervisor.mjs --detach。')
92
93
  process.exit(1)
93
94
  }
94
- const result = psFile(restart, ['-Check'])
95
- const text = String(result.stdout || '').replace(/^\uFEFF/u, '')
96
- if (text.trim() === '') {
97
- console.error('读取状态失败:' + (result.stderr || '').slice(0, 300))
98
- process.exit(1)
99
- }
100
- console.log(text.trim())
101
95
  }
102
96
 
103
97
  function remove() {
104
- requireWindows()
105
- const result = ps(`Unregister-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Confirm:$false -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName '${TASK_RESTART}' -Confirm:$false -ErrorAction SilentlyContinue; Write-Output 'removed'`)
106
- if (String(result.stdout).includes('removed')) {
107
- console.log(` ✓ 已卸载计划任务(脚本仍保留在 ${targetDir})`)
98
+ const file = startupPath()
99
+ if (fs.existsSync(file)) {
100
+ fs.rmSync(file, { force: true })
101
+ console.log(` ✓ 已删除启动项:${file}`)
108
102
  } else {
109
- console.error('卸载失败:' + (result.stderr || '').slice(0, 300))
110
- process.exit(1)
103
+ console.log(' 启动项不存在')
111
104
  }
112
105
  }
113
106
 
114
- function restart({ immediate }) {
115
- requireWindows()
116
- const script = path.join(targetDir, 'restart-now.ps1')
117
- if (!fs.existsSync(script)) {
118
- console.error('还没安装:先跑 dsh-homing-watchdog install')
119
- process.exit(1)
120
- }
107
+ async function restart(immediate) {
121
108
  const mode = immediate ? 'immediate' : 'default'
122
- const reason = immediate ? '命令行请求(立即)' : '命令行请求'
123
- // 用计划任务跑,避免重启时把当前调用它的进程一起杀掉
124
- const cmd = `
125
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${script}" -Mode ${mode} -Reason "${reason}"'
126
- $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(5)
127
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 30)
128
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
129
- Register-ScheduledTask -TaskName '${TASK_RESTART}' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
130
- Write-Output 'queued'
131
- `
132
- const result = ps(cmd)
133
- if (String(result.stdout).includes('queued')) {
134
- console.log(`已排队(模式 ${mode}),5 秒后开始等空闲;日志:${path.join(targetDir, 'restart.log')}`)
135
- } else {
136
- console.error('排队失败:' + (result.stderr || '').slice(0, 300))
109
+ try {
110
+ const res = await call(`/restart?mode=${mode}`)
111
+ console.log(res.status === 202 ? ` 已请求重启(模式 ${mode})` : ` 请求被拒绝(HTTP ${res.status})`)
112
+ } catch {
113
+ console.error('守护进程没在运行。先 install 或手动启动 supervisor.mjs --detach。')
137
114
  process.exit(1)
138
115
  }
139
116
  }
140
117
 
141
- const [command, ...rest] = process.argv.slice(2)
142
- const has = (flag) => rest.includes(flag)
118
+ async function stop() {
119
+ try {
120
+ await call('/stop')
121
+ console.log(' 守护进程已退出(不会自动拉起 DSH)')
122
+ } catch {
123
+ console.error('守护进程没在运行')
124
+ process.exit(1)
125
+ }
126
+ }
143
127
 
144
128
  switch (command) {
145
129
  case 'install': install(); break
146
- case 'status': status(); break
130
+ case 'status': await status(); break
147
131
  case 'remove': remove(); break
148
- case 'restart': restart({ immediate: has('--immediate') || has('-i') }); break
132
+ case 'restart': await restart(has('--immediate') || has('-i')); break
133
+ case 'stop': await stop(); break
149
134
  default:
150
- console.log(`用法: dsh-homing-watchdog <install|status|remove|restart> [--immediate]
135
+ console.log(`用法: dsh-homing-watchdog <install|status|remove|restart|stop> [--immediate]
151
136
 
152
- install 安装/更新重启脚本与看门狗计划任务(换电脑后跑这个)
153
- status 查看进程、端口、会话活动与能否重启
154
- remove 卸载计划任务(保留脚本文件)
155
- restart 重启 DSH;默认等会话空闲,加 --immediate 则一空闲就重启
137
+ install 写入登录自启(Windows 启动项 / macOS LaunchAgent / Linux systemd user unit)
138
+ status 向守护进程查询状态
139
+ remove 删除登录自启
140
+ restart 请求重启 DSH(默认等空闲,--immediate 立即)
141
+ stop 让守护进程退出(不再拉起 DSH)
156
142
  `)
157
143
  process.exit(command === undefined ? 0 : 1)
158
144
  }
package/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-mobile:把本机 DSH 开放给手机/微信(随 DSH 启动)
1
+ # dsh-homing:把本机 DSH 开放给手机/微信(随 DSH 启动)
2
2
  #
3
3
  # 配置说明:
4
4
  # serverHost 云服务器 IP(留空则只在本机/局域网提供服务,不起隧道)
@@ -9,14 +9,14 @@
9
9
  # bindAddress 本机监听地址;'::' 表示局域网 + 回环都监听(默认)
10
10
  # publicUrl 手机通过公网访问的入口,只用于启动日志
11
11
  # funcValue 入口暗号:必须带 ?func=<这个值>,留空则关闭该闸门
12
- # login 是否要求用户名密码登录(账号密码存在 $DSH_HOME/integrations/dsh-mobile/auth.json)
12
+ # login 是否要求用户名密码登录(账号密码存在 $DSH_HOME/integrations/dsh-homing/auth.json)
13
13
  # tls 'auto' = 自动生成自签证书(局域网也是 HTTPS);'files' = 用 tlsCert/tlsKey;'off' = 明文(仅本机调试)
14
14
  # tlsCert/tlsKey tls=files 时的证书与私钥路径
15
15
  - insert:
16
- - id: dsh-mobile
16
+ - id: dsh-homing
17
17
  name: '@andy.ian/dsh-homing'
18
18
  config:
19
- serverHost: '' # 服务器地址建议写在 $DSH_HOME/integrations/dsh-mobile/settings.json,改完自动重连
19
+ serverHost: '' # 服务器地址建议写在 $DSH_HOME/integrations/dsh-homing/settings.json,改完自动重连
20
20
  sshUser: ubuntu
21
21
  sshPort: 22
22
22
  sshKey: ''