@andy.ian/dsh-homing 2.1.5 → 2.1.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.
package/bin/inbox.mjs ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 调试收件箱的命令行工具(给会话侧使用)。
4
+ *
5
+ * node bin/inbox.mjs list 列出消息(默认只列等待回复的)
6
+ * node bin/inbox.mjs list --all 列出全部
7
+ * node bin/inbox.mjs reply <id> <文本>
8
+ * node bin/inbox.mjs read <id> 显示单条
9
+ *
10
+ * 数据位置:<DSH_HOME>/integrations/dsh-homing/debug-inbox/messages.json
11
+ */
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+
16
+ const dshHome = process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
17
+ const file = path.join(dshHome, 'integrations', 'dsh-homing', 'debug-inbox', 'messages.json')
18
+ const read = () => { try { const v = JSON.parse(fs.readFileSync(file, 'utf8')); return Array.isArray(v) ? v : [] } catch { return [] } }
19
+ const write = (v) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(v, null, 2), 'utf8') }
20
+
21
+ const args = process.argv.slice(2)
22
+ const command = args[0] ?? 'list'
23
+
24
+ if (command === 'list') {
25
+ const all = read()
26
+ const rows = args.includes('--all') ? all : all.filter((m) => !m.reply)
27
+ if (rows.length === 0) { console.log('没有待处理消息。'); process.exit(0) }
28
+ for (const m of rows) {
29
+ console.log(`[${m.id}] ${m.at} 会话=${m.sessionTitle || m.sessionId || '-'} 图片=${m.images?.length ?? 0}`)
30
+ console.log(' ' + String(m.text || '').replaceAll('\n', '\n '))
31
+ }
32
+ } else if (command === 'read') {
33
+ const m = read().find((x) => x.id === args[1])
34
+ if (!m) { console.log('找不到消息:', args[1]); process.exit(1) }
35
+ console.log(JSON.stringify(m, null, 2))
36
+ } else if (command === 'reply') {
37
+ const all = read()
38
+ const m = all.find((x) => x.id === args[1])
39
+ if (!m) { console.log('找不到消息:', args[1]); process.exit(1) }
40
+ m.reply = args.slice(2).join(' ') || '(空回复)'
41
+ m.repliedAt = new Date().toISOString().replace('T', ' ').slice(0, 19)
42
+ write(all)
43
+ console.log('已回复', m.id)
44
+ } else {
45
+ console.log('用法: node bin/inbox.mjs list [--all] | read <id> | reply <id> <文本>')
46
+ }
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 窗口代理守护进程(Node 实现)。
4
+ *
5
+ * 对外:本地套接字(Windows 命名管道 / POSIX UDS),行 JSON 请求。
6
+ * 对内:
7
+ * - Windows 的窗口操作(list/capture/click/key/...)代理给常驻的
8
+ * PowerShell 工作进程(window-agent.ps1 的 stdio 模式)执行;
9
+ * - 转屏按平台分派:Windows 走工作进程(ChangeDisplaySettingsEx),
10
+ * Linux 走 xrandr,macOS 走 displayplacer。
11
+ *
12
+ * 单实例由套接字名独占保证;空闲超时自动退出;请求带 token。
13
+ */
14
+ import { execFile, spawn } from 'node:child_process'
15
+ import fs from 'node:fs'
16
+ import net from 'node:net'
17
+ import path from 'node:path'
18
+ import readline from 'node:readline'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ import { agentDir, loadOrCreateToken, removeStaleSocket, socketName, socketPath } from '../lib/local-socket.mjs'
22
+ import { powershellExe } from '../lib/exec-path.mjs'
23
+ import { createLogWriter } from '../lib/log-file.mjs'
24
+
25
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
26
+ const WORKER = path.join(HERE, '..', 'lib', 'window-agent.ps1')
27
+
28
+ const NAME = process.env.DSH_AGENT_PIPE || socketName()
29
+ const SOCKET = socketPath(NAME)
30
+ const TOKEN = process.env.DSH_AGENT_TOKEN || loadOrCreateToken()
31
+ const IDLE_SECONDS = Math.max(10, Number(process.env.DSH_AGENT_IDLE_SECONDS) || 300)
32
+ const LOG_FILE = path.join(agentDir(), 'window-agent.log')
33
+
34
+ const writeLogLine = createLogWriter(LOG_FILE)
35
+
36
+ function log(message) {
37
+ writeLogLine(`${new Date().toISOString()} [node-daemon] ${message}\n`)
38
+ }
39
+
40
+ const isWindows = process.platform === 'win32'
41
+
42
+ // ---------------- PowerShell 工作进程(仅 Windows) ----------------
43
+
44
+ let worker = null
45
+ let workerReader = null
46
+ let workerSeq = 0
47
+ const workerPending = new Map()
48
+
49
+ function ensureWorker() {
50
+ if (!isWindows) throw new Error('窗口操作仅支持 Windows')
51
+ if (worker !== null && worker.exitCode === null) return worker
52
+ const child = spawn(powershellExe(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', WORKER], {
53
+ windowsHide: true,
54
+ stdio: ['pipe', 'pipe', 'pipe'],
55
+ // stdio 工作进程只被守护进程使用,不需要 token(避免二次鉴权)
56
+ env: { ...process.env, DSH_AGENT_TOKEN: '' },
57
+ })
58
+ child.stderr.on('data', () => { /* 工作进程 stderr 忽略 */ })
59
+ workerReader = readline.createInterface({ input: child.stdout })
60
+ workerReader.on('line', (line) => {
61
+ const text = line.trim()
62
+ if (!text.startsWith('{')) return
63
+ let message = null
64
+ try { message = JSON.parse(text) } catch { return }
65
+ const resolve = workerPending.get(message.id)
66
+ if (resolve === undefined) return
67
+ workerPending.delete(message.id)
68
+ resolve(message)
69
+ })
70
+ const failPending = () => {
71
+ for (const [, resolve] of workerPending) resolve({ ok: false, error: '窗口工作进程已退出' })
72
+ workerPending.clear()
73
+ worker = null
74
+ }
75
+ child.on('exit', () => { log('worker exit'); failPending() })
76
+ child.on('error', () => { log('worker error'); failPending() })
77
+ worker = child
78
+ return child
79
+ }
80
+
81
+ function workerCall(request, timeoutMs = 20_000) {
82
+ const child = ensureWorker()
83
+ const id = String(++workerSeq)
84
+ return new Promise((resolve) => {
85
+ const timer = setTimeout(() => {
86
+ workerPending.delete(id)
87
+ resolve({ ok: false, error: 'timeout' })
88
+ }, timeoutMs)
89
+ workerPending.set(id, (message) => {
90
+ clearTimeout(timer)
91
+ resolve(message)
92
+ })
93
+ try {
94
+ child.stdin.write(JSON.stringify({ id, ...request }) + '\n')
95
+ } catch (error) {
96
+ clearTimeout(timer)
97
+ workerPending.delete(id)
98
+ resolve({ ok: false, error: String(error?.message ?? error) })
99
+ }
100
+ })
101
+ }
102
+
103
+ // ---------------- 转屏(跨平台分派) ----------------
104
+
105
+ const run = (command, args, timeoutMs = 20_000) => new Promise((resolve) => {
106
+ execFile(command, args, { windowsHide: true, timeout: timeoutMs }, (error, stdout, stderr) => {
107
+ resolve({ error, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
108
+ })
109
+ })
110
+
111
+ async function linuxPrimaryOutput() {
112
+ const { stdout, error } = await run('xrandr', ['--query'])
113
+ if (error) return null
114
+ const lines = stdout.split('\n')
115
+ const line = lines.find((item) => /\bconnected\s+primary\b/u.test(item))
116
+ ?? lines.find((item) => /\bconnected\b/u.test(item))
117
+ if (!line) return null
118
+ return line.split(/\s+/u)[0] ?? null
119
+ }
120
+
121
+ async function linuxScreenSize() {
122
+ const { stdout } = await run('xrandr', ['--query'])
123
+ const line = stdout.split('\n').find((item) => /\bconnected\s+primary\b/u.test(item))
124
+ ?? stdout.split('\n').find((item) => /\bconnected\b/u.test(item))
125
+ const match = line?.match(/(\d+)x(\d+)\+/u)
126
+ if (!match) return { width: 0, height: 0 }
127
+ return { width: Number(match[1]), height: Number(match[2]) }
128
+ }
129
+
130
+ async function rotatePlatform(mode) {
131
+ const portrait = mode === 'portrait'
132
+ if (isWindows) {
133
+ const result = await workerCall({ cmd: 'rotate', mode: portrait ? 'portrait' : 'landscape' })
134
+ return {
135
+ ok: result.ok === true,
136
+ result: result.result ?? null,
137
+ screen: { width: Number(result.screenWidth) || 0, height: Number(result.screenHeight) || 0 },
138
+ detail: `windows result=${result.result ?? '?'}`,
139
+ }
140
+ }
141
+ if (process.platform === 'linux') {
142
+ const output = await linuxPrimaryOutput()
143
+ if (output === null) return { ok: false, detail: 'no connected output (xrandr)' }
144
+ const { error } = await run('xrandr', ['--output', output, '--rotate', portrait ? 'left' : 'normal'])
145
+ if (error) return { ok: false, detail: String(error.message ?? error).slice(0, 200) }
146
+ return { ok: true, result: 0, screen: await linuxScreenSize(), detail: `${output} -> ${portrait ? 'left' : 'normal'}` }
147
+ }
148
+ if (process.platform === 'darwin') {
149
+ const list = await run('displayplacer', ['list'])
150
+ if (list.error) return { ok: false, detail: 'displayplacer not installed' }
151
+ const idMatch = list.stdout.match(/Persistent screen id:\s*(\S+)/u)
152
+ if (!idMatch) return { ok: false, detail: 'screen id not found' }
153
+ const rotation = portrait ? 'rotation:90' : 'rotation:0'
154
+ const applied = await run('displayplacer', [`id:${idMatch[1]}`, rotation, 'scaling:on'])
155
+ if (applied.error) return { ok: false, detail: String(applied.error.message ?? applied.error).slice(0, 200) }
156
+ return { ok: true, result: 0, detail: `${idMatch[1]} -> ${rotation}` }
157
+ }
158
+ return { ok: false, detail: 'unsupported platform' }
159
+ }
160
+
161
+ // ---------------- 请求处理 ----------------
162
+
163
+ let queue = Promise.resolve()
164
+
165
+ async function handle(request) {
166
+ const cmd = String(request.cmd ?? '')
167
+ if (cmd === 'ping') return { ok: true, pong: true }
168
+ if (cmd === 'version') {
169
+ return { ok: true, version: '2', platform: process.platform, pid: process.pid, pipe: NAME }
170
+ }
171
+ if (cmd === 'shutdown') {
172
+ setTimeout(() => process.exit(0), 50)
173
+ return { ok: true, shutdown: true }
174
+ }
175
+ if (cmd === 'rotate') {
176
+ const mode = request.mode === 'landscape' ? 'landscape' : 'portrait'
177
+ return rotatePlatform(mode)
178
+ }
179
+ // 其余窗口操作:Windows 交给工作进程
180
+ if (!isWindows) return { ok: false, error: '窗口操作仅支持 Windows' }
181
+ const { id: _ignoredId, token: _ignoredToken, ...payload } = request
182
+ return workerCall(payload, 25_000)
183
+ }
184
+
185
+ const server = net.createServer((socket) => {
186
+ let buffer = ''
187
+ socket.setEncoding('utf8')
188
+ socket.on('data', (chunk) => {
189
+ buffer += chunk
190
+ while (true) {
191
+ const index = buffer.indexOf('\n')
192
+ if (index < 0) break
193
+ const line = buffer.slice(0, index).trim()
194
+ buffer = buffer.slice(index + 1)
195
+ if (line === '') continue
196
+ let request = null
197
+ try { request = JSON.parse(line) } catch {
198
+ socket.write(JSON.stringify({ ok: false, error: 'bad json' }) + '\n')
199
+ continue
200
+ }
201
+ if (String(request.token ?? '') !== TOKEN) {
202
+ socket.write(JSON.stringify({ id: request.id, ok: false, error: 'unauthorized' }) + '\n')
203
+ continue
204
+ }
205
+ const id = request.id
206
+ queue = queue.then(async () => {
207
+ let result
208
+ try {
209
+ result = await handle(request)
210
+ } catch (error) {
211
+ result = { ok: false, error: String(error?.message ?? error) }
212
+ }
213
+ try { socket.write(JSON.stringify({ id, ...result }) + '\n') } catch { /* 已断开 */ }
214
+ })
215
+ }
216
+ })
217
+ socket.on('error', () => { /* 忽略 */ })
218
+ })
219
+
220
+ function start() {
221
+ removeStaleSocket(SOCKET)
222
+ server.once('error', (error) => {
223
+ if (error.code === 'EADDRINUSE') {
224
+ log('socket busy, another daemon is running')
225
+ process.exit(3)
226
+ }
227
+ log('listen error: ' + String(error.message ?? error))
228
+ process.exit(1)
229
+ })
230
+ server.listen(SOCKET, () => {
231
+ log(`listen ${SOCKET} pid=${process.pid}`)
232
+ })
233
+ }
234
+
235
+ // 空闲退出:没有活动连接时计时
236
+ let idleTimer = null
237
+ let clients = 0
238
+
239
+ function armIdle() {
240
+ if (clients > 0) return
241
+ if (idleTimer !== null) clearTimeout(idleTimer)
242
+ idleTimer = setTimeout(() => {
243
+ log('idle exit')
244
+ try { worker?.kill() } catch { /* 忽略 */ }
245
+ try { server.close() } catch { /* 忽略 */ }
246
+ process.exit(0)
247
+ }, IDLE_SECONDS * 1000)
248
+ idleTimer.unref?.()
249
+ }
250
+
251
+ server.on('connection', (socket) => {
252
+ clients += 1
253
+ if (idleTimer !== null) {
254
+ clearTimeout(idleTimer)
255
+ idleTimer = null
256
+ }
257
+ socket.on('close', () => {
258
+ clients -= 1
259
+ armIdle()
260
+ })
261
+ })
262
+
263
+ process.on('exit', () => {
264
+ try { worker?.kill() } catch { /* 忽略 */ }
265
+ removeStaleSocket(SOCKET)
266
+ })
267
+
268
+ start()
@@ -18,6 +18,7 @@ import readline from 'node:readline'
18
18
  import { fileURLToPath } from 'node:url'
19
19
 
20
20
  import { loadOrCreateToken, socketName, socketPath } from './local-socket.mjs'
21
+ import { findNodeRuntime } from './node-runtime.mjs'
21
22
 
22
23
  const HERE = path.dirname(fileURLToPath(import.meta.url))
23
24
  const DAEMON = path.join(HERE, '..', 'bin', 'window-agent-daemon.mjs')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.5",
3
+ "version": "2.1.6",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -54,7 +54,9 @@
54
54
  "!lib/vendor/node_modules/ssh2/test/**",
55
55
  "!lib/vendor/node_modules/ssh2/examples/**",
56
56
  "SECURITY.md",
57
- "permissions.json"
57
+ "permissions.json",
58
+ "bin/window-agent-daemon.mjs",
59
+ "bin/inbox.mjs"
58
60
  ],
59
61
  "publishConfig": {
60
62
  "access": "public",