@aibyzero/cm-workflow 0.16.8 → 0.17.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.
Files changed (226) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/README.md +22 -3
  4. package/VERSION +1 -1
  5. package/compat/claude-commands/cm-notify.md +3 -0
  6. package/docs/cm-control-policy-v2.md +331 -0
  7. package/docs/execution-optimizations.md +1 -1
  8. package/docs/external-models.md +3 -3
  9. package/docs/human-correction.md +5 -5
  10. package/docs/installation.md +1 -1
  11. package/docs/js-workflow-control.md +119 -78
  12. package/docs/next-steps.md +19 -2
  13. package/docs/untested-branches.md +2 -3
  14. package/docs/user-guide.md +105 -5
  15. package/package.json +2 -1
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  17. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +103 -68
  18. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +79 -27
  19. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  20. package/runtime/js/cm-ai/control-policy.mjs +111 -0
  21. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  22. package/runtime/js/cm-ai/drive-bootstrap.mjs +11 -8
  23. package/runtime/js/cm-ai/drive-core.mjs +9 -0
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +883 -69
  25. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  26. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  27. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  28. package/runtime/js/cm-ai/gate-bridge.mjs +4 -4
  29. package/runtime/js/cm-ai/host-check.mjs +4 -1
  30. package/runtime/js/cm-ai/host-conversation-execution.mjs +33 -24
  31. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  32. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  33. package/runtime/js/cm-ai/host-qa-executor.mjs +49 -4
  34. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +53 -9
  35. package/runtime/js/cm-ai/host-qa-policy.mjs +63 -21
  36. package/runtime/js/cm-ai/host-review-authority.mjs +2 -2
  37. package/runtime/js/cm-ai/host-review-file.mjs +1 -1
  38. package/runtime/js/cm-ai/host-session.mjs +1 -1
  39. package/runtime/js/cm-ai/host-tool-bridge.mjs +43 -3
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +21 -10
  41. package/runtime/js/cm-ai/host.mjs +1 -2
  42. package/runtime/js/cm-ai/operator-guidance.mjs +89 -3
  43. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  44. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  45. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  46. package/runtime/js/cm-ai/review-package.mjs +26 -5
  47. package/runtime/js/cm-ai/reviewed-deliveries.mjs +1 -1
  48. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  49. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  50. package/runtime/js/cm-ai/task-runner.mjs +629 -121
  51. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  52. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  53. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  54. package/runtime/js/cm-fix/execution.mjs +176 -48
  55. package/runtime/js/cm-fix/host.mjs +2 -1
  56. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  57. package/runtime/js/cm-fix/progress.mjs +13 -3
  58. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  59. package/runtime/js/cm-fix/repair.mjs +11 -3
  60. package/runtime/js/cm-fix/test-author.mjs +10 -3
  61. package/runtime/js/cm-idea/session.mjs +67 -4
  62. package/runtime/js/cm-init/review-evidence.mjs +3 -1
  63. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  64. package/runtime/js/cm-prd/review-host.mjs +1 -1
  65. package/runtime/js/cm-prd/review-publication.mjs +5 -3
  66. package/runtime/js/cm-prd/session.mjs +43 -0
  67. package/runtime/js/cm-refactor/records.mjs +98 -8
  68. package/runtime/js/cm-refactor/workflow.mjs +80 -10
  69. package/runtime/js/cm-test/host.mjs +10 -3
  70. package/runtime/js/cm-test/session.mjs +45 -6
  71. package/runtime/js/notify-safe-read.mjs +49 -0
  72. package/runtime/js/notify-send.mjs +313 -0
  73. package/runtime/js/notify.mjs +164 -37
  74. package/runtime/js/policy-binding-compat.mjs +55 -0
  75. package/runtime/review.md +52 -7
  76. package/runtime/task-gates.md +107 -9
  77. package/scripts/ci-test-shards.mjs +67 -0
  78. package/scripts/ci-test-shards.test.mjs +64 -0
  79. package/scripts/ci-test-weights.json +222 -0
  80. package/scripts/cm-ai-abandon-effect-position.test.mjs +71 -10
  81. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  82. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  83. package/scripts/cm-ai-answer-gap-fixture.mjs +89 -0
  84. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  85. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  86. package/scripts/cm-ai-batch-drive.mjs +98 -34
  87. package/scripts/cm-ai-batch-drive.test.mjs +124 -16
  88. package/scripts/cm-ai-batch-host.mjs +167 -29
  89. package/scripts/cm-ai-batch-host.test.mjs +303 -31
  90. package/scripts/cm-ai-batch-run-fixture.mjs +452 -0
  91. package/scripts/cm-ai-batch-run-member-stops.test.mjs +26 -0
  92. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  93. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  94. package/scripts/cm-ai-batch-run.mjs +213 -25
  95. package/scripts/cm-ai-batch-run.test.mjs +21 -341
  96. package/scripts/cm-ai-bootstrap-flow.test.mjs +1 -7
  97. package/scripts/cm-ai-bootstrap.test.mjs +2 -3
  98. package/scripts/cm-ai-control-launch.test.mjs +219 -0
  99. package/scripts/cm-ai-control-policy.test.mjs +124 -0
  100. package/scripts/cm-ai-control-v2-drive.test.mjs +270 -0
  101. package/scripts/cm-ai-develop-answer-invalid.test.mjs +97 -0
  102. package/scripts/cm-ai-develop-call-timeout.test.mjs +146 -0
  103. package/scripts/cm-ai-develop-driver-gaps.test.mjs +37 -23
  104. package/scripts/cm-ai-direct-review.test.mjs +348 -0
  105. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  106. package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +54 -25
  107. package/scripts/cm-ai-drive.mjs +142 -58
  108. package/scripts/cm-ai-drive.test.mjs +70 -84
  109. package/scripts/cm-ai-fix-integration.test.mjs +3 -5
  110. package/scripts/cm-ai-fix-later-delivery.test.mjs +3 -6
  111. package/scripts/cm-ai-fix-run-delivery.test.mjs +3 -6
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +267 -0
  113. package/scripts/cm-ai-host-fixture.mjs +296 -0
  114. package/scripts/cm-ai-host-protected.test.mjs +253 -0
  115. package/scripts/cm-ai-host.mjs +122 -100
  116. package/scripts/cm-ai-host.test.mjs +35 -776
  117. package/scripts/cm-ai-launch-diagnostics.test.mjs +5 -3
  118. package/scripts/cm-ai-legacy-history.test.mjs +53 -0
  119. package/scripts/cm-ai-light-modules.test.mjs +54 -0
  120. package/scripts/cm-ai-multi-root.test.mjs +4 -4
  121. package/scripts/cm-ai-nested-execution.test.mjs +16 -19
  122. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  123. package/scripts/cm-ai-progress.test.mjs +10 -8
  124. package/scripts/cm-ai-project-qa-gate.test.mjs +37 -10
  125. package/scripts/cm-ai-protected-scope.test.mjs +8 -5
  126. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  127. package/scripts/cm-ai-qa-config-revision.test.mjs +1 -9
  128. package/scripts/cm-ai-qa-fingerprint-config.test.mjs +12 -9
  129. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +95 -13
  130. package/scripts/cm-ai-qa-fixed-log.test.mjs +41 -0
  131. package/scripts/cm-ai-qa-recovery-args.test.mjs +7 -0
  132. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +59 -14
  133. package/scripts/cm-ai-review-drift-precedence.test.mjs +1 -1
  134. package/scripts/cm-ai-review-failure.test.mjs +137 -32
  135. package/scripts/cm-ai-review-timeout-config.test.mjs +3 -1
  136. package/scripts/cm-ai-review-timeout.test.mjs +132 -67
  137. package/scripts/cm-ai-run.mjs +91 -28
  138. package/scripts/cm-ai-run.test.mjs +11 -38
  139. package/scripts/cm-ai-selection-guard.test.mjs +2 -2
  140. package/scripts/cm-ai-session-chain.test.mjs +18 -15
  141. package/scripts/cm-ai-spec-rebind.test.mjs +14 -18
  142. package/scripts/cm-ai-supersede.test.mjs +489 -51
  143. package/scripts/cm-blocked-reason.test.mjs +2 -3
  144. package/scripts/cm-capability-gate.test.mjs +33 -1
  145. package/scripts/cm-check-drive-files.mjs +8 -0
  146. package/scripts/cm-check-drive.test.mjs +2 -5
  147. package/scripts/cm-check-runtime.sh +4 -2
  148. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  149. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  150. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  151. package/scripts/cm-claude-worker.test.mjs +23 -5
  152. package/scripts/cm-controlled-correction.test.mjs +469 -0
  153. package/scripts/cm-external-batch-host.test.mjs +30 -11
  154. package/scripts/cm-external-model-host.test.mjs +1 -1
  155. package/scripts/cm-external-model-recovery.test.mjs +32 -12
  156. package/scripts/cm-external-qa-fix.test.mjs +1 -1
  157. package/scripts/cm-external-review-reconciliation.test.mjs +6 -24
  158. package/scripts/cm-fix-abandon.test.mjs +163 -10
  159. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  160. package/scripts/cm-fix-drive.mjs +25 -7
  161. package/scripts/cm-fix-host.mjs +8 -7
  162. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  163. package/scripts/cm-fix-review-recovery.test.mjs +36 -1
  164. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  165. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  166. package/scripts/cm-host-documentation.test.mjs +49 -0
  167. package/scripts/cm-host-qa-executor.test.mjs +23 -12
  168. package/scripts/cm-host-qa-policy.test.mjs +43 -16
  169. package/scripts/cm-host-review-authority.test.mjs +0 -31
  170. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  171. package/scripts/cm-idea-drive.mjs +49 -11
  172. package/scripts/cm-idea-drive.test.mjs +66 -0
  173. package/scripts/cm-idea-host.mjs +106 -16
  174. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  175. package/scripts/cm-init-drive.mjs +41 -7
  176. package/scripts/cm-init-host.mjs +61 -12
  177. package/scripts/cm-knowledge-closeout.test.mjs +3 -3
  178. package/scripts/cm-log-event.mjs +21 -10
  179. package/scripts/cm-notify-command.test.mjs +936 -0
  180. package/scripts/cm-notify-read-drift.test.mjs +270 -0
  181. package/scripts/cm-notify.mjs +481 -0
  182. package/scripts/cm-notify.test.mjs +312 -23
  183. package/scripts/cm-patrol.test.mjs +3 -2
  184. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  185. package/scripts/cm-prd-drive.mjs +18 -5
  186. package/scripts/cm-prd-drive.test.mjs +15 -0
  187. package/scripts/cm-prd-host.mjs +37 -4
  188. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  189. package/scripts/cm-prd-review-gate.mjs +56 -0
  190. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  191. package/scripts/cm-refactor-drive.mjs +52 -8
  192. package/scripts/cm-refactor-drive.test.mjs +44 -0
  193. package/scripts/cm-refactor-host.test.mjs +10 -6
  194. package/scripts/cm-release-smoke.sh +2 -0
  195. package/scripts/cm-task-gate-correction.test.mjs +69 -16
  196. package/scripts/cm-task-gate.mjs +368 -34
  197. package/scripts/cm-task-gate.py +2 -0
  198. package/scripts/cm-task-gate.test.mjs +252 -4
  199. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  200. package/scripts/cm-test-drive.mjs +21 -5
  201. package/scripts/fixtures/bootstrap-review-runner.mjs +1 -7
  202. package/scripts/fixtures/claude-review-process.mjs +1 -1
  203. package/scripts/fixtures/native-gate-fixture.mjs +18 -0
  204. package/scripts/policy-binding-compat.test.mjs +103 -0
  205. package/scripts/scan-public-safety.py +4 -0
  206. package/scripts/validate-public-repo.py +4 -0
  207. package/skills/cm-ai/SKILL.md +8 -6
  208. package/skills/cm-ai/references/N3-execute-task.md +17 -2
  209. package/skills/cm-ai/references/N4-review.md +11 -21
  210. package/skills/cm-ai/references/N5-mark-done.md +1 -1
  211. package/skills/cm-ai/references/N6-qa-eval.md +49 -21
  212. package/skills/cm-ai/references/js-host-modes.md +35 -14
  213. package/skills/cm-ai/references/js-host-qa-recovery.md +85 -11
  214. package/skills/cm-ai/references/js-host-recovery.md +181 -21
  215. package/skills/cm-ai/references/js-host.md +76 -32
  216. package/skills/cm-check/SKILL.md +3 -3
  217. package/skills/cm-fix/SKILL.md +12 -0
  218. package/skills/cm-fix/references/js-host.md +44 -5
  219. package/skills/cm-idea/references/js-host.md +27 -2
  220. package/skills/cm-init/references/js-host.md +17 -4
  221. package/skills/cm-notify/SKILL.md +34 -0
  222. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  223. package/skills/cm-prd/references/js-host.md +1 -1
  224. package/skills/cm-refactor/SKILL.md +12 -0
  225. package/skills/cm-refactor/references/js-host.md +17 -0
  226. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,936 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import fsp from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import http from 'node:http';
