dsh-mobile-plugin 0.5.60 → 0.5.62

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.
@@ -22,8 +22,11 @@
22
22
  */
23
23
 
24
24
  const http = require('node:http');
25
+ const fs = require('node:fs');
26
+ const path = require('node:path');
25
27
 
26
28
  const { sendJson, readJsonBody } = require('../shared/http-util');
29
+ const { dshHome } = require('../shared/paths');
27
30
  const { hasPermission } = require('./permissions.js');
28
31
  const { hostPortOf, launchTokenOf } = require('./host-web.js');
29
32
  const { discoverDataServices } = require('./third-party-extensions.js');
@@ -37,6 +40,41 @@ const REQUEST_TIMEOUT_MS = 20000;
37
40
  /** 只放行这几种方法:读、写、删各一个,别的一律当非法。 */
38
41
  const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']);
39
42
 
43
+ /**
44
+ * 取数通道的逐条现场记录:`~/.dsh/mobile-extension-data.log`(一行一条 JSON)。
45
+ *
46
+ * **为什么落文件而不是打标准输出**:桌面 App 起的宿主没有终端,标准输出看不到(作者手册
47
+ * 9.3 那条)。而这一条链在手机上断掉时,屏幕只会说一句「取数失败」——它可能断在 App 根本没
48
+ * 发过来、服务没登记、路径不在 `allow`、插件路由没响应、目标服务自己报错中的任何一格,从
49
+ * 手机上永远分不出来。所以每一发都记一行,**失败也记**,并且失败那一行带着分档的 `code`。
50
+ *
51
+ * 三个刻意的口径:
52
+ * 1. **不记请求体与响应体**:里面可能有凭据和内容,调试要的是「断在哪一格」,不是内容本身。
53
+ * 2. **写完就同步落盘、失败一律吞掉**:这条日志绝不能把一次取数搞挂。
54
+ * 3. **有界**:超过 2 MiB 滚到 `.1` 重来。它是现场记录,不是审计账。
55
+ */
56
+ const LOG_LIMIT_BYTES = 2 * 1024 * 1024;
57
+
58
+ function logFile() {
59
+ return path.join(dshHome(), 'mobile-extension-data.log');
60
+ }
61
+
62
+ function logLine(entry) {
63
+ try {
64
+ const file = logFile();
65
+ try {
66
+ const stat = fs.statSync(file);
67
+ if (stat.size > LOG_LIMIT_BYTES) fs.renameSync(file, `${file}.1`);
68
+ } catch {
69
+ /* 还没这个文件:第一次写 */
70
+ }
71
+ fs.appendFileSync(file, `${JSON.stringify(entry)}\n`);
72
+ } catch {
73
+ /* 记不下来不该影响这一次取数 */
74
+ }
75
+ }
76
+
77
+
40
78
  /** 只要这几项响应头:页面解析正文够用了,别把一整套头也搬来搬去。 */
41
79
  function pickHeaders(headers) {
42
80
  const out = {};
@@ -208,34 +246,65 @@ function browserCookie(port, token) {
208
246
  * 让扩展页像对待一个普通 Response 一样对待它(4xx / 5xx 也照原样,页面自己判断)。
209
247
  */
210
248
  async function handleExtensionData(ctx, req, res) {
249
+ const startedAt = Date.now();
250
+ /** 这一次的现场:拒绝时也要能定位到「哪个服务、哪条路径、哪台设备」。 */
251
+ const trace = {
252
+ service: null,
253
+ path: null,
254
+ method: null,
255
+ device: (req && req.__dshRecord && req.__dshRecord.deviceId) || null,
256
+ };
257
+ /**
258
+ * 所有拒绝只走这一个口子:写一行日志、再回那个形状固定的失败包。
259
+ *
260
+ * 分档的 `code` 就是定位用的那一格 —— `service-unknown` 是插件没登记服务、`path-not-allowed`
261
+ * 是 `allow` 没盖住、`service-unavailable` 是目标端口拿不到,`upstream-error` 才是目标服务
262
+ * 自己回的 4xx/5xx(那时它已经把请求收到了)。
263
+ */
264
+ const fail = (status, code, message, upstream) => {
265
+ logLine({
266
+ at: new Date().toISOString(),
267
+ ...trace,
268
+ status,
269
+ code,
270
+ upstream: upstream === undefined ? null : upstream,
271
+ ms: Date.now() - startedAt,
272
+ });
273
+ return failure(res, status, code, message);
274
+ };
275
+
211
276
  const body = await readJsonBody(req, MAX_REQUEST_BYTES);
212
277
  if (!body || typeof body.service !== 'string' || typeof body.path !== 'string') {
213
- return failure(res, 400, 'bad-request', '需要 { service, path }');
278
+ return fail(400, 'bad-request', '需要 { service, path }');
214
279
  }
215
280
  const service = body.service.trim();
281
+ trace.service = service;
282
+ // 路径在读出来的时候就记下:拒绝服务那几种情况也要能看见页面想打哪儿。
283
+ trace.path = body.path.trim();
216
284
  const spec = specOf(ctx, service);
217
- if (!spec) return failure(res, 404, 'service-unknown', `没有登记这个服务:${service}`);
285
+ if (!spec) return fail(404, 'service-unknown', `没有登记这个服务:${service}`);
218
286
 
219
287
  const method = typeof body.method === 'string' ? body.method.trim().toUpperCase() : 'GET';
220
- if (!METHODS.has(method)) return failure(res, 400, 'bad-method', `不支持的方法:${method}`);
288
+ trace.method = method;
289
+ if (!METHODS.has(method)) return fail(400, 'bad-method', `不支持的方法:${method}`);
221
290
  // 这条路由在外层永远是 POST(分类表只能按它当读放行),真正的方法藏在 body 里。所以写方法
222
291
  // 必须在这里按设备单独判:只读档设备否则能借代发通道对扩展后台发写请求。
223
292
  if (method !== 'GET' && !hasPermission(req.__dshRecord, 'files.write')) {
224
- return failure(res, 403, 'permission-denied', '这台设备没有执行该操作的权限');
293
+ return fail(403, 'permission-denied', '这台设备没有执行该操作的权限');
225
294
  }
226
295
 
227
- const path = body.path.trim();
228
- if (!path.startsWith('/') || path.startsWith('//')) return failure(res, 400, 'bad-path', '路径必须是本源内的绝对路径');
229
- const pathname = path.split('?')[0];
296
+ const targetPath = trace.path;
297
+ if (!targetPath.startsWith('/') || targetPath.startsWith('//')) return fail(400, 'bad-path', '路径必须是本源内的绝对路径');
298
+ const pathname = targetPath.split('?')[0];
230
299
  if (spec.allow.length > 0 && !spec.allow.some((prefix) => pathname.startsWith(prefix))) {
231
- return failure(res, 403, 'path-not-allowed', `这个服务不开放该路径:${pathname}`);
300
+ return fail(403, 'path-not-allowed', `这个服务不开放该路径:${pathname}`);
232
301
  }
233
302
 
234
303
  let target;
235
304
  try {
236
305
  target = await spec.resolve();
237
306
  } catch (error) {
238
- return failure(res, 503, 'service-unavailable', `${service} 现在不可用:${(error && error.reason) || 'unavailable'}`);
307
+ return fail(503, 'service-unavailable', `${service} 现在不可用:${(error && error.reason) || 'unavailable'}`);
239
308
  }
240
309
 
241
310
  let cookie = '';
@@ -244,7 +313,18 @@ async function handleExtensionData(ctx, req, res) {
244
313
  }
245
314
  const reqBody = typeof body.body === 'string' ? body.body : undefined;
246
315
  const contentType = typeof body.contentType === 'string' ? body.contentType : undefined;
247
- const result = await proxyRequest(target.port, cookie, method, path, reqBody, contentType);
316
+ const result = await proxyRequest(target.port, cookie, method, targetPath, reqBody, contentType);
317
+ // 到达目标服务之后的一切都记在这里:`upstream` 是目标回来的状态码(0 = 连都没连上)。
318
+ // 页面那句「取数失败」到底是它自己回了 500、还是根本没走到这里,看这一格就分得清。
319
+ logLine({
320
+ at: new Date().toISOString(),
321
+ ...trace,
322
+ status: result.status,
323
+ code: result.status === 0 ? 'upstream-unreachable' : (result.status >= 400 ? 'upstream-error' : null),
324
+ upstream: result.status,
325
+ bytes: typeof result.body === 'string' ? result.body.length : 0,
326
+ ms: Date.now() - startedAt,
327
+ });
248
328
  sendJson(res, 200, { ok: true, status: result.status, headers: result.headers, body: result.body });
249
329
  }
250
330