dsh-mobile-plugin 0.5.112 → 0.5.114

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.
@@ -1,4 +1,4 @@
1
- // 节点小宝设备端的安装与启动:下载官方二进制、按平台装成系统服务、确保它在跑。
1
+ // 节点小宝设备端的安装与启动:下载官方设备端 / 安装脚本、按平台装成系统服务、确保它在跑。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -6,12 +6,12 @@
6
6
  * 装成**系统服务**——它的设备身份写在系统目录里,只有以 root 跑才存得住,否则每次重启都当新
7
7
  * 设备(实测:普通用户跑,重启后 peerid 变空、线路全掉)。
8
8
  *
9
- * 所以这里绕不开一次管理员授权。插件能做的是把整件事自动化:自己下载、自己装、自己拉起,
10
- * 用户只在系统弹出的授权框里确认一次(Touch ID / 输密码)。这是操作系统对「装系统服务」的
11
- * 规矩,不是我们多要一步。
9
+ * 所以这里绕不开一次管理员授权。插件能做的是把整件事自动化:macOS 自己下载二进制、写服务定义;
10
+ * Windows 与 Linux 跑官方的一键安装脚本;用户只在系统弹出的授权框里确认一次(Touch ID / 密码、
11
+ * UAC、polkit)。这是操作系统对「装系统服务」的规矩,不是我们多要一步。
12
12
  *
13
- * 只做 macOS:它的 launchd 服务定义简单、我们也在这套上实测过。Linux 的 systemd 与 Windows
14
- * 的服务注册各自还有一套没验过的细节,先如实报「这一版没接」,不猜着写。
13
+ * 三个平台的本地管理口与绑定链接都由 probe.cjs 只读探测;面板的「装没装」以探测为准,不靠
14
+ * 各平台的文件标记。无图形授权的 Linux 服务器弹不出 polkit 框,会如实报错,不猜着装成功。
15
15
  */
16
16
 
17
17
  const { execFile } = require('node:child_process');
@@ -25,6 +25,8 @@ const BINARY = path.join(INSTALL_DIR, 'NodeBabyLinkService');
25
25
  const PLIST = '/Library/LaunchDaemons/com.iepose.NodeBabyLinkService.plist';
26
26
  const LOG_DIR = path.join(INSTALL_DIR, 'logs');
27
27
  const CDN = 'https://cdn.ionewu.com/upgrade/jdxb';
28
+ const WINDOWS_INSTALLER = 'https://iepose.com/install.ps1';
29
+ const LINUX_INSTALLER = 'https://iepose.com/install.sh';
28
30
  const DOWNLOAD_TIMEOUT_MS = 120_000;
29
31
  /** 授权框等人点:给足三分钟,但别无限挂着。 */
30
32
  const ELEVATE_TIMEOUT_MS = 180_000;
@@ -34,13 +36,20 @@ const START_WAIT_MS = 15_000;
34
36
  function platformKey(platform, arch) {
35
37
  const p = String(platform || process.platform);
36
38
  const a = String(arch || process.arch);
37
- if (p !== 'darwin') return '';
38
- if (a === 'arm64') return 'darwin-arm64';
39
- if (a === 'x64') return 'darwin-x64';
39
+ if (p === 'darwin') {
40
+ if (a === 'arm64') return 'darwin-arm64';
41
+ if (a === 'x64') return 'darwin-x64';
42
+ return '';
43
+ }
44
+ // 官方 Windows 精简版明确不支持 32 位;Linux 的安装脚本按架构自己下载。
45
+ if (p === 'win32') return a === 'x64' ? 'win32-x64' : '';
46
+ if (p === 'linux') return a === 'x64' || a === 'arm64' ? `linux-${a}` : '';
40
47
  return '';
41
48
  }
42
49
 
43
50
  function downloadUrl(key) {
51
+ if (key === 'win32-x64') return WINDOWS_INSTALLER;
52
+ if (key === 'linux-x64' || key === 'linux-arm64') return LINUX_INSTALLER;
44
53
  const arch = key === 'darwin-arm64' ? 'arm64' : 'amd64';
45
54
  return `${CDN}/NodeBabyLinkService.darwin.${arch}.${VERSION}`;
46
55
  }
@@ -56,6 +65,13 @@ function looksLikeMachO(buffer) {
56
65
  return MACHO_MAGICS.has(buffer.readUInt32BE(0));
57
66
  }
58
67
 
68
+ /** 官方安装脚本是纯文本;被强制门户换成网页时当场认出来,别把 HTML 拿去提权执行。 */
69
+ function looksLikeScript(buffer) {
70
+ const text = Buffer.isBuffer(buffer) ? buffer.toString('utf8', 0, Math.min(buffer.length, 4096)) : String(buffer || '');
71
+ if (!text.trim()) return false;
72
+ return !/^\s*<(?:!doctype|html|script|title)\b/i.test(text);
73
+ }
74
+
59
75
  /** `launchctl list <label>`:加载了就有输出,没加载退出码非 0。 */
60
76
  function serviceLoaded(options = {}) {
61
77
  const run = typeof options.run === 'function' ? options.run : defaultRun;
@@ -66,13 +82,14 @@ function serviceLoaded(options = {}) {
66
82
 
67
83
  function defaultRun(file, args, opts = {}) {
68
84
  return new Promise((resolve) => {
69
- execFile(file, args, { timeout: opts.timeoutMs || 10_000, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
85
+ execFile(file, args, { timeout: opts.timeoutMs || 10_000, maxBuffer: 1 << 20, windowsHide: true }, (err, stdout, stderr) => {
70
86
  resolve({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout || ''), stderr: String(stderr || '') });
71
87
  });
72
88
  });
73
89
  }
74
90
 
75
- /** 本机装没装:服务定义与二进制都在,才算装过(只装了一半的照实报没装)。 */
91
+ /** macOS 的文件标记:服务定义与二进制都在,才算装过(只装了一半的照实报没装)。
92
+ * 其它平台的真实状态由本地管理口探测给出,不用这份文件标记。 */
76
93
  function installedSync() {
77
94
  try {
78
95
  return fs.existsSync(PLIST) && fs.existsSync(BINARY);
@@ -106,8 +123,8 @@ function plistBody() {
106
123
  }
107
124
 
108
125
  /**
109
- * 以管理员权限跑一段 shell。macOS 上就是系统自带的授权框(`do shell script ... with
110
- * administrator privileges`);它会弹出 Touch ID / 密码,用户点一下确认,脚本才以 root 跑。
126
+ * 以管理员权限跑一段 shell(macOS)。系统自带的授权框(do shell script ... with
127
+ * administrator privileges)会弹 Touch ID / 密码,用户点一下确认,脚本才以 root 跑。
111
128
  *
112
129
  * 脚本先写到用户自己的临时目录(0700):同一个人能改的只有这一份,跨不过权限边界;写死命令
113
130
  * 串反而要跟一堆引号打架,出错时也看不出哪一步断的。
@@ -126,6 +143,24 @@ function runElevated(script, options = {}) {
126
143
  });
127
144
  }
128
145
 
146
+ /** Windows:Start-Process -Verb RunAs 弹 UAC,等官方安装脚本跑完把退出码透传回来。 */
147
+ function runWindowsScript(file, options = {}) {
148
+ const run = typeof options.run === 'function' ? options.run : defaultRun;
149
+ const args = `-NoProfile -ExecutionPolicy Bypass -File '${String(file).replace(/'/g, "''")}'`;
150
+ const quotedArgs = `'${args.replace(/'/g, "''")}'`;
151
+ const script = `$p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${quotedArgs} -Verb RunAs -Wait -PassThru; exit $p.ExitCode`;
152
+ return run('powershell.exe', ['-NoProfile', '-Command', script], {
153
+ timeoutMs: options.timeoutMs || ELEVATE_TIMEOUT_MS,
154
+ windowsHide: true,
155
+ });
156
+ }
157
+
158
+ /** Linux:pkexec 弹 polkit 授权框,脚本路径作为独立参数传,不经 shell。 */
159
+ function runLinuxScript(file, options = {}) {
160
+ const run = typeof options.run === 'function' ? options.run : defaultRun;
161
+ return run('pkexec', ['bash', file], { timeoutMs: options.timeoutMs || ELEVATE_TIMEOUT_MS });
162
+ }
163
+
129
164
  /**
130
165
  * 装好并拉起来。
131
166
  *
@@ -134,70 +169,121 @@ function runElevated(script, options = {}) {
134
169
  */
135
170
  async function install(options = {}) {
136
171
  const key = options.platformKey || platformKey(options.platform, options.arch);
137
- if (!key) return { ok: false, installed: installedSync(), started: false, error: '这一版只接了 macOS 的自动安装' };
138
- if (installedSync() && await serviceLoaded(options)) {
139
- return { ok: true, installed: true, started: true, error: '' };
172
+ const isMac = key.startsWith('darwin');
173
+ if (!key) {
174
+ return {
175
+ ok: false, installed: installedSync(), started: false,
176
+ error: '这一版只接了 macOS、Windows x64 与 Linux x64/arm64 的自动安装',
177
+ };
140
178
  }
179
+
180
+ let alreadyInstalled = false;
181
+ if (isMac) {
182
+ if (installedSync() && await serviceLoaded(options)) {
183
+ return { ok: true, installed: true, started: true, error: '' };
184
+ }
185
+ } else {
186
+ // Windows / Linux 以本地管理口为准:装过就不再跑官方脚本(它会进入卸载 / 升级菜单)。
187
+ try {
188
+ const probeStatus = typeof options.probeStatus === 'function'
189
+ ? options.probeStatus
190
+ : () => require('./probe.cjs').readStatus(options);
191
+ const snapshot = await probeStatus();
192
+ alreadyInstalled = Boolean(snapshot && snapshot.installed);
193
+ if (alreadyInstalled) return { ok: true, installed: true, started: true, error: '' };
194
+ } catch {
195
+ // 探测失败当作没装,继续走安装;装完还要再探一次才算成功。
196
+ }
197
+ }
198
+
141
199
  const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch;
142
- if (typeof fetchImpl !== 'function') return { ok: false, installed: installedSync(), started: false, error: '当前环境没有可用的 fetch' };
200
+ if (typeof fetchImpl !== 'function') {
201
+ return { ok: false, installed: alreadyInstalled, started: false, error: '当前环境没有可用的 fetch' };
202
+ }
143
203
 
144
204
  let temp = '';
145
205
  try {
146
206
  const response = await fetchImpl(downloadUrl(key), { redirect: 'follow' });
147
207
  if (!response || response.ok !== true) {
148
- return { ok: false, installed: installedSync(), started: false, error: `下载设备端失败(HTTP ${response && response.status ? response.status : '?'})` };
208
+ return {
209
+ ok: false, installed: alreadyInstalled, started: false,
210
+ error: `下载设备端失败(HTTP ${response && response.status ? response.status : '?'})`,
211
+ };
149
212
  }
150
213
  const buffer = Buffer.from(await response.arrayBuffer());
151
- if (!looksLikeMachO(buffer)) {
152
- return { ok: false, installed: installedSync(), started: false, error: '下载到的不是可执行文件,可能被网络拦截了' };
214
+ if (!(isMac ? looksLikeMachO(buffer) : looksLikeScript(buffer))) {
215
+ return {
216
+ ok: false, installed: alreadyInstalled, started: false,
217
+ error: isMac ? '下载到的不是可执行文件,可能被网络拦截了' : '下载到的不是安装脚本,可能被网络拦截了',
218
+ };
153
219
  }
154
- temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-jdxb-bin-')), 'NodeBabyLinkService');
220
+ const name = isMac ? 'NodeBabyLinkService' : (key.startsWith('win32') ? 'install.ps1' : 'install.sh');
221
+ temp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-jdxb-')), name);
155
222
  fs.writeFileSync(temp, buffer, { mode: 0o700 });
156
223
  } catch (error) {
157
- return { ok: false, installed: installedSync(), started: false, error: `下载设备端失败:${error && error.message ? error.message : String(error)}` };
224
+ return {
225
+ ok: false, installed: alreadyInstalled, started: false,
226
+ error: `下载设备端失败:${error && error.message ? error.message : String(error)}`,
227
+ };
158
228
  }
159
229
 
160
- const script = [
161
- 'set -e',
162
- `mkdir -p '${INSTALL_DIR}' '${LOG_DIR}'`,
163
- `cp '${temp}' '${BINARY}'`,
164
- `chmod 755 '${BINARY}'`,
165
- `cat > '${PLIST}' <<'PLIST_EOF'`,
166
- plistBody(),
167
- 'PLIST_EOF',
168
- `chmod 644 '${PLIST}'`,
169
- `launchctl unload '${PLIST}' 2>/dev/null || true`,
170
- `launchctl load -w '${PLIST}'`,
171
- ].join('\n');
172
-
173
- const elevated = await runElevated(script, options);
230
+ let elevated;
231
+ try {
232
+ if (isMac) {
233
+ const script = [
234
+ 'set -e',
235
+ `mkdir -p '${INSTALL_DIR}' '${LOG_DIR}'`,
236
+ `cp '${temp}' '${BINARY}'`,
237
+ `chmod 755 '${BINARY}'`,
238
+ `cat > '${PLIST}' <<'PLIST_EOF'`,
239
+ plistBody(),
240
+ 'PLIST_EOF',
241
+ `chmod 644 '${PLIST}'`,
242
+ `launchctl unload '${PLIST}' 2>/dev/null || true`,
243
+ `launchctl load -w '${PLIST}'`,
244
+ ].join('\n');
245
+ elevated = await runElevated(script, options);
246
+ } else if (key.startsWith('win32')) {
247
+ elevated = await runWindowsScript(temp, options);
248
+ } else {
249
+ elevated = await runLinuxScript(temp, options);
250
+ }
251
+ } catch (error) {
252
+ elevated = { code: 1, stdout: '', stderr: String(error && error.message ? error.message : error) };
253
+ }
174
254
  try { fs.rmSync(path.dirname(temp), { recursive: true, force: true }); } catch {}
255
+
175
256
  if (elevated.code !== 0) {
176
257
  const detail = String(elevated.stderr || '').trim().split('\n').filter(Boolean).slice(-1)[0] || '';
177
- // 用户点了取消时 osascript 会回 -128;这时别报「安装失败」,说清是他取消了。
178
- const cancelled = /-128|User canceled/i.test(`${elevated.stderr || ''}${elevated.stdout || ''}`);
258
+ // 取消 / 拒绝授权各平台措辞不同:osascript 回 -128,UAC 是 "canceled by the user",
259
+ // polkit 是 "Not authorized" / "dismissed"。统一说清是没通过授权,不是安装本身坏了。
260
+ const cancelled = /-128|user cancel|canceled by the user|not authorized|dismissed/i.test(`${elevated.stderr || ''}${elevated.stdout || ''}`);
179
261
  return {
180
262
  ok: false,
181
- installed: installedSync(),
263
+ installed: alreadyInstalled || installedSync(),
182
264
  started: false,
183
265
  error: cancelled ? '授权被取消,设备端没有安装' : `安装没成功${detail ? `:${detail}` : ''}`,
184
266
  };
185
267
  }
186
268
 
187
- // 脚本以 root 跑完了就当装上了:文件在不在不该由这个进程猜二遍(它也无权读 root 区)。
188
- // 真要用得起来看的是下面这条端口应答。
269
+ // 脚本以管理员权限跑完了就当装上了:真要用得起来看的是下面这条管理口应答。
189
270
  const started = await waitForPort(options);
190
271
  return { ok: started, installed: true, started, error: started ? '' : '设备端装好了,但本地管理口没起来,请查看系统服务状态' };
191
272
  }
192
273
 
193
- /** 装完等管理口应答:`launchctl load` 返回不代表进程已经监听,别装完立刻报没起来。 */
274
+ /** 装完等管理口应答:`launchctl load` / 安装脚本返回不代表进程已经监听。 */
194
275
  async function waitForPort(options = {}) {
195
- const probe = typeof options.probePort === 'function' ? options.probePort : require('./probe.cjs').probePort;
196
- const port = Number(options.port) > 0 ? Number(options.port) : 2080;
276
+ const probeModule = require('./probe.cjs');
277
+ const probe = typeof options.probePort === 'function' ? options.probePort : probeModule.probePort;
278
+ const platform = String(options.platform || process.platform);
279
+ const endpoints = Array.isArray(options.endpoints) ? options.endpoints : probeModule.endpointsFor(platform);
280
+ const candidates = endpoints.length ? endpoints : [{ host: '127.0.0.1', port: Number(options.port) > 0 ? Number(options.port) : 2080 }];
197
281
  const deadline = Date.now() + (Number(options.waitMs) > 0 ? Number(options.waitMs) : START_WAIT_MS);
198
282
  while (Date.now() < deadline) {
199
- const result = await probe(port, { timeoutMs: 1500 });
200
- if (result && result.ok) return true;
283
+ for (const { host, port } of candidates) {
284
+ const result = await probe(port, { host, timeoutMs: 1500 });
285
+ if (result && result.ok) return true;
286
+ }
201
287
  if (typeof options.sleep === 'function') await options.sleep(500);
202
288
  else await new Promise((resolve) => setTimeout(resolve, 500));
203
289
  }
@@ -211,8 +297,13 @@ module.exports = {
211
297
  PLIST,
212
298
  platformKey,
213
299
  downloadUrl,
300
+ looksLikeMachO,
301
+ looksLikeScript,
214
302
  installedSync,
215
303
  serviceLoaded,
304
+ runElevated,
305
+ runWindowsScript,
306
+ runLinuxScript,
216
307
  install,
217
308
  waitForPort,
218
- };
309
+ };
@@ -1,3 +1,4 @@
1
+ // 整包按平台选打包命令:Windows 没有系统 zip,改用自带 tar(见 pack-directory)。
1
2
  // 目录返回真实来源与声明元数据;未知年龄与未公开链接保持空值。
2
3
  'use strict';
3
4
 
@@ -27,6 +28,7 @@ const { sendJson } = require('../shared/http-util');
27
28
  const thirdParty = require('./third-party-extensions');
28
29
  const { metadataOf } = require('./extension-metadata.cjs');
29
30
  const registry = require('../../extension-registry/index.json');
31
+ const { packDirectory } = require('./pack-directory');
30
32
 
31
33
  /** 只有登记了实际扩展 slug 的条目才有官网详情;私装包不凭空获得公开记录。 */
32
34
  function registryMetadata(slug, packageName) {
@@ -354,17 +356,14 @@ async function handleCatalogArchive(_ctx, req, res, root = catalogRoot(), plugin
354
356
  /**
355
357
  * 把一个目录打成 zip 字节(与 `extension-dev.js` 的整包同一条命令)。
356
358
  *
357
- * 用系统的 `zip`:宿主不引第三方压缩库,而 `zip` 三个桌面系统都有。`-X` 去掉多余的扩展属性、
358
- * `-q` 安静、`-r` 递归;从目录里执行、打包 `.`,所以包内路径是相对路径,手机解出来的键与文件
359
- * 清单里的 `path` 对得上。
359
+ * 用系统命令打包,宿主不引第三方压缩库:mac/Linux 用 `zip`,Windows 没有系统 zip,
360
+ * 改用自带的 `tar -a`(按 `.zip` 扩展名选格式)。两条命令都从目录里执行、打包 `.`,
361
+ * 所以包内路径是相对路径,手机解出来的键与文件清单里的 `path` 对得上。
360
362
  */
361
363
  function zipDirectory(directory) {
362
364
  const outFile = path.join(require('node:os').tmpdir(), `dshm-catalog-${process.pid}-${Date.now()}.zip`);
363
365
  try {
364
- require('node:child_process').execFileSync('zip', ['-r', '-q', '-X', outFile, '.'], {
365
- cwd: directory,
366
- stdio: 'pipe',
367
- });
366
+ packDirectory(directory, outFile);
368
367
  return fs.readFileSync(outFile);
369
368
  } finally {
370
369
  try { fs.rmSync(outFile, { force: true }); } catch { /* 临时文件删不掉不影响结果 */ }
@@ -1,3 +1,4 @@
1
+ // 整包按平台选打包命令:Windows 没有系统 zip,改用自带 tar(见 pack-directory)。
1
2
  // 开发包也返回实际声明的用途、来源、年龄与能力,供手动安装前确认。
2
3
  'use strict';
3
4
 
@@ -23,6 +24,7 @@ const path = require('node:path');
23
24
  const { sendJson } = require('../shared/http-util');
24
25
  const { dshHome } = require('../shared/paths');
25
26
  const { metadataOf } = require('./extension-metadata.cjs');
27
+ const { packDirectory } = require('./pack-directory');
26
28
 
27
29
  /** 开发包根目录名。目录不存在时按需建出来 —— 作者要往里放东西。 */
28
30
  const DEV_ROOT_NAME = 'extension-dev';
@@ -267,17 +269,14 @@ async function handleDevArchive(_ctx, req, res) {
267
269
  /**
268
270
  * 把一个目录打成 zip 字节。
269
271
  *
270
- * 用系统的 `zip`(与产包脚本同一条命令):宿主不引第三方压缩库,而 `zip` 三个桌面系统都有。
271
- * `-X` 去掉多余的扩展属性、`-q` 安静、`-r` 递归;从目录里执行、打包 `.`,所以包内路径是
272
- * 相对路径,手机解出来的键与文件清单里的 `path` 对得上。
272
+ * 用系统命令打包,宿主不引第三方压缩库:mac/Linux 用 `zip`,Windows 没有系统 zip,
273
+ * 改用自带的 `tar -a`(按 `.zip` 扩展名选格式)。两条命令都从目录里执行、打包 `.`,
274
+ * 所以包内路径是相对路径,手机解出来的键与文件清单里的 `path` 对得上。
273
275
  */
274
276
  function zipDirectory(directory) {
275
277
  const outFile = path.join(require('node:os').tmpdir(), `dshm-dev-${process.pid}-${Date.now()}.zip`);
276
278
  try {
277
- require('node:child_process').execFileSync('zip', ['-r', '-q', '-X', outFile, '.'], {
278
- cwd: directory,
279
- stdio: 'pipe',
280
- });
279
+ packDirectory(directory, outFile);
281
280
  return fs.readFileSync(outFile);
282
281
  } finally {
283
282
  try { fs.rmSync(outFile, { force: true }); } catch { /* 临时文件删不掉不影响结果 */ }
@@ -0,0 +1,48 @@
1
+ // 用途:轮询平台现有反馈读取端点,等线程里出现第一条新官方回复;超时给改用 read 的提示。
2
+ 'use strict';
3
+
4
+ const { readFeedback } = require('./feedback-read.cjs');
5
+
6
+ /** 两秒一问、最多两分钟;不是长连接,到点就停,不无限等。 */
7
+ const DEFAULT_INTERVAL_MS = 2_000;
8
+ const DEFAULT_TIMEOUT_MS = 2 * 60_000;
9
+ const TIMEOUT_MESSAGE = '暂时没收到回复,请用 read 查看';
10
+
11
+ /**
12
+ * 轮询现有 /api/sdk/feedback(与 read 同一端点)等第一条官方回复。
13
+ * 只读公开反馈,不读凭据、不碰会话内容。
14
+ *
15
+ * 选项:afterMessageId(已见过的最大 id,默认 0)、intervalMs(默认 2 秒)、
16
+ * timeoutMs(默认 2 分钟)。平台没有公开事件流可用,所以每轮沿用 read 的线程视图,
17
+ * 取第一条 author 为 staff 且 id 大于水位的消息;提交后立刻到达的回复也在第一轮被看到。
18
+ * 到点仍无回复返回 { timedOut: true, message };HTTP 与网络错误照状态抛出。
19
+ */
20
+ async function watchFeedback(threadKey, options = {}) {
21
+ const key = typeof threadKey === 'string' ? threadKey.trim() : '';
22
+ if (!key) throw Object.assign(new Error('watch 需要 threadKey'), { status: 400 });
23
+ const opts = options && typeof options === 'object' ? options : {};
24
+ const afterMessageId = Number.isFinite(opts.afterMessageId) ? opts.afterMessageId : 0;
25
+ const timeoutMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS;
26
+ const intervalMs = Number.isFinite(opts.intervalMs) && opts.intervalMs > 0 ? opts.intervalMs : DEFAULT_INTERVAL_MS;
27
+ const deadline = Date.now() + timeoutMs;
28
+
29
+ for (;;) {
30
+ const thread = await readFeedback(key);
31
+ const messages = Array.isArray(thread?.messages) ? thread.messages : [];
32
+ const reply = messages.find((message) => message && message.author === 'staff'
33
+ && typeof message.id === 'number' && message.id > afterMessageId);
34
+ if (reply) {
35
+ return {
36
+ id: reply.id,
37
+ author: 'staff',
38
+ content: reply.content,
39
+ created_at: reply.created_at,
40
+ };
41
+ }
42
+ const remaining = deadline - Date.now();
43
+ if (remaining <= 0) return { timedOut: true, message: TIMEOUT_MESSAGE };
44
+ await new Promise(resolve => setTimeout(resolve, Math.min(intervalMs, remaining)));
45
+ }
46
+ }
47
+
48
+ module.exports = { DEFAULT_INTERVAL_MS, DEFAULT_TIMEOUT_MS, TIMEOUT_MESSAGE, watchFeedback };
@@ -1,4 +1,4 @@
1
- // 用途:插件反馈统一提交与读取口;工具和本机面板按线程查看官方回复、继续跟进。
1
+ // 用途:插件反馈统一提交、读取与轮询等回复口;工具和本机面板按线程查看官方回复、继续跟进。
2
2
  'use strict';
3
3
 
4
4
  /**
@@ -10,7 +10,8 @@
10
10
  * - **分发平台**:公开反馈接口(`/api/sdk/feedback`)。明确指定设备号时带上那台手机的
11
11
  * 身份;没指定时用这台电脑上的插件安装身份;没配手机时依然能交,受影响手机那几格留空。
12
12
  * 诊断文本作为 text/plain 附件一起发。线程 key 当场回显,可在本机面板或工具里读取
13
- * 官方回复,再带同一个 key 继续补充;线程历史由提交端保留,不写进 App 的反馈列表。
13
+ * 官方回复,再带同一个 key 继续补充;submit 后也可以用 watch 每两秒轮询现有反馈端点等官方回复,
14
+ * 最多两分钟,超时提示改用 read。线程历史由提交端保留,不写进 App 的反馈列表。
14
15
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
15
16
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
16
17
  *
@@ -24,6 +25,7 @@
24
25
  const { randomUUID } = require('node:crypto');
25
26
  const { version: COMPONENT_VERSION } = require('../../package.json');
26
27
  const { readFeedback } = require('./feedback-read.cjs');
28
+ const { watchFeedback } = require('./feedback-watch.cjs');
27
29
 
28
30
  const PLATFORM_ORIGIN = 'https://app.wnluo.com';
29
31
  const FEEDBACK_PATH = '/api/sdk/feedback';
@@ -66,7 +68,7 @@ function feedbackChannels() {
66
68
  {
67
69
  kind: 'distribution',
68
70
  name: 'APP 分发系统反馈',
69
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。提交后给出可复制的线程 key,可在本机面板或工具 read 动作查看官方回复,再用 submit 带 threadKey 继续补充;不会写进 App 的反馈列表。',
71
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。没配手机也能提交:指定设备号才带那台手机的身份,否则用这台电脑的插件安装身份;诊断文本作 text/plain 附件。提交后给出可复制的线程 key,可在本机面板或工具用 watch 定时轮询现有反馈端点等第一条官方回复(每两秒一次,最多两分钟,超时提示改用 read);需要看历史再 read,用 submit 带 threadKey 继续补充;不会写进 App 的反馈列表。',
70
72
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
71
73
  requiresLogin: false,
72
74
  },
@@ -240,15 +242,15 @@ function registerFeedbackTool(ctx, deps) {
240
242
  ctx.tools.register(defineTool({
241
243
  name: 'dsh_feedback',
242
244
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
243
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. Use `read` with the thread key to view the conversation and official replies, then `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
245
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it. You do NOT need to find the root cause: describe what you observed, what you already checked, and what is still uncertain. No paired phone is required either; without an explicitly chosen device the plugin submits under its local installation identity, with a text/plain diagnostics attachment and a thread key you can show to the user. After `submit`, call `watch` with the returned threadKey: it checks the existing feedback endpoint every two seconds for the first official reply, for at most two minutes, then stops with a hint to use `read`. It is polling, not a live stream. Use `read` with the thread key only when you need to review the conversation history, and `submit` with the same threadKey to follow up. The local feedback dialog can show these threads; they are not written into the in-app feedback list. '
244
246
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
245
247
  + 'Use `channels` to list both routes.',
246
248
  parameters: {
247
249
  action: {
248
250
  type: 'string',
249
251
  required: true,
250
- enum: ['channels', 'read', 'submit'],
251
- description: 'channels: list the feedback routes. read: view a thread and replies. submit: open a feedback thread or follow up using threadKey.',
252
+ enum: ['channels', 'read', 'submit', 'watch'],
253
+ description: 'channels: list the feedback routes. read: view a thread and replies. submit: open a feedback thread or follow up using threadKey. watch: after submit, poll the existing read endpoint for the first official staff reply on that threadKey (every two seconds, up to two minutes, then a hint to use read).',
252
254
  },
253
255
  content: {
254
256
  type: 'string',
@@ -256,7 +258,11 @@ function registerFeedbackTool(ctx, deps) {
256
258
  },
257
259
  threadKey: {
258
260
  type: 'string',
259
- description: 'Required for read. Optional for submit: append to this existing feedback thread instead of opening a new one.',
261
+ description: 'Required for read and watch. Optional for submit: append to this existing feedback thread instead of opening a new one.',
262
+ },
263
+ afterMessageId: {
264
+ type: 'number',
265
+ description: 'Optional for watch: only return a staff reply whose id is greater than this value. Defaults to 0; pass the highest id already seen so an old reply is not returned again.',
260
266
  },
261
267
  deviceId: {
262
268
  type: 'string',
@@ -287,6 +293,8 @@ function registerFeedbackTool(ctx, deps) {
287
293
  submitted: { type: 'boolean' },
288
294
  thread: { type: 'object', additionalProperties: true },
289
295
  threadKey: { type: 'string' },
296
+ reply: { type: 'object', additionalProperties: true },
297
+ timedOut: { type: 'boolean' },
290
298
  message: { type: 'string' },
291
299
  },
292
300
  },
@@ -304,6 +312,12 @@ function registerFeedbackTool(ctx, deps) {
304
312
  const submitted = await submitFeedback(deps, args.content, args.threadKey, args.deviceId);
305
313
  return { action: 'submit', submitted: true, threadKey: submitted.threadKey, message: submitted.message };
306
314
  }
315
+ case 'watch': {
316
+ const reply = await watchFeedback(args.threadKey, { afterMessageId: args.afterMessageId });
317
+ return reply && reply.timedOut
318
+ ? { action: 'watch', threadKey: args.threadKey, timedOut: true, message: reply.message }
319
+ : { action: 'watch', threadKey: args.threadKey, reply };
320
+ }
307
321
  default:
308
322
  throw new Error(`未知的 action:${args.action}`);
309
323
  }
@@ -321,6 +335,10 @@ function renderSummary(value) {
321
335
  return `反馈 ${value.threadKey}(${value.thread.status})\n${value.thread.messages.map(message => `[${message.author === 'staff' ? '官方' : '用户'} ${message.created_at}] ${message.content}`).join('\n')}`;
322
336
  case 'submit':
323
337
  return value.message || '已提交反馈。';
338
+ case 'watch':
339
+ return value.reply
340
+ ? `反馈 ${value.threadKey} 收到官方回复(${value.reply.created_at}):${value.reply.content}`
341
+ : `反馈 ${value.threadKey} ${value.message || '暂时没收到回复,请用 read 查看。'}`;
324
342
  default:
325
343
  return '完成。';
326
344
  }
@@ -356,4 +374,5 @@ module.exports = {
356
374
  registerFeedbackTool,
357
375
  submissionIdFor,
358
376
  submitFeedback,
377
+ watchFeedback,
359
378
  };
@@ -10,6 +10,10 @@
10
10
  *
11
11
  * 写入侧(POST /host-settings/mutate)与桌面端同一口径:只走宿主的 settings.mutate,用按路径
12
12
  * 寻址的 op(set / unset)+ expectedRevision 做乐观并发,绝不整段 replace。
13
+ *
14
+ * 权限档那一项(permission)只有 defaultPreset 是 volatile,describe 下发时会丢掉档位目录
15
+ * presets;手机那行「默认权限预设」要靠这份目录列候选,所以转发时从宿主的 permissionPresets
16
+ * 服务把目录补回去(见 augmentPermissionPresets)。
13
17
  */
14
18
 
15
19
  const { sendJson, readJsonBody } = require('../shared/http-util');
@@ -262,6 +266,57 @@ function normalizeProvider(item) {
262
266
  return { provider, displayName, active: item.active === true };
263
267
  }
264
268
 
269
+ /**
270
+ * 给 permission 命名空间补回档位目录。
271
+ *
272
+ * DSH 的 permission 项只有 defaultPreset 是 volatile 字段:settings.describe 下发时只投影
273
+ * volatile 字段,presets 这张「档名 → { sandbox, approval }」映射不在其中,手机端于是解析不出
274
+ * 候选档,「默认权限预设」那行整行不画。这里从同进程的 permissionPresets.catalog() 拿目录补回
275
+ * value.presets(形状与桌面端一致),App 的 mapPointerTarget / mapPointerChoices 就能认出来。
276
+ *
277
+ * 只取 defaultOptions(配置表里的档),不含 auto 这种 per-call 的临时档 —— volatile 的
278
+ * defaultPreset 只会指向配置表里的档。拿不到服务或目录为空就原样返回,不改动别的命名空间。
279
+ *
280
+ * @param {object} ctx 插件上下文(用 ctx.get 取同进程宿主服务)
281
+ * @param {Array} namespaces 已经 normalizeNamespace 过的命名空间数组(原地补 value)
282
+ */
283
+ function augmentPermissionPresets(ctx, namespaces) {
284
+ const permission = (Array.isArray(namespaces) ? namespaces : [])
285
+ .find((item) => item && item.ns === 'permission');
286
+ if (!permission) return;
287
+ const presets = typeof ctx?.get === 'function' ? ctx.get('permissionPresets') : null;
288
+ if (!presets || typeof presets.catalog !== 'function') return;
289
+
290
+ let catalog;
291
+ try {
292
+ catalog = presets.catalog();
293
+ } catch {
294
+ return;
295
+ }
296
+ const configured = catalog && Array.isArray(catalog.defaultOptions) ? catalog.defaultOptions : [];
297
+ if (configured.length === 0) return;
298
+
299
+ const table = {};
300
+ for (const option of configured) {
301
+ const value = option && typeof option.value === 'string' ? option.value : '';
302
+ if (!value) continue;
303
+ // 值只要有「对象」形状就能过 App 的 mapPointerTarget;保留真实 name/description 供日后读数。
304
+ table[value] = {
305
+ ...(typeof option.name === 'string' ? { name: option.name } : {}),
306
+ ...(typeof option.description === 'string' ? { description: option.description } : {}),
307
+ };
308
+ }
309
+ if (Object.keys(table).length === 0) return;
310
+
311
+ const base = permission.value && typeof permission.value === 'object' && !Array.isArray(permission.value)
312
+ ? permission.value
313
+ : {};
314
+ permission.value = {
315
+ ...base,
316
+ presets: { ...(base.presets && typeof base.presets === 'object' ? base.presets : {}), ...table },
317
+ };
318
+ }
319
+
265
320
  /** GET /api/mobile/v1/host-settings —— 宿主设置命名空间(只读、已脱敏)。 */
266
321
  async function handleHostSettings(ctx, req, res) {
267
322
  // 宿主的 settings.describe 不接受取消信号(apiproxy 的 invoke 也只传 request),故只传信封。
@@ -277,6 +332,7 @@ async function handleHostSettings(ctx, req, res) {
277
332
  .map(normalizeNamespace)
278
333
  .filter(Boolean)
279
334
  .slice(0, HOST_SETTINGS_MAX_NAMESPACES);
335
+ augmentPermissionPresets(ctx, namespaces);
280
336
 
281
337
  let webProviders;
282
338
  try {
@@ -470,6 +526,7 @@ module.exports = {
470
526
  boundValue,
471
527
  credentialRefOf,
472
528
  normalizeNamespace,
529
+ augmentPermissionPresets,
473
530
  normalizeProvider,
474
531
  normalizeOps,
475
532
  };
@@ -0,0 +1,26 @@
1
+ // 给手机下发整包时按平台选打包命令:Windows 没有系统 zip,改用自带的 tar。
2
+ 'use strict';
3
+
4
+ const { execFileSync } = require('node:child_process');
5
+
6
+ /**
7
+ * 按平台给出把目录打成 zip 的命令。
8
+ *
9
+ * 宿主不引第三方压缩库:mac/Linux 用系统 zip,Windows 用系统自带的 bsdtar —— `tar -a`
10
+ * 按输出文件名推断格式,`.zip` 就是 zip。Windows 上直接调 zip 会 `spawnSync zip ENOENT`,
11
+ * 装第三方插件自带的扩展时整包那步就失败了。
12
+ *
13
+ * `platform` 单独收一个参数,是为了让守卫在 mac 上也能钉住 Windows 那条命令。
14
+ */
15
+ function packCommand(platform, outFile) {
16
+ if (platform === 'win32') return { command: 'tar', args: ['-a', '-cf', outFile, '.'] };
17
+ return { command: 'zip', args: ['-r', '-q', '-X', outFile, '.'] };
18
+ }
19
+
20
+ /** 从 directory 里打成 outFile 这份 zip;包内是相对路径,不带目录那一层。 */
21
+ function packDirectory(directory, outFile) {
22
+ const { command, args } = packCommand(process.platform, outFile);
23
+ execFileSync(command, args, { cwd: directory, stdio: 'pipe' });
24
+ }
25
+
26
+ module.exports = { packCommand, packDirectory };