@skathio/somi 4.1.0 → 5.0.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 (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +83 -228
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +28 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +40 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +165 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +73 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +38 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +181 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -226
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -278
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -301
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -128
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -371
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -141
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,198 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of scripts/lib/path-facts.mjs. Risk: a committed config or a hostile path list lowering a floor (a glob
3
- // removed, a container dropped so two modules fold into one), or a config glob costing unbounded time. Pure strings,
4
- // no mocks. Usage: node path-facts-tests.mjs <module path>; tests/scripts/fact-sheet.sh runs it on the module and on
5
- // scratch mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network.
6
-
7
- import { spawnSync } from 'node:child_process';
8
- import fs from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { fileURLToPath, pathToFileURL } from 'node:url';
13
-
14
- const modPath = path.resolve(process.argv[2]);
15
- const M = await import(pathToFileURL(modPath).href);
16
- const { classifyPaths, MAX_GLOBS, MAX_GLOB_CHARS, BUILTIN_CONTAINERS } = M;
17
- const { mergeConfig } = await import(pathToFileURL(path.join(path.dirname(fileURLToPath(import.meta.url)), '../../../scripts/lib/config-files.mjs')).href);
18
-
19
- let pass = 0; let fail = 0;
20
- const skip = (name, why) => console.log(` skip ${name} (${why})`);
21
- const clip = (v) => JSON.stringify(v).slice(0, 160);
22
- const check = (name, got, want) => {
23
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${clip(want)}, got ${clip(got)})`); }
24
- };
25
- // A throw is reported as a result, so a broken module fails the named check instead of ending the run.
26
- const run = (paths, config) => { try { return classifyPaths(paths, config); } catch { return { threw: true }; } };
27
- const one = (p, config) => run([p], config).files?.[0] ?? { threw: true };
28
- const hits = (p, config) => { const f = one(p, config); return [f.sensitive, f.boundary, f.contract]; };
29
- const modules = (paths, config) => run(paths, config).modules;
30
- const sizing = (o) => ({ sizing: o });
31
- const with1 = (key, list) => sizing({ [key]: list });
32
-
33
- console.log('== path facts: glob classes ==');
34
- check('an unconfigured repo flags .env, a migrations directory, a lockfile and a route file', [
35
- hits('.env'), hits('db/migrations/001_init.sql'), hits('package-lock.json'), hits('src/routes/users.js'),
36
- ], [
37
- [['deny_list'], ['deny_list'], []],
38
- [['migrations'], ['data'], []],
39
- [[], [], ['lockfile']],
40
- [[], ['routes'], []],
41
- ]);
42
- check('flags secrets, auth, crypto and infra as sensitive', [
43
- hits('lib/client_secret.go')[0], hits('src/auth/login.ts')[0], hits('pkg/crypto/aes.go')[0], hits('.github/workflows/ci.yml')[0], hits('infra/main.tf')[0],
44
- ], [['secrets'], ['auth'], ['crypto'], ['infra', 'ci'], ['infra']]);
45
- check('flags sinks and contracts', [
46
- hits('app/uploads/handler.py')[1], hits('x/Spawn.js')[1], hits('db/schema.sql')[1], hits('package.json')[2], hits('api/openapi.yaml')[2], hits('proto/a.proto')[2],
47
- ], [['input'], ['process'], ['data'], ['manifest'], ['schema'], ['schema']]);
48
- const CI_PATHS = ['.github/workflows/ci.yml', '.gitlab-ci.yml', 'x/.circleci/config.yml', '.travis.yml', 'azure-pipelines.yml', 'bitbucket-pipelines.yml', 'Jenkinsfile', 'ci/Jenkinsfile', '.gitlab/ci/build.yml', '.gitlab-ci.yaml', 'action.yml', 'sub/action.yaml', '.gitea/workflows/w.yml', '.forgejo/workflows/w.yml', 'Jenkinsfile.groovy', 'build.jenkinsfile', 'azure-pipelines-ci.yaml', '.azure-pipelines/b.yml', '.buildkite/pipeline.yml', '.drone.yml', '.woodpecker/b.yml', '.woodpecker.yaml', 'appveyor.yml', 'cloudbuild.yaml', 'buildspec.yml', '.pre-commit-config.yaml'];
49
- check('every CI system is a ci hit in the sensitive list (a sensitive name, so it raises), and a look-alike is not', [CI_PATHS.map((p) => hits(p)[0].includes('ci')), ['docs/ci.md', 'src/jenkins.md', 'ci/run.sh', 'azure.md', 'action.md'].map((p) => hits(p)[0].includes('ci'))], [CI_PATHS.map(() => true), Array(5).fill(false)]);
50
- check('does not flag ordinary source or a look-alike', [hits('src/util/strings.js'), hits('docs/author.md'), hits('README.md')], [[[], [], []], [[], [], []], [[], [], []]]);
51
- check('matching is case-folded', [hits('DB/Migrations/001.SQL'), hits('SRC/Routes/X.JS')[1]], [[['migrations'], ['data'], []], ['routes']]);
52
- check('a directory glob with a slash is anchored and also matches what is under it', [
53
- hits('x/y.js', with1('sensitive_paths', ['x'])), hits('a/x/y.js', with1('sensitive_paths', ['x/**'])), hits('x/a/b.js', with1('sensitive_paths', ['x/**'])), hits('a/x/b.js', with1('sensitive_paths', ['**/x'])),
54
- ].map((h) => h[0]), [['config'], [], ['config'], ['config']]);
55
- check('a config glob is literal text except star, question mark and a ** segment', [
56
- hits('abc', with1('sensitive_paths', ['a.c']))[0], hits('a.c', with1('sensitive_paths', ['a.c']))[0], hits('(x|y)', with1('sensitive_paths', ['(x|y)']))[0],
57
- hits('x', with1('sensitive_paths', ['(x|y)']))[0], hits('aXc', with1('sensitive_paths', ['a?c']))[0], hits('abbc', with1('sensitive_paths', ['a*c']))[0],
58
- ], [[], ['config'], ['config'], [], ['config'], ['config']]);
59
-
60
- console.log('== path facts: production, test and module key ==');
61
- check('a test file is not a production file, and a fixtures directory is not a test directory', run(['tests/a.sh', 'src/a.test.js', 'lib/b_test.go', 'x/__tests__/c.js', 'test_d.py', 'scripts/lib/e-tests.mjs', 'src/f.js', 'docs/g.md', 'app/fixtures/seed.json']).production_files, 3);
62
- check('module key: first segment, a root file is the one module with the empty key, a deep file is its first directory', [
63
- one('README.md').module, one('LICENSE').module, one('scripts/lib/a.mjs').module, one('a/b/c/d.js').module, one('./x\\y.js').module,
64
- ], ['', '', 'scripts', 'a', 'x']);
65
- check('module key under a built-in container is <container>/<segment>; a file directly in a container is the container', [
66
- one('packages/a/x.js').module, one('src/a/b/c.js').module, one('apps/web/x').module, one('libs/core/x').module, one('src/main.js').module,
67
- ], ['packages/a', 'src/a', 'apps/web', 'libs/core', 'src']);
68
- check('a configured container splits its children, however its name is written', [one('services/a/x', with1('module_containers', ['services'])).module, one('Services/B/x', with1('module_containers', ['SERVICES'])).module, one('services/a/x').module,
69
- one('services/a/x', with1('module_containers', ['services/'])).module, one('services/a/x', with1('module_containers', ['./services'])).module], ['services/a', 'Services/B', 'services', 'services/a', 'services/a']);
70
- const LONG_PATH = 'a/'.repeat(200);
71
- check('an unusable entry has a module key no real path can have: it never merges with a first segment like ?0', [modules([LONG_PATH, '?0/a.js']), modules([LONG_PATH, '/?0/a.js']), modules([null, '?0/a.js', '?1/a.js', LONG_PATH])], [2, 2, 4]);
72
- check('the module key keeps the case of the path: packages/Foo and packages/foo are two modules, the container still matches folded', [modules(['packages/Foo/x', 'packages/foo/y']), one('PACKAGES/a/x').module], [2, 'PACKAGES/a']);
73
- check('a trailing dot or space on a segment does not hide a glob hit', [hits('package.json.')[2], hits('db/migrations ./1.sql')[0]], [['manifest'], ['migrations']]);
74
- check('the trim is an extra reading: a dots-only directory does not shift an anchored glob, and a trailing dot does not hide a wildcard', [
75
- hits('infra/.../prod/db.yml', with1('sensitive_paths', ['infra/*/prod/**']))[0], hits('infra/prod/db.yml', with1('sensitive_paths', ['infra/*/prod/**']))[0], hits('billing./x', with1('sensitive_paths', ['billing.*']))[0],
76
- ], [['config'], [], ['config']]);
77
- check('a name that trims to a test directory is still production code', [one('tests./a.js').production, run(['tests./a.js', 'tests/a.js']).production_files], [true, 1]);
78
- check('a code point that folds to a separator stays inside its segment: tests\uff0fx.js is production code, not a test directory', [one('tests\uff0fx.js').production, run(['tests\uff0fx.js', 'src/a.js']).production_files], [true, 2]);
79
- const SEP_ANCHORED = with1('sensitive_paths', ['infra/*/prod/**']); const SEP_PLAIN = with1('sensitive_paths', ['infra/a/b/**']);
80
- check('a code point that folds to a separator: the primary reading keeps it one segment (hits infra/*/prod/**), the re-split reading is an extra one (hits infra/a/b/**), and neither widens a plain path', [
81
- hits('infra/a\uff0fb/prod/db.yml', SEP_ANCHORED)[0], hits('infra/a\uff0fb/x', SEP_PLAIN)[0], hits('infra/a/b/prod/db.yml', SEP_ANCHORED)[0], hits('infra/ab/x', SEP_PLAIN)[0],
82
- ], [['config'], ['config'], [], []]);
83
- check('a glob or a container written with a trailing dot or space is trimmed like a path segment', [
84
- hits('services/x', with1('sensitive_paths', ['services.']))[0], hits('services./x', with1('sensitive_paths', ['services']))[0], hits('a/b', with1('sensitive_paths', ['a./b']))[0],
85
- one('services/a/x', with1('module_containers', ['services.'])).module, one('services./a/x', with1('module_containers', ['services'])).module, one('services./a/x', with1('module_containers', ['services. '])).module,
86
- ], [['config'], ['config'], ['config'], 'services/a', 'services./a', 'services./a']);
87
-
88
- console.log('== path facts: the deny list floors whatever the config says ==');
89
- const withEnv = run(['src/a.js', '.env']); const without = run(['src/a.js', 'src/b.js']);
90
- check('a denied name reports a deny_list hit in the sensitive and boundary lists and the same list without it does not', [withEnv.sensitive, withEnv.boundary, without.sensitive.includes('deny_list'), without.boundary.includes('deny_list')], [['deny_list'], ['deny_list'], false, false]);
91
- check('every path carries the denied fact, and a denied name hits even when the config tries to list others only', [
92
- one('src/a.js').denied, one('config/KEY.PEM').denied, one('.git/config', with1('sensitive_paths', ['zzz'])).sensitive.includes('deny_list'), one('id_rsa', sizing({ sensitive_paths: [], module_containers: [] })).boundary,
93
- ], [false, true, true, ['deny_list']]);
94
- check('an unusable entry floors instead of vanishing: not a string, over the length cap, not an array, over the count cap', [
95
- one(null).denied, one('a/'.repeat(200)).denied, run('src/a.js').sensitive, run(Array(41).fill('a.js')).boundary, one('a/'.repeat(200)).path,
96
- ], [true, true, ['deny_list'], ['deny_list'], '']);
97
- check('an unusable list reports the counts at the path cap', [run('src/a.js'), run(Array(41).fill('a.js'))].map((r) => [r.files.length, r.production_files, r.modules]), [[40, 40, 40], [40, 40, 40]]);
98
-
99
- console.log('== path facts: config only adds ==');
100
- const ALL = ['.env', 'db/migrations/1.sql', 'package-lock.json', 'src/routes/u.js', 'lib/secret.js', '.circleci/config.yml'];
101
- const base = run(ALL);
102
- check('config globs are added to the built-ins, not instead of them', [hits('zed/x.js', with1('sensitive_paths', ['zed']))[0], run(ALL, with1('sensitive_paths', ['zzz'])).sensitive], [['config'], base.sensitive]);
103
- const a = { sizing: { sensitive_paths: ['a/**'] } }; const b = { sizing: { sensitive_paths: ['b/**'] } };
104
- const merged = mergeConfig(a, b);
105
- check('mergeConfig replaces an array between layers: global [a] plus project [b] is [b]', merged.sizing.sensitive_paths, ['b/**']);
106
- check('the merged config adds only b, and every built-in still flags', [hits('b/x')[0], hits('a/x')[0], hits('b/x', merged)[0], hits('a/x', merged)[0], run(ALL, merged).sensitive.filter((n) => n !== 'config')], [[], [], ['config'], [], base.sensitive]);
107
- const LAYER_MIX = [with1('sensitive_paths', ['q']), with1('sensitive_paths', []), sizing({ sensitive_paths: ['..'] }), sizing({ module_containers: ['a..b'] }), null, undefined, 'x'];
108
- check('a later layer, valid, empty, invalid or absent, cannot remove an earlier layer\'s sensitive glob', LAYER_MIX.map((p) => hits('b/x', [with1('sensitive_paths', ['b']), p])[0]), LAYER_MIX.map(() => ['config']));
109
- check('a later layer cannot remove an earlier layer\'s container, and an earlier layer cannot remove a later one\'s', LAYER_MIX.map((p) => [modules(['services/a/x', 'services/b/y'], [with1('module_containers', ['services']), p]), modules(['services/a/x', 'services/b/y'], [p, with1('module_containers', ['services'])])]), LAYER_MIX.map(() => [2, 2]));
110
- check('one invalid key drops only itself: its sibling key and the other layers still apply', [
111
- hits('good/x', sizing({ sensitive_paths: ['good'], module_containers: ['..'] }))[0], modules(['services/a/x', 'services/b/y'], sizing({ sensitive_paths: ['..'], module_containers: ['services'] })),
112
- hits('good/x', [sizing({ sensitive_paths: ['..'] }), sizing({ sensitive_paths: ['good'] })])[0], hits('one/x', [sizing({ sensitive_paths: ['one', '..'] })])[0],
113
- ], [['config'], 2, ['config'], []]);
114
- check('config cannot remove a built-in glob even when it lists nothing or something else', [run(ALL, with1('sensitive_paths', [])).sensitive, run(ALL, sizing({ sensitive_paths: ['q'], module_containers: ['q'] })).files.map((f) => f.sensitive.length > 0)], [base.sensitive, [true, true, false, false, true, true]]);
115
- check('a config cannot remove the ci class: it stays a sensitive hit with an empty list, an other list and a hostile one', [with1('sensitive_paths', []), with1('sensitive_paths', ['zzz']), with1('sensitive_paths', ['..']), null].map((c) => hits('.circleci/config.yml', c)[0].includes('ci')), [true, true, true, true]);
116
-
117
- const WRAP = (g, p) => ({ config: with1('sensitive_paths', ['merged']), global: { path: null, present: true, config: g }, project: { path: 'p', present: true, config: p } });
118
- check('loadConfig\'s {global, project} result is the layers [global.config, project.config]: an empty project list keeps the global glob, and the merged .config is not read', [
119
- hits('zed/x', WRAP(with1('sensitive_paths', ['zed']), with1('sensitive_paths', [])))[0], hits('p/x', WRAP(with1('sensitive_paths', ['zed']), with1('sensitive_paths', ['p'])))[0],
120
- hits('merged/x', WRAP({}, {}))[0], hits('zed/x', WRAP(with1('sensitive_paths', ['zed']), {}))[0], hits('zed/x', { global: {}, project: {} })[0],
121
- ], [['config'], ['config'], [], ['config'], []]);
122
-
123
- console.log('== path facts: caps count the folded text ==');
124
- const FDFA = '\ufdfa'; // one character that folds to eighteen
125
- const L = with1('sensitive_paths', ['q']);
126
- check('a path whose fold exceeds the path cap is an unusable entry with the floor, one at the cap is usable', [one(FDFA.repeat(14)).denied, one(FDFA.repeat(14)).path, one(FDFA.repeat(13)).denied, one('a/'.repeat(119) + 'a').denied], [true, '', false, false]);
127
- check('a glob whose fold exceeds the glob cap is refused and named, and so is one whose raw text does though its fold is short; one at the cap is accepted', [hits('q/x', with1('sensitive_paths', [FDFA.repeat(6)]))[0], run(['a.js'], with1('sensitive_paths', [FDFA.repeat(6)])).refused,
128
- run(['a.js'], with1('sensitive_paths', ['e\u0301'.repeat(51)])).refused, run(['a.js'], with1('sensitive_paths', [FDFA.repeat(5)])).refused], [[], ['sensitive_paths'], ['sensitive_paths'], []]);
129
- check('more layers than loadConfig supplies floor every path, and two do not', [run(['a.js'], [L, L, L]).files[0].denied, run(['a.js'], [L, L]).files[0].denied, run(['a.js'], [L, L]).files[0].path], [true, false, 'a.js']);
130
- check('a refused key is named in refused, once, and a valid or absent one is not', [run(['a.js'], sizing({ sensitive_paths: ['*.'], module_containers: 'x' })).refused, run(['a.js'], [with1('sensitive_paths', 5), with1('sensitive_paths', 6)]).refused, run(['a.js'], sizing({ sensitive_paths: ['q'] })).refused, run(['a.js']).refused], [['module_containers', 'sensitive_paths'], ['sensitive_paths'], [], []]);
131
-
132
- console.log('== path facts: the module override only splits ==');
133
- const PAIR = ['packages/a/x', 'packages/b/y'];
134
- check('an unconfigured repo counts packages/a and packages/b as two modules', modules(PAIR), 2);
135
- const FOLDING = [undefined, {}, null, 'x', [], sizing({}), sizing(null), with1('module_containers', []), with1('module_containers', ['services']), with1('sensitive_paths', ['q']),
136
- sizing({ module_containers: ['packages'] }), sizing({ module_containers: ['src'], sensitive_paths: [] }), sizing({ module_containers: 'packages' }), sizing({ module_containers: ['..', 'a/b'] }),
137
- sizing({ module_containers: [], sensitive_paths: 7 }), { sizing: { module_containers: { packages: false } } }, { module_containers: [] }, sizing({ __proto__: { module_containers: [] } })];
138
- const ROWS = ['packages/a/x', 'packages/b/y', 'src/a/y', 'services/a/x', 'services/b/y', 'README.md'];
139
- check('still two with an empty container list, a config that omits the built-ins, and a config naming extra containers', FOLDING.map((c) => modules(PAIR, c)), FOLDING.map(() => 2));
140
- check('no config in a finite table yields a module count below the unconfigured one', FOLDING.map((c) => modules(ROWS, c) >= modules(ROWS)), FOLDING.map(() => true));
141
- check('extra containers raise the count and nothing else does', [modules(ROWS), modules(ROWS, with1('module_containers', ['services']))], [5, 6]);
142
- check('one name under two containers is two modules, and two files in one module are one', [modules(['packages/a/x', 'src/a/y']), modules(['packages/a/x', 'packages/a/z']), one('src/a/y').module], [2, 1, 'src/a']);
143
- check('the built-in containers are the stated list', BUILTIN_CONTAINERS, ['packages', 'apps', 'libs', 'src']);
144
-
145
- console.log('== path facts: hostile config ==');
146
- const HOSTILE = [
147
- with1('sensitive_paths', ['x'.repeat(10000)]), with1('sensitive_paths', ['x'.repeat(MAX_GLOB_CHARS + 1)]), with1('sensitive_paths', ['..']), with1('sensitive_paths', ['a/../b']), with1('sensitive_paths', ['/etc/passwd']),
148
- with1('sensitive_paths', ['C:\\x']), with1('sensitive_paths', ['\\x']), with1('sensitive_paths', 'abc'), with1('sensitive_paths', 5), with1('sensitive_paths', { a: 1 }), with1('sensitive_paths', [1]),
149
- with1('sensitive_paths', ['']), with1('sensitive_paths', ['/']), with1('sensitive_paths', ['.']), with1('sensitive_paths', ['./']), with1('sensitive_paths', ['a\u0000b']), with1('sensitive_paths', ['a\u202eb']), with1('sensitive_paths', Array(MAX_GLOBS + 1).fill('q')),
150
- with1('sensitive_paths', [' ']), with1('sensitive_paths', ['. ']), with1('sensitive_paths', ['*.']), with1('sensitive_paths', ['*/.']), with1('sensitive_paths', ['*\uff0f.']), with1('sensitive_paths', ['a/**. /b']), with1('module_containers', [' ']), with1('module_containers', ['. ']),
151
- with1('module_containers', ['a/b']), with1('module_containers', ['..']), with1('module_containers', ['a\\b']), with1('module_containers', 'src'),
152
- sizing({ sensitive_paths: ['good', '..'], module_containers: ['..'] }), with1('module_containers', ['*']), with1('module_containers', ['a*']), with1('module_containers', ['**']),
153
- ];
154
- const HOSTILE_PATHS = ['.env', 'good/x.js', 'services/a/x', 'services/b/y', 'q/z', 'src/routes/a.js', 'packages/a/x', 'packages/b/y', '../x', 'a/../b', 'etc/passwd', 'x', 'c:/x', 'a\u0000b', 'a\u202eb', 'a/b.js', 'a/c/x', 'a/d/y', 'x'.repeat(MAX_GLOB_CHARS + 1)];
155
- const baseline = run(HOSTILE_PATHS);
156
- check('a hostile section reads as the defaults: the same facts as no config', HOSTILE.map((c) => ({ ...run(HOSTILE_PATHS, c), refused: [] })), HOSTILE.map(() => baseline));
157
- check('the caps are stated: a section at the limit is accepted', [hits('q', with1('sensitive_paths', Array(MAX_GLOBS).fill('q')))[0], hits('y'.repeat(MAX_GLOB_CHARS), with1('sensitive_paths', ['y'.repeat(MAX_GLOB_CHARS)]))[0]], [['config'], ['config']]);
158
-
159
- // Pathological shapes in their own process with a clock, so a hang is a failed check and not a stuck suite.
160
- const SHAPES = ['(a+)+$', '(a|aa)+$', 'a*a*a*a*a*a*a*a*a*a*b', '**/**/**/**/**/**/x', '*?*?*?*?*?*?*?*?c'];
161
- const VICTIMS = [`${'a'.repeat(32)}!`, 'a/'.repeat(100), 'a'.repeat(200)];
162
- // The real worst case under the caps (measured on the development machine): 40 paths, the cap, each of 119 segments with a trailing-dot segment and
163
- // a U+FF0F, so all four readings differ, against two full layers (what loadConfig supplies) of 32 globs that keep every position alive (`**/a/` x19 and one
164
- // of 31 adjacent **): about 2.5 s in-process, about 60 ms a path. The caps on the folded text are what bound it: before them a glob of `*` and 98 `?` against
165
- // U+FDFA paths took 17 s. This check times 20 such paths, about 1.3 s, against a 2.6 s bound; the quadratic-step mutant takes about 5.4 s: a margin of about 2x each side.
166
- // A caller with many paths bounds the total itself (escalation-facts reads the clock between chunks).
167
- const GLOBS = Array.from({ length: MAX_GLOBS }, (_, i) => (i ? '**/a/'.repeat(19) : '**/'.repeat(31)) + 'z');
168
- const WORST = `${'a/'.repeat(58)}a./${'a/'.repeat(30)}a/${'a/'.repeat(28)}a`;
169
- // Adjacent ** in a glob are one step: 64 globs of 31 of them on the same paths take about 0.12 s collapsed (40 paths) and about 2.2 s without the collapse; bound 1 s.
170
- const STARS = Array(MAX_GLOBS).fill(`${'**/'.repeat(31)}z`);
171
- const child = `import * as M from ${JSON.stringify(pathToFileURL(modPath).href)};
172
- const jobs = JSON.parse(process.argv[1]);
173
- console.log(JSON.stringify(jobs.map(({ paths, layers }) => M.classifyPaths(paths, layers.map((globs) => ({ sizing: { sensitive_paths: globs } }))).sensitive)));`;
174
- const timedJobs = (jobs, boundMs) => spawnSync(process.execPath, ['--input-type=module', '-e', child, JSON.stringify(jobs)], { encoding: 'utf8', timeout: boundMs });
175
- const outcome = (t) => (t.status === 0 ? JSON.parse(t.stdout) : `child ended ${t.status ?? t.signal}`);
176
- // fact-sheet.sh sets SKIP_TIMED=mutant-run for the scratch mutants that these checks do not name, so most of them need not wait for the child.
177
- // Only that exact value skips: a stray exported SKIP_TIMED=1 never turns the cost check off, here or when this lib is run directly.
178
- // Residual, stated: the stray-seam check there runs the real module with SKIP_TIMED=1, not a stale copy that is named like a sentinel; the guard is the exact comparison below.
179
- const skipTimed = process.env.SKIP_TIMED === 'mutant-run';
180
- const SHAPE_JOBS = SHAPES.map((s) => ({ paths: VICTIMS, layers: [[s]] }));
181
- if (skipTimed) skip('nested-quantifier shapes, star runs and two layers of the largest glob list', 'SKIP_TIMED=mutant-run is set by the mutation runs that do not name this check');
182
- else check('nested-quantifier shapes, star runs and two layers of the largest glob list on 119-segment paths with four readings finish inside the time bound and match nothing',
183
- outcome(timedJobs([...SHAPE_JOBS, { paths: Array(20).fill(WORST), layers: [GLOBS, GLOBS] }], 2600)), [...SHAPES.map(() => []), []]);
184
- if (skipTimed) skip('adjacent ** segments in a glob are one step', 'SKIP_TIMED=mutant-run is set by the mutation runs that do not name this check');
185
- else check('adjacent ** segments in a glob are one step: 64 globs of 31 of them on 40 four-reading paths finish inside the time bound', outcome(timedJobs([{ paths: Array(40).fill(WORST), layers: [STARS, STARS] }], 1000)), [[]]);
186
- check('a nested-quantifier glob is literal text: it matches only itself', [hits('(a+)+$', with1('sensitive_paths', ['(a+)+$']))[0], hits('a', with1('sensitive_paths', ['(a+)+$']))[0]], [['config'], []]);
187
-
188
- console.log('== path facts: no content ==');
189
- const SECRET = 'TOPSECRET-FILE-CONTENT';
190
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'path-facts-')); process.on('exit', () => fs.rmSync(dir, { recursive: true, force: true }));
191
- fs.mkdirSync(path.join(dir, 'src')); fs.writeFileSync(path.join(dir, 'src/a.js'), SECRET); fs.writeFileSync(path.join(dir, '.env'), SECRET);
192
- const result = run(['src/a.js', '.env', 'src/b.js']);
193
- check('a result holds only the fixed fact fields, none of the file text', [JSON.stringify(result).includes(SECRET), Object.keys(result), Object.keys(result.files[0])], [false,
194
- ['files', 'production_files', 'modules', 'sensitive', 'boundary', 'contract', 'refused'], ['path', 'denied', 'production', 'module', 'sensitive', 'boundary', 'contract']]);
195
- check('the module touches no filesystem API', /node:fs|readFile|openSync|statSync/.test(fs.readFileSync(modPath, 'utf8')), false);
196
-
197
- console.log(`SUMMARY ${pass + fail} ${fail}`);
198
- process.exit(fail ? 1 : 0);
@@ -1,201 +0,0 @@
1
- #!/usr/bin/env node
2
- // Tests of scripts/lib/path-safety.mjs. Risk: a model-named path reaching the filesystem outside the project or a
3
- // secret inside it. Real temp tree, no mocks; the only seams are the module's own (`realpath`, `constants`). Usage:
4
- // node path-safety-tests.mjs <module path>; tests/scripts/fact-sheet.sh runs it on the module and on scratch
5
- // mutants of it, and each mutant must turn the test named there red. Hermetic: no model, no network, no randomness.
6
-
7
- import { spawnSync } from 'node:child_process';
8
- import fs from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { fileURLToPath, pathToFileURL } from 'node:url';
13
-
14
- const modPath = path.resolve(process.argv[2]);
15
- const M = await import(pathToFileURL(modPath).href);
16
- const { inspectPath, denyListed, refuseList, REFUSAL_IDS, MAX_PATHS, MAX_PATH_CHARS, MAX_FILE_BYTES } = M;
17
-
18
- const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'path-safety-')));
19
- process.on('exit', () => { try { fs.chmodSync(path.join(base, 'root', 'locked'), 0o700); } catch { /* already gone */ } fs.rmSync(base, { recursive: true, force: true }); });
20
- const root = path.join(base, 'root');
21
- const put = (rel, body = 'x') => { fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); fs.writeFileSync(path.join(root, rel), body); };
22
- put('a.txt', 'hello'); put('sub/b.txt'); put('..x'); put('locked/.env'); put('locked/f.txt'); put('config/secret.txt');
23
- fs.mkdirSync(path.join(root, 'folder')); fs.mkdirSync(path.join(base, 'outside'));
24
- fs.writeFileSync(path.join(base, 'outside', 'secret.txt'), 'outside');
25
- fs.symlinkSync('a.txt', path.join(root, 'link.txt')); fs.symlinkSync('sub', path.join(root, 'linkdir'));
26
- fs.symlinkSync('../outside/secret.txt', path.join(root, 'escape.txt')); fs.symlinkSync('../outside/secret.txt', path.join(root, '.env'));
27
- fs.writeFileSync(path.join(root, 'big.bin'), Buffer.alloc(MAX_FILE_BYTES + 1)); fs.writeFileSync(path.join(root, 'max.bin'), Buffer.alloc(MAX_FILE_BYTES));
28
- const fifo = spawnSync('mkfifo', [path.join(root, 'pipe')]).status === 0;
29
- fs.chmodSync(path.join(root, 'locked'), 0o000);
30
-
31
- let pass = 0; let fail = 0;
32
- const skip = (name, why) => console.log(` skip ${name} (${why})`);
33
- const check = (name, got, want) => {
34
- if (isDeepStrictEqual(got, want)) { pass++; console.log(` ok ${name}`); } else { fail++; console.log(` FAIL ${name} (want ${JSON.stringify(want)}, got ${JSON.stringify(got)})`); }
35
- };
36
- // A throw is reported as a result, so a broken module fails the named check instead of ending the run.
37
- const ins = (raw, probe, seams) => { try { return inspectPath(root, raw, probe, seams); } catch { return { kind: 'threw' }; } };
38
- const refusalOf = (raw, seams) => { const r = ins(raw, null, seams); return r.kind === 'refused' ? r.refusal : r.kind; };
39
- const refusals = (list, seams) => list.map((p) => refusalOf(p, seams));
40
- const same = (n, v) => Array(n).fill(v);
41
- const DENIED = { kind: 'denied' };
42
-
43
- // Runs fn with the filesystem entry points counted; returns the names called.
44
- const WATCH = ['lstatSync', 'statSync', 'openSync', 'fstatSync', 'closeSync', 'readSync', 'readFileSync', 'accessSync', 'existsSync', 'readdirSync', 'readlinkSync', 'opendirSync'];
45
- function watched(fn) {
46
- const calls = []; const saved = {}; const realpath = fs.realpathSync; const native = realpath.native;
47
- for (const n of WATCH) { saved[n] = fs[n]; fs[n] = (...a) => { calls.push(n); return saved[n](...a); }; }
48
- fs.realpathSync = Object.assign((...a) => { calls.push('realpathSync'); return realpath(...a); }, { native: (...a) => { calls.push('realpathSync.native'); return native(...a); } });
49
- try { fn(); } finally { fs.realpathSync = realpath; for (const n of WATCH) fs[n] = saved[n]; }
50
- return calls;
51
- }
52
-
53
- // A call in its own process with a clock, so a hang is a failed check and not a stuck suite.
54
- // `swap` stands in for a file replaced by another between the walk and the open: the canonical path becomes it.
55
- function inChild(raw, swap = '') {
56
- const seam = 'process.argv[3] ? { realpath: (p) => (p.endsWith(process.argv[2]) ? process.argv[3] : fs.realpathSync.native(p)) } : undefined';
57
- const code = `import fs from 'node:fs'; import * as M from ${JSON.stringify(pathToFileURL(modPath).href)}; console.log(JSON.stringify(M.inspectPath(process.argv[1], process.argv[2], null, ${seam})));`;
58
- const r = spawnSync(process.execPath, ['--input-type=module', '-e', code, root, raw, swap], { encoding: 'utf8', timeout: 5000 });
59
- return r.status === 0 ? JSON.parse(r.stdout) : `child ended ${r.status ?? r.signal}`;
60
- }
61
-
62
- console.log('== path safety: refusing malformed names ==');
63
- check('refuses an absolute path, a drive path and a UNC path', refusals(['/etc/passwd', 'C:\\x', 'c:x', '\\\\srv\\share\\x', '\\x']), same(5, 'absolute'));
64
- check('refuses a parent segment in any position or separator', refusals(['../a.txt', 'sub/../../a.txt', 'sub\\..\\..\\a.txt', 'a/..', '.. /x', '..../x']), same(6, 'traversal'));
65
- check('refuses NUL and control characters', refusals(['a\0.txt', 'a\n.txt', 'a\u001b[0m', 'a\u007f', 'a\u0085']), same(5, 'control'));
66
- check('refuses bidi, zero-width and line-separator characters', refusals(['\u202eagro.txt', 'a\u2066b', 'a\u200bb', 'a\u2028b', 'a\ufeffb']), same(5, 'control'));
67
- check('refuses lone surrogates and keeps paired ones', [refusals(['a\ud800b', '\udc00']), ins('\u{1F600}.txt').kind], [same(2, 'control'), 'contained']);
68
- check('refuses an empty, dot-only or non-string name', refusals(['', '.', './', './/.', 5, null, undefined, {}, ['a.txt']]), same(9, 'malformed'));
69
- const LONG = `${'.'.repeat(10000)}x`; // long enough that a quadratic trim costs seconds, short enough to keep the suite quick
70
- const t0 = performance.now();
71
- const longResults = [ins(LONG), refuseList(Array(MAX_PATHS + 1).fill(LONG)), refuseList([LONG]), denyListed(LONG)];
72
- check('a huge name is refused as path_length and denied, in bounded time', [longResults, performance.now() - t0 < 500], [[{ kind: 'refused', refusal: 'path_length', denied: true }, { kind: 'refused', refusal: 'path_count', denied: true }, null, true], true]);
73
- check('refuses a name over the length cap and accepts one at it', [refusalOf('a'.repeat(MAX_PATH_CHARS + 1)), ins('a'.repeat(MAX_PATH_CHARS))], ['path_length', { kind: 'contained', exists: false, rel: 'a'.repeat(MAX_PATH_CHARS) }]);
74
- check('refuses a list over the count cap and accepts one at it', [refuseList(Array(MAX_PATHS + 1).fill('a.txt')), refuseList(Array(MAX_PATHS).fill('a.txt')), refuseList('a.txt')], [{ kind: 'refused', refusal: 'path_count' }, null, { kind: 'refused', refusal: 'malformed' }]);
75
- check('a list over the cap keeps the denied fact of any name in it', refuseList([...Array(MAX_PATHS).fill('a.txt'), '.env']), { kind: 'refused', refusal: 'path_count', denied: true });
76
- check('a list far over the cap is refused as denied without being scanned', [refuseList(same(4 * MAX_PATHS + 1, 'a.txt')), refuseList(same(4 * MAX_PATHS, 'a.txt'))], [{ kind: 'refused', refusal: 'path_count', denied: true }, { kind: 'refused', refusal: 'path_count' }]);
77
- const marker = 'SECRETMARK\u00e9';
78
- const hostile = [`../${marker}`, `/${marker}`, `${marker}\0`, `${marker}/nope/x`, `${marker}/a.txt`, `x${'y'.repeat(MAX_PATH_CHARS)}${marker}`];
79
- const out = JSON.stringify(hostile.map((p) => ins(p)));
80
- check('refusals are closed ASCII ids and never contain the input', [REFUSAL_IDS.every((id) => /^[a-z_]+$/.test(id)), Object.isFrozen(REFUSAL_IDS), out.includes('SECRETMARK'), /^[\x20-\x7e]*$/.test(out)], [true, true, false, true]);
81
- check('every refusal the suite saw is in the closed list', [...new Set(hostile.map((p) => refusalOf(p)))].every((id) => REFUSAL_IDS.includes(id)), true);
82
-
83
- console.log('== path safety: the deny list is name-only ==');
84
- const SECRET_NAMES = ['.env', 'cfg/.env.local', 'id_rsa', 'k/id_rsa.pub', 'id_dsa', 'id_ecdsa', 'id_ed25519', 'a.pem', 'a.key', 'a.p12', 'a.pfx', 'a.crt', 'a.cer', 'a.der', 'a.jks', 'a.keystore', 'a.ppk', '.git/config', 'sub/.git/HEAD', '.git',
85
- '.npmrc', 'h/.netrc', '.git-credentials', '.pypirc', '.pgpass', 'terraform.tfstate', 'a.tfvars', 'a.kdbx', '.ssh/config', 'x/.gnupg/k', '.aws/credentials',
86
- 'prod.netrc', 'x.pgpass', 'credentials.json', 'gcp/Credentials.JSON', 'service-account.json', 'service_account.json', 'serviceAccountKey.json', 'service-account-prod.json', 'client_secret.json', 'client_secret_123.apps.json', 'terraform.tfstate.backup', 'prod.tfstate.backup',
87
- 'key.json', 'gcp/Key.JSON', 'key.json.', 'prod.tfstate.1600000000.backup'];
88
- check('denies .env, key and certificate file names and any .git segment', refusals(SECRET_NAMES), same(SECRET_NAMES.length, 'denied'));
89
- const TERMINATED = ['service-account\nprod.json', 'client_secret\u2028x.json', 'client_secret\r\ny.json', 'prod.tfstate.\n.backup', 'prod.tfstate.1\u2029.backup'];
90
- check('denies a name with a line terminator inside the matched span, and the refusal keeps the denied fact', [TERMINATED.filter((n) => !denyListed(n)), TERMINATED.map((n) => inspectPath(root, n).denied)], [[], same(TERMINATED.length, true)]);
91
- check('credentials/ is denied as a directory, with anything under it', ['credentials/token.txt', 'a/credentials/b/c', 'credentials\\x'].map(denyListed), same(3, true));
92
- check('does not deny look-alikes', ['.gitignore', '.github/workflows/a.yml', 'environment.md', 'src/keyboard.js', 'key.txt', 'sub/b.txt', 'a.pem.txt', 'notes~.txt', 'terraform.tf', '.aws.md', 'ssh/a'].map(denyListed), same(11, false));
93
- check('does not deny the look-alikes of the added names', ['credentials.md', 'account.json', 'service-account.md', 'service.json', 'netrc.md', 'netrc', 'pgpass', 'client_secret.md', 'client-secret.txt', 'a.tfstate.bak', 'notes.backup', 'tfstate.backup.md', 'credentials.json.md', 'monkey.json', 'key.json.md', 'prod.tfstate.1600000000.bak'].filter(denyListed), []);
94
- check('a bare config stays allowed on purpose, as a file and as a directory, while the secret-bearing configs are denied by their segment', [['config', 'config/app.yml', 'src/config', 'config.json'].filter(denyListed), ['.git/config', '.ssh/config', '.aws/config', '.kube/config', '.docker/config.json'].filter((n) => !denyListed(n))], [[], []]);
95
- const HOOK_NAMES = ['gcp-key.json', 'a/b-credentials.json', 'service-account.json', 'service-account-prod.json', 'secret.yaml', 'secrets.yaml', 'secret.yml', 'config/secrets.yml', 'secret.json', 'secrets.json', 'credentials', 'x/credentials',
96
- 'a.tfstate', '_netrc', '_pgpass', '.htpasswd', 'a.p8', '.vault-token', '.kube/config', 'x/.docker/config.json'];
97
- check('denies the secret names the repository secret-write hook denies', HOOK_NAMES.filter((n) => !denyListed(n)), []);
98
- check('does not deny look-alikes of those names', ['credentials.md', 'terraform.tf', 'service-account.md', 'secrets.md', 'secret.txt', 'secretsanta.json', 'monkey.json', 'key.json.md', 'a.mp8', 'htpasswd', 'vault-token', 'netrc', 'a.tfstates', '.dockerignore', '.kubernetes', 'docs/kube/a'].filter(denyListed), []);
99
- // Parity with the secret-write hook (hooks/pre-tool/block-secret-writes.mjs, the file hooks.json runs; common.mjs holds only
100
- // the matching helpers). Each SECRET_PATTERNS literal is read from the hook's source with its flags, built with
101
- // new RegExp, and must match the basename of its own representative: the widest name it matches (an unanchored
102
- // suffix gets `a.<suffix>`, so the overlap with a prefix or exact rule cannot hide a gap). Every representative must be
103
- // denied here. The hook runs on import and exports nothing, so its text is the only way to read the list.
104
- // `^config$` is the one pattern whose basename is allowed here (see NAME_EXACT): its representative is denied through
105
- // the `.aws` segment, and a bare `config` is pinned as allowed above.
106
- const HOOK_TABLE = [
107
- [String.raw`/^\.env$/`, '.env'], [String.raw`/^\.env\.local$/`, '.env.local'], [String.raw`/^\.env\.production$/`, '.env.production'], [String.raw`/^\.env\.prod$/`, '.env.prod'],
108
- [String.raw`/^\.env\.staging$/`, '.env.staging'], [String.raw`/^\.env\.secret$/`, '.env.secret'], [String.raw`/\.pem$/`, 'a.pem'], [String.raw`/\.key$/`, 'a.key'], [String.raw`/\.p12$/`, 'a.p12'],
109
- [String.raw`/\.pfx$/`, 'a.pfx'], [String.raw`/\.jks$/`, 'a.jks'], [String.raw`/^id_rsa$/`, 'id_rsa'], [String.raw`/^id_ed25519$/`, 'id_ed25519'], [String.raw`/^id_ecdsa$/`, 'id_ecdsa'],
110
- [String.raw`/^id_dsa$/`, 'id_dsa'], [String.raw`/^credentials$/`, 'credentials'], [String.raw`/^config$/`, '.aws/config'], [String.raw`/-key\.json$/`, 'gcp-key.json'],
111
- [String.raw`/-credentials\.json$/`, 'gcp-credentials.json'], [String.raw`/service-account.*\.json$/`, 'my-service-account-prod.json'], [String.raw`/\.netrc$/`, 'prod.netrc'],
112
- [String.raw`/\.pgpass$/`, 'prod.pgpass'], [String.raw`/\.kdbx$/`, 'a.kdbx'], [String.raw`/secrets?\.ya?ml$/`, 'my-secrets.yml'], [String.raw`/secrets?\.json$/`, 'my-secrets.json'],
113
- ];
114
- // SECRET_HOOK_SOURCE is a seam for fact-sheet.sh's hook mutants only: it is read when it names a file called hook-mutant.mjs, so a
115
- // stray exported value (a stale copy, /dev/null) can never repoint the parity check, here or when this lib is run directly.
116
- const hookSeam = path.basename(process.env.SECRET_HOOK_SOURCE ?? '') === 'hook-mutant.mjs' ? process.env.SECRET_HOOK_SOURCE : undefined;
117
- const hookFile = hookSeam ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../hooks/pre-tool/block-secret-writes.mjs');
118
- // The block runs from its opening line to the first line that is just `];`, so a character class inside a pattern cannot end it early.
119
- const hookLiterals = (() => {
120
- try {
121
- if (fs.statSync(hookFile).size > 65536) return null;
122
- const block = /const SECRET_PATTERNS = \[\n([\s\S]*?)\n\];/.exec(fs.readFileSync(hookFile, 'utf8'));
123
- if (!block) return null;
124
- const lines = block[1].split('\n').filter((l) => l.trim() !== '' && !l.trim().startsWith('//'));
125
- const found = lines.map((l) => /^\s*(\/(.+)\/([a-z]*)),\s*(?:\/\/.*)?$/.exec(l));
126
- return { patterns: found.filter(Boolean).map((m) => ({ literal: m[1], source: m[2], flags: m[3] })), unparsed: found.filter((m) => !m).length };
127
- } catch { return null; }
128
- })();
129
- const parsed = hookLiterals?.patterns ?? [];
130
- const repOf = new Map(HOOK_TABLE);
131
- // A pattern whose flags changed has no row of its own; it is still tried against the representative of its body.
132
- const repOfBody = new Map(HOOK_TABLE.map(([literal, rep]) => [literal.slice(1, literal.lastIndexOf('/')), rep]));
133
- const hookBase = (rep) => rep.replace(/\\/g, '/').split('/').pop();
134
- check('the hook secret-name patterns and the representative table list the same literals, flags included, and every line parses', [hookLiterals !== null, hookLiterals?.unparsed, parsed.filter((p) => !repOf.has(p.literal)).map((p) => p.literal), HOOK_TABLE.map(([l]) => l).filter((l) => !parsed.some((p) => p.literal === l))], [true, 0, [], []]);
135
- check('each hook pattern, built with its own flags, matches the basename of its representative', parsed.filter((p) => { const rep = repOf.get(p.literal) ?? repOfBody.get(p.source); return rep !== undefined && !new RegExp(p.source, p.flags).test(hookBase(rep)); }).map((p) => p.literal), []);
136
- check('every representative of a hook pattern is denied here', HOOK_TABLE.filter(([, rep]) => !denyListed(rep)).map(([l]) => l), []);
137
- const WIN = ['ENV~1', 'ENV~1.LOC', 'GIT~1/config', 'key.pem::$DATA', 'a/b:c'];
138
- check('denies Windows short names and stream suffixes', refusals(WIN), same(WIN.length, 'denied'));
139
- const CASED = ['.ENV', '.Env.local', 'ID_RSA', 'Key.PEM', '.Git/config', '.GIT/hooks/x', 'CERT.Crt'];
140
- check('floors drive-letter paths and ~<digit> names as denied, on purpose', ['C:\\x', 'c:x', 'file~1.txt', 'notes~2'].map(denyListed), same(4, true));
141
- check('denies case variants exactly as the lower-case forms', refusals(CASED), same(CASED.length, 'denied'));
142
- check('denies a name that only full case folding reads as denied', refusals(['.pgpa\u00df', '.\u00dfh']), same(2, 'denied'));
143
- check('denies a name written with another separator, a trailing dot or space, or compatibility characters', refusals(['sub\\.env', '.git\\config', '.env.', 'Key.pem ', '\uff0eenv', '.\uff45\uff4e\uff56', '\uff49\uff44_rsa']), same(7, 'denied'));
144
- const FOLDED_SEP = ['x\uff0f.env', 'service-account\uff0fprod.json', 'client_secret\uff0fx.json', 'a\uff3c.git', 'service-account\ufe68prod.json', 'client_secret\u2100x.json', 'client_secret\u2105x.json'];
145
- check('denies a name whose compatibility fold writes a separator: the segment whole and its pieces both count', refusals(FOLDED_SEP), same(FOLDED_SEP.length, 'denied'));
146
- check('a fold-to-separator code point does not deny a plain name', ['a\uff0fb.txt', 'a\ufe68b', 'src\u2100main.js'].map(denyListed), same(3, false));
147
- check('a deny-listed name is decided without any filesystem call, for a root that does not exist too', [watched(() => { inspectPath(root, '.env'); inspectPath(root, 'sub/.GIT/x'); inspectPath('/nonexistent-root', 'a.pem', null, { realpath: () => { throw new Error('called'); } }); })], [[]]);
148
- check('denied names make no call to the injected realpath', (() => { let n = 0; ins('.env', null, { realpath: (p) => { n++; return p; } }); return n; })(), 0);
149
- check('a missing, a symlinked and an unreadable-directory .env give the same result', [ins('nothing/.env'), ins('.env'), ins('locked/.env'), ins('.env.missing')], same(4, DENIED));
150
- check('a deny-listed name with a missing parent or in a non-directory is still denied', [ins('a.txt/.env'), ins('nope/deeper/key.pem')], same(2, DENIED));
151
- check('a malformed deny-listed name returns the refusal id and denied: true', [ins('../../.env'), ins('/x/id_rsa'), ins('a\0/.env'), ins('.git/../x'), ins('x'.repeat(MAX_PATH_CHARS + 1) + '/.env')], [['traversal'], ['absolute'], ['control'], ['traversal'], ['path_length']].map(([refusal]) => ({ kind: 'refused', refusal, denied: true })));
152
- check('a malformed name that is not deny-listed carries no denied fact', [ins('../x'), ins('/etc/passwd')], [{ kind: 'refused', refusal: 'traversal' }, { kind: 'refused', refusal: 'absolute' }]);
153
- const canon = (to) => (p) => (p.endsWith(`${path.sep}secret.txt`) ? p.replace('secret.txt', to) : fs.realpathSync.native(p));
154
- check('a path whose canonical on-disk spelling is a denied name is denied with no open', [ins('config/secret.txt', null, { realpath: canon('KEY.PEM') }), watched(() => ins('config/secret.txt', null, { realpath: canon('KEY.PEM') })).filter((c) => c === 'openSync')], [DENIED, []]);
155
- check('the canonical re-check also covers a .git directory spelled differently', ins('config/secret.txt', null, { realpath: (p) => (p.endsWith('secret.txt') ? path.join(root, '.GIT', 'secret.txt') : fs.realpathSync.native(p)) }), DENIED);
156
- check('the canonical path from the injected realpath is the one reported', ins('config/secret.txt', null, { realpath: (p) => (p.endsWith('secret.txt') ? path.join(root, 'sub', 'b.txt') : fs.realpathSync.native(p)) }).rel, 'sub/b.txt');
157
-
158
- console.log('== path safety: containment and plain files ==');
159
- check('refuses a symlinked file, a file under a symlinked directory and a symlink that leaves the root', refusals(['link.txt', 'linkdir/b.txt', 'linkdir', 'escape.txt']), same(4, 'symlink'));
160
- check('refuses a path whose canonical form leaves the root, is the root, or is its parent', refusals(['a.txt'], { realpath: (p) => (p.endsWith('a.txt') ? path.join(base, 'outside', 'secret.txt') : fs.realpathSync.native(p)) }).concat(refusals(['a.txt', 'sub/b.txt'], { realpath: (p) => (p.endsWith('b.txt') ? base : p.endsWith('a.txt') ? root : fs.realpathSync.native(p)) })), same(3, 'escape'));
161
- check('a file whose name begins with two dots is inside the root', ins('..x', null).kind, 'contained');
162
- check('refuses a link swapped in after the check, because the open does not follow it', refusalOf('a.txt', { realpath: (p) => (p.endsWith('a.txt') ? path.join(root, 'link.txt') : fs.realpathSync.native(p)) }), 'symlink');
163
- const swapTo = (rel) => ({ realpath: (p) => (p.endsWith('a.txt') ? path.join(root, rel) : fs.realpathSync.native(p)) });
164
- check('refuses a directory, a path through a file, a path under a missing directory, and a directory swapped in', [refusalOf('folder'), refusalOf('a.txt/x'), refusalOf('nope/new.txt'), refusalOf('a.txt', swapTo('folder'))], ['not_file', 'not_file', 'no_parent', 'not_file']);
165
- check('a FIFO is refused and the call returns, also when swapped in after the check', fifo ? [inChild('pipe'), inChild('a.txt', path.join(root, 'pipe'))] : 'no mkfifo', same(2, { kind: 'refused', refusal: 'not_file' }));
166
- check('a device is refused', fs.existsSync('/dev/null') ? inspectPath('/dev', 'null') : 'no /dev/null', { kind: 'refused', refusal: 'not_file' });
167
- check('refuses a file over the size cap and accepts one at it', [refusalOf('big.bin'), ins('max.bin').size], ['file_size', MAX_FILE_BYTES]);
168
- // Linux only: NAME_MAX counts bytes there (255), so 128 two-byte characters are over it; APFS counts characters and accepts them.
169
- const longName = '\u00e9'.repeat(128);
170
- if (process.platform !== 'linux') skip('a name the filesystem cannot look up is refused as unreadable', 'not Linux: the name limit counts bytes only there');
171
- else check('a name the filesystem cannot look up is refused as unreadable, for any user', refusalOf(longName), 'unreadable');
172
- if (process.getuid?.() === 0) skip('a file in an unreadable directory is refused as unreadable', 'running as root, which reads it');
173
- else check('a file in an unreadable directory is refused as unreadable', refusalOf('locked/f.txt'), 'unreadable');
174
- check('an unreadable root is refused, not read through', inspectPath(path.join(base, 'no-root'), 'a.txt'), { kind: 'refused', refusal: 'unreadable' });
175
- check('a new path in the root or in an existing directory is contained', [ins('new.txt'), ins('sub\\new.txt')], [{ kind: 'contained', exists: false, rel: 'new.txt' }, { kind: 'contained', exists: false, rel: 'sub/new.txt' }]);
176
- check('a Windows-style separator reaches the same file', ins('sub\\b.txt'), { kind: 'contained', exists: true, rel: 'sub/b.txt', size: 1 });
177
- check('a plain file is contained with its size and no content', ins('a.txt'), { kind: 'contained', exists: true, rel: 'a.txt', size: 5 });
178
- check('result keys per kind are fixed: nothing carries file content', [ins('a.txt', () => true), ins('new.txt'), ins('.env'), ins('../x'), ins('..x', () => false)].map((r) => Object.keys(r).sort().join()), ['answer,exists,kind,rel,size', 'exists,kind,rel', 'kind', 'kind,refusal', 'answer,exists,kind,rel,size']);
179
-
180
- console.log('== path safety: the descriptor ==');
181
- check('the probe gets an open descriptor and the size and its answer is a boolean', [ins('a.txt', (fd, size) => size === 5 && fs.readSync(fd, Buffer.alloc(5), 0, 5, 0) === 5).answer, ins('a.txt', () => 'hello').answer, ins('a.txt', () => 1).answer], [true, false, false]);
182
- const openClose = (fn) => { const c = watched(fn); return [c.filter((n) => n === 'openSync').length, c.filter((n) => n === 'closeSync').length]; };
183
- check('the descriptor is closed after a probe, after a refusal and after a probe that throws', [openClose(() => ins('a.txt', () => true)), openClose(() => ins('a.txt', null, swapTo('folder'))), openClose(() => ins('big.bin')), openClose(() => { try { inspectPath(root, 'a.txt', () => { throw new Error('probe'); }); } catch { /* only reached by a module that rethrows */ } })], same(4, [1, 1]));
184
- const failingClose = (probe) => { const real = fs.closeSync; fs.closeSync = (fd) => { real(fd); throw new Error('EIO'); }; try { return ins('a.txt', probe); } finally { fs.closeSync = real; } };
185
- check('a close that fails is unreadable with no probe, and the probe refusal with one', [failingClose(null), failingClose(() => true)], [{ kind: 'refused', refusal: 'unreadable' }, { kind: 'refused', refusal: 'probe' }]);
186
- check('a probe that closes the descriptor is a refusal, not a throw', ins('a.txt', (fd) => { fs.closeSync(fd); return true; }), { kind: 'refused', refusal: 'probe' });
187
- check('an error from the probe is a refusal and its message does not leave', ins('a.txt', () => { throw new Error('PROBEMSG'); }), { kind: 'refused', refusal: 'probe' });
188
- check('a path that does not exist, a directory or a FIFO opens nothing', openClose(() => { ins('new.txt'); ins('folder'); ins('pipe'); }), [0, 0]);
189
- const openFlags = () => { const real = fs.openSync; const seen = []; fs.openSync = (p, f, ...r) => { seen.push(f); return real(p, f, ...r); }; try { ins('a.txt'); } finally { fs.openSync = real; } return seen; };
190
- check('the open follows no link, cannot block, and never takes a controlling terminal', openFlags().map((f) => [fs.constants.O_NOFOLLOW, fs.constants.O_NONBLOCK, fs.constants.O_NOCTTY ?? 0].every((b) => (f & b) === b)), [true]);
191
- const spied = watched(() => ins('a.txt'));
192
- check('the filesystem spy sees the calls a contained path makes', [spied.includes('lstatSync'), spied.includes('realpathSync.native')], [true, true]);
193
-
194
- console.log('== path safety: a platform without O_NOFOLLOW ==');
195
- const noFollow = { ...fs.constants, O_NOFOLLOW: undefined }; const noBlock = { ...fs.constants, O_NONBLOCK: undefined };
196
- check('fails closed with `platform` for every reading call', [refusalOf('a.txt', { constants: noFollow }), refusalOf('new.txt', { constants: noFollow }), refusalOf('a.txt', { constants: noBlock }), refusalOf('a.txt', { constants: {} })], same(4, 'platform'));
197
- check('still decides names without the flag: denied stays denied and malformed keeps its id', [ins('.env', null, { constants: noFollow }), ins('../.env', null, { constants: noFollow }), ins('../x', null, { constants: noFollow })], [DENIED, { kind: 'refused', refusal: 'traversal', denied: true }, { kind: 'refused', refusal: 'traversal' }]);
198
- check('never opens without the flag', watched(() => ins('a.txt', null, { constants: noFollow })).filter((c) => c === 'openSync'), []);
199
-
200
- console.log(`SUMMARY ${pass + fail} ${fail}`);
201
- process.exit(fail ? 1 : 0);
@@ -1,61 +0,0 @@
1
- #!/usr/bin/env node
2
- // Asserts task02's mutant/control pair differ ONLY in expiry enforcement.
3
- //
4
- // Two layers, because neither is sufficient alone:
5
- // 1. SOURCE — the code-only diff must be exactly one contiguous insertion hunk, and every line
6
- // in it must belong to the expiry vocabulary.
7
- // 2. BEHAVIOUR — cross-verified over well-formed AND malformed inputs.
8
- //
9
- // Layer 1 replaced a "locate the expiry block by regex and delete it" check. That shape absorbed
10
- // anything written inside the matched region: the end anchor was the first `^ *}$`, so injecting
11
- // `if (payload.sub === 'admin') throw new Error('bad signature');` above the expiry test was
12
- // stripped along with it and passed at 38/38. A single-hunk assertion cannot absorb an extra
13
- // statement anywhere, because an extra statement is either inside the hunk (caught by the
14
- // vocabulary check) or makes a second hunk (caught by the count).
15
- //
16
- // Lives in a file rather than a `node -e "..."` block: those are shell-quoted context where a
17
- // backtick is command substitution and a double quote ends the program. That has bitten once
18
- // already, silently.
19
-
20
- import { readFileSync } from 'node:fs';
21
-
22
- const codeLines = (f) =>
23
- readFileSync(f, 'utf8')
24
- .split('\n')
25
- .filter((l) => { const t = l.trim(); return t && !t.startsWith('//') && !t.startsWith('*') && t !== '/**'; });
26
-
27
- // 'expired token', adjective-noun, matching the candidate-visible house style the shipped
28
- // token.mjs establishes ('malformed token', 'bad signature') and its shipped tests assert on.
29
- // It read 'token expired' until 2026-09-17, alone against that convention and against the very
30
- // next line of its own file -- every one of the first three real draws wrote a correct
31
- // expiry test, asserted /expired token/ by following the convention in front of it, and was
32
- // failed at the control step for word order the task never specified.
33
- const EXPIRY_VOCAB = /^(if \(typeof payload\.exp|throw new Error\('expired token'\);|\}|nowMs|&&)/;
34
-
35
- const [mutFile, ctlFile] = process.argv.slice(2);
36
- const mut = codeLines(mutFile);
37
- const ctl = codeLines(ctlFile);
38
-
39
- // Longest-common-subsequence-free: the control is the mutant plus an insertion, so walk both and
40
- // collect maximal runs present in ctl but not mut, in order.
41
- const hunks = [];
42
- let i = 0, j = 0, cur = null;
43
- while (j < ctl.length) {
44
- if (i < mut.length && mut[i] === ctl[j]) {
45
- if (cur) { hunks.push(cur); cur = null; }
46
- i++; j++;
47
- } else {
48
- (cur ??= []).push(ctl[j]);
49
- j++;
50
- }
51
- }
52
- if (cur) hunks.push(cur);
53
-
54
- const out = (m) => { process.stdout.write(m); process.exit(0); };
55
- if (i !== mut.length) out(`control does not contain every mutant line (diverged at mutant line ${i + 1}: ${JSON.stringify(mut[i])})`);
56
- if (hunks.length === 0) out('control is identical to the mutant - it does not enforce expiry');
57
- if (hunks.length > 1) out(`control adds ${hunks.length} separate hunks, not one: ${JSON.stringify(hunks.map((h) => h[0]))}`);
58
-
59
- const stray = hunks[0].map((l) => l.trim()).filter((l) => !EXPIRY_VOCAB.test(l));
60
- if (stray.length) out(`the added hunk contains non-expiry code: ${JSON.stringify(stray[0])}`);
61
- out('ok');