@andy.ian/dsh-homing 2.2.2 → 2.3.0

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/lib/office.mjs CHANGED
@@ -8,6 +8,10 @@
8
8
  * - 只在本机跑一次转换,产物缓存到临时目录,同一文件只转一次。
9
9
  *
10
10
  * 找不到引擎时优雅降级:返回错误,页面提示"下载后用 WPS 打开"。
11
+ *
12
+ * 查找入口与创建转换器都支持注入(env / existsFn / execPath / resourcesPath /
13
+ * findKit / importModule / getKit):测试据此覆盖各种安装位置与失败分支,
14
+ * 不必真的装 LibreOffice,也不会启动任何外部进程。
11
15
  */
12
16
  import fs from 'node:fs'
13
17
  import os from 'node:os'
@@ -25,26 +29,33 @@ const exists = (file) => {
25
29
  try { return fs.statSync(file).isFile() } catch { return false }
26
30
  }
27
31
 
28
- /** 找 DSH 自带的 libreoffice-kit 入口;找不到返回 null */
29
- export function findOfficeKit() {
30
- const explicit = process.env.DSH_HOMING_OFFICE_KIT?.trim()
31
- if (explicit && exists(explicit)) return explicit
32
+ /**
33
+ * 找 DSH 自带的 libreoffice-kit 入口;找不到返回 null
34
+ * @param {{ env?: object, existsFn?: Function, execPath?: string, resourcesPath?: string }} [options]
35
+ */
36
+ export function findOfficeKit({
37
+ env = process.env,
38
+ existsFn = exists,
39
+ execPath = process.execPath,
40
+ resourcesPath = process.resourcesPath,
41
+ } = {}) {
42
+ const explicit = env.DSH_HOMING_OFFICE_KIT?.trim()
43
+ if (explicit && existsFn(explicit)) return explicit
32
44
 
33
- // Electron 主进程:process.resourcesPath 直接指向 resources/
34
45
  const candidates = []
35
- const resources = process.resourcesPath
36
- if (typeof resources === 'string' && resources !== '') {
37
- candidates.push(path.join(resources, 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
38
- candidates.push(path.join(resources, 'app', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
46
+ // Electron 主进程:process.resourcesPath 直接指向 resources/
47
+ if (typeof resourcesPath === 'string' && resourcesPath !== '') {
48
+ candidates.push(path.join(resourcesPath, 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
49
+ candidates.push(path.join(resourcesPath, 'app', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
39
50
  }
40
51
  // 常见安装位置(当前用户安装 / 全机安装)
41
- const local = process.env.LOCALAPPDATA
42
- const pf = process.env.ProgramFiles || 'C:\\Program Files'
52
+ const local = env.LOCALAPPDATA
53
+ const pf = env.ProgramFiles || 'C:\\Program Files'
43
54
  if (local) candidates.push(path.join(local, 'Programs', 'DeepSeek Harness', 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
44
55
  candidates.push(path.join(pf, 'DeepSeek Harness', 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'))
45
56
 
46
57
  // 兜底:从可执行文件位置向上找
47
- const exeDir = path.dirname(process.execPath)
58
+ const exeDir = path.dirname(execPath)
48
59
  candidates.push(
49
60
  path.join(exeDir, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'),
50
61
  path.join(exeDir, 'resources', 'app', 'node_modules', '@deepseek-ai', 'libreoffice-kit', 'lib', 'index.js'),
@@ -58,19 +69,23 @@ export function findOfficeKit() {
58
69
  cursor = path.dirname(cursor)
59
70
  }
60
71
 
61
- return candidates.find(exists) ?? null
72
+ return candidates.find(existsFn) ?? null
62
73
  }
63
74
 
64
75
  let converterPromise = null
65
76
  let converter = null
66
77
 
67
- async function getConverter() {
78
+ /**
79
+ * 取得(并缓存)转换器
80
+ * @param {{ findKit?: Function, importModule?: Function }} [options]
81
+ */
82
+ export async function getConverter({ findKit = findOfficeKit, importModule = (url) => import(url) } = {}) {
68
83
  if (converter !== null) return converter
69
84
  if (converterPromise === null) {
70
85
  converterPromise = (async () => {
71
- const entry = findOfficeKit()
86
+ const entry = findKit()
72
87
  if (entry === null) throw new Error('未找到 DSH 自带的 LibreOffice 引擎')
73
- const mod = await import(pathToFileURL(entry).href)
88
+ const mod = await importModule(pathToFileURL(entry).href)
74
89
  if (typeof mod.createConverter !== 'function') throw new Error('LibreOffice 引擎接口不可用')
75
90
  const created = await mod.createConverter({ timeoutMs: 180_000 })
76
91
  converter = created
@@ -99,23 +114,30 @@ export function cacheKey(absPath) {
99
114
  /**
100
115
  * 把 Office 文件转成 PDF(带缓存)。
101
116
  * 返回 { ok, path, bytes, cached, error }
117
+ * @param {string} inputPath
118
+ * @param {{ getKit?: Function }} [options]
102
119
  */
103
- export async function renderPdf(inputPath) {
120
+ export async function renderPdf(inputPath, { getKit = getConverter } = {}) {
104
121
  if (!exists(inputPath)) return { ok: false, error: '文件不存在' }
105
122
  const dir = cacheDir()
106
123
  const key = cacheKey(inputPath)
107
124
  const target = path.join(dir, `${key}.pdf`)
108
125
 
109
126
  try {
110
- if (exists(target)) return { ok: true, path: target, bytes: fs.statSync(target).size, cached: true }
111
- } catch { /* 缓存坏了就重转 */ }
127
+ const cachedStat = fs.statSync(target)
128
+ if (cachedStat.isFile()) return { ok: true, path: target, bytes: cachedStat.size, cached: true }
129
+ } catch { /* 缓存不存在或不可读:继续转一次 */ }
112
130
 
113
131
  try {
114
- const kit = await getConverter()
132
+ const kit = await getKit()
115
133
  fs.mkdirSync(dir, { recursive: true })
116
134
  const temp = path.join(dir, `${key}.${process.pid}.tmp.pdf`)
117
135
  await kit.render({ inputPath: path.resolve(inputPath), outputPath: temp })
118
136
  if (!exists(temp)) return { ok: false, error: '转换没有生成 PDF' }
137
+ // 缓存位可能被占成目录/残留文件(异常退出导致):先清掉再落盘。
138
+ // 这里不额外 try/catch —— 万一清不掉,让外层 catch 统一返回失败原因,
139
+ // 免得留下永远走不到的死分支。
140
+ fs.rmSync(target, { recursive: true, force: true })
119
141
  fs.renameSync(temp, target)
120
142
  return { ok: true, path: target, bytes: fs.statSync(target).size, cached: false }
121
143
  } catch (error) {
@@ -8,6 +8,10 @@
8
8
  * - darwin:displayplacer(需要用户安装)
9
9
  *
10
10
  * 统一返回 { ok, platform, detail }
11
+ *
12
+ * 所有平台相关依赖都可注入(platform / runFn / rotateWin / listWindowsFn /
13
+ * rotateScreenFn / markerPath):测试据此覆盖 linux / darwin / 未知平台分支,
14
+ * 不需要真的转屏,也不会在测试机上拉起窗口代理进程。
11
15
  */
12
16
  import { execFile } from 'node:child_process'
13
17
  import fs from 'node:fs'
@@ -18,21 +22,21 @@ import { promisify } from 'node:util'
18
22
  const run = promisify(execFile)
19
23
 
20
24
  // 记录"竖屏是不是我们切过去的",用于崩溃/断开后自动恢复横屏
21
- const MARKER = path.join(os.tmpdir(), 'dsh-homing-orientation.json')
25
+ const DEFAULT_MARKER = path.join(os.tmpdir(), 'dsh-homing-orientation.json')
22
26
 
23
- function writeMarker(mode) {
27
+ function writeMarker(mode, markerPath = DEFAULT_MARKER) {
24
28
  try {
25
29
  if (mode === 'portrait') {
26
- fs.writeFileSync(MARKER, JSON.stringify({ byUs: true, ts: Date.now() }))
30
+ fs.writeFileSync(markerPath, JSON.stringify({ byUs: true, ts: Date.now() }))
27
31
  } else {
28
- fs.rmSync(MARKER, { force: true })
32
+ fs.rmSync(markerPath, { force: true })
29
33
  }
30
34
  } catch { /* 忽略 */ }
31
35
  }
32
36
 
33
- function markerPresent() {
37
+ function markerPresent(markerPath = DEFAULT_MARKER) {
34
38
  try {
35
- return JSON.parse(fs.readFileSync(MARKER, 'utf8')).byUs === true
39
+ return JSON.parse(fs.readFileSync(markerPath, 'utf8')).byUs === true
36
40
  } catch {
37
41
  return false
38
42
  }
@@ -47,43 +51,53 @@ function assertMode(mode) {
47
51
  }
48
52
 
49
53
  /** Linux:找到主输出(connected 且带 primary,否则取第一个 connected) */
50
- async function linuxPrimaryOutput() {
51
- const { stdout } = await run('xrandr', ['--query'])
52
- const lines = stdout.split('\n')
54
+ async function linuxPrimaryOutput(runFn) {
55
+ const { stdout } = await runFn('xrandr', ['--query'])
56
+ const lines = String(stdout ?? '').split('\n')
53
57
  const primary = lines.find((line) => /\bconnected\s+primary\b/u.test(line))
54
58
  const connected = lines.find((line) => /\bconnected\b/u.test(line))
55
59
  const line = primary ?? connected
56
60
  if (!line) return null
57
- return line.split(/\s+/u)[0] ?? null
61
+ return line.split(/\s+/u)[0]
58
62
  }
59
63
 
60
- async function rotateLinux(mode) {
61
- const output = await linuxPrimaryOutput()
64
+ async function rotateLinux(mode, runFn) {
65
+ const output = await linuxPrimaryOutput(runFn)
62
66
  if (output === null) {
63
67
  return { ok: false, platform: 'linux', detail: 'no connected output (xrandr)' }
64
68
  }
65
69
  const rotate = mode === 'portrait' ? 'left' : 'normal'
66
- await run('xrandr', ['--output', output, '--rotate', rotate])
70
+ await runFn('xrandr', ['--output', output, '--rotate', rotate])
67
71
  return { ok: true, platform: 'linux', detail: `${output} -> ${rotate}` }
68
72
  }
69
73
 
70
- async function rotateMac(mode) {
74
+ async function rotateMac(mode, runFn) {
71
75
  // displayplacer 需要参数:screen id;先用 list 解析
72
- const { stdout } = await run('displayplacer', ['list'])
73
- const idMatch = stdout.match(/Persistent screen id:\s*(\S+)/u)
76
+ const { stdout } = await runFn('displayplacer', ['list'])
77
+ const idMatch = String(stdout ?? '').match(/Persistent screen id:\s*(\S+)/u)
74
78
  if (!idMatch) {
75
79
  return { ok: false, platform: 'darwin', detail: 'displayplacer: screen id not found' }
76
80
  }
77
81
  const rotation = mode === 'portrait' ? 'rotation:90' : 'rotation:0'
78
- await run('displayplacer', [`id:${idMatch[1]}`, rotation, 'res:1920x1080', 'scaling:on'])
82
+ await runFn('displayplacer', [`id:${idMatch[1]}`, rotation, 'res:1920x1080', 'scaling:on'])
79
83
  return { ok: true, platform: 'darwin', detail: `${idMatch[1]} -> ${rotation}` }
80
84
  }
81
85
 
82
- async function rotateWindows(mode) {
83
- // 转屏统一交给 Node 转屏守护进程(窗口代理守护进程)执行:
84
- // 守护进程内有独立的转屏工作进程,不会被窗口列表/截图等请求阻塞;
85
- // 它还会在长时间无活动或 DSH 退出后自动恢复横屏。
86
- const { rotateScreen } = await import('./window-remote.mjs')
86
+ /** 加载窗口代理客户端(单独抽出来便于测试,导入本身无副作用) */
87
+ export async function loadWindowRemote() {
88
+ return import('./window-remote.mjs')
89
+ }
90
+
91
+ /**
92
+ * Windows:转屏统一交给 Node 转屏守护进程(窗口代理守护进程)执行:
93
+ * 守护进程内有独立的转屏工作进程,不会被窗口列表/截图等请求阻塞;
94
+ * 它还会在长时间无活动或 DSH 退出后自动恢复横屏。
95
+ * @param {'portrait'|'landscape'} mode
96
+ * @param {{ rotateScreenFn?: Function, loadRemote?: Function }} [options]
97
+ */
98
+ export async function rotateWindows(mode, options = {}) {
99
+ const loadRemote = options.loadRemote ?? loadWindowRemote
100
+ const rotateScreen = options.rotateScreenFn ?? (await loadRemote()).rotateScreen
87
101
  const result = await rotateScreen(mode, 20_000)
88
102
  const screen = result.screen ?? {
89
103
  width: Number(result.screenWidth) || 0,
@@ -97,68 +111,89 @@ async function rotateWindows(mode) {
97
111
  }
98
112
  }
99
113
 
100
- /** 设置屏幕方向:portrait(竖屏)/ landscape(横屏) */
101
- export async function setOrientation(mode) {
114
+ /**
115
+ * 设置屏幕方向:portrait(竖屏)/ landscape(横屏)
116
+ * @param {'portrait'|'landscape'} mode
117
+ * @param {{ platform?: string, runFn?: Function, rotateWin?: Function, markerPath?: string }} [options]
118
+ */
119
+ export async function setOrientation(mode, options = {}) {
120
+ const { platform = process.platform, runFn = run, rotateWin = rotateWindows, markerPath } = options
102
121
  assertMode(mode)
103
122
  try {
104
123
  let result
105
- if (process.platform === 'win32') result = await rotateWindows(mode)
106
- else if (process.platform === 'linux') result = await rotateLinux(mode)
107
- else if (process.platform === 'darwin') result = await rotateMac(mode)
108
- else result = { ok: false, platform: process.platform, detail: 'unsupported platform' }
109
- if (result.ok === true) writeMarker(mode)
124
+ if (platform === 'win32') result = await rotateWin(mode)
125
+ else if (platform === 'linux') result = await rotateLinux(mode, runFn)
126
+ else if (platform === 'darwin') result = await rotateMac(mode, runFn)
127
+ else result = { ok: false, platform, detail: 'unsupported platform' }
128
+ if (result.ok === true) writeMarker(mode, markerPath)
110
129
  return result
111
130
  } catch (error) {
112
131
  return {
113
132
  ok: false,
114
- platform: process.platform,
133
+ platform,
115
134
  detail: String(error?.stderr ?? error?.message ?? error).slice(0, 200),
116
135
  }
117
136
  }
118
137
  }
119
138
 
120
- /** 当前是否竖屏:Windows 用屏幕宽高判断,其它平台用 xrandr 输出判断 */
121
- export async function isPortrait() {
122
- if (process.platform === 'win32') {
123
- const { listWindows, stopAgent } = await import('./window-remote.mjs')
124
- const info = await listWindows()
125
- if (typeof stopAgent === 'function') stopAgent()
139
+ /**
140
+ * 当前是否竖屏:Windows 用屏幕宽高判断,其它平台用 xrandr 输出判断
141
+ * @param {{ platform?: string, runFn?: Function, listWindowsFn?: Function, stopAgentFn?: Function }} [options]
142
+ */
143
+ export async function isPortrait(options = {}) {
144
+ const { platform = process.platform, runFn = run } = options
145
+ if (platform === 'win32') {
146
+ const loadRemote = options.loadRemote ?? loadWindowRemote
147
+ const remote = options.listWindowsFn
148
+ ? { listWindows: options.listWindowsFn, stopAgent: options.stopAgentFn ?? (() => {}) }
149
+ : await loadRemote()
150
+ const info = await remote.listWindows()
151
+ if (typeof remote.stopAgent === 'function') remote.stopAgent()
126
152
  const w = Number(info.screenWidth ?? 0)
127
153
  const h = Number(info.screenHeight ?? 0)
128
154
  if (w <= 0 || h <= 0) return null
129
155
  return h > w
130
156
  }
131
- if (process.platform === 'linux') {
132
- const { stdout } = await run('xrandr', ['--query'])
133
- const line = stdout.split('\n').find((item) => /\bconnected\s+primary\b/u.test(item))
134
- ?? stdout.split('\n').find((item) => /\bconnected\b/u.test(item))
157
+ if (platform === 'linux') {
158
+ const { stdout } = await runFn('xrandr', ['--query'])
159
+ const lines = String(stdout ?? '').split('\n')
160
+ const line = lines.find((item) => /\bconnected\s+primary\b/u.test(item))
161
+ ?? lines.find((item) => /\bconnected\b/u.test(item))
135
162
  if (!line) return null
136
163
  const match = line.match(/(\d+)x(\d+)\+/u)
137
164
  if (!match) return null
138
165
  return Number(match[2]) > Number(match[1])
139
166
  }
140
- if (process.platform === 'darwin') {
141
- const { stdout } = await run('displayplacer', ['list'])
142
- return /rotation:90/u.test(stdout)
167
+ if (platform === 'darwin') {
168
+ const { stdout } = await runFn('displayplacer', ['list'])
169
+ return /rotation:90/u.test(String(stdout ?? ''))
143
170
  }
144
171
  return null
145
172
  }
146
173
 
147
-
148
- /** 若上次是我们切的竖屏,启动/断开时恢复横屏(死锁/崩溃兜底) */
149
- export async function ensureLandscape() {
150
- if (!markerPresent()) return { ok: false, skipped: true, detail: 'no marker' }
151
- const portrait = await isPortrait()
174
+ /**
175
+ * 若上次是我们切的竖屏,启动/断开时恢复横屏(死锁/崩溃兜底)
176
+ * @param {object} [options] 透传给 setOrientation / isPortrait
177
+ */
178
+ export async function ensureLandscape(options = {}) {
179
+ const { markerPath } = options
180
+ if (!markerPresent(markerPath)) return { ok: false, skipped: true, detail: 'no marker' }
181
+ const portrait = await isPortrait(options)
152
182
  if (portrait !== true) {
153
- writeMarker('landscape')
183
+ writeMarker('landscape', markerPath)
154
184
  return { ok: true, skipped: true, detail: 'already landscape' }
155
185
  }
156
- const result = await setOrientation('landscape')
157
- if (result.ok === true) writeMarker('landscape')
186
+ const result = await setOrientation('landscape', options)
187
+ if (result.ok === true) writeMarker('landscape', markerPath)
158
188
  return result
159
189
  }
160
190
 
161
191
  /** 当前是否有"我们切了竖屏"的标记 */
162
- export function hasOrientationMarker() {
163
- return markerPresent()
192
+ export function hasOrientationMarker(markerPath = DEFAULT_MARKER) {
193
+ return markerPresent(markerPath)
194
+ }
195
+
196
+ /** 测试用:清掉标记文件,避免影响其它用例 */
197
+ export function clearOrientationMarker(markerPath = DEFAULT_MARKER) {
198
+ writeMarker('landscape', markerPath)
164
199
  }
package/lib/pty.mjs CHANGED
@@ -78,14 +78,7 @@ const waitFor = async (predicate, timeoutMs = 8000) => {
78
78
  return false
79
79
  }
80
80
 
81
- export const terminalDir = (dshHome = resolveDshHome()) => {
82
- const dir = path.join(dshHome, 'integrations', 'dsh-homing', 'terminal')
83
- // 老版本把 sshd 的密钥/配置放在 dsh-homing/terminal 下;新目录没有就沿用旧的,
84
- // 避免改名后终端连不上(密钥变了 sshd 得重建,会话会断一下)。
85
- const legacy = path.join(dshHome, 'integrations', 'dsh-homing', 'terminal')
86
- if (!fs.existsSync(dir) && fs.existsSync(legacy)) return legacy
87
- return dir
88
- }
81
+ export const terminalDir = (dshHome = resolveDshHome()) => path.join(dshHome, 'integrations', 'dsh-homing', 'terminal')
89
82
 
90
83
  export const ensureKeyPair = (dir) => {
91
84
  const key = path.join(dir, 'id_ed25519')
@@ -294,8 +287,8 @@ export class PtyTerminal {
294
287
  /** 切换工作目录(会话是常驻的,所以只发一条 cd) */
295
288
  changeDir(winPath) {
296
289
  if (typeof winPath !== 'string' || winPath.trim() === '') return false
290
+ // 这里 trim 后必非空,cdCommand 只会返回命令字符串(空串才返回 null),无需再判空。
297
291
  const command = cdCommand(this.shellId, winPath, this.shell?.cdStyle ?? '')
298
- if (command === null) return false
299
292
  this.cwd = winPath.trim()
300
293
  return this.write(command)
301
294
  }
package/lib/recover.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 一键自救:注销 Service Worker、清 Cache Storage、清 caches,再回首页。
3
+ *
4
+ * 适用场景(2026-11-15 手机首页一直转圈):
5
+ * 浏览器/系统残留了旧的 Service Worker,它会把旧的页面壳从缓存里回放出来,
6
+ * 而旧壳引用的 `/assets/index-旧哈希.js` 早已不存在 → 页面永远停在加载状态。
7
+ * 这种情况下"清站点数据"有时清不掉 SW 注册,需要主动 unregister。
8
+ */
9
+ (() => {
10
+ const out = document.getElementById('out')
11
+ const lines = []
12
+ const log = (text) => {
13
+ lines.push(text)
14
+ if (out) out.textContent = lines.join('\n')
15
+ }
16
+
17
+ async function run() {
18
+ log('UA: ' + navigator.userAgent)
19
+
20
+ if (navigator.serviceWorker && navigator.serviceWorker.getRegistrations) {
21
+ try {
22
+ const registrations = await navigator.serviceWorker.getRegistrations()
23
+ log('发现 Service Worker: ' + registrations.length + ' 个')
24
+ for (const registration of registrations) {
25
+ const scope = registration.scope
26
+ const ok = await registration.unregister()
27
+ log(' 注销 ' + scope + ' → ' + (ok ? '成功' : '失败'))
28
+ }
29
+ } catch (error) {
30
+ log('注销 Service Worker 出错:' + String(error && error.message ? error.message : error))
31
+ }
32
+ } else {
33
+ log('这个浏览器不支持 Service Worker 注册查询')
34
+ }
35
+
36
+ if (typeof caches !== 'undefined' && caches.keys) {
37
+ try {
38
+ const names = await caches.keys()
39
+ log('Cache Storage: ' + (names.length ? names.join(', ') : '空'))
40
+ for (const name of names) {
41
+ const ok = await caches.delete(name)
42
+ log(' 删除缓存 ' + name + ' → ' + (ok ? '成功' : '失败'))
43
+ }
44
+ } catch (error) {
45
+ log('清 Cache Storage 出错:' + String(error && error.message ? error.message : error))
46
+ }
47
+ }
48
+
49
+ try {
50
+ if (window.localStorage) {
51
+ const keys = Object.keys(localStorage)
52
+ log('localStorage 键: ' + (keys.length ? keys.join(', ') : '空'))
53
+ for (const key of keys) {
54
+ if (key.startsWith('dsh')) localStorage.removeItem(key)
55
+ }
56
+ }
57
+ } catch (error) {
58
+ log('清 localStorage 出错:' + String(error && error.message ? error.message : error))
59
+ }
60
+
61
+ log('\n清理完成。现在打开 https://' + location.host + '/ (或点下面的链接)。')
62
+ log('如果首页要求登录,正常登录一次即可。')
63
+ }
64
+
65
+ run().catch((error) => log('自救脚本出错:' + String(error && error.message ? error.message : error)))
66
+ })()
package/lib/secret.mjs CHANGED
@@ -3,13 +3,15 @@
3
3
  *
4
4
  * 目的:settings.json 里不再出现明文 VNC 密码。
5
5
  * 通过 PowerShell 调用 ProtectedData;明文只经环境变量传递,不出现在命令行参数里。
6
+ *
7
+ * 两个函数都接受可注入的 `platform` / `exec`(默认取真实值):
8
+ * 这样测试能覆盖「非 Windows 直接返回 null」和「PowerShell 抛错」等分支,
9
+ * 不必在 CI 上真的调用 DPAPI,也不必依赖运行平台。
6
10
  */
7
11
  import { execFile } from 'node:child_process'
8
12
  import { promisify } from 'node:util'
9
13
 
10
- const run = promisify(execFile)
11
-
12
- const PS = process.platform === 'win32' ? 'powershell.exe' : null
14
+ const defaultRun = promisify(execFile)
13
15
 
14
16
  const PROTECT_SCRIPT = [
15
17
  'Add-Type -AssemblyName System.Security;',
@@ -23,10 +25,19 @@ const UNPROTECT_SCRIPT = [
23
25
  '[Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($b,$null,\'CurrentUser\'))',
24
26
  ].join(' ')
25
27
 
26
- /** 加密为 DPAPI Base64 字符串;非 Windows 返回 null */
27
- export async function protectSecret(plain) {
28
+ function powershellFor(platform) {
29
+ return platform === 'win32' ? 'powershell.exe' : null
30
+ }
31
+
32
+ /**
33
+ * 加密为 DPAPI Base64 字符串;非 Windows 或入参无效时返回 null。
34
+ * @param {string} plain
35
+ * @param {{ platform?: string, exec?: Function }} [options]
36
+ */
37
+ export async function protectSecret(plain, { platform = process.platform, exec = defaultRun } = {}) {
38
+ const PS = powershellFor(platform)
28
39
  if (PS === null || typeof plain !== 'string' || plain === '') return null
29
- const { stdout } = await run(PS, ['-NoProfile', '-NonInteractive', '-Command', PROTECT_SCRIPT], {
40
+ const { stdout } = await exec(PS, ['-NoProfile', '-NonInteractive', '-Command', PROTECT_SCRIPT], {
30
41
  env: { ...process.env, DSH_SECRET: plain },
31
42
  windowsHide: true,
32
43
  timeout: 15_000,
@@ -34,10 +45,15 @@ export async function protectSecret(plain) {
34
45
  return stdout.trim()
35
46
  }
36
47
 
37
- /** 解密 DPAPI Base64 字符串;失败返回 null */
38
- export async function unprotectSecret(encrypted) {
48
+ /**
49
+ * 解密 DPAPI Base64 字符串;非 Windows 或入参无效时返回 null。
50
+ * @param {string} encrypted
51
+ * @param {{ platform?: string, exec?: Function }} [options]
52
+ */
53
+ export async function unprotectSecret(encrypted, { platform = process.platform, exec = defaultRun } = {}) {
54
+ const PS = powershellFor(platform)
39
55
  if (PS === null || typeof encrypted !== 'string' || encrypted === '') return null
40
- const { stdout } = await run(PS, ['-NoProfile', '-NonInteractive', '-Command', UNPROTECT_SCRIPT], {
56
+ const { stdout } = await exec(PS, ['-NoProfile', '-NonInteractive', '-Command', UNPROTECT_SCRIPT], {
41
57
  env: { ...process.env, DSH_SECRET: encrypted },
42
58
  windowsHide: true,
43
59
  timeout: 15_000,
package/lib/shells.mjs CHANGED
@@ -73,14 +73,14 @@ const quote = (value) => (isWindows ? `"${value.replaceAll('"', '\\"')}"` : `'${
73
73
 
74
74
  /** POSIX 路径风格(bash 系列在 Windows 上需要 /d/...) */
75
75
  const toPosixBashPath = (winPath) => {
76
+ // 调用点已用 /^[A-Za-z]:[\\/]/ 判断过是盘符路径,这里必定能匹配,不需要 null 兜底。
76
77
  const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
77
- if (match === null) return winPath.replaceAll('\\', '/')
78
78
  return '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
79
79
  }
80
80
 
81
81
  const toWslPath = (winPath) => {
82
+ // 同上:只被 cdCommand 在盘符路径分支里调用,match 不可能为 null。
82
83
  const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
83
- if (match === null) return winPath.replaceAll('\\', '/')
84
84
  return '/mnt/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
85
85
  }
86
86
 
@@ -90,6 +90,8 @@ function buildDesResponse(password, challenge) {
90
90
  return Buffer.from(des.encrypt([...challenge]))
91
91
  }
92
92
 
93
+ export { ByteQueue }
94
+
93
95
  /**
94
96
  * 接管一条已升级的 WebSocket,完成"服务端认证 + 浏览器无认证"的桥接。
95
97
  * @param {object} options
@@ -98,11 +100,12 @@ function buildDesResponse(password, challenge) {
98
100
  * @param {number} options.port
99
101
  * @param {() => Promise<string>} options.getPassword
100
102
  * @param {(error: Error) => void} [options.onError]
103
+ * @param {Function} [options.connect] 建立 TCP 连接(测试可注入假 socket)
101
104
  */
102
- export function startVncAuthProxy({ ws, host, port, getPassword, onError }) {
105
+ export function startVncAuthProxy({ ws, host, port, getPassword, onError, connect = net.connect }) {
103
106
  const client = new ByteQueue('client')
104
107
  const upstream = new ByteQueue('upstream')
105
- const tcp = net.connect({ host, port })
108
+ const tcp = connect({ host, port })
106
109
  let closed = false
107
110
 
108
111
  const finish = (error) => {
@@ -76,11 +76,11 @@ export function charToKey(char) {
76
76
  return null
77
77
  }
78
78
 
79
+ // 唯一调用点是 charToKey 的 Shift 符号分支,入参只可能是 SHIFTED_SYMBOLS 的值:
80
+ // 普通符号(都在 SYMBOL_CODES 里)或数字,不存在其它可能,故无需字母/未知兜底。
79
81
  function symbolCode(char) {
80
82
  if (SYMBOL_CODES[char]) return SYMBOL_CODES[char]
81
- if (/^[0-9]$/u.test(char)) return digitCode(char)
82
- if (/^[a-z]$/u.test(char)) return letterCode(char)
83
- return 'Unidentified'
83
+ return digitCode(char)
84
84
  }
85
85
 
86
86
  /** inputType → 特殊键 */
package/lib/vnc-probe.mjs CHANGED
@@ -25,24 +25,22 @@ export function probeVnc({ host = '127.0.0.1', port = 5900, timeoutMs = 600 } =
25
25
  if (cached && Date.now() - cached.at < CACHE_MS) return Promise.resolve(cached.ok)
26
26
 
27
27
  return new Promise((resolve) => {
28
- let settled = false
29
- let timer = null
30
28
  const socket = net.connect({ host, port })
31
29
 
30
+ // 只有三种结局:连上、出错、超时。每种都先销毁套接字并清定时器,
31
+ // 所以任意时刻只会结算一次,不需要额外的"已结算"标记。
32
32
  const finish = (ok) => {
33
- if (settled) return
34
- settled = true
35
- if (timer !== null) clearTimeout(timer)
36
- try { socket.destroy() } catch { /* 忽略 */ }
33
+ clearTimeout(timer)
34
+ // net.Socket#destroy 对已销毁的套接字是空操作(Node 文档保证),无需 try/catch
35
+ socket.destroy()
37
36
  cache.set(key, { ok, at: Date.now() })
38
37
  resolve(ok)
39
38
  }
40
39
 
41
- timer = setTimeout(() => finish(false), timeoutMs)
42
- timer.unref?.()
40
+ // 只有"连不上"才需要超时;连上即返回,所以不需要 socket.setTimeout
41
+ const timer = setTimeout(() => finish(false), timeoutMs)
42
+ timer.unref()
43
43
  socket.once('connect', () => finish(true))
44
44
  socket.once('error', () => finish(false))
45
- socket.once('timeout', () => finish(false))
46
- socket.setTimeout?.(timeoutMs)
47
45
  })
48
46
  }