8
+ import {PassThrough} from 'node:stream';
9
+ import {performance} from 'node:perf_hooks';
10
+ import {spawnSync} from 'node:child_process';
11
+ import {fileURLToPath} from 'node:url';
12
+ import {parseAssignments,readPrivateFile,readSecret,runSender,responseCodeType,readRegularFile,entryDecision,WINDOWS_UNSUPPORTED,SEND_EXIT} from '../runtime/js/notify-send.mjs';
13
+ import {main,notifyStatus,switchChannel,turnOff,sendTest,formatTest,previewText,formatPreview,managedSenderPath,classifyCommand,SENDER_SOURCE,TEMPLATES} from './cm-notify.mjs';
14
+
15
+ // Every test works in its own temp CM_WORKFLOW_HOME / log home / HOME: the
16
+ // real ~/.cm-workflow/notify.json would push to the user's phone.
17
+ const BARK_SECRET='FakeBarkKey123456',OTHER_BARK_SECRET='OtherKey12345',PUSH_SECRET='FakePushplusToken789'; // gitleaks:allow 测试用合成假值,不是真实密钥
18
+ const CLI=fileURLToPath(new URL('./cm-notify.mjs',import.meta.url));
19
+ const posix=process.platform!=='win32';
20
+ function sandbox(t){
21
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-cmd-')));
22
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
23
+ const home=path.join(root,'cm-home');fs.mkdirSync(home,{mode:0o700});
24
+ const env={...process.env,CM_WORKFLOW_HOME:home,CM_WORKFLOW_LOG_HOME:path.join(root,'logs'),HOME:path.join(root,'user'),USERPROFILE:path.join(root,'user')};
25
+ delete env.CM_NOTIFY_DRY_RUN;delete env.HTTPS_PROXY;delete env.https_proxy;
26
+ const write=(name,text,mode=0o600)=>{const file=path.join(home,name);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,text,{mode});fs.chmodSync(file,mode);return file;};
27
+ const read=name=>fs.readFileSync(path.join(home,name),'utf8');
28
+ const exists=name=>fs.existsSync(path.join(home,name));
29
+ const snapshot=()=>{
30
+ const out={};
31
+ const walk=dir=>{for(const entry of fs.readdirSync(dir,{withFileTypes:true})){
32
+ const file=path.join(dir,entry.name);
33
+ if(entry.isDirectory())walk(file);else out[path.relative(home,file)]=fs.readFileSync(file).toString('base64');
34
+ }};
35
+ walk(home);return out;
36
+ };
37
+ const cli=(args,extra={})=>spawnSync(process.execPath,[CLI,...args],{encoding:'utf8',env:{...env,...extra},timeout:30000});
38
+ const log=()=>exists('notify.log')?read('notify.log'):'';
39
+ return {root,home,env,write,read,exists,snapshot,cli,log};
40
+ }
41
+ const noSecret=(text,label='output')=>{for(const secret of [BARK_SECRET,PUSH_SECRET])assert(!String(text).includes(secret),`${label} leaks a secret`);};
42
+ const sink=()=>{let text='';return {stream:{write:chunk=>{text+=chunk;return true;}},text:()=>text};};
43
+ const endedStdin=(line='{"title":"x"}\n')=>{const s=new PassThrough();s.end(line);return s;};
44
+
45
+ // Loopback server standing in for Bark/pushplus. `request` rewrites the
46
+ // target host to it; this injection exists only in the module API.
47
+ async function fakeServer(t,handler){
48
+ const seen=[];
49
+ const server=http.createServer((req,res)=>{let body='';req.on('data',c=>body+=c);req.on('end',()=>{seen.push({method:req.method,url:req.url,headers:req.headers,body});handler(req,res,body);});});
50
+ await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
51
+ t.after(()=>{server.closeAllConnections?.();server.close();});
52
+ const port=server.address().port,targets=[];
53
+ const request=(options,callback)=>{targets.push({hostname:options.hostname,path:options.path,rejectUnauthorized:options.rejectUnauthorized});
54
+ return http.request({...options,hostname:'127.0.0.1',port},callback);};
55
+ return {seen,targets,request,port};
56
+ }
57
+ const json=(res,status,value)=>{res.writeHead(status,{'Content-Type':'application/json'});res.end(typeof value==='string'?value:JSON.stringify(value));};
58
+
59
+ test('secret files parse strictly as data and errors name the line, never the value',()=>{
60
+ const ok=parseAssignments(`# 注释\n\nexport BARK_KEY="${BARK_SECRET}"\n BARK_SERVER='https://bark.example.com' \n`,['BARK_KEY','BARK_SERVER'],'bark.env');
61
+ assert.deepEqual(ok.values,{BARK_KEY:BARK_SECRET,BARK_SERVER:'https://bark.example.com'});
62
+ assert.deepEqual(ok.lines,{BARK_KEY:3,BARK_SERVER:4});
63
+ assert.equal(parseAssignments(`BARK_KEY="${BARK_SECRET}'\n`,['BARK_KEY'],'b').values.BARK_KEY,`"${BARK_SECRET}'`,'unmatched quotes are kept');
64
+ for(const [text,line] of [[`BARK_KEY=${BARK_SECRET}\nBARK_KEY=${BARK_SECRET}\n`,2],[`OTHER=${BARK_SECRET}\n`,1],
65
+ [`# c\n${BARK_SECRET}\n`,2],[`$(echo ${BARK_SECRET})=1\n`,1],[`=x\n`,1]]){
66
+ assert.throws(()=>parseAssignments(text,['BARK_KEY','BARK_SERVER'],'bark.env'),error=>{
67
+ assert.equal(error.exit,SEND_EXIT.config);assert.equal(error.detail.line,line);
68
+ assert.match(error.message,new RegExp(`bark.env 第 ${line} 行`));noSecret(error.message);return true;});
69
+ }
70
+ });
71
+
72
+ test('secret files must be private regular files with mode 600 on POSIX',{skip:!posix},async t=>{
73
+ const s=sandbox(t);
74
+ const file=s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`,0o644);
75
+ await assert.rejects(()=>readPrivateFile(file,'bark.env'),/必须是自己的普通文件且权限 600/);
76
+ await assert.rejects(()=>readPrivateFile(file,'bark.env',{platform:'win32'}),error=>error.message===WINDOWS_UNSUPPORTED,'Windows is refused, never trusted');
77
+ fs.chmodSync(file,0o600);assert.equal(await readPrivateFile(file,'bark.env'),`BARK_KEY=${BARK_SECRET}\n`);
78
+ const link=path.join(s.home,'pushplus.env');fs.symlinkSync(file,link);
79
+ await assert.rejects(()=>readPrivateFile(link,'pushplus.env'),/普通文件/);
80
+ s.write('big.env','#'.repeat(70*1024));await assert.rejects(()=>readPrivateFile(path.join(s.home,'big.env'),'big.env'),/太大/);
81
+ fs.writeFileSync(path.join(s.home,'bad.env'),Buffer.from([0x42,0xff,0xfe]),{mode:0o600});
82
+ await assert.rejects(()=>readPrivateFile(path.join(s.home,'bad.env'),'bad.env'),/读取 bad.env 失败/);
83
+ });
84
+
85
+ test('secret values are validated per channel with file and line in the message',async t=>{
86
+ const s=sandbox(t);
87
+ const cases=[
88
+ ['bark',`BARK_KEY=\n`,'empty',/bark.env 第 1 行 BARK_KEY 未填写/],
89
+ ['bark',`# only comments\n`,'empty',/bark.env BARK_KEY 未填写/],
90
+ ['bark',`BARK_KEY=short\n`,'invalid',/第 1 行 BARK_KEY 格式不对/],
91
+ ['bark',`BARK_KEY=${'a1'.repeat(32)}\n`,'invalid',/Device Token/],
92
+ ['bark',`BARK_KEY=${BARK_SECRET}\nBARK_SERVER=http://bark.example.com\n`,'invalid',/第 2 行 BARK_SERVER 必须是不带路径的 https 地址/],
93
+ ['bark',`BARK_KEY=${BARK_SECRET}\nBARK_SERVER=https://bark.example.com/path\n`,'invalid',/第 2 行 BARK_SERVER/],
94
+ ['pushplus',`PUSHPLUS_TOKEN=''\n`,'empty',/pushplus.env 第 1 行 PUSHPLUS_TOKEN 未填写/],
95
+ ['pushplus',`PUSHPLUS_TOKEN=has-dash-${PUSH_SECRET}\n`,'invalid',/PUSHPLUS_TOKEN 格式不对/],
96
+ ];
97
+ for(const [channel,text,state,pattern] of cases){
98
+ s.write(`${channel}.env`,text);
99
+ await assert.rejects(()=>readSecret(s.home,channel),error=>{assert.equal(error.detail.state,state,text);assert.match(error.message,pattern);noSecret(error.message);return true;});
100
+ }
101
+ fs.rmSync(path.join(s.home,'bark.env'));
102
+ await assert.rejects(()=>readSecret(s.home,'bark'),error=>error.detail.state==='missing');
103
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
104
+ assert.deepEqual(await readSecret(s.home,'bark'),{key:BARK_SECRET,server:'https://api.day.app'});
105
+ });
106
+
107
+ test('success needs HTTP 200 and a numeric JSON code 200',()=>{
108
+ assert.deepEqual(responseCodeType('{"code":200}'),{ok:true,type:'number'});
109
+ for(const [raw,type] of [['{"code":"200"}','string'],['{"code":true}','boolean'],['{"code":null}','null'],['{"msg":1}','missing'],['oops','not_json'],['[200]','missing'],['{"code":[200]}','array']])
110
+ assert.deepEqual(responseCodeType(raw),{ok:false,type},raw);
111
+ });
112
+
113
+ test('dry-run reads no secret and touches no network',async t=>{
114
+ const s=sandbox(t);s.write('notify-channel.conf','CHANNEL=pushplus\n');
115
+ const out=sink(),err=sink();
116
+ const code=await runSender({env:{...s.env,CM_NOTIFY_DRY_RUN:'1',CM_NOTIFY_TITLE:'标题',CM_NOTIFY_BODY:'正文'},home:s.home,stdin:endedStdin(),
117
+ stdout:out.stream,stderr:err.stream,request:()=>{throw new Error('network used');}});
118
+ assert.equal(code,0,err.text());
119
+ assert.equal(out.text(),`POST https://www.pushplus.plus/send\n${JSON.stringify({token:'<已隐藏>',title:'标题',content:'正文',template:'txt',channel:'wechat'})}\n`);
120
+ assert(!s.exists('pushplus.env'));
121
+ });
122
+
123
+ test('bark and pushplus requests: fields, numeric code check, rejected responses never echo values',async t=>{
124
+ const s=sandbox(t);
125
+ s.write('notify-channel.conf','CHANNEL=bark\n');
126
+ let reply=(req,res)=>json(res,200,{code:200,message:'success'});
127
+ const server=await fakeServer(t,(req,res,body)=>reply(req,res,body));
128
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\nBARK_SERVER=https://bark.example.com:8443\n`);
129
+ const run=async(env={})=>{const out=sink(),err=sink();
130
+ const code=await runSender({env:{...s.env,CM_NOTIFY_TITLE:'t'.repeat(150),CM_NOTIFY_BODY:'正文',...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,request:server.request});
131
+ noSecret(out.text()+err.text());return {code,out:out.text(),err:err.text()};};
132
+ let result=await run();
133
+ assert.equal(result.code,0,result.err);
134
+ assert.deepEqual(server.targets.at(-1),{hostname:'bark.example.com',path:'/push',rejectUnauthorized:true});
135
+ assert.deepEqual(JSON.parse(server.seen.at(-1).body),{device_key:BARK_SECRET,title:'t'.repeat(100),body:'正文',group:'CM',level:'active'});
136
+ assert.match(server.seen.at(-1).headers['content-type'],/application\/json/);
137
+ for(const [status,body,type] of [[200,{code:'200',echo:BARK_SECRET},'string'],[200,{code:true},'boolean'],[500,{code:200},'number'],
138
+ [200,`{"code":400,"msg":"${BARK_SECRET}"}`,'number'],[200,'not json '+BARK_SECRET,'not_json']]){
139
+ reply=(req,res)=>json(res,status,body);
140
+ result=await run();
141
+ assert.equal(result.code,SEND_EXIT.rejected,JSON.stringify(body));
142
+ assert.equal(result.err,`cm-notify: bark 推送返回 http=${status} code类型=${type}\n`);
143
+ }
144
+ // Redirects are not followed: one request, rejected.
145
+ const before=server.seen.length;
146
+ reply=(req,res)=>{res.writeHead(302,{Location:'https://evil.example/steal'});res.end();};
147
+ result=await run();
148
+ assert.equal(result.code,SEND_EXIT.rejected);assert.match(result.err,/http=302/);assert.equal(server.seen.length,before+1);
149
+ reply=(req,res)=>{res.writeHead(200);res.end('x'.repeat(70*1024));};
150
+ result=await run();assert.equal(result.code,SEND_EXIT.rejected);assert.match(result.err,/响应过大/);
151
+ // pushplus goes to the fixed endpoint with its own fields.
152
+ s.write('notify-channel.conf','CHANNEL=pushplus\n');s.write('pushplus.env',`PUSHPLUS_TOKEN=${PUSH_SECRET}\n`);
153
+ reply=(req,res)=>json(res,200,{code:200});
154
+ result=await run();
155
+ assert.equal(result.code,0,result.err);
156
+ assert.deepEqual(server.targets.at(-1),{hostname:'www.pushplus.plus',path:'/send',rejectUnauthorized:true});
157
+ assert.deepEqual(JSON.parse(server.seen.at(-1).body),{token:PUSH_SECRET,title:'t'.repeat(100),content:'正文',template:'txt',channel:'wechat'});
158
+ });
159
+
160
+ test('network failure exits 3, the deadline (also while waiting on stdin) 5 and unexpected errors 6, without details',async t=>{
161
+ const s=sandbox(t);
162
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
163
+ const server=await fakeServer(t,()=>{});// never answers
164
+ let err=sink();
165
+ let code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,request:server.request,deadlineMs:300});
166
+ assert.equal(code,SEND_EXIT.deadline);assert.equal(err.text(),'cm-notify: 整次调用超过 1 秒,已放弃\n');
167
+ err=sink();const silent=new PassThrough();t.after(()=>silent.destroy());
168
+ const started=process.hrtime.bigint();
169
+ code=await runSender({env:s.env,home:s.home,stdin:silent,stdout:sink().stream,stderr:err.stream,request:()=>{throw new Error('must not send');},deadlineMs:200});
170
+ assert.equal(code,SEND_EXIT.deadline);assert.match(err.text(),/整次调用超过/);
171
+ assert(Number(process.hrtime.bigint()-started)/1e6<2000);
172
+ // A line without EOF is enough: the sender does not wait for the stream to end.
173
+ const open=new PassThrough();open.write('{"title":"x"}\n');t.after(()=>open.destroy());
174
+ code=await runSender({env:{...s.env,CM_NOTIFY_DRY_RUN:'1'},home:s.home,stdin:open,stdout:sink().stream,stderr:sink().stream,deadlineMs:2000});
175
+ assert.equal(code,0);
176
+ err=sink();
177
+ code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,request:()=>{throw new Error(`boom ${BARK_SECRET}`);}});
178
+ assert.equal(code,SEND_EXIT.unexpected);assert.equal(err.text(),'cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n');
179
+ err=sink();
180
+ code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream,
181
+ request:(options,callback)=>http.request({...options,hostname:'127.0.0.1',port:1},callback)});
182
+ assert.equal(code,SEND_EXIT.network);assert.equal(err.text(),'cm-notify: bark 网络请求失败\n');
183
+ });
184
+
185
+ const [major,minor]=process.versions.node.split('.').map(Number);
186
+ test('HTTPS_PROXY is honoured through a CONNECT tunnel on Node 24.5+',{skip:!(major>24||(major===24&&minor>=5))},async t=>{
187
+ const s=sandbox(t);s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
188
+ const connects=[];
189
+ const proxy=http.createServer();proxy.on('connect',(req,socket)=>{connects.push(req.url);socket.destroy();});
190
+ await new Promise(resolve=>proxy.listen(0,'127.0.0.1',resolve));t.after(()=>proxy.close());
191
+ const err=sink(),proxyPort=proxy.address().port;
192
+ const code=await runSender({env:{...s.env,HTTPS_PROXY:`http://127.0.0.1:${proxyPort}`},home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:err.stream});
193
+ assert.equal(code,SEND_EXIT.network);assert.deepEqual(connects,['api.day.app:443']);noSecret(err.text());
194
+ });
195
+
196
+ test('the sender runs as a standalone copy: config problems exit 2, dry-run exit 0',t=>{
197
+ const s=sandbox(t);
198
+ const copy=path.join(s.root,'elsewhere','cm-notify-send.mjs');fs.mkdirSync(path.dirname(copy));fs.copyFileSync(SENDER_SOURCE,copy);
199
+ const run=extra=>spawnSync(process.execPath,[copy],{input:'{"title":"x"}\n',encoding:'utf8',env:{...s.env,...extra},timeout:20000});
200
+ let result=run({});assert.equal(result.status,2);assert.equal(result.stderr,'cm-notify: 读不到 notify-channel.conf\n');
201
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
202
+ result=run({CM_NOTIFY_DRY_RUN:'1'});assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/^POST https:\/\/api.day.app\/push\n/);noSecret(result.stdout);
203
+ result=spawnSync(process.execPath,[copy,'--check'],{input:'',encoding:'utf8',env:s.env,timeout:20000});
204
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stdout,'cm-notify: 渠道 bark 配置可解析(未发送)\n');
205
+ s.write('bark.env','BARK_KEY=\n');result=run({});assert.equal(result.status,2);assert.match(result.stderr,/bark.env 第 1 行 BARK_KEY 未填写/);
206
+ });
207
+
208
+ test('status shows each channel as missing, empty, malformed or filled, marks the active one, never a value',async t=>{
209
+ const s=sandbox(t);
210
+ let status=(await notifyStatus(s.home));
211
+ assert.equal(status.active,null);assert.equal(status.config.state,'missing');
212
+ assert.deepEqual([status.channels.bark.state,status.channels.pushplus.state],['missing','missing']);
213
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('pushplus.env','PUSHPLUS_TOKEN=\n');
214
+ {
215
+ assert.equal(s.cli(['bark']).status,0);
216
+ let result=s.cli([]);
217
+ assert.equal(result.status,0,result.stderr);
218
+ assert.match(result.stdout,/发送命令:CM 托管发送器/);
219
+ assert.match(result.stdout,/当前渠道:bark(生效中)/);
220
+ assert.match(result.stdout,/渠道 bark[当前]:已填写,可解析/);
221
+ assert.match(result.stdout,new RegExp(`渠道 pushplus:未填写 — .*pushplus.env\\n 请在 .*pushplus.env 第 1 行 PUSHPLUS_TOKEN= 后面填写`));
222
+ noSecret(result.stdout+result.stderr);
223
+ s.write('pushplus.env',`PUSHPLUS_TOKEN=${PUSH_SECRET}\nEXTRA=1\n`);
224
+ result=s.cli(['status','--json']);const parsed=JSON.parse(result.stdout);
225
+ assert.equal(parsed.active,'bark');assert.equal(parsed.channels.pushplus.state,'invalid');assert.equal(parsed.channels.pushplus.line,2);
226
+ noSecret(result.stdout);
227
+ if(posix){
228
+ fs.chmodSync(path.join(s.home,'bark.env'),0o644);
229
+ result=s.cli([]);assert.match(result.stdout,/渠道 bark[当前]:格式不对/);assert.match(result.stdout,/chmod 600/);noSecret(result.stdout);
230
+ }
231
+ assert.equal(s.log(),'','status writes nothing, not even notify.log');
232
+ }
233
+ });
234
+
235
+ test('switching refuses an unfilled or malformed target and leaves every existing file unchanged',t=>{
236
+ const s=sandbox(t);
237
+ s.write('notify.json',JSON.stringify({version:1,command:['/bin/echo','custom'],waitMinutes:7}));
238
+ s.write('notify-channel.conf','CHANNEL=bark\n');
239
+ let before=s.snapshot();
240
+ let result=s.cli(['pushplus']);
241
+ assert.equal(result.status,2);
242
+ assert.match(result.stderr,/没有切换到 pushplus,原有设置都没动:未填写(文件不存在)。已新建空模板 .*pushplus.env(权限 600)。请在 .*pushplus.env 第 3 行 PUSHPLUS_TOKEN= 后面填写/);
243
+ const after=s.snapshot();
244
+ assert.equal(after['pushplus.env'],Buffer.from(TEMPLATES.pushplus.text).toString('base64'),'only the missing template is new');
245
+ delete after['pushplus.env'];assert.deepEqual(after,before);
246
+ if(posix)assert.equal(fs.statSync(path.join(s.home,'pushplus.env')).mode&0o777,0o600);
247
+ assert.equal(TEMPLATES.pushplus.text.split('\n')[TEMPLATES.pushplus.line-1],'PUSHPLUS_TOKEN=');
248
+ assert.equal(TEMPLATES.bark.text.split('\n')[TEMPLATES.bark.line-1],'BARK_KEY=');
249
+ before=s.snapshot();
250
+ result=s.cli(['pushplus']);
251
+ assert.equal(result.status,2);assert.match(result.stderr,/未填写。请在 .*pushplus.env 第 3 行 PUSHPLUS_TOKEN= 后面填写/);
252
+ assert.deepEqual(s.snapshot(),before);
253
+ s.write('pushplus.env',`# x\nPUSHPLUS_TOKEN=${PUSH_SECRET}\nPUSHPLUS_TOKEN=${PUSH_SECRET}\n`);before=s.snapshot();
254
+ result=s.cli(['pushplus']);
255
+ assert.equal(result.status,2);assert.match(result.stderr,/格式不对。pushplus.env 第 3 行无法识别或重复;请打开 .*pushplus.env 第 3 行修正/);
256
+ assert.deepEqual(s.snapshot(),before);noSecret(result.stderr);
257
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('notify.json','{not json');before=s.snapshot();
258
+ result=s.cli(['bark']);assert.equal(result.status,2);assert.match(result.stderr,/不是有效 JSON/);assert.deepEqual(s.snapshot(),before);
259
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,managedSenderPath(s.home)],waitMinutes:0}));before=s.snapshot();
260
+ result=s.cli(['bark']);assert.equal(result.status,2);assert.match(result.stderr,/其他字段无效(wait_minutes)/);assert.deepEqual(s.snapshot(),before);
261
+ assert.equal(s.cli(['bark','extra']).status,2);assert.equal(s.cli(['--nope']).status,2);
262
+ });
263
+
264
+ test('a custom notify.json command is never overwritten silently; --replace-custom backs it up first',t=>{
265
+ const s=sandbox(t);
266
+ const original=JSON.stringify({version:1,command:['/usr/local/bin/my-notify','--flag'],waitMinutes:12,idleMinutes:30,note:'keep'});
267
+ s.write('notify.json',original);s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
268
+ const before=s.snapshot();
269
+ let result=s.cli(['bark']);
270
+ assert.equal(result.status,2);assert.match(result.stderr,/你自己配置的提醒命令,cm-notify 不会静默覆盖.*--replace-custom/);
271
+ assert.deepEqual(s.snapshot(),before);
272
+ assert.match(s.cli([]).stdout,/发送命令:自定义命令/);
273
+ result=s.cli(['bark','--replace-custom']);
274
+ assert.equal(result.status,0,result.stderr);
275
+ const backups=fs.readdirSync(s.home).filter(name=>name.startsWith('notify.json.bak-'));
276
+ assert.equal(backups.length,1);assert.equal(s.read(backups[0]),original);
277
+ const next=JSON.parse(s.read('notify.json'));
278
+ assert.deepEqual(next,{version:1,command:[process.execPath,managedSenderPath(s.home)],waitMinutes:12,idleMinutes:30,note:'keep'});
279
+ assert.equal(s.read('notify-channel.conf').trim().split('\n').at(-1),'CHANNEL=bark');
280
+ assert(fs.readFileSync(managedSenderPath(s.home)).equals(fs.readFileSync(SENDER_SOURCE)));
281
+ });
282
+
283
+ test('the legacy private cm-notify.py layout is recognised and migrated with a backup; its files keep working',t=>{
284
+ const s=sandbox(t);
285
+ const legacy=s.write('cm-notify.py','#!/usr/bin/python3 -I\n# private\n',0o700);
286
+ const original=JSON.stringify({version:1,command:[legacy],waitMinutes:10});
287
+ s.write('notify.json',original);s.write('notify-channel.conf','# 本机\nCHANNEL=bark\n');
288
+ s.write('bark.env',`export BARK_KEY='${BARK_SECRET}'\n`);s.write('pushplus.env',`PUSHPLUS_TOKEN=${PUSH_SECRET}\n`);
289
+ let result=s.cli([]);
290
+ assert.match(result.stdout,/旧版本机脚本 cm-notify.py/);assert.match(result.stdout,/当前渠道:bark(生效中)/);
291
+ result=s.cli(['pushplus']);
292
+ assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/原 cm-notify.py 未改动/);
293
+ assert.equal(fs.readFileSync(legacy,'utf8'),'#!/usr/bin/python3 -I\n# private\n');
294
+ assert.deepEqual(JSON.parse(s.read('notify.json')).command,[process.execPath,managedSenderPath(s.home)]);
295
+ assert.equal(JSON.parse(s.read('notify.json')).waitMinutes,10);
296
+ assert.equal(s.read(fs.readdirSync(s.home).find(name=>name.startsWith('notify.json.bak-'))),original);
297
+ const check=spawnSync(process.execPath,[managedSenderPath(s.home),'--check'],{input:'',encoding:'utf8',env:s.env});
298
+ assert.equal(check.status,0,check.stderr);assert.match(check.stdout,/渠道 pushplus 配置可解析/);
299
+ result=s.cli(['bark']);assert.equal(result.status,0);
300
+ assert.equal(fs.readdirSync(s.home).filter(name=>name.startsWith('notify.json.bak-')).length,1,'managed → managed needs no backup');
301
+ });
302
+
303
+ test('off moves notify.json aside; switching back restores its other fields',t=>{
304
+ const s=sandbox(t);
305
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
306
+ assert.equal(s.cli(['off']).stdout.trim(),'提醒本来就没有开启,什么都没改。');
307
+ assert.equal(s.cli(['bark']).status,0);
308
+ const config=JSON.parse(s.read('notify.json'));config.waitMinutes=20;s.write('notify.json',JSON.stringify(config));
309
+ let result=s.cli(['off']);assert.equal(result.status,0);
310
+ assert(!s.exists('notify.json'));assert(s.exists('notify.off.json'));
311
+ assert.match(s.cli([]).stdout,/发送命令:已关闭/);
312
+ assert.equal(s.cli(['test']).status,2);
313
+ result=s.cli(['bark']);assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/已从 notify.off.json 恢复/);
314
+ assert(!s.exists('notify.off.json'));assert.equal(JSON.parse(s.read('notify.json')).waitMinutes,20);
315
+ assert.equal(turnOff(s.home).changed,true);
316
+ });
317
+
318
+ test('test refuses when the active secret is not filled and never runs the sender',t=>{
319
+ const s=sandbox(t);
320
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);assert.equal(s.cli(['bark']).status,0);
321
+ s.write('bark.env','BARK_KEY=\n');
322
+ let result=s.cli(['test']);
323
+ assert.equal(result.status,2);assert.match(result.stderr,/没有发送:当前渠道 bark 未填写。请在 .*bark.env 第 1 行 BARK_KEY= 后面填写/);
324
+ s.write('bark.env','BARK_KEY=bad!\n');
325
+ result=s.cli(['test']);assert.equal(result.status,2);assert.match(result.stderr,/没有发送:当前渠道 bark 格式不对/);
326
+ fs.rmSync(path.join(s.home,'bark.env'));
327
+ result=s.cli(['test']);assert.equal(result.status,2);assert.match(result.stderr,/未填写(文件不存在)/);
328
+ assert.equal(s.log(),'','the sender was never started');
329
+ });
330
+
331
+ test('test goes through the configured command, bypasses dedupe/limits, and reports only the exit code',async t=>{
332
+ const s=sandbox(t);
333
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`+'BARK_SERVER=https://127.0.0.1:1'+'\n');assert.equal(s.cli(['bark']).status,0);
334
+ let result=s.cli(['test'],{CM_NOTIFY_DRY_RUN:'1'});
335
+ assert.equal(result.status,0,result.stderr);
336
+ assert.match(result.stdout,/^渠道 bark:演练模式(CM_NOTIFY_DRY_RUN=1),没有运行发送命令、没有联网,也没有读取或检查密钥文件(是否填好请用 \/cm:notify 查看);下面是按渠道设置生成的脱敏请求。\nPOST https:\/\/api.day.app\/push\n/);
337
+ assert.match(result.stdout,/"device_key":"<已隐藏>","title":"CM 测试推送"/);noSecret(result.stdout);
338
+ assert.equal(s.log(),'','dry-run runs nothing');
339
+ result=s.cli(['test']);// real sender, loopback port 1: refused connection, no external network
340
+ assert.equal(result.status,SEND_EXIT.network,result.stderr);
341
+ assert.equal(result.stdout,'渠道 bark:退出码 3,网络请求失败。\n');
342
+ noSecret(result.stdout+result.stderr);noSecret(s.log(),'notify.log');
343
+ assert.match(s.log(),/test cm-notify key=- test failed exit_3/);
344
+ // A custom command receives the same contract as the runtime launcher.
345
+ const record=path.join(s.root,'record.json'),script=path.join(s.root,'fake.mjs');
346
+ fs.writeFileSync(script,`import fs from 'node:fs';let input='';process.stdin.on('data',c=>input+=c);process.stdin.on('end',()=>{
347
+ fs.writeFileSync(${JSON.stringify(record)},JSON.stringify({title:process.env.CM_NOTIFY_TITLE,body:process.env.CM_NOTIFY_BODY,stdin:input}));
348
+ process.stderr.write('custom says ${BARK_SECRET}');});`);
349
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,script]}));
350
+ for(let round=0;round<6;round++){result=s.cli(['test']);assert.equal(result.status,0,result.stderr);}
351
+ assert.equal(result.stdout,'自定义命令:退出码 0,已被推送服务接受(不代表已送达)。\n');noSecret(result.stdout+result.stderr,'custom output is not shown');
352
+ const seen=JSON.parse(fs.readFileSync(record,'utf8'));
353
+ assert.equal(seen.title,'CM 测试推送');assert.match(seen.body,/^这是 \/cm:notify test 发出的测试消息。\n时间:\d\d:\d\d$/);
354
+ assert.deepEqual(JSON.parse(seen.stdin),{title:seen.title,body:seen.body,event:'test',workflow:'cm-notify'});assert(seen.stdin.endsWith('\n'));
355
+ assert(!s.exists('notify-state.json'),'test pushes are not deduped or counted');
356
+ const slow=path.join(s.root,'slow.mjs');fs.writeFileSync(slow,'setTimeout(()=>{},60000);');
357
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,slow]}));
358
+ const timed=await sendTest(s.home,{env:s.env,timeoutMs:300});
359
+ assert.deepEqual([timed.exit,timed.reason],[null,'timeout']);
360
+ });
361
+
362
+ test('switch writes everything or nothing, and the CLI refuses the real home under node --test',async t=>{
363
+ const s=sandbox(t);
364
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('notify-channel.conf','CHANNEL=pushplus\n');
365
+ const before=s.snapshot();
366
+ await assert.rejects(()=>switchChannel(s.home,'bark',{senderSource:path.join(s.root,'missing.mjs')}),/找不到发送器/);
367
+ assert.deepEqual(s.snapshot(),before);
368
+ if(posix){
369
+ fs.mkdirSync(path.join(s.home,'notify'));fs.symlinkSync(path.join(s.root,'x'),managedSenderPath(s.home));
370
+ await assert.rejects(()=>switchChannel(s.home,'bark'),/不是普通文件/);
371
+ fs.rmSync(path.join(s.home,'notify'),{recursive:true});
372
+ assert.deepEqual(s.snapshot(),before);
373
+ }
374
+ const env={...process.env,NODE_TEST_CONTEXT:'child'};delete env.CM_WORKFLOW_HOME;
375
+ const err=sink();
376
+ assert.equal(await main(['status'],{env,stdout:sink().stream,stderr:err.stream}),2);
377
+ assert.match(err.text(),/必须设置 CM_WORKFLOW_HOME/);
378
+ });
379
+
380
+ test('only the exact command shape counts as managed or legacy; look-alikes are custom and protected',t=>{
381
+ const s=sandbox(t);
382
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
383
+ const sender=managedSenderPath(s.home),legacy=path.join(s.home,'cm-notify.py');
384
+ for(const command of [['/bin/echo',sender],[process.execPath,sender,'--extra'],['node',sender],[path.join(s.root,'nodejs'),sender],
385
+ [process.execPath,path.join(s.home,'notify','other.mjs')],['/usr/bin/python3',legacy],[legacy,'--flag']]){
386
+ s.write('notify.json',JSON.stringify({version:1,command}));const before=s.snapshot();
387
+ assert.equal(classifyCommand(s.home,command),'custom',JSON.stringify(command));
388
+ const result=s.cli(['bark']);
389
+ assert.equal(result.status,2,JSON.stringify(command));assert.match(result.stderr,/--replace-custom/);
390
+ assert.deepEqual(s.snapshot(),before);
391
+ }
392
+ assert.equal(classifyCommand(s.home,[process.execPath,sender]),'managed');
393
+ assert.equal(classifyCommand(s.home,[legacy]),'legacy');
394
+ });
395
+
396
+ test('test never relays any command output, maps exit codes to fixed words, strips NODE_OPTIONS and runs the checked snapshot',async t=>{
397
+ const s=sandbox(t);
398
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);assert.equal(s.cli(['bark']).status,0);
399
+ const record=path.join(s.root,'record.json');
400
+ const fake=code=>`import fs from 'node:fs';process.stdin.resume();process.stdin.on('end',()=>{
401
+ fs.writeFileSync(${JSON.stringify(record)},JSON.stringify({options:process.env.NODE_OPTIONS??null,execArgv:process.execArgv}));
402
+ process.stdout.write('${BARK_SECRET}\\n');process.stderr.write('cm-notify: leaked ${BARK_SECRET}\\n');process.exit(${code});});`;
403
+ // The installed managed sender itself is replaced: same command shape, output still never shown.
404
+ const preload=path.join(s.root,'preload.cjs');fs.writeFileSync(preload,'// harmless for the manager itself\n');
405
+ // The replaced sender is no longer this plugin's copy: original words, 5/6 unknown, and an update hint.
406
+ const words={0:'已被推送服务接受(不代表已送达)',2:'配置或密钥问题',3:'网络失败或超时',4:'服务端拒绝',5:'未知',6:'未知',7:'未知'};
407
+ const staleHint='托管发送器与当前插件版本不同,退出码按旧含义解释;重新执行 /cm:notify bark 更新。';
408
+ for(const [code,word] of Object.entries(words)){
409
+ fs.writeFileSync(managedSenderPath(s.home),fake(code),{mode:0o600});
410
+ const result=s.cli(['test'],{NODE_OPTIONS:`--require=${preload}`});
411
+ assert.equal(result.status,Number(code),result.stderr);
412
+ assert.equal(result.stdout,`渠道 bark:退出码 ${code},${word}。${staleHint}\n`);noSecret(result.stdout+result.stderr);
413
+ assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')),{options:null,execArgv:[]},'NODE_OPTIONS is not passed to the sender');
414
+ }
415
+ // Dry-run never runs the installed command.
416
+ fs.rmSync(record);
417
+ const dry=s.cli(['test'],{CM_NOTIFY_DRY_RUN:'1'});
418
+ assert.equal(dry.status,0);assert(!fs.existsSync(record));noSecret(dry.stdout);assert.match(dry.stdout,/<已隐藏>/);
419
+ // Custom commands cannot be dry-run.
420
+ const other=path.join(s.root,'other.mjs');fs.writeFileSync(other,fake(0));
421
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,other]}));
422
+ const refused=s.cli(['test'],{CM_NOTIFY_DRY_RUN:'1'});assert.equal(refused.status,2);assert.match(refused.stderr,/演练模式只适用于/);assert(!fs.existsSync(record));
423
+ // The command that runs is the snapshot that was checked, even if notify.json changes in between.
424
+ fs.writeFileSync(managedSenderPath(s.home),fake(0),{mode:0o600});
425
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,managedSenderPath(s.home)]}));
426
+ const result=await sendTest(s.home,{env:s.env,beforeSpawn:()=>s.write('notify.json',JSON.stringify({version:1,command:['/bin/sh','-c','exit 9']}))});
427
+ assert.equal(result.exit,0);assert.deepEqual(JSON.parse(fs.readFileSync(record,'utf8')).execArgv,[]);
428
+ assert.equal(result.senderCurrent,false);
429
+ assert.equal(formatTest(result),`渠道 bark:退出码 0,已被推送服务接受(不代表已送达)。${staleHint}`);
430
+ });
431
+
432
+ test('test explains 3/5/6 with the new words only for the current managed sender',()=>{
433
+ const current={kind:'managed',channel:'bark',dry:false,reason:null,senderCurrent:true};
434
+ assert.equal(formatTest({...current,exit:3}),'渠道 bark:退出码 3,网络请求失败。');
435
+ assert.equal(formatTest({...current,exit:5}),'渠道 bark:退出码 5,超过 12 秒期限(可能已送达)。');
436
+ assert.equal(formatTest({...current,exit:6}),'渠道 bark:退出码 6,意外错误。');
437
+ assert.equal(formatTest({...current,exit:7}),'渠道 bark:退出码 7,未知。');
438
+ // A custom or legacy command keeps the original meaning of its exit codes.
439
+ for(const [kind,who] of [['custom','自定义命令'],['legacy','渠道 bark']])for(const [exit,word] of [[3,'网络失败或超时'],[5,'未知'],[6,'未知']])
440
+ assert.equal(formatTest({kind,channel:'bark',dry:false,reason:null,exit}),`${who}:退出码 ${exit},${word}。`);
441
+ // An older managed sender: original words plus the update hint, also when the command did not end normally.
442
+ const stale={...current,senderCurrent:false},hint='托管发送器与当前插件版本不同,退出码按旧含义解释;重新执行 /cm:notify bark 更新。';
443
+ assert.equal(formatTest({...stale,exit:3}),`渠道 bark:退出码 3,网络失败或超时。${hint}`);
444
+ assert.equal(formatTest({...stale,exit:5}),`渠道 bark:退出码 5,未知。${hint}`);
445
+ assert.equal(formatTest({...stale,exit:null,reason:'timeout'}),`渠道 bark:命令没有正常结束(timeout),未知。${hint}`);
446
+ });
447
+
448
+ // Simulated slow reads: file-system calls of the sender replaced through its module API.
449
+ const delayedOps=({lstatMs=0,block=false,before}={})=>({open:fsp.open,lstat:async(file,options)=>{
450
+ before?.();
451
+ if(block){const end=performance.now()+lstatMs;while(performance.now()<end){}}
452
+ else if(lstatMs)await new Promise(resolve=>setTimeout(resolve,lstatMs));
453
+ return fsp.lstat(file,options);}});
454
+
455
+ test('slow reads (blocking or async) end with 5 on time; dry-run, --check and sends never return 0 after the budget',async t=>{
456
+ const s=sandbox(t);
457
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
458
+ let sent=0;const request=()=>{sent++;throw new Error('must not send');};
459
+ const kinds={blocking:delayedOps({lstatMs:100,block:true}),slowAsync:delayedOps({lstatMs:400})};
460
+ for(const [kind,fileOps] of Object.entries(kinds))for(const [argv,env] of [[[],{}],[[],{CM_NOTIFY_DRY_RUN:'1'}],[['--check'],{}]])for(const deadlineMs of [20,60]){
461
+ const err=sink(),out=sink();const begin=performance.now();
462
+ const code=await runSender({argv,env:{...s.env,...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,fileOps,request,deadlineMs});
463
+ const took=performance.now()-begin,label=`${kind} ${argv} ${JSON.stringify(env)} ${deadlineMs}`;
464
+ assert.equal(code,SEND_EXIT.deadline,label);assert.equal(out.text(),'',label);
465
+ assert.match(err.text(),/^cm-notify: 整次调用超过 1 秒,已放弃/,label);
466
+ if(kind==='slowAsync')assert(took<deadlineMs+150,`${label} returned on time (${Math.round(took)} ms)`);
467
+ }
468
+ assert.equal(sent,0,'no request was started after the budget ran out');
469
+ // Every exit 0 checks the budget itself: time passes during a read but the timer has not run yet.
470
+ const server0=await fakeServer(t,(req,res)=>json(res,200,{code:200}));
471
+ for(const [argv,env,req] of [[['--check'],{},request],[[],{CM_NOTIFY_DRY_RUN:'1'},request],[[],{},server0.request]]){
472
+ let now=0,reads=0;const err=sink(),out=sink();
473
+ const lastRead=argv.length||env.CM_NOTIFY_DRY_RUN?(argv.length?2:1):99;
474
+ const code=await runSender({argv,env:{...s.env,...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,deadlineMs:5000,
475
+ clock:()=>now,request:(...args)=>{now=6000;return req(...args);},fileOps:delayedOps({before:()=>{if(++reads===lastRead)now=6000;}})});
476
+ assert.equal(code,SEND_EXIT.deadline,`${argv} ${JSON.stringify(env)}`);assert.equal(out.text(),'');assert.match(err.text(),/整次调用超过 5 秒,已放弃/);
477
+ }
478
+ assert.equal(server0.seen.length,1,'the late send was accepted but is still reported as 5');
479
+ // With enough budget the same slow read still sends.
480
+ const server=await fakeServer(t,(req,res)=>json(res,200,{code:200}));
481
+ const code=await runSender({env:s.env,home:s.home,stdin:endedStdin(),stdout:sink().stream,stderr:sink().stream,fileOps:kinds.blocking,request:server.request,deadlineMs:2000});
482
+ assert.equal(code,0);assert.equal(server.seen.length,1);
483
+ });
484
+
485
+ test('the process entry arms a hard timer: a read that never settles still exits 5 at the deadline',async t=>{
486
+ const s=sandbox(t);
487
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
488
+ const sender=new URL('../runtime/js/notify-send.mjs',import.meta.url).href;
489
+ // The soft deadline is disabled so only the hard timer can end the process.
490
+ const script=`import {runCli} from ${JSON.stringify(sender)};
491
+ import fsp from 'node:fs/promises';
492
+ runCli({argv:[],deadlineMs:300,softDeadlineMs:1e9,senderOptions:{fileOps:{open:fsp.open,lstat:()=>new Promise(()=>{})}}});`;
493
+ for(const extra of [{},{CM_NOTIFY_DRY_RUN:'1'}]){
494
+ const begin=performance.now();
495
+ const result=spawnSync(process.execPath,['--input-type=module','-e',script],{input:'{}\n',encoding:'utf8',env:{...s.env,...extra},timeout:10000});
496
+ const took=performance.now()-begin;
497
+ assert.equal(result.status,SEND_EXIT.deadline,result.stderr);assert.equal(result.stdout,'');
498
+ assert.equal(result.stderr,'cm-notify: 整次调用超过 1 秒,已放弃\n');
499
+ assert(took<3000,`exited on time (${Math.round(took)} ms)`);
500
+ }
501
+ });
502
+
503
+ test('process-level errors (uncaught exception, unhandled rejection) exit 6 with only the fixed line',t=>{
504
+ const s=sandbox(t);
505
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
506
+ const sender=new URL('../runtime/js/notify-send.mjs',import.meta.url).href;
507
+ const faults={uncaught:`setImmediate(()=>{throw new Error('boom ${BARK_SECRET}');});`,
508
+ rejection:`Promise.reject(new Error('boom ${BARK_SECRET}'));`};
509
+ for(const [kind,fault] of Object.entries(faults)){
510
+ // The read never settles and the deadline is far away, so only the process-level handler can end it.
511
+ const script=`import {runCli} from ${JSON.stringify(sender)};
512
+ import fsp from 'node:fs/promises';
513
+ runCli({argv:[],deadlineMs:8000,softDeadlineMs:1e9,senderOptions:{fileOps:{open:fsp.open,lstat:()=>{${fault}return new Promise(()=>{});}}}});`;
514
+ const result=spawnSync(process.execPath,['--input-type=module','-e',script],{input:'{}\n',encoding:'utf8',env:s.env,timeout:10000});
515
+ assert.equal(result.status,SEND_EXIT.unexpected,`${kind} ${result.stderr}`);assert.equal(result.stdout,'',kind);
516
+ assert.equal(result.stderr,'cm-notify: 意外错误(详情已隐藏,避免带出密钥)\n',kind);noSecret(result.stderr);
517
+ }
518
+ });
519
+
520
+ test('off restores the previous notify.off.json when moving notify.json fails, and names the backup if that fails too',t=>{
521
+ const s=sandbox(t);
522
+ const on=JSON.stringify({version:1,command:['/bin/true'],waitMinutes:5}),old=JSON.stringify({version:1,command:['/bin/false'],note:'old off'});
523
+ const fail=(match,code='EACCES')=>{const calls=[];return {calls,ops:{renameSync:(from,to)=>{calls.push([path.basename(from),path.basename(to)]);
524
+ if(match(from,to,calls.length)){const error=new Error('injected');error.code=code;throw error;}return fs.renameSync(from,to);}}};};
525
+ const reset=()=>{for(const name of fs.readdirSync(s.home))fs.rmSync(path.join(s.home,name),{recursive:true});s.write('notify.json',on);s.write('notify.off.json',old);};
526
+ // Second rename fails: the old off file goes back to its place.
527
+ reset();let before=s.snapshot();
528
+ let fault=fail((from,to,n)=>n===2);
529
+ assert.throws(()=>turnOff(s.home,{ops:fault.ops}),error=>{assert.match(error.message,/关闭失败(EACCES):notify.json 仍在原处,提醒仍开启;原来的 notify.off.json 已放回原处/);return true;});
530
+ assert.deepEqual(s.snapshot(),before);assert.equal(fault.calls.length,3);
531
+ // Second rename and the restore both fail: the message names the backup path, and the backup holds the old content.
532
+ reset();
533
+ fault=fail((from,to,n)=>n>=2);
534
+ assert.throws(()=>turnOff(s.home,{ops:fault.ops}),error=>{
535
+ const backup=fs.readdirSync(s.home).find(name=>name.startsWith('notify.off.json.bak-'));
536
+ assert(backup);assert.equal(s.read(backup),old);assert.equal(s.read('notify.json'),on);assert(!s.exists('notify.off.json'));
537
+ assert(error.message.includes(path.join(s.home,backup)),error.message);assert.match(error.message,/放回时也失败(EACCES),请手动把它改回 notify.off.json/);return true;});
538
+ // First rename fails: nothing changed.
539
+ reset();before=s.snapshot();
540
+ assert.throws(()=>turnOff(s.home,{ops:fail(()=>true).ops}),/什么都没改/);assert.deepEqual(s.snapshot(),before);
541
+ // Without an old off file a failed move reports that notify.json is still on.
542
+ reset();fs.rmSync(path.join(s.home,'notify.off.json'));before=s.snapshot();
543
+ assert.throws(()=>turnOff(s.home,{ops:fail(()=>true).ops}),/notify.json 仍在原处,提醒仍开启;其他文件没改/);assert.deepEqual(s.snapshot(),before);
544
+ // Normal path keeps the old off file as a backup.
545
+ reset();const done=turnOff(s.home);assert.equal(done.changed,true);assert.equal(s.read('notify.off.json'),on);assert.equal(fs.readFileSync(done.backup,'utf8'),old);
546
+ });
547
+
548
+ test('a partly written switch is rolled back without extra copies; whatever cannot be restored is named with where its content is',async t=>{
549
+ const s=sandbox(t);
550
+ const custom=JSON.stringify({version:1,command:['/usr/local/bin/mine'],waitMinutes:9});
551
+ const reset=()=>{for(const name of fs.readdirSync(s.home))fs.rmSync(path.join(s.home,name),{recursive:true});
552
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('notify-channel.conf','# 原来\nCHANNEL=pushplus\n');s.write('notify.json',custom);};
553
+ const injected=code=>Object.assign(new Error('injected'),{code});
554
+ const faulty=({rename=()=>false,unlink=()=>false})=>({writeFileSync:fs.writeFileSync,chmodSync:fs.chmodSync,
555
+ renameSync:(from,to)=>{if(rename(from,to))throw injected('EIO');return fs.renameSync(from,to);},
556
+ unlinkSync:file=>{if(unlink(file))throw injected('EBUSY');return fs.unlinkSync(file);}});
557
+ const conf=path.join(s.home,'notify-channel.conf'),notifyJson=path.join(s.home,'notify.json'),sender=managedSenderPath(s.home);
558
+ const tempTo=target=>(from,to)=>from.endsWith('.tmp')&&to===target;// the atomic write of `target`
559
+ const isBackup=from=>path.basename(from).startsWith('notify.json.bak-');
560
+ const noCopies=()=>assert.deepEqual(fs.readdirSync(s.home).filter(name=>/restore|\.tmp$/.test(name)),[],'no rescue copies or temp files');
561
+ const escape=text=>text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
562
+ // 1. Writing notify.json fails; sender and channel file are put back and the renamed original returns: byte-identical.
563
+ reset();let before=s.snapshot();
564
+ await assert.rejects(()=>switchChannel(s.home,'bark',{replaceCustom:true,ops:faulty({rename:tempTo(notifyJson)})}),error=>{
565
+ assert.match(error.message,new RegExp(`切换失败:写 ${escape(notifyJson)} 时失败(EIO);已写入的文件都已恢复原样`));
566
+ assert.deepEqual(error.unrestored,[]);assert.deepEqual(error.restored,[conf,sender,notifyJson]);return true;});
567
+ assert.deepEqual(s.snapshot(),before,'no backup left behind and nothing changed');noCopies();
568
+ // 2. Restoring the channel file fails too: never claims success, says its old content is not on disk, no copy is made.
569
+ reset();
570
+ let confWrites=0;
571
+ await assert.rejects(()=>switchChannel(s.home,'bark',{replaceCustom:true,ops:faulty({rename:(from,to)=>tempTo(notifyJson)(from,to)||(tempTo(conf)(from,to)&&++confWrites>1)})}),error=>{
572
+ assert.doesNotMatch(error.message,/都已恢复原样/);
573
+ assert.deepEqual(error.unrestored.map(entry=>entry.file),[conf]);
574
+ assert(error.message.includes(`${conf} 没能恢复(EIO),原内容没有留在磁盘上`),error.message);
575
+ assert(error.message.includes(`已恢复:${sender}、${notifyJson}`),error.message);return true;});
576
+ assert.equal(s.read('notify.json'),custom,'the renamed original is back');
577
+ assert.match(s.read('notify-channel.conf'),/CHANNEL=bark/,'the unrestored file is reported, not hidden');noCopies();
578
+ // 3. The renamed original cannot be put back: the message says where it still is.
579
+ reset();
580
+ await assert.rejects(()=>switchChannel(s.home,'bark',{replaceCustom:true,ops:faulty({rename:(from,to)=>tempTo(notifyJson)(from,to)||isBackup(from)})}),error=>{
581
+ const backup=fs.readdirSync(s.home).find(name=>name.startsWith('notify.json.bak-'));
582
+ assert(backup);assert.equal(s.read(backup),custom);assert(!s.exists('notify.json'));
583
+ assert(error.message.includes(`${notifyJson} 没能改回原名(EIO),原内容仍在 ${path.join(s.home,backup)}`),error.message);return true;});
584
+ noCopies();
585
+ // 4. A newly created sender that cannot be removed is reported as such.
586
+ reset();
587
+ await assert.rejects(()=>switchChannel(s.home,'bark',{replaceCustom:true,ops:faulty({rename:tempTo(notifyJson),unlink:file=>file===sender})}),error=>{
588
+ assert(error.message.includes(`${sender} 是这次新建的,没能删除(EBUSY)`),error.message);return true;});
589
+ // 5. The backup rename itself fails: nothing changed.
590
+ reset();before=s.snapshot();
591
+ await assert.rejects(()=>switchChannel(s.home,'bark',{replaceCustom:true,ops:faulty({rename:(from,to)=>from===notifyJson})}),/备份 .* 失败(EIO),什么都没改/);
592
+ assert.deepEqual(s.snapshot(),before);
593
+ reset();assert.equal(s.cli(['bark','--replace-custom']).status,0);
594
+ });
595
+
596
+ test('the backup of a replaced config is the original file renamed, so its permissions travel with it',{skip:!posix},t=>{
597
+ const s=sandbox(t);
598
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
599
+ const original=s.write('notify.json',JSON.stringify({version:1,command:['/usr/local/bin/mine']}),0o640);
600
+ const ino=fs.statSync(original).ino;
601
+ assert.equal(s.cli(['bark','--replace-custom']).status,0);
602
+ const backup=path.join(s.home,fs.readdirSync(s.home).find(name=>name.startsWith('notify.json.bak-')));
603
+ assert.equal(fs.statSync(backup).ino,ino,'same file, renamed');assert.equal(fs.statSync(backup).mode&0o777,0o640);
604
+ assert.equal(fs.statSync(original).mode&0o777,0o600,'the new notify.json is private');assert.notEqual(fs.statSync(original).ino,ino);
605
+ // From notify.off.json: the off file itself becomes the backup.
606
+ fs.rmSync(original);const off=s.write('notify.off.json',JSON.stringify({version:1,command:['/usr/local/bin/mine'],idleMinutes:30}),0o640);
607
+ const offIno=fs.statSync(off).ino;
608
+ assert.equal(s.cli(['pushplus','--replace-custom']).status,2,'pushplus secret is missing');
609
+ s.write('pushplus.env','PUSHPLUS_TOKEN=FakePushplusToken789\n');
610
+ assert.equal(s.cli(['pushplus','--replace-custom']).status,0);
611
+ const offBackup=path.join(s.home,fs.readdirSync(s.home).find(name=>name.startsWith('notify.off.json.bak-')));
612
+ assert.equal(fs.statSync(offBackup).ino,offIno);assert(!s.exists('notify.off.json'));assert.equal(JSON.parse(s.read('notify.json')).idleMinutes,30);
613
+ });
614
+
615
+ test('the opened handle must be the file that was checked by path: a swap is refused before reading',async t=>{
616
+ const s=sandbox(t);
617
+ const file=s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`),other=s.write('other.env',`BARK_KEY=${OTHER_BARK_SECRET}\n`);
618
+ // The path is swapped between the lstat check and the open.
619
+ const swapped={lstat:fsp.lstat,open:async(...args)=>{fs.renameSync(file,`${file}.old`);fs.renameSync(other,file);return fsp.open(...args);}};
620
+ await assert.rejects(()=>readPrivateFile(file,'bark.env',{fileOps:swapped}),error=>{
621
+ assert.equal(error.exit,SEND_EXIT.config);assert.match(error.message,/bark.env 在核对期间被替换/);noSecret(error.message);return true;});
622
+ assert.equal(await readPrivateFile(file,'bark.env'),`BARK_KEY=${OTHER_BARK_SECRET}\n`,'an unchanged path reads normally');
623
+ });
624
+
625
+ test('Windows is refused on every path with exit 2 and no network',async t=>{
626
+ const s=sandbox(t);
627
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
628
+ let sent=0;const request=()=>{sent++;throw new Error('must not send');};
629
+ // The sender: normal, --check and dry-run.
630
+ for(const [argv,env] of [[[],{}],[['--check'],{}],[[],{CM_NOTIFY_DRY_RUN:'1'}]]){
631
+ const out=sink(),err=sink();
632
+ const code=await runSender({argv,env:{...s.env,...env},home:s.home,stdin:endedStdin(),stdout:out.stream,stderr:err.stream,platform:'win32',request,
633
+ fileOps:{lstat:()=>{throw new Error('must not touch files');},open:()=>{throw new Error('must not touch files');}}});
634
+ assert.equal(code,SEND_EXIT.config,`${argv}`);assert.equal(out.text(),'');assert.equal(err.text(),`cm-notify: ${WINDOWS_UNSUPPORTED}\n`);
635
+ }
636
+ assert.equal(sent,0);
637
+ // The manager: switch, test and dry-run refuse before touching any file; nothing is created.
638
+ assert.equal(s.cli(['bark']).status,0,'set up on POSIX first');
639
+ const before=s.snapshot();
640
+ for(const [argv,env] of [[['bark'],{}],[['pushplus'],{}],[['pushplus','--replace-custom'],{}],[['test'],{}],[['test'],{CM_NOTIFY_DRY_RUN:'1'}]]){
641
+ const out=sink(),err=sink();
642
+ const code=await main(argv,{env:{...s.env,...env},stdout:out.stream,stderr:err.stream,platform:'win32'});
643
+ assert.equal(code,2,`${argv}`);assert.equal(out.text(),'');assert.equal(err.text(),`cm-notify: ${WINDOWS_UNSUPPORTED}\n`);
644
+ }
645
+ assert.deepEqual(s.snapshot(),before,'no file changed, no template created, nothing logged');
646
+ // Status still shows the channel and whether each secret file exists, without reading secret content.
647
+ fs.chmodSync(path.join(s.home,'bark.env'),0o000);
648
+ const out=sink();
649
+ assert.equal(await main([],{env:s.env,stdout:out.stream,stderr:sink().stream,platform:'win32'}),0);
650
+ assert.match(out.text(),new RegExp(WINDOWS_UNSUPPORTED));
651
+ assert.match(out.text(),/当前渠道:bark(Windows 上不会发送)/);
652
+ assert.match(out.text(),/渠道 bark:文件存在(Windows 上不读取内容,无法判断是否填好)/);
653
+ assert.match(out.text(),/渠道 pushplus:未填写(文件不存在)/);noSecret(out.text());
654
+ fs.chmodSync(path.join(s.home,'bark.env'),0o600);
655
+ });
656
+
657
+ test('time spent before the sender work counts toward the same 12 s budget',async t=>{
658
+ const s=sandbox(t);
659
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
660
+ const sender=new URL('../runtime/js/notify-send.mjs',import.meta.url).href;
661
+ const run=(body,extra={})=>{const begin=performance.now();
662
+ const result=spawnSync(process.execPath,['--input-type=module','-e',`import {runCli} from ${JSON.stringify(sender)};\n${body}`],
663
+ {input:'{}\n',encoding:'utf8',env:{...s.env,...extra},timeout:15000});
664
+ return {...result,took:performance.now()-begin};};
665
+ // The start recorded at entry is honoured: time already spent leaves no budget for an exit 0.
666
+ for(const argv of [['--check'],[]]){
667
+ const result=run(`import {performance} from 'node:perf_hooks';runCli({argv:${JSON.stringify(argv)},startedAt:performance.now()-12050});`,{CM_NOTIFY_DRY_RUN:'1'});
668
+ assert.equal(result.status,SEND_EXIT.deadline,`${argv} ${result.stderr}`);assert.equal(result.stdout,'');assert(result.took<5000);
669
+ }
670
+ // 250 ms already spent, the slow read needs more than the 50 ms left: 5, never 0.
671
+ const result=run(`import {performance} from 'node:perf_hooks';import fsp from 'node:fs/promises';
672
+ runCli({argv:['--check'],deadlineMs:300,startedAt:performance.now()-250,senderOptions:{fileOps:{open:fsp.open,lstat:async(f,o)=>{await new Promise(r=>setTimeout(r,200));return fsp.lstat(f,o);}}}});`);
673
+ assert.equal(result.status,SEND_EXIT.deadline,result.stderr);assert.equal(result.stdout,'');assert(result.took<3000);
674
+ });
675
+
676
+ test('entry is decided by import.meta.main alone: imported does nothing, unsupported Node exits 3, Windows is refused first',()=>{
677
+ assert.equal(entryDecision(true,'darwin'),'run');assert.equal(entryDecision(true,'linux'),'run');
678
+ assert.equal(entryDecision(true,'win32'),'windows');
679
+ assert.equal(entryDecision(false,'win32'),'imported');assert.equal(entryDecision(false,'linux'),'imported');
680
+ assert.equal(entryDecision(undefined,'linux'),'unsupported_node');assert.equal(entryDecision(undefined,'win32'),'unsupported_node');
681
+ const source=fs.readFileSync(SENDER_SOURCE,'utf8'),manager=fs.readFileSync(fileURLToPath(new URL('./cm-notify.mjs',import.meta.url)),'utf8');
682
+ assert.doesNotMatch(source+manager,/realpath/,'no path resolution is used for entry detection');
683
+ // In the sender the hard timer is armed and the Windows refusal follows it before any other statement runs.
684
+ const order=['const ENTRY_STARTED_AT','const ENTRY=entryDecision','process.exit(3);}','const ENTRY_HARD_TIMER',"if(ENTRY==='windows')",'export const SEND_EXIT'].map(mark=>source.indexOf(mark));
685
+ assert(order.every((at,i)=>at>=0&&(i===0||at>order[i-1])),`entry order ${order}`);
686
+ });
687
+
688
+ test('symlinked entries with another name still run, both sender and manager',{skip:!posix},t=>{
689
+ const s=sandbox(t);
690
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
691
+ const senderAlias=path.join(s.root,'alias-sender.mjs');fs.symlinkSync(SENDER_SOURCE,senderAlias);
692
+ let result=spawnSync(process.execPath,[senderAlias,'--check'],{input:'',encoding:'utf8',env:s.env,timeout:15000});
693
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stdout,'cm-notify: 渠道 bark 配置可解析(未发送)\n');
694
+ const managerAlias=path.join(s.root,'notify-alias.mjs');fs.symlinkSync(CLI,managerAlias);
695
+ result=spawnSync(process.execPath,[managerAlias,'status'],{encoding:'utf8',env:s.env,timeout:15000});
696
+ assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/CM 提醒设置/);noSecret(result.stdout);
697
+ });
698
+
699
+ test('the manager refuses Windows as its first action, before the test-home guard or any file access',async t=>{
700
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-win-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
701
+ const home=path.join(root,'never-created');
702
+ for(const env of [{...process.env,NODE_TEST_CONTEXT:'child',CM_WORKFLOW_HOME:undefined},{...process.env,CM_WORKFLOW_HOME:home}])
703
+ for(const argv of [['bark'],['pushplus','--replace-custom'],['test'],['nonsense']]){
704
+ const err=sink(),out=sink();
705
+ assert.equal(await main(argv,{env,stdout:out.stream,stderr:err.stream,platform:'win32'}),2,`${argv}`);
706
+ assert.equal(err.text(),`cm-notify: ${WINDOWS_UNSUPPORTED}\n`);assert.equal(out.text(),'');
707
+ }
708
+ assert(!fs.existsSync(home),'nothing was created');
709
+ });
710
+
711
+ test('the channel file is read through the safe boundary: never via a symlink, size capped, identity checked',async t=>{
712
+ const s=sandbox(t);
713
+ const secret=s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`),conf=path.join(s.home,'notify-channel.conf');
714
+ fs.symlinkSync(secret,conf);
715
+ const noOpen={lstat:fsp.lstat,open:()=>{throw new Error('must not open');}};
716
+ await assert.rejects(()=>readRegularFile(conf,'notify-channel.conf',{fileOps:noOpen}),error=>{
717
+ assert.match(error.message,/notify-channel.conf 必须是普通文件(不能是符号链接)/);noSecret(error.message);return true;});
718
+ // Windows status shows the problem without reading the linked secret.
719
+ const out=sink();
720
+ assert.equal(await main([],{env:s.env,stdout:out.stream,stderr:sink().stream,platform:'win32'}),0);
721
+ assert.match(out.text(),/当前渠道:无法确定:notify-channel.conf 必须是普通文件(不能是符号链接)/);noSecret(out.text());
722
+ // POSIX status refuses the link as well.
723
+ const posixOut=sink();
724
+ assert.equal(await main([],{env:s.env,stdout:posixOut.stream,stderr:sink().stream,platform:'linux'}),0);
725
+ assert.match(posixOut.text(),/当前渠道:无法确定:notify-channel.conf 必须是自己的普通文件且权限 600/);noSecret(posixOut.text());
726
+ fs.rmSync(conf);
727
+ // Directories, oversized files and swapped files are refused.
728
+ fs.mkdirSync(conf);await assert.rejects(()=>readRegularFile(conf,'notify-channel.conf'),/必须是普通文件/);fs.rmdirSync(conf);
729
+ fs.writeFileSync(conf,'#'.repeat(70*1024));
730
+ await assert.rejects(()=>readRegularFile(conf,'notify-channel.conf',{fileOps:noOpen}),/notify-channel.conf 太大/);
731
+ fs.writeFileSync(conf,'CHANNEL=bark\n');const other=s.write('other.conf','CHANNEL=pushplus\n');
732
+ const swapped={lstat:fsp.lstat,open:async(...args)=>{fs.renameSync(conf,`${conf}.old`);fs.renameSync(other,conf);return fsp.open(...args);}};
733
+ await assert.rejects(()=>readRegularFile(conf,'notify-channel.conf',{fileOps:swapped}),/在核对期间被替换/);
734
+ assert.equal(await readRegularFile(conf,'notify-channel.conf'),'CHANNEL=pushplus\n');
735
+ });
736
+
737
+ test('the installed sender detects its entry without file-system resolution, also through a symlinked path',{skip:!posix},t=>{
738
+ const s=sandbox(t);
739
+ s.write('notify-channel.conf','CHANNEL=bark\n');s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
740
+ const real=path.join(s.root,'real');fs.mkdirSync(real);fs.copyFileSync(SENDER_SOURCE,path.join(real,'cm-notify-send.mjs'));
741
+ const linked=path.join(s.root,'linked');fs.symlinkSync(real,linked);
742
+ for(const dir of [real,linked]){
743
+ const result=spawnSync(process.execPath,[path.join(dir,'cm-notify-send.mjs'),'--check'],{input:'',encoding:'utf8',env:s.env,timeout:15000});
744
+ assert.equal(result.status,0,result.stderr);assert.equal(result.stdout,'cm-notify: 渠道 bark 配置可解析(未发送)\n');
745
+ }
746
+ });
747
+
748
+ test('manager dry-run never opens or checks the secret file',async t=>{
749
+ const s=sandbox(t);
750
+ const file=s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);assert.equal(s.cli(['bark']).status,0);
751
+ // An unreadable, an empty and a missing secret file all give the same dry-run result: it is never read.
752
+ const cases=[()=>fs.chmodSync(file,0o000),()=>{fs.chmodSync(file,0o600);fs.writeFileSync(file,'BARK_KEY=\n');},()=>fs.rmSync(file)];
753
+ for(const prepare of cases){
754
+ prepare();
755
+ const result=s.cli(['test'],{CM_NOTIFY_DRY_RUN:'1'});
756
+ assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/也没有读取或检查密钥文件/);
757
+ assert.match(result.stdout,/"device_key":"<已隐藏>"/);noSecret(result.stdout);
758
+ }
759
+ // Without dry-run the same missing file is refused.
760
+ const result=s.cli(['test']);assert.equal(result.status,2);assert.match(result.stderr,/未填写(文件不存在)/);
761
+ });
762
+
763
+ // Optional notify.json `text` is the user's: /cm:notify keeps it (and any other
764
+ // unknown key) across switch, off and on, and status says which text is in use.
765
+ const CUSTOM_TEXT={titlePrefix:'提醒',headlines:{default:'卡住了',done:'完工'},fields:{default:['nextAction','task','time']},labels:{task:'工单'}};
766
+ test('custom text survives switch, off and on; status shows 文案:默认/自定义/无效 and writes nothing',t=>{
767
+ const s=sandbox(t);
768
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('pushplus.env',`PUSHPLUS_TOKEN=${PUSH_SECRET}\n`);
769
+ assert.equal(s.cli(['bark']).status,0);
770
+ assert.match(s.cli([]).stdout,/\n文案:默认\n/);
771
+ assert.equal(JSON.parse(s.cli(['--json']).stdout).config.textState,'default');
772
+ const config={...JSON.parse(s.read('notify.json')),text:CUSTOM_TEXT,note:'kept'};s.write('notify.json',JSON.stringify(config));
773
+ let result=s.cli([]);assert.match(result.stdout,/\n文案:自定义(\/cm:notify preview 查看效果)\n/);
774
+ let parsed=JSON.parse(s.cli(['status','--json']).stdout);
775
+ assert.equal(parsed.config.textState,'custom');assert.equal(JSON.stringify(parsed).includes('卡住了'),false,'status lists no custom strings');
776
+ result=s.cli(['pushplus']);assert.equal(result.status,0,result.stderr);assert.doesNotMatch(result.stdout,/text 无效/);
777
+ assert.deepEqual(JSON.parse(s.read('notify.json')).text,CUSTOM_TEXT);assert.equal(JSON.parse(s.read('notify.json')).note,'kept');
778
+ assert.equal(s.cli(['off']).status,0);
779
+ assert.deepEqual(JSON.parse(s.read('notify.off.json')).text,CUSTOM_TEXT);
780
+ assert.doesNotMatch(s.cli([]).stdout,/文案:/);
781
+ result=s.cli(['bark']);assert.equal(result.status,0,result.stderr);
782
+ const restored=JSON.parse(s.read('notify.json'));
783
+ assert.deepEqual(restored.text,CUSTOM_TEXT);assert.equal(restored.note,'kept');assert.equal(restored.command[1],managedSenderPath(s.home));
784
+ assert.match(s.cli([]).stdout,/\n文案:自定义/);
785
+ // A broken text is kept as written, never dropped; notices stay on with the default text.
786
+ const broken={...restored,text:{fields:{default:['diff']}}};s.write('notify.json',JSON.stringify(broken));
787
+ result=s.cli([]);assert.match(result.stdout,/\n文案:默认(notify.json 里的 text 无效:fields,已改用默认文案,提醒照常发送)\n/);
788
+ assert.match(result.stdout,/当前渠道:bark(生效中)/);
789
+ parsed=JSON.parse(s.cli(['--json']).stdout);assert.equal(parsed.config.textState,'invalid');assert.equal(parsed.config.textReason,'fields');
790
+ result=s.cli(['pushplus']);assert.equal(result.status,0,result.stderr);
791
+ assert.match(result.stdout,/提示:notify.json 里的 text 无效(fields),提醒使用默认文案/);
792
+ assert.deepEqual(JSON.parse(s.read('notify.json')).text,broken.text);
793
+ assert.equal(s.log(),'','status and switch write nothing to notify.log');
794
+ noSecret(s.cli([]).stdout);
795
+ });
796
+
797
+ test('preview prints every event from sample fields with the current text; it sends, logs and changes nothing',async t=>{
798
+ const s=sandbox(t);
799
+ const at={now:Date.parse('2026-10-08T08:00:00.000Z'),timeZone:'Asia/Shanghai'};
800
+ let preview=await previewText(s.home,at);
801
+ assert.equal(preview.textState,null);assert.deepEqual(preview.messages.map(m=>m.event),['stuck','waiting','idle','idle_waiting','dead','done']);
802
+ assert.equal(preview.messages[0].title,'CM cm-ai 需要人处理 · demo-app');
803
+ assert.equal(preview.messages[5].body,'项目:demo-app\n任务:T-001\n时间:16:00');
804
+ assert.match(formatPreview(preview),/^提醒文案预览,用示例字段生成,不发送。文案:默认(没有生效的 notify.json,按默认文案预览)\n/);
805
+ // Point notify.json at a command that would record any run: preview must never run it.
806
+ const ran=path.join(s.root,'ran');
807
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,'-e',`require('fs').writeFileSync(${JSON.stringify(ran)},'x')`],text:CUSTOM_TEXT}));
808
+ preview=await previewText(s.home,at);
809
+ assert.equal(preview.textState,'custom');
810
+ assert.deepEqual(preview.messages.map(m=>m.title),['提醒 cm-ai 卡住了 · demo-app','提醒 cm-ai 等待会话应答 · demo-app','提醒 cm-ai 疑似空转 · demo-app',
811
+ '提醒 cm-ai 在等你 · demo-app','提醒 cm-ai 宿主已退出未收尾 · demo-app','提醒 cm-ai 完工 · demo-app']);
812
+ assert.equal(preview.messages[0].body,'下一步:核对原因后恢复原运行\n工单:T-001\n时间:16:00');
813
+ assert.equal(preview.messages[5].body,'项目:demo-app\n工单:T-001\n时间:16:00');
814
+ const before=s.snapshot();
815
+ let result=s.cli(['preview']);assert.equal(result.status,0,result.stderr);
816
+ assert.match(result.stdout,/^提醒文案预览,用示例字段生成,不发送。文案:自定义\n\n【卡住,需要人处理】stuck\n标题:提醒 cm-ai 卡住了 · demo-app\n下一步:核对原因后恢复原运行\n工单:T-001\n时间:\d\d:\d\d\n/);
817
+ assert.match(result.stdout,/【流程已结束】done\n标题:提醒 cm-ai 完工 · demo-app\n/);
818
+ assert.equal(JSON.parse(s.cli(['preview','--json']).stdout).messages.length,6);
819
+ // Also allowed on Windows: it reads notify.json only, never a secret file.
820
+ const out=sink();assert.equal(await main(['preview'],{env:s.env,stdout:out.stream,stderr:sink().stream,platform:'win32'}),0);
821
+ assert.match(out.text(),/标题:提醒 cm-ai 卡住了 · demo-app/);
822
+ s.write('notify.json',JSON.stringify({version:1,command:['/bin/true'],text:{labels:{secret:'x'}}}));
823
+ assert.match(s.cli(['preview']).stdout,/文案:默认(notify.json 里的 text 无效:labels,已改用默认文案,提醒照常发送)\n\n【卡住,需要人处理】stuck\n标题:CM cm-ai 需要人处理 · demo-app\n/);
824
+ s.write('notify.json','not json');
825
+ assert.match(s.cli(['preview']).stdout,/文案:默认(notify.json 无效,按默认文案预览)/);
826
+ s.write('notify.json',JSON.stringify({version:1,command:[process.execPath,'-e',`require('fs').writeFileSync(${JSON.stringify(ran)},'x')`],text:CUSTOM_TEXT}));
827
+ assert.deepEqual(s.snapshot(),before,'preview wrote nothing');assert(!fs.existsSync(ran),'the command never ran');
828
+ assert.equal(s.log(),'');
829
+ });
830
+
831
+ // notify.json is read through the same safe boundary as the channel file in
832
+ // every manager path: a symlink (e.g. to a secret file), a FIFO or an oversized
833
+ // file is never read; status says so instead of guessing.
834
+ test('status, preview, test and switch never follow a notify.json symlink or read a non-regular or oversized file',{skip:!posix},async t=>{
835
+ const s=sandbox(t);
836
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);s.write('notify-channel.conf','CHANNEL=bark\n');
837
+ // The link target is valid JSON with a marker: if anything followed the link, the marker would show up.
838
+ const target=s.write('elsewhere.json',JSON.stringify({version:1,command:['/bin/true'],text:{headlines:{default:'LEAKED'}}}));
839
+ const link=path.join(s.home,'notify.json');fs.symlinkSync(target,link);
840
+ let status=await notifyStatus(s.home);
841
+ assert.equal(status.config.state,'invalid');assert.equal(status.config.reason,'not_regular_file');
842
+ let result=s.cli([]);assert.equal(result.status,0,result.stderr);
843
+ assert.match(result.stdout,/发送命令:notify.json 不是普通文件(可能是符号链接),cm-notify 不读取它,无法确认提醒是否生效/);
844
+ const preview=await previewText(s.home,{now:Date.parse('2026-10-08T08:00:00.000Z'),timeZone:'UTC'});
845
+ assert.equal(preview.state,'invalid');assert.equal(preview.textState,null);
846
+ assert.equal(preview.messages[0].title,'CM cm-ai 需要人处理 · demo-app');
847
+ result=s.cli(['preview']);assert.equal(result.status,0);assert.doesNotMatch(result.stdout,/LEAKED/);
848
+ assert.match(result.stdout,/文案:默认(notify.json 无效,按默认文案预览)/);
849
+ result=s.cli(['test']);assert.equal(result.status,2);assert.match(result.stderr,/notify.json 无效(not_regular_file)/);
850
+ result=s.cli(['bark']);assert.equal(result.status,2);assert.match(result.stderr,/不是普通文件/);
851
+ assert(fs.lstatSync(link).isSymbolicLink());assert.match(fs.readFileSync(target,'utf8'),/LEAKED/);
852
+ // The same for notify.off.json as the base of a switch.
853
+ fs.unlinkSync(link);fs.symlinkSync(target,path.join(s.home,'notify.off.json'));
854
+ result=s.cli(['bark']);assert.equal(result.status,2);assert.match(result.stderr,/不是普通文件/);
855
+ assert(!s.exists('notify.json'));fs.unlinkSync(path.join(s.home,'notify.off.json'));
856
+ // A FIFO is refused at once instead of blocking the read.
857
+ assert.equal(spawnSync('mkfifo',[link]).status,0);
858
+ const started=performance.now();status=await notifyStatus(s.home);
859
+ assert.equal(status.config.reason,'not_regular_file');assert(performance.now()-started<5000);
860
+ fs.unlinkSync(link);
861
+ // Oversized: not read, reported as such.
862
+ s.write('notify.json',JSON.stringify({version:1,command:['/bin/true'],pad:'x'.repeat(70*1024)}));
863
+ status=await notifyStatus(s.home);assert.equal(status.config.reason,'too_large');
864
+ assert.match(s.cli([]).stdout,/notify.json 超过 64 KiB,cm-notify 不读取它/);
865
+ // Switching from an oversized notify.off.json is refused before anything is read or written.
866
+ fs.renameSync(path.join(s.home,'notify.json'),path.join(s.home,'notify.off.json'));
867
+ const beforeSwitch=s.snapshot();
868
+ result=s.cli(['bark']);assert.equal(result.status,2);assert.match(result.stderr,/notify.off.json 超过 64 KiB,cm-notify 不会改它/);
869
+ assert.deepEqual(s.snapshot(),beforeSwitch);fs.unlinkSync(path.join(s.home,'notify.off.json'));
870
+ // A regular file still works, byte for byte as the runtime reads it (a BOM stays invalid JSON for both).
871
+ s.write('notify.json',''+JSON.stringify({version:1,command:['/bin/true']}));
872
+ status=await notifyStatus(s.home);assert.equal(status.config.state,'invalid');assert.equal(status.config.reason,'not_json');
873
+ s.write('notify.json',JSON.stringify({version:1,command:['/bin/true'],text:{headlines:{default:'卡住了'}}}));
874
+ status=await notifyStatus(s.home);assert.equal(status.config.state,'custom');assert.equal(status.config.textState,'custom');
875
+ assert.equal(s.log(),'');
876
+ });
877
+
878
+ // The file a switch writes is re-indented and gets a new command, so it can
879
+ // grow; it must stay within the 64 KiB the manager itself reads. Checked on the
880
+ // exact bytes before any backup or write.
881
+ test('switch refuses to write a notify.json over the 64 KiB read cap and keeps the original; at the cap it works',async t=>{
882
+ const s=sandbox(t);
883
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
884
+ const node='/opt/node/bin/node',sender=managedSenderPath(s.home);
885
+ // Pad so that the rewritten file is exactly `target` bytes.
886
+ const config=pad=>({version:1,command:[node,sender],note:'x'.repeat(pad)});
887
+ const written=pad=>Buffer.byteLength(`${JSON.stringify(config(pad),null,2)}\n`);
888
+ const padFor=target=>target-written(0);
889
+ for(const name of ['notify.json','notify.off.json']){
890
+ for(const extra of ['notify.json','notify.off.json'])if(s.exists(extra))fs.unlinkSync(path.join(s.home,extra));
891
+ // Compact input below the cap that grows past it once re-indented.
892
+ const over=JSON.stringify(config(padFor(65537)));
893
+ assert(Buffer.byteLength(over)<=65536,'the input itself is readable');
894
+ s.write(name,over);const before=s.snapshot();
895
+ await assert.rejects(()=>switchChannel(s.home,'bark',{execPath:node}),error=>{
896
+ assert.match(error.message,/改写后的 notify.json 会有 65537 字节,超过 65536 字节(64 KiB)的读取上限/);return true;});
897
+ assert.deepEqual(s.snapshot(),before,`${name}: nothing renamed, written or created`);
898
+ // Exactly at the cap: switch succeeds and every later command still reads it.
899
+ s.write(name,JSON.stringify(config(padFor(65536))));
900
+ const result=await switchChannel(s.home,'bark',{execPath:node});
901
+ assert.equal(result.fromOff,name==='notify.off.json');
902
+ assert.equal(fs.statSync(path.join(s.home,'notify.json')).size,65536);
903
+ const status=await notifyStatus(s.home);assert.equal(status.config.state,'managed');assert.equal(status.config.reason,undefined);
904
+ assert.equal((await switchChannel(s.home,'bark',{execPath:node})).channel,'bark');
905
+ }
906
+ });
907
+
908
+ // A regular file replaced by a FIFO between the lstat check and open must not
909
+ // block on a writer: the open is non-blocking and the handle's type check refuses it.
910
+ test('a file swapped for a FIFO between the check and open is refused at once instead of waiting for a writer',{skip:!posix},async t=>{
911
+ const s=sandbox(t);
912
+ const cases=[['notify-channel.conf','CHANNEL=bark\n',(file,fileOps)=>readRegularFile(file,'notify-channel.conf',{fileOps}),/notify-channel.conf 必须是普通文件/],
913
+ ['notify.json','{"version":1}',(file,fileOps)=>readRegularFile(file,'notify.json',{fileOps,bytes:true}),/notify.json 必须是普通文件/],
914
+ ['bark.env',`BARK_KEY=${BARK_SECRET}\n`,(file,fileOps)=>readPrivateFile(file,'bark.env',{fileOps}),/bark.env 必须是自己的普通文件且权限 600/]];
915
+ for(const [name,content,read,refused] of cases){
916
+ const file=s.write(name,content),flags=[];
917
+ const swapToFifo={lstat:fsp.lstat,open:async(target,flag)=>{flags.push(flag);fs.unlinkSync(target);
918
+ assert.equal(spawnSync('mkfifo',['-m','600',target]).status,0);return fsp.open(target,flag);}};
919
+ // A build that blocks fails here; the waiting open is then given a writer
920
+ // (held open briefly) so it completes and the test process can still exit.
921
+ let timer,writer=null;
922
+ const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{
923
+ try{writer=fs.openSync(file,fs.constants.O_RDWR|fs.constants.O_NONBLOCK);}catch{}
924
+ reject(new Error('open blocked on the FIFO'));},3000);});
925
+ t.after(async()=>{clearTimeout(timer);await new Promise(resolve=>setTimeout(resolve,200));if(writer!==null)fs.closeSync(writer);});
926
+ await assert.rejects(Promise.race([read(file,swapToFifo),deadline]),error=>{assert.match(error.message,refused);noSecret(error.message);return true;});
927
+ clearTimeout(timer);
928
+ assert.equal(flags.length,1);assert.notEqual(flags[0]&fs.constants.O_NONBLOCK,0,`${name} opened non-blocking`);
929
+ assert.notEqual(flags[0]&fs.constants.O_NOFOLLOW,0);
930
+ fs.unlinkSync(file);
931
+ }
932
+ // Regular files still read exactly as before through the same flags.
933
+ s.write('bark.env',`BARK_KEY=${BARK_SECRET}\n`);
934
+ assert.equal(await readPrivateFile(path.join(s.home,'bark.env'),'bark.env'),`BARK_KEY=${BARK_SECRET}\n`);
935
+ assert.deepEqual(await readRegularFile(s.write('notify.json','{}'),'notify.json',{bytes:true}),Buffer.from('{}'));
936
+ });