dsh-mobile-plugin 0.5.99 → 0.5.101

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.
@@ -9,17 +9,11 @@
9
9
  * 一句话分工:headline 是 agent 自己说的(reason / displayReason),事实行是电脑从原始参数
10
10
  * 算出来的;删除 / 推送 / 装软件高亮。算不出来就**不出这一行**,绝不糊一句会让用户误判的话。
11
11
  *
12
- * 动作类别键 `classKey`(`<tool>:<class>[@档位]`)既做「这一类以后都同意」的记账键,也做「同一轮
13
- * 重复请求」的比较键,两处必须用同一份,所以只在这里算一遍。
12
+ * 动作类别键 `classKey`(`<tool>:<class>`)只用来判断「同一轮里相同请求再次出现」——比较的是
13
+ * 类别 + 原始参数,避免同一轮把同一条命令问两遍。它是纯比较用的键,不做任何跨轮记忆。
14
14
  *
15
- * 「以后都同意」的粒度是这里最要紧的一处判断,四条都只认参数本身(`rememberable`):
16
- * - 删除 / 推送 / 装软件 / 跑第三方包(`isIrreversibleClass`);
17
- * - 写到**会话工作区之外**(`isWithin`):记 `write:abs` 等于「以后任意路径都能静默改」;
18
- * - **解析不出内容的壳**:内联执行的代码(`node -e` / `python3 -c`)、带命令替换的 shell、
19
- * 解释器跑外部脚本文件(`bash install.sh`)、管道把内容喂进 shell(`curl … | sh`);
20
- * - 只起包装作用的程序先剥掉(`WRAPPERS`),否则记的是 `env` / `timeout` / `xargs` 这类壳。
21
- *
22
- * 详见 docs/dev-map / decisions 里这条改动的原因。
15
+ * 只起包装作用的程序先剥掉(`WRAPPERS`),否则 `env` / `timeout` / `xargs` 会把真正干活的
16
+ * 那条命令藏起来,同轮比较就会把不同命令当成同一条。
23
17
  */
24
18
 
25
19
  /** 整行事实的字符上限(中文按 1 计)。先保数量与动词,再保目标名。 */
@@ -42,14 +36,6 @@ const WRAPPERS = new Set(['sudo', 'env', 'nohup', 'nice', 'stdbuf', 'command', '
42
36
  const WRAPPER_WITH_ARG = new Set(['timeout', 'nice', 'time']);
43
37
  /** 包装器的这些选项自带取值:`sudo -u root rm` 里 `root` 是用户名,不是命令。 */
44
38
  const OPTS_WITH_VALUE = new Set(['-u', '-g', '-n', '-p', '-C', '-S', '-I', '-L', '-P', '--signal', '--kill-after', '--user', '--group', '-s']);
45
- /** 跑第三方包的程序:等同于装软件,不给记忆(见 `isIrreversibleClass` 的理由)。 */
46
- const RUNNER_PROGS = new Set(['npx', 'bunx', 'uvx']);
47
- /** 内联执行代码的解释器:`node -e …` / `python3 -c …` 看不出来里面干了什么。 */
48
- const INTERPRETERS = new Set(['node', 'deno', 'bun', 'python', 'python3', 'ruby', 'perl', 'php']);
49
- /** 壳解释器:`bash install.sh`、`curl … | sh` 这两种跑的内容同样读不到静态参数里。 */
50
- const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'fish']);
51
- /** 记账键里的档位尾巴:只有这两档是真档位,`unknown` 不加(见 `deriveApprovalFacts`)。 */
52
- const KEY_TIERS = new Set(['workspace-write', 'danger-full-access']);
53
39
  /** 包管理器 → 装包动词集合。 */
54
40
  const PM_INSTALL = {
55
41
  npm: new Set(['install', 'i', 'add']),
@@ -99,23 +85,6 @@ function pathOf(args) {
99
85
  return '';
100
86
  }
101
87
 
102
- /**
103
- * 这个落点是不是「会话工作区里面」。
104
- *
105
- * 判不准的一律算外面(不给记忆):`~` 开头的路径本函数不展开,相对路径在没有 cwd 时也说不清
106
- * —— 把说不清的当里面,等于给了一条能静默改到 `~/.zshrc` 的规则。
107
- */
108
- function isWithin(p, cwd) {
109
- if (typeof p !== 'string' || !p) return false;
110
- if (typeof cwd !== 'string' || !cwd) return false;
111
- if (p.startsWith('~')) return false;
112
- const norm = p.replace(/\\/g, '/');
113
- const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '');
114
- if (/^[A-Za-z]:|^\//.test(norm)) return norm === root || norm.startsWith(`${root}/`);
115
- // 相对路径:没写 `..` 就算在工作区里(`../x` 或 `a/../../x` 一律当外面)。
116
- return !/(^|\/)\.\.(\/|$)/.test(norm);
117
- }
118
-
119
88
  /** 把一个目标清单收成「a、b 等 N 个」,最多 `MAX_TARGETS` 个。 */
120
89
  function listTargets(names) {
121
90
  const clean = names.map((n) => String(n || '').trim()).filter(Boolean);
@@ -244,11 +213,11 @@ function clauseOfSegment(tokens) {
244
213
  return { clause: host ? `连 ${host}` : `跑 ${prog}`, highlight: false, prog };
245
214
  }
246
215
 
247
- // 重定向写文件(段内出现 > 或 >>)。写到工作区外与 write 同一口径:句子照旧说,但不给记忆。
216
+ // 重定向写文件(段内出现 > 或 >>)。
248
217
  const redirect = tokens.findIndex((t) => t === '>' || t === '>>');
249
218
  if (redirect >= 0 && tokens[redirect + 1]) {
250
219
  const target = unquote(tokens[redirect + 1]);
251
- return { clause: `写 ${baseOf(target)}`, highlight: false, nowhere: !isWithin(target, opts.cwd), prog };
220
+ return { clause: `写 ${baseOf(target)}`, highlight: false, prog };
252
221
  }
253
222
 
254
223
  // 其它程序
@@ -295,34 +264,7 @@ function isOpaque(toolName, args) {
295
264
  return false;
296
265
  }
297
266
 
298
- /** 判断一段命令是不是「内联执行代码」:`node -e …` / `python3 -c …` / `<prog> -m …` 之类。 */
299
- function isInlineCode(tokens) {
300
- if (!tokens || tokens.length === 0) return false;
301
- const prog = baseOf(tokens[0] || '');
302
- if (!INTERPRETERS.has(prog)) return false;
303
- return tokens.slice(1).some((t) => t === '-e' || t === '--eval' || t === '-c' || t === '-m' || /^-[a-z]*[ecm]$/.test(t));
304
- }
305
-
306
- /**
307
- * 这一段是不是「内容读不到」的执行:解释器/壳跑外部脚本文件,或管道把内容喂进壳。
308
- *
309
- * 与 `isOpaque` 同一个口径:命中的整张卡标 `nowhere`(不可「以后都同意」)。理由很直接:
310
- * `bash install.sh` 里那支脚本、`curl … | sh` 那条管道喂进来的脚本,实际内容都不在这条
311
- * 命令的静态参数里;按程序名记成 `bash:bash` / `bash:curl+sh` 就等于「以后任意脚本静默执行」。
312
- * `-e/-c` 那种内联执行由上面的 `isInlineCode` 处理,这里不重复。
313
- */
314
- function isUnparseableExec(tokens) {
315
- if (!tokens || tokens.length === 0) return false;
316
- const prog = baseOf(tokens[0] || '');
317
- // 壳解释器:`bash install.sh` / 管道末端的 `sh`(`curl … | sh`)——交给它的脚本看不到。
318
- if (SHELLS.has(prog)) return true;
319
- // 其它解释器带一个位置参数(脚本文件):`python a.py`、`node server.js` —— 文件内容看不到。
320
- // 只有选项(`node --version`)没有脚本可跑,不算。
321
- if (INTERPRETERS.has(prog)) return tokens.slice(1).some((t) => !t.startsWith('-'));
322
- return false;
323
- }
324
-
325
- /** 单次调用 → `{ clause, highlight, nowhere, classKey }`。 */
267
+ /** 单次调用 → `{ clause, highlight, classKey }`。 */
326
268
  function callToPiece(toolName, args) {
327
269
  const name = typeof toolName === 'string' ? toolName : '';
328
270
  if (name === 'bash') {
@@ -332,33 +274,23 @@ function callToPiece(toolName, args) {
332
274
  if (isOpaque(name, args)) {
333
275
  const segs = splitSegments(args.command);
334
276
  const prog = segs.length ? baseOf(segs[0][0] || '') : 'bash';
335
- // 解析不出来的壳不给记忆:`node -e` / `python3 -c` 里面能写任何东西,记成「以后同意 node」
336
- // 就是「以后任意脚本静默放行」。
337
- return { clause: `跑 ${prog}(内容无法静态解析)`, highlight: false, nowhere: true, classKey: `bash:${prog}` };
277
+ return { clause: `跑 ${prog}(内容无法静态解析)`, highlight: false, classKey: `bash:${prog}` };
338
278
  }
339
279
  const segs = splitSegments(args.command);
340
280
  const clauses = [];
341
281
  let highlight = false;
342
- let nowhere = false;
343
282
  for (const tokens of segs) {
344
- // 段内联执行代码(`python3 -c "…"`)或解释器/壳跑外部脚本:整张卡不给记忆,
345
- // 理由同上面的 `isOpaque`。
346
- if (isInlineCode(tokens) || isUnparseableExec(tokens)) nowhere = true;
347
283
  const piece = clauseOfSegment(tokens);
348
284
  if (!piece) continue;
349
285
  if (piece.clause) clauses.push(piece.clause);
350
286
  if (piece.highlight) highlight = true;
351
- if (piece.nowhere) nowhere = true;
352
287
  }
353
- return { clause: clauses.join(';'), highlight, nowhere, classKey: bashClassKey(args.command) };
288
+ return { clause: clauses.join(';'), highlight, classKey: bashClassKey(args.command) };
354
289
  }
355
290
 
356
291
  if (name === 'write' || name === 'edit') {
357
292
  const p = pathOf(args);
358
293
  if (!p) return { clause: '', highlight: false, classKey: `tool:${name}` };
359
- // 工作区外一律不给记忆(`nowhere` 只管「能不能记」,不改这一行的颜色):写 `~/.zshrc`、
360
- // `~/.ssh/authorized_keys`、开机启动项都是这一类,而用户点头时想的是「工作区里改文件」。
361
- if (!isWithin(p, opts.cwd)) return { clause: `改 ${baseOf(p)}`, highlight: false, nowhere: true, classKey: `${name}:abs` };
362
294
  const d = dirKeyOf(p, opts.cwd);
363
295
  return { clause: `改 ${baseOf(p)}`, highlight: false, classKey: `${name}:${d}` };
364
296
  }
@@ -392,7 +324,7 @@ function callToPiece(toolName, args) {
392
324
 
393
325
  /** 危险度排序,用于多调用聚合时取「最危险那条」做 classKey。 */
394
326
  function dangerRank(classKey) {
395
- const key = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '');
327
+ const key = String(classKey || '');
396
328
  if (/^(bash:rm|bash:rmdir|bash:unlink|bash:shred)$/.test(key)) return 5;
397
329
  if (key === 'bash:git:push' || key === 'bash:git:reset' || key === 'bash:git:clean') return 5;
398
330
  if (INSTALL_MANAGERS.has((key.split(':')[1] || '').split(':')[0]) && /install|add|:i$/.test(key)) return 4;
@@ -401,35 +333,11 @@ function dangerRank(classKey) {
401
333
  return 1;
402
334
  }
403
335
 
404
- /** 把 classKey 翻成给人看的一句(撤销页 / 按钮用)。档位尾巴只进键,不进这句人话。 */
405
- function labelOf(classKey) {
406
- const parts = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '').split(':');
407
- const tool = parts[0];
408
- if (tool === 'bash') {
409
- if (parts[1] === 'git' && parts[2]) {
410
- const map = { push: 'git push', commit: 'git commit', reset: 'git reset', clean: 'git clean' };
411
- return `Bash · ${map[parts[2]] || `git ${parts[2]}`}`;
412
- }
413
- if (parts.length === 3) {
414
- return `Bash · ${parts[1]} ${parts[2] === 'add' || parts[2] === 'install' || parts[2] === 'i' ? '装包' : parts[2]}`;
415
- }
416
- const prog = parts[1] || '';
417
- if (DELETE_PROGS.has(prog)) return 'Bash · 删除文件';
418
- if (prog === 'curl' || prog === 'wget') return 'Bash · 联网请求';
419
- return `Bash · 运行 ${prog || '命令'}`;
420
- }
421
- if (tool === 'write' || tool === 'edit') return `改文件 · ${parts[1] || '未知目录'}`;
422
- if (tool === 'read') return `读文件 · ${parts[1] || '未知目录'}`;
423
- if (tool === 'web_fetch') return `联网 · ${parts[1] || '网页'}`;
424
- if (tool === 'tool') return `工具 · ${parts[1] || '未知'}`;
425
- return tool ? String(classKey) : '';
426
- }
427
-
428
336
  let opts = {};
429
337
 
430
338
  /**
431
339
  * 主入口:`calls` = `{toolName, args}` 或它的数组;`options.cwd` 用于写/读文件的目录归类。
432
- * 返回 `{ fact, highlight, classKey, classLabel, rememberable }`。
340
+ * 返回 `{ fact, highlight, classKey }`。
433
341
  */
434
342
  function deriveApprovalFacts(calls, options) {
435
343
  opts = isRecord(options) ? options : {};
@@ -443,8 +351,6 @@ function deriveApprovalFacts(calls, options) {
443
351
  const nonEmpty = pieces.filter((p) => p.clause);
444
352
  const joined = nonEmpty.map((p) => p.clause).slice(0, MAX_CLAUSES).join(';');
445
353
  const highlight = pieces.some((p) => p.highlight);
446
- /** 有一处写到了工作区外 / 是解析不出内容的壳:整张卡不给「以后都同意」。 */
447
- const nowhere = pieces.some((p) => p.nowhere);
448
354
  let fact = joined;
449
355
  if (fact.length > FACT_MAX) {
450
356
  // 先保数量与动词、再保目标名:若带「等 N 个」,保住这段后缀,只截前面的目标清单。
@@ -458,68 +364,12 @@ function deriveApprovalFacts(calls, options) {
458
364
  }
459
365
  }
460
366
 
461
- // classKey:多调用取最危险那条;单调用就是它自己。
367
+ // classKey:多调用取最危险那条;单调用就是它自己。只用于同轮重复比较。
462
368
  let classKey = pieces.length ? pieces[0].classKey : 'tool:unknown';
463
369
  for (const p of pieces) {
464
370
  if (dangerRank(p.classKey) > dangerRank(classKey)) classKey = p.classKey;
465
371
  }
466
- // 高亮是同一份解析给出的第二个信号:删除 / 推送 / reset / clean / 装包只在这几处点亮
467
- // (见 `clauseOfSegment`)。组合命令的类别键容易把危险那一段藏进 `a+b`,两条一起看才不漏。
468
- // `nowhere` 是第三个信号:写到了工作区外面(含重定向),那类不给记忆,理由见 `callToPiece`。
469
- let rememberable = isRememberable(classKey) && !highlight && !nowhere;
470
- // 档位尾巴:`workspace-write` 与 `danger-full-access` 下的同名动作不是同一条授权 —— 「以后
471
- // 都同意在工作区里改文件」不该把「升到完全访问」也一起放行。记在键里,换档后重新弹卡;
472
- // 档位认不出(`unknown`)就不加尾巴,那种键只和同样认不出档位的请求互相匹配。
473
- if (rememberable && KEY_TIERS.has(opts.tier)) classKey = `${classKey}@${opts.tier}`;
474
- return {
475
- fact,
476
- highlight,
477
- classKey,
478
- classLabel: labelOf(classKey),
479
- rememberable,
480
- };
481
- }
482
-
483
- /**
484
- * 哪些动作类别**永远不许**被「这一类以后都同意」记住。
485
- *
486
- * 判据分两层,两层都只看原始请求折出来的东西(`deriveApprovalFacts` 的输入就是原始参数):
487
- * - **动作类别**(classKey):删除类程序、`git push` / `git reset` / `git clean`、装包动词;
488
- * - **高亮**(highlight):上面这几类一旦被解析出来就会置高亮,多段命令(`cd x && rm -rf y`)
489
- * 的类别键是 `bash:cd+rm` 这种组合,单看类别字符串容易漏,高亮是同一份解析给出的第二个信号。
490
- *
491
- * 理由:`rm` 这个类别一旦被记住,任意 `rm`(包括 `rm -rf ~`)都变成静默放行 —— 这不是「同类」,
492
- * 只是「同名」。推送、装软件同理(推送会动远端,装包会执行第三方脚本)。这三类一律每次问,
493
- * 宁可多推一张卡。
494
- */
495
- function isIrreversibleClass(classKey) {
496
- // 记账键可能带档位尾巴(`bash:git:push@danger-full-access`),先剥掉再判。
497
- const key = String(classKey || '').replace(/@(?:workspace-write|danger-full-access|unknown)$/, '');
498
- if (!key) return false;
499
- // `git rm` 也是删文件(只是经过了 git),`git push/reset/clean` 会动远端或不可恢复。
500
- if (key === 'bash:git:push' || key === 'bash:git:reset' || key === 'bash:git:clean' || key === 'bash:git:rm') return true;
501
- if (!key.startsWith('bash:')) return false;
502
- // 组合键(`bash:cd+rm`)与单程序键(`bash:rm`)都拆成「程序[:动词]」逐段看。
503
- for (const part of key.slice('bash:'.length).split('+')) {
504
- const [prog, verb] = part.split(':');
505
- if (!prog) continue;
506
- if (DELETE_PROGS.has(prog)) return true;
507
- if (INSTALL_MANAGERS.has(prog) && PM_INSTALL[prog].has(String(verb || '').toLowerCase())) return true;
508
- // `npx 某个包`:跑的就是刚装下来的第三方包,与装软件同一条理由。
509
- if (RUNNER_PROGS.has(prog)) return true;
510
- }
511
- return false;
512
- }
513
-
514
- /**
515
- * 键退化到 `tool:<name>`(无区分度)时不给「以后都同意」;删除 / 推送 / 装软件这三类也不给
516
- * (见 `isIrreversibleClass`);其余给。
517
- */
518
- function isRememberable(classKey) {
519
- if (!classKey || classKey === 'tool:unknown') return false;
520
- if (classKey.startsWith('tool:')) return false;
521
- if (isIrreversibleClass(classKey)) return false;
522
- return true;
372
+ return { fact, highlight, classKey };
523
373
  }
524
374
 
525
375
  /** 归一化的关键参数摘要(同轮重复比较用;字符串直接比,不用哈希)。 */
@@ -547,8 +397,5 @@ function keyArgsOf(toolName, args) {
547
397
  module.exports = {
548
398
  deriveApprovalFacts,
549
399
  keyArgsOf,
550
- labelOf,
551
- isRememberable,
552
- isIrreversibleClass,
553
400
  FACT_MAX,
554
401
  };
@@ -16,22 +16,14 @@
16
16
  * 钩子上没有宿主 id,且与 `approval/asked` 的到达顺序不定,所以两个来源共用一张挂起项表:
17
17
  * 先到的建项,后到的补字段。
18
18
  *
19
- * 在三档结论之外还加了两样东西(都不扩能力面、都是展示或本地策略):
20
- * - **「这一类以后都同意」(allowed-class)**:宿主只有 allowed-once 能放行,收到这类回答时把
21
- * 当前这条折成 allowed-once 交回,同时按动作类别(`approval-facts.js` 算的 `classKey`)在本机
22
- * `approval-memory.js` 记一条规则;之后同类请求直接静默放行、不再弹卡,规则可在设置页撤销。
19
+ * 另外两样东西(都不扩能力面、都只是展示):
23
20
  * - **事实行**:宿主 `approval/request` 钩子不带工具参数,所以按 callId 回会话日志取原始参数,
24
- * 由 `approval-facts.js` 折成一句话随卡下发(删/推/装高亮);算不出就不出这一行。动作类别里
25
- * 带沙箱档位(`<base>@<tier>`):同一条命令在「工作区内」与「完全访问」下不是同一类授权。
26
- * - **拒绝理由**:手机上写的理由随结算帧下发一份,同时记进 `approval-memory.js` 的最近拒绝
27
- * 记录 —— 只写在挂起项上会随结算一起消失,用户事后无从回看。
21
+ * 由 `approval-facts.js` 折成一句话随卡下发(删/推/装高亮);算不出就不出这一行。动作类别只
22
+ * 用来判断「同一轮里重复请求」,不做跨轮记忆。
23
+ * - **拒绝理由**:手机上写的理由随结算帧下发一份,卡收起前那一瞬间的提示要能说出「为什么」。
28
24
  * 另有「同一轮里相同请求再次出现直接 auto-reject」(`turnState` 记本轮签名)。
29
25
  *
30
- * `classLabel`(类别人话)在推卡时随卡下发,供第三颗按钮旁那行说明;撤销接口在写盘失败时
31
- * 回非 ok,手机据此保留那一行并提示重试,不把没删成的规则当成已撤销。
32
- *
33
- * 「以后都同意」的 remembered 由 `approval-memory.addRule` 的返回值决定(写盘失败回 false),
34
- * 与撤销同一口径。审批的 approvalId 一经下发不再变:钩子先到时的占位 id 保持不变,宿主真 id
26
+ * 审批的 approvalId 一经下发不再变:钩子先到时的占位 id 保持不变,宿主真 id
35
27
  * 另存 `realApprovalId`,只用于认领 `approval/decided` —— App 的审批队列按 approvalId 去重。
36
28
  */
37
29
 
@@ -40,7 +32,6 @@ const { sendJson, readJsonBody } = require('../shared/http-util');
40
32
  const { cancelForwardedRequests } = require('./host-bridge/transport.js');
41
33
  const { sessionIdOf } = require('./session-id.js');
42
34
  const facts = require('./approval-facts.js');
43
- const approvalMemory = require('./approval-memory.js');
44
35
  const { anyApprover } = require('./permissions.js');
45
36
  const { credentialsEntry } = require('../shared/credentials-entry.js');
46
37
 
@@ -57,13 +48,11 @@ function canShowCards() {
57
48
  }
58
49
 
59
50
  /**
60
- * `/approval/respond` 认三种结论(与 App 的按钮一一对应):
51
+ * `/approval/respond` 认两种结论(与 App 的按钮一一对应):
61
52
  * - `allowed-once` 允许一次;
62
- * - `rejected` 拒绝(可带一句 reason);
63
- * - `allowed-class` 「这一类以后都同意」——本桥把**当前这条折成 allowed-once 交回宿主**(宿主
64
- * 只有 allowed-once 能放行,没有第三档),同时把动作类别记进本机规则账;之后同类不再弹卡。
53
+ * - `rejected` 拒绝(可带一句 reason)。
65
54
  */
66
- const ANSWER_OUTCOMES = new Set(['allowed-once', 'rejected', 'allowed-class']);
55
+ const ANSWER_OUTCOMES = new Set(['allowed-once', 'rejected']);
67
56
  /** 宿主 `approval/decided` 的结论词表(`dsh-user-approval` 的 OUTCOMES)。 */
68
57
  const DECISIONS = new Set(['allowed-once', 'rejected', 'cancelled', 'unavailable']);
69
58
  /** 拒绝理由长度上限(只落本机,宿主不接收 reason)。 */
@@ -132,10 +121,6 @@ function cardFrame(entry) {
132
121
  // 事实行:电脑从原始参数算出来的一句人话;算不出就不带(App 不渲染这一行)。
133
122
  ...(entry.fact ? { fact: entry.fact } : {}),
134
123
  ...(entry.factHighlight ? { factHighlight: true } : {}),
135
- // 能算出动作类别时才给「这一类以后都同意」那颗按钮。
136
- ...(entry.rememberable ? { rememberable: true } : {}),
137
- // 类别的人话(「Bash · 删除文件(完全访问)」):第三颗按钮旁边要让人知道「这一类」是哪一类。
138
- ...(entry.classLabel ? { classLabel: entry.classLabel } : {}),
139
124
  // 危险命令的原文:事实行是概括,用户要判断得看原句。
140
125
  ...(entry.command ? { command: entry.command } : {}),
141
126
  };
@@ -175,13 +160,12 @@ function pushCard(entry) {
175
160
  // 只有这条推送能把它带到系统通知上。只有「已绑上钩子 = 答得动」的卡才推,
176
161
  // 否则用户点进来是一条必然 409 的死卡。
177
162
  if (entry.bound && pushNotifier) {
178
- // 事实行与「以后都同意」要一起带到系统通知上:通知栏那张卡拿不到 App 面板,只靠这几样
179
- // 值才知道这条要动什么、点哪颗按钮。标题由装配层补(只有镜像调度器手里有会话名)。
163
+ // 事实行要一起带到系统通知上:通知栏那张卡拿不到 App 面板,只靠这一样值才知道这条要动
164
+ // 什么。标题由装配层补(只有镜像调度器手里有会话名)。
180
165
  try {
181
166
  pushNotifier(entry.sessionId, cardFrame(entry), {
182
167
  fact: entry.fact,
183
168
  factHighlight: entry.factHighlight,
184
- rememberable: entry.rememberable,
185
169
  });
186
170
  } catch { /* 推送失败不影响建卡 */ }
187
171
  }
@@ -476,9 +460,7 @@ function applyFacts(entry, session) {
476
460
  );
477
461
  entry.fact = derived.fact;
478
462
  entry.factHighlight = derived.highlight;
479
- entry.rememberable = derived.rememberable;
480
463
  entry.classKey = derived.classKey;
481
- entry.classLabel = derived.classLabel;
482
464
  entry.keyArgs = facts.keyArgsOf(entry.toolName, args);
483
465
  entry.command = commandOf(entry.toolName, args);
484
466
  }
@@ -590,32 +572,6 @@ function rememberDuplicate(sessionId, prepared) {
590
572
  }
591
573
  }
592
574
 
593
- /** 这条审批的动作类别是否已被用户「以后都同意」(只认能区分的键)。 */
594
- function classAlreadyAllowed(prepared) {
595
- if (!prepared || !prepared.rememberable || !prepared.classKey) return false;
596
- try { return approvalMemory.hasRule(prepared.classKey); } catch { return false; }
597
- }
598
-
599
- /**
600
- * 宽松版:档位没认出来(`approval/asked` 那条事件常常不带 `reason`)时,按类别基名再问一遍
601
- * 规则账 —— 账里存的是带档位的键。
602
- *
603
- * **只给 `noteAsk` 用**:那一侧的判断只决定「要不要建卡」,判错最多是钩子那侧自己建项(卡
604
- * 照样出);而钩子那侧必须严格,档位不明就绝不能凭基名静默放行。
605
- */
606
- function classAllowedByBase(prepared) {
607
- if (!prepared || !prepared.rememberable || !prepared.classKey) return false;
608
- if (prepared.tier !== 'unknown') return false;
609
- const base = classBaseOf(prepared.classKey);
610
- if (base === prepared.classKey) return false;
611
- try {
612
- return approvalMemory.listRules().some((rule) => classBaseOf(rule.classKey) === base);
613
- } catch {
614
- return false;
615
- }
616
- }
617
-
618
-
619
575
  /**
620
576
  * `approval/asked`:宿主记下这次审批。details 见 `dsh-user-approval` 的 `request()`。
621
577
  *
@@ -647,9 +603,9 @@ function noteAsk(session, sessionId, data) {
647
603
  pushCard(existing);
648
604
  return;
649
605
  }
650
- // 2) 没有挂起项:先算事实,判一下这条会不会被钩子静默放行 / 自动拒。会的话什么都不建。
606
+ // 2) 没有挂起项:先算事实,判一下这条会不会被钩子自动拒。会的话什么都不建。
651
607
  const prepared = prepareFacts(session, ask);
652
- if (classAlreadyAllowed(prepared) || classAllowedByBase(prepared) || isDuplicate(sessionId, prepared)) return;
608
+ if (isDuplicate(sessionId, prepared)) return;
653
609
  // 3) 真会弹卡的才建项。
654
610
  const entry = entryFor(sessionId, ask);
655
611
  applyFacts(entry, session);
@@ -745,14 +701,9 @@ async function onApprovalRequest(ctx, request, next) {
745
701
  const sessionId = sessionIdOfRequest(request);
746
702
  if (!sessionId) return next();
747
703
  const session = request.agent && request.agent.session ? request.agent.session : null;
748
- // 事实行与动作类别:在钩子这侧从日志原始参数算(手机线路已裁参数)。下半段的
749
- // 「已同意 / 本轮重复」要用同一份,所以在这里算一次。
704
+ // 事实行与动作类别:在钩子这侧从日志原始参数算(手机线路已裁参数)。下半段的同轮去重要用
705
+ // 同一份,所以在这里算一次。
750
706
  const prepared = prepareFacts(session, request);
751
- // 「这一类以后都同意」:同类动作之前被用户放行过,这次直接静默放行,不弹卡也不转发。
752
- if (classAlreadyAllowed(prepared)) {
753
- rememberDuplicate(sessionId, prepared);
754
- return 'allowed-once';
755
- }
756
707
  // 同一轮里相同请求再次出现:直接拒,不再问一次(原因由 App 侧展示)。
757
708
  if (isDuplicate(sessionId, prepared)) {
758
709
  return 'rejected';
@@ -816,29 +767,6 @@ async function handleApprovalRespond(ctx, req, res) {
816
767
  if (entry && !entry.settled && entry.bound
817
768
  && entry.sessionId === body.sessionId
818
769
  && (entry.approvalId === body.approvalId || entry.realApprovalId === body.approvalId)) {
819
- // 「这一类以后都同意」:宿主只有 allowed-once 能放行,当前这条折成 allowed-once 交回;
820
- // 同时把动作类别记进本机规则账(能区分的键才记),之后同类不再弹卡。
821
- if (body.outcome === 'allowed-class') {
822
- let remembered = false;
823
- if (entry.rememberable && entry.classKey) {
824
- try {
825
- // 用 addRule 的返回值决定 remembered:写盘失败时它回 false(与 removeRule 的撤销口径
826
- // 对齐),不能把没落成盘的规则回报成「已记住」,否则重启后规则又没了。
827
- remembered = approvalMemory.addRule({ classKey: entry.classKey, label: facts.labelOf(entry.classKey) }) === true;
828
- } catch { /* 落盘失败不影响这一发放行 */ }
829
- }
830
- settle(entry, 'allowed-once');
831
- cancelForwardedCards(ctx, entry);
832
- return sendJson(res, 200, { ok: true, accepted: true, remembered });
833
- }
834
- if (body.outcome === 'rejected') {
835
- // 理由落可查处:只写在挂起项上会随结算一起消失(全仓没人读得到),这里记进账本,
836
- // 设置页的「最近拒绝」才说得出来拒了哪一类、当初为什么拒。没填理由也记一条 ——
837
- // 那一节列的是「最近拒了什么」,不是「最近写了理由的拒绝」。
838
- try {
839
- approvalMemory.recordDecision({ classKey: entry.classKey, reason });
840
- } catch { /* 落盘失败不影响这一发拒绝 */ }
841
- }
842
770
  settle(entry, body.outcome, { reason });
843
771
  cancelForwardedCards(ctx, entry);
844
772
  return sendJson(res, 200, { ok: true, accepted: true });
@@ -884,52 +812,9 @@ async function respondViaLegacyProxy(ctx, message) {
884
812
  }
885
813
  }
886
814
 
887
- /**
888
- * GET /api/mobile/v1/approval/rules —— 列出本机记住的「同类动作自动放行」规则,外加最近的
889
- * 拒绝记录(给撤销页与「最近拒绝」小节,一次请求取回)。
890
- */
891
- async function handleApprovalRules(ctx, req, res) {
892
- let rules = [];
893
- let decisions = [];
894
- try { rules = approvalMemory.listRules(); } catch { rules = []; }
895
- try { decisions = approvalMemory.listDecisions(); } catch { decisions = []; }
896
- // 拒绝记录里存的是原始类别键,撤销页要给人看:这里补一句人话标签(同一条规则共用一份)。
897
- const labeled = decisions.map((decision) => {
898
- if (!decision || typeof decision !== 'object') return decision;
899
- if (decision.label || !decision.classKey) return decision;
900
- try { return { ...decision, label: facts.labelOf(decision.classKey) }; } catch { return decision; }
901
- });
902
- sendJson(res, 200, { ok: true, rules, decisions: labeled });
903
- }
904
-
905
- /**
906
- * POST /api/mobile/v1/approval/rules/revoke —— body `{classKey}`,撤掉一条规则。
907
- * 撤销权是「以后都同意」成立的前提:用户点错了随时能收回。
908
- */
909
- async function handleApprovalRuleRevoke(ctx, req, res) {
910
- const body = await readJsonBody(req);
911
- const classKey = body && typeof body.classKey === 'string' ? body.classKey : '';
912
- if (!classKey) {
913
- return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { classKey }' } });
914
- }
915
- let removed = false;
916
- try {
917
- removed = approvalMemory.removeRule(classKey);
918
- } catch {
919
- // 写盘失败:如实报错,手机那一行才不会被划掉(否则重启后规则又冒回来,用户白撤销一场)。
920
- return sendJson(res, 500, {
921
- ok: false,
922
- error: { code: 'rule-persist-failed', message: '电脑上没能删掉这条规则,请稍后再试' },
923
- });
924
- }
925
- sendJson(res, 200, { ok: true, removed });
926
- }
927
-
928
815
  module.exports = {
929
816
  installApprovalBridge,
930
817
  handleApprovalRespond,
931
- handleApprovalRules,
932
- handleApprovalRuleRevoke,
933
818
  attachSession,
934
819
  hasPending,
935
820
  pendingCardOf,
@@ -18,7 +18,7 @@
18
18
  * - **读坏不 404**:文件缺失、读一半、结构不对、缺键,一律逐键并到默认表,绝不 404。
19
19
  * 这张表的缺省就是「能用」,把它读成故障等于让通知系统凭空瘫掉。
20
20
  * - **写整表替换**:PUT 收的是完整 `events`,逐键 clamp 到三档枚举、未知键丢弃,再原子
21
- * 落盘(照 `approval-memory.js` 的 mkdir + 临时文件 + rename + 0o600)。写不进去如实回失败。
21
+ * 落盘(mkdir + 临时文件 + rename + 0o600)。写不进去如实回失败。
22
22
  */
23
23
 
24
24
  const fs = require('node:fs');
@@ -122,7 +122,7 @@ function readEvents(deviceId) {
122
122
  }
123
123
 
124
124
  /**
125
- * 原子写整份文件(照 approval-memory:mkdir + 临时文件 + rename + 0o600)。
125
+ * 原子写整份文件(mkdir + 临时文件 + rename + 0o600)。
126
126
  * 写失败安静返回 false,让调用方如实回 500,不抛。
127
127
  */
128
128
  function saveStore(store) {
@@ -233,15 +233,15 @@ function createPushNotifier(deps) {
233
233
  * 报告一张「等你处理」的卡(审批 / 提问 / 计划评审)。
234
234
  *
235
235
  * 入参 `card` 就是桥里 `cardFrame(entry)` 的产物:审批卡 type 'approval/requested'
236
- * (rpcId / approvalId / toolName? / reason? / fact? / factHighlight? / rememberable?),
236
+ * (rpcId / approvalId / toolName? / reason? / fact? / factHighlight?),
237
237
  * 提问卡 type 'question/requested'
238
238
  * (rpcId / questions[{id,question,header?,detail?,options?,multiSelect?,intent?}])。
239
239
  * 组出的 `interaction` 是给两端原生挂按钮、把用户答复回传要用的固定结构;`category`
240
240
  * 是 iOS 通知类别的名字(App 侧注册同名字符串才会长出按钮)。
241
241
  *
242
- * `hints` 是桥那侧多给的几样东西:`{ fact, factHighlight, rememberable, title }`。
243
- * 前三样是审批卡上新长出来的展示信息(事实行 / 那一行高亮 / 能不能「以后都同意」),
244
- * 通知栏里得原样带上,否则手机在后台看到的还是三档之前那张卡。`title` 是会话名。
242
+ * `hints` 是桥那侧多给的几样东西:`{ fact, factHighlight, title }`。
243
+ * 前两样是审批卡上的展示信息(事实行 / 那一行高亮),通知栏里得原样带上,否则手机在后台
244
+ * 看到的还是没长事实行的那张卡。`title` 是会话名。
245
245
  */
246
246
  function notifyInteraction(sessionId, card, hints = {}) {
247
247
  if (!sessionId || !card || typeof card !== 'object') return;
@@ -288,7 +288,6 @@ function createPushNotifier(deps) {
288
288
  ? (typeof hint.fact === 'string' && hint.fact ? hint.fact : (typeof card.fact === 'string' ? card.fact : ''))
289
289
  : '';
290
290
  const factHighlight = !!(hint.factHighlight || card.factHighlight);
291
- const rememberable = kind === 'approval' && !!(hint.rememberable || card.rememberable);
292
291
  const interaction = {
293
292
  kind,
294
293
  rpcId,
@@ -297,11 +296,10 @@ function createPushNotifier(deps) {
297
296
  ? { approvalId: card.approvalId }
298
297
  : {}),
299
298
  summary,
300
- // 事实行与「以后都同意」:审批卡原来只写给 App 面板,通知栏那张卡拿不到,用户点开前
301
- // 不知道这条要动什么。跟 `cardFrame` 同一份值(桥已经算好,这里不重算)。
299
+ // 事实行:审批卡原来只写给 App 面板,通知栏那张卡拿不到,用户点开前不知道这条要动什么。
300
+ // 跟 `cardFrame` 同一份值(桥已经算好,这里不重算)。
302
301
  ...(fact ? { fact } : {}),
303
302
  ...(fact && factHighlight ? { factHighlight: true } : {}),
304
- ...(rememberable ? { rememberable: true } : {}),
305
303
  // 通知栏能不能就地作答:只有原生挂得出按钮的那一种形状才为真(见 `isAnswerable`)。
306
304
  answerable,
307
305
  ...(kind !== 'approval'
@@ -159,7 +159,18 @@ function profileNodeModulesOf(ctx) {
159
159
  }
160
160
 
161
161
  function registerMobileRoutes(deps) {
162
- const { registerRoute, tailcat, p2p, registerUpgradeRoute, guarded, state, getControl, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, mux = { handleUpgrade: () => {} }, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
162
+ const { registerRoute: registerRouteRaw, registerUpgradeRoute: registerUpgradeRouteRaw, tailcat, p2p, guarded, state, getControl, hostMetadata, getSidecarSnapshot, safeLanCandidates, safeIpv6Candidates, lanPortInUse, mux = { handleUpgrade: () => {} }, preview, core, pairingApproval, rotatePairing, getHistoryKey, credentials, dropDeviceStreams } = deps;
163
+ /**
164
+ * 移动端路由对**宿主层**要匿名:安全由 `guarded` 里的设备凭据校验负责,不能指望桌面会话。
165
+ * 新版宿主把未声明 `auth` 的路由按 `required` 处理,手机没有桌面 peer,就会在网关层被判
166
+ * 403/401,根本进不到 token 守卫。这里统一给移动路由补 `auth: 'anonymous'`;控制面
167
+ * `/api/relay/*` 不经过本函数,仍保持要求桌面会话。
168
+ */
169
+ const anonymousRoute = (route) => (route && route.auth === undefined ? { ...route, auth: 'anonymous' } : route)
170
+ const registerRoute = (route) => registerRouteRaw(anonymousRoute(route))
171
+ const registerUpgradeRoute = typeof registerUpgradeRouteRaw === 'function'
172
+ ? (route) => registerUpgradeRouteRaw(anonymousRoute(route))
173
+ : registerUpgradeRouteRaw
163
174
  const currentRelayUrl = () => {
164
175
  const tunnel = getSidecarSnapshot?.()?.tunnel
165
176
  return state.enabled && tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || null : null
@@ -564,9 +575,6 @@ function registerMobileRoutes(deps) {
564
575
  route('/api/mobile/v1/events/stream', events.handleDeviceStream)
565
576
  route('/api/mobile/v1/question/respond', questions.handleQuestionRespond)
566
577
  route('/api/mobile/v1/approval/respond', approvals.handleApprovalRespond)
567
- // 「这类以后都同意」的本机规则账:读列表 + 逐条撤销(撤销页用)。
568
- route('/api/mobile/v1/approval/rules', approvals.handleApprovalRules)
569
- route('/api/mobile/v1/approval/rules/revoke', approvals.handleApprovalRuleRevoke)
570
578
  route('/api/mobile/v1/session/goal', sessions.handleGoalAction)
571
579
  route('/api/mobile/v1/session/queue/update', sessions.handleQueueUpdate)
572
580
  route('/api/mobile/v1/workspaces', workspaces.handleWorkspaces)
@@ -98,13 +98,19 @@ export function createRuntime() {
98
98
  dispatchOuterUpgrade = typeof outerUpgrade === 'function' ? outerUpgrade : null
99
99
  }
100
100
 
101
- /** 给 route.handler 外面套「进 +1 / 出 -1」;拿不到 handler 原样返回。 */
101
+ /**
102
+ * 给 route.handler 外面套「进 +1 / 出 -1」;拿不到 handler 原样返回。
103
+ *
104
+ * 必须**原样透传全部实参**:新版 web 服务器按 `handler(req, res, peer)` 调用,第三个
105
+ * 是准入后的 peer 上下文;只转 `(req, res)` 会丢掉 peer,RPC 端拿不到身份就一直挂着
106
+ * 不响应(表现为桌面「Loading plugins…」卡死、`/api` 全部超时)。
107
+ */
102
108
  function wrapInFlight(route) {
103
109
  if (!route || typeof route.handler !== 'function') return route
104
110
  const handler = route.handler
105
- route.handler = async (req, res) => {
111
+ route.handler = async (...args) => {
106
112
  inFlight += 1
107
- try { return await handler(req, res) } finally { inFlight = Math.max(0, inFlight - 1) }
113
+ try { return await handler(...args) } finally { inFlight = Math.max(0, inFlight - 1) }
108
114
  }
109
115
  return route
110
116
  }
@@ -112,16 +118,20 @@ export function createRuntime() {
112
118
  function ensureHttpDispatcher(path, sample) {
113
119
  if (httpDispatchers.has(path) || !dispatchServer || !dispatchOuter) return
114
120
  const dispatcher = {
121
+ // 原样带上样例路由的其余字段(尤其 `auth` 准入策略)——新版宿主按 `auth` 判准入,
122
+ // 漏掉它会被当成 "required",把本该由插件自己 token 守卫的移动端路由挡在网关外。
123
+ ...(sample || {}),
115
124
  kind: sample && sample.kind,
116
125
  path,
117
- handler: async (req, res) => {
126
+ handler: async (...args) => {
127
+ const res = args[1]
118
128
  const live = liveHttp.get(path)
119
129
  if (!live || typeof live.handler !== 'function') {
120
130
  try { res.statusCode = 404 } catch { /* ignore */ }
121
131
  try { res.end && res.end('') } catch { /* ignore */ }
122
132
  return
123
133
  }
124
- return live.handler(req, res)
134
+ return live.handler(...args)
125
135
  },
126
136
  }
127
137
  const unregister = dispatchOuter.call(dispatchServer, wrapInFlight(dispatcher))
@@ -132,13 +142,14 @@ export function createRuntime() {
132
142
  if (upDispatchers.has(path) || !dispatchServer || !dispatchOuterUpgrade) return
133
143
  const dispatcher = {
134
144
  ...(sample || {}),
135
- handler: (req, socket, head) => {
145
+ handler: (...args) => {
146
+ const [, socket] = args
136
147
  const live = liveUp.get(path)
137
148
  if (!live || typeof live.handler !== 'function') {
138
149
  try { if (socket) socket.destroy() } catch { /* ignore */ }
139
150
  return
140
151
  }
141
- return live.handler(req, socket, head)
152
+ return live.handler(...args)
142
153
  },
143
154
  }
144
155
  const unregister = dispatchOuterUpgrade.call(dispatchServer, dispatcher)
@@ -629,10 +640,10 @@ export function createRuntime() {
629
640
  wrapHandler: (route) => {
630
641
  if (!route || typeof route.handler !== 'function') return route
631
642
  const handler = route.handler
632
- route.handler = async (req, res) => {
643
+ route.handler = async (...args) => {
633
644
  inFlight += 1
634
645
  try {
635
- return await handler(req, res)
646
+ return await handler(...args)
636
647
  } finally {
637
648
  inFlight = Math.max(0, inFlight - 1)
638
649
  }
@@ -104,7 +104,7 @@ export function installTransportHosts(ctx) {
104
104
  })
105
105
  try {
106
106
  if (typeof ctx.webServer.registerUpgrade === 'function') {
107
- ctx.effect(() => ctx.webServer.registerUpgrade({ path: '/api/mobile/v1/mux', handler: muxService.handleUpgrade }), 'dsh-mobile-plugin: mux upgrade route')
107
+ ctx.effect(() => ctx.webServer.registerUpgrade({ path: '/api/mobile/v1/mux', handler: muxService.handleUpgrade, auth: 'anonymous' }), 'dsh-mobile-plugin: mux upgrade route')
108
108
  }
109
109
  } catch { /* 宿主没有升级路由能力时这条不挂,App 走 HTTP/SSE 兜底 */ }
110
110
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.99",
3
+ "version": "0.5.101",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",
@@ -1,206 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 审批记忆账:用户按「这一类以后都同意」放行过的动作类别,回在这里记一条。
5
- *
6
- * 为什么单独一本账:审批桥本身的挂起项全在内存里(宿主重启就没了),而「以后都同意」是一种
7
- * 跨会话、跨重启都要生效的持久偏好;它必须落盘,并且**能在 UI 里逐条撤销** —— 撤销权是这条
8
- * 功能成立的前提(用户点错了随时能收回),所以这里提供按 classKey 的删除。
9
- *
10
- * 同一本账还带**最近的拒绝记录**:用户在审批卡上拒掉一条时把理由写下来,设置页的「最近拒绝」
11
- * 一节才有得对账(理由当时只在卡上闪一下,卡一结算就没了)。这份记录只给人看,不参与任何
12
- * 判定,所以只留最近若干条、超了挤掉最老的。
13
- *
14
- * 落盘位置 `<DSH_HOME>/storages/mobile-plugin/approval-rules.json`,照移动端那几份账本的
15
- * 同一套「原子写 + 读坏当空」的边界:账本读不动不能把审批拦在门外,写失败也只影响「重启后
16
- * 还在不在」。`DSH_MOBILE_APPROVAL_RULES` 只给测试注入路径用。
17
- *
18
- * 撤销走的是真删除:写盘失败时 `removeRule` 抛错而非报成功,免得界面划掉后重启规则又回来。
19
- */
20
-
21
- const fs = require('node:fs');
22
- const path = require('node:path');
23
-
24
- const { dshHome } = require('../shared/paths.js');
25
- // 只借一个纯函数判据(删除 / 推送 / 装软件这三类不给「以后都同意」),不反向依赖。
26
- const { isIrreversibleClass } = require('./approval-facts.js');
27
-
28
- const VERSION = 1;
29
- /** 规则条数上限:纯兜底,超了挤掉最老的(规则很小,正常远到不了)。 */
30
- const MAX_RULES = 500;
31
- /** 拒绝记录上限:只是给人对账用的流水,留最近这些就够了。 */
32
- const MAX_DECISIONS = 50;
33
-
34
- function rulesFile() {
35
- return process.env.DSH_MOBILE_APPROVAL_RULES
36
- || path.join(dshHome(), 'storages', 'mobile-plugin', 'approval-rules.json');
37
- }
38
-
39
- function isRecord(value) {
40
- return typeof value === 'object' && value !== null && !Array.isArray(value);
41
- }
42
-
43
- function textOf(value, max) {
44
- if (typeof value !== 'string') return '';
45
- return value.replace(/\s+/g, ' ').trim().slice(0, max);
46
- }
47
-
48
- function normalizeRule(entry) {
49
- if (!isRecord(entry)) return null;
50
- const classKey = textOf(entry.classKey, 200);
51
- if (!classKey) return null;
52
- // 删除 / 推送 / 装软件这三类**永远不认**,读到也当没写过(见 approval-facts 的
53
- // `isIrreversibleClass`):旧版本记下过 `bash:rm`,不清掉的话一次「以后都同意」会继续
54
- // 把任意 `rm` 静默放行。这里在加载口清洗,下一次写盘就把它们从文件里抹掉。
55
- if (isIrreversibleClass(classKey)) return null;
56
- return {
57
- classKey,
58
- label: textOf(entry.label, 120) || classKey,
59
- createdAt: Number.isFinite(entry.createdAt) ? entry.createdAt : Date.now(),
60
- };
61
- }
62
-
63
- function emptyStore() {
64
- return { version: VERSION, updatedAt: 0, rules: [], decisions: [] };
65
- }
66
-
67
- /** 一条拒绝记录:形状不对的丢掉,读坏的文件不能把页面撑炸。 */
68
- function normalizeDecision(entry) {
69
- if (!isRecord(entry)) return null;
70
- const classKey = textOf(entry.classKey, 200);
71
- if (!classKey) return null;
72
- const reason = textOf(entry.reason, 200);
73
- return {
74
- classKey,
75
- reason: reason || undefined,
76
- at: Number.isFinite(entry.at) ? entry.at : Date.now(),
77
- };
78
- }
79
-
80
- /** 读账:文件不存在 / 读坏 / 形状不对一律当空,绝不抛。 */
81
- function readStore() {
82
- let raw;
83
- try {
84
- raw = JSON.parse(fs.readFileSync(rulesFile(), 'utf8'));
85
- } catch {
86
- return emptyStore();
87
- }
88
- if (!isRecord(raw) || !Array.isArray(raw.rules)) return emptyStore();
89
- const rules = [];
90
- for (const entry of raw.rules) {
91
- const rule = normalizeRule(entry);
92
- if (rule) rules.push(rule);
93
- }
94
- const decisions = [];
95
- for (const entry of Array.isArray(raw.decisions) ? raw.decisions : []) {
96
- const decision = normalizeDecision(entry);
97
- if (decision) decisions.push(decision);
98
- }
99
- return {
100
- version: VERSION,
101
- updatedAt: Number.isFinite(raw.updatedAt) ? raw.updatedAt : 0,
102
- rules,
103
- decisions,
104
- };
105
- }
106
-
107
- /** 原子写:先写临时文件再 rename;写失败安静返回 false,不抛。 */
108
- function saveStore(store) {
109
- const file = rulesFile();
110
- let rules = store.rules.slice();
111
- if (rules.length > MAX_RULES) {
112
- rules = rules.sort((a, b) => a.createdAt - b.createdAt).slice(rules.length - MAX_RULES);
113
- }
114
- let decisions = (store.decisions || []).slice();
115
- if (decisions.length > MAX_DECISIONS) decisions = decisions.slice(decisions.length - MAX_DECISIONS);
116
- const next = { ...store, version: VERSION, updatedAt: Date.now(), rules, decisions };
117
- try {
118
- fs.mkdirSync(path.dirname(file), { recursive: true });
119
- const tmp = `${file}.${process.pid}.tmp`;
120
- fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
121
- fs.renameSync(tmp, file);
122
- return true;
123
- } catch {
124
- return false;
125
- }
126
- }
127
-
128
- /** 列出全部规则(给撤销页)。 */
129
- function listRules() {
130
- return readStore().rules.map((rule) => ({ classKey: rule.classKey, label: rule.label }));
131
- }
132
-
133
- /** 这一类是否已被允许。 */
134
- function hasRule(classKey) {
135
- if (!classKey) return false;
136
- return readStore().rules.some((rule) => rule.classKey === classKey);
137
- }
138
-
139
- /** 记一条(已存在则更新 label,不重复)。不可记的类别直接拒(见 `normalizeRule`)。 */
140
- function addRule({ classKey, label }) {
141
- const key = textOf(classKey, 200);
142
- if (!key) return false;
143
- if (isIrreversibleClass(key)) return false;
144
- const store = readStore();
145
- const at = store.rules.findIndex((rule) => rule.classKey === key);
146
- if (at >= 0) {
147
- store.rules[at] = { ...store.rules[at], label: textOf(label, 120) || store.rules[at].label };
148
- } else {
149
- store.rules.push({ classKey: key, label: textOf(label, 120) || key, createdAt: Date.now() });
150
- }
151
- return saveStore(store);
152
- }
153
-
154
- /**
155
- * 撤一条。true = 真删掉并落盘;false = 本来就不在(算成功,结果一样)。
156
- *
157
- * 写盘失败**抛错**,不报「已删掉」:否则界面把这一行划掉、插件一重启规则又回来,用户以为撤销
158
- * 成了。调用方据此回非 ok,手机才保留那一行并提示重试。
159
- */
160
- function removeRule(classKey) {
161
- const key = textOf(classKey, 200);
162
- if (!key) return false;
163
- const store = readStore();
164
- const next = store.rules.filter((rule) => rule.classKey !== key);
165
- if (next.length === store.rules.length) return false;
166
- store.rules = next;
167
- if (!saveStore(store)) throw new Error('审批规则写盘失败');
168
- return true;
169
- }
170
-
171
- /** 最近的拒绝记录(新的在前),给设置页「最近拒绝」那一节。 */
172
- function listDecisions() {
173
- return readStore().decisions
174
- .slice()
175
- .sort((a, b) => b.at - a.at)
176
- .map((decision) => ({
177
- classKey: decision.classKey,
178
- reason: decision.reason,
179
- at: decision.at,
180
- }));
181
- }
182
-
183
- /**
184
- * 记一条拒绝。只给人对账用,不参与任何判定;缺 classKey 就不记(没有类别的行在页面上说不出
185
- * 是哪一类被拒),落盘失败也只影响这一条留不留得下来。
186
- */
187
- function recordDecision({ classKey, reason } = {}) {
188
- const key = textOf(classKey, 200);
189
- if (!key) return false;
190
- const store = readStore();
191
- store.decisions.push({
192
- classKey: key,
193
- reason: textOf(reason, 200) || undefined,
194
- at: Date.now(),
195
- });
196
- return saveStore(store);
197
- }
198
-
199
- module.exports = {
200
- listRules,
201
- hasRule,
202
- addRule,
203
- removeRule,
204
- listDecisions,
205
- recordDecision,
206
- };