@countinghouse/ch-local 0.0.0-stage → 1.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 (262) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +361 -2
  3. package/bin/ch-local.js +472 -0
  4. package/clients/claude-code/.claude-plugin/plugin.json +6 -0
  5. package/clients/claude-code/.mcp.json +11 -0
  6. package/clients/claude-code/bin/launch.js +235 -0
  7. package/clients/claude-code/bin/win-acl.js +420 -0
  8. package/clients/claude-code/skills/ci-failure-triage/SKILL.md +21 -0
  9. package/clients/claude-code/skills/countinghouse-module/SKILL.md +177 -0
  10. package/clients/claude-code/skills/countinghouse-setup/SKILL.md +74 -0
  11. package/lib/allowlist.js +65 -0
  12. package/lib/aside.js +16 -0
  13. package/lib/atomic.js +45 -0
  14. package/lib/auto-apply.js +245 -0
  15. package/lib/auto-upgrade.js +98 -0
  16. package/lib/availability.js +307 -0
  17. package/lib/ceiling.js +280 -0
  18. package/lib/clean-text.js +20 -0
  19. package/lib/cli-change.js +38 -0
  20. package/lib/client-conditions-fixtures.js +143 -0
  21. package/lib/client-conditions.js +656 -0
  22. package/lib/clients.js +179 -0
  23. package/lib/command-line.js +202 -0
  24. package/lib/conditions-command.js +116 -0
  25. package/lib/control.js +134 -0
  26. package/lib/credential-store.js +414 -0
  27. package/lib/credentials-command.js +344 -0
  28. package/lib/daemon-requests.js +137 -0
  29. package/lib/daemon.js +888 -0
  30. package/lib/describe-module.js +137 -0
  31. package/lib/description-check.js +175 -0
  32. package/lib/failed-json.js +43 -0
  33. package/lib/gc.js +274 -0
  34. package/lib/github-token.js +57 -0
  35. package/lib/handoff-io.js +73 -0
  36. package/lib/held-back.js +116 -0
  37. package/lib/hidden-input.js +64 -0
  38. package/lib/history.js +49 -0
  39. package/lib/home.js +372 -0
  40. package/lib/in-place.js +1036 -0
  41. package/lib/install-plan.js +142 -0
  42. package/lib/install.js +846 -0
  43. package/lib/installed-description.js +153 -0
  44. package/lib/integrity.js +7 -0
  45. package/lib/lock.js +456 -0
  46. package/lib/lockfile-rules.js +98 -0
  47. package/lib/machine.js +20 -0
  48. package/lib/module-credentials.js +403 -0
  49. package/lib/module-record.js +298 -0
  50. package/lib/module-roles.js +44 -0
  51. package/lib/module-seams.js +26 -0
  52. package/lib/module-store.js +202 -0
  53. package/lib/module-values.js +334 -0
  54. package/lib/names.js +31 -0
  55. package/lib/next-steps.js +8 -0
  56. package/lib/node-check.js +56 -0
  57. package/lib/npm-fetch.js +123 -0
  58. package/lib/npm-release.js +99 -0
  59. package/lib/npm-upgrade.js +146 -0
  60. package/lib/npm.js +41 -0
  61. package/lib/outside-edits.js +162 -0
  62. package/lib/own-applied.js +175 -0
  63. package/lib/own-command.js +380 -0
  64. package/lib/own-file.js +120 -0
  65. package/lib/own-record.js +96 -0
  66. package/lib/own-tree.js +336 -0
  67. package/lib/pack-table.js +290 -0
  68. package/lib/packs-command.js +570 -0
  69. package/lib/packs.js +219 -0
  70. package/lib/pins.js +64 -0
  71. package/lib/pipe-probe.js +82 -0
  72. package/lib/plain-read.js +63 -0
  73. package/lib/private-file.js +90 -0
  74. package/lib/private-write.js +33 -0
  75. package/lib/provenance.js +234 -0
  76. package/lib/record.js +82 -0
  77. package/lib/registry.js +22 -0
  78. package/lib/release-pins.js +350 -0
  79. package/lib/release-pins.json +4225 -0
  80. package/lib/release-tags.js +12 -0
  81. package/lib/release.js +36 -0
  82. package/lib/restart-command.js +161 -0
  83. package/lib/rollback.js +227 -0
  84. package/lib/run-liveness.js +15 -0
  85. package/lib/runtime-log.js +287 -0
  86. package/lib/sandbox-support.js +17 -0
  87. package/lib/semver-order.js +40 -0
  88. package/lib/session-socket.js +69 -0
  89. package/lib/session-table.js +238 -0
  90. package/lib/session.js +281 -0
  91. package/lib/settings-command.js +82 -0
  92. package/lib/settings.js +564 -0
  93. package/lib/shim-binary.js +152 -0
  94. package/lib/shim-config.js +159 -0
  95. package/lib/shim-install.js +365 -0
  96. package/lib/sigstore/README.md +44 -0
  97. package/lib/sigstore/npm-keys.json +18 -0
  98. package/lib/sigstore/trusted-root.json +126 -0
  99. package/lib/snippets.js +76 -0
  100. package/lib/start.js +721 -0
  101. package/lib/store-files.js +48 -0
  102. package/lib/store-paths.js +33 -0
  103. package/lib/swap-preload.js +38 -0
  104. package/lib/tar.js +220 -0
  105. package/lib/uninstall.js +314 -0
  106. package/lib/unpack.js +41 -0
  107. package/lib/upgrade-stamp.js +63 -0
  108. package/lib/upgrade.js +281 -0
  109. package/lib/watch.js +40 -0
  110. package/lib/win-acl.js +420 -0
  111. package/node_modules/@sigstore/bundle/LICENSE +202 -0
  112. package/node_modules/@sigstore/bundle/README.md +19 -0
  113. package/node_modules/@sigstore/bundle/dist/build.d.ts +18 -0
  114. package/node_modules/@sigstore/bundle/dist/build.js +100 -0
  115. package/node_modules/@sigstore/bundle/dist/bundle.d.ts +74 -0
  116. package/node_modules/@sigstore/bundle/dist/bundle.js +24 -0
  117. package/node_modules/@sigstore/bundle/dist/error.d.ts +4 -0
  118. package/node_modules/@sigstore/bundle/dist/error.js +25 -0
  119. package/node_modules/@sigstore/bundle/dist/index.d.ts +8 -0
  120. package/node_modules/@sigstore/bundle/dist/index.js +43 -0
  121. package/node_modules/@sigstore/bundle/dist/serialized.d.ts +74 -0
  122. package/node_modules/@sigstore/bundle/dist/serialized.js +49 -0
  123. package/node_modules/@sigstore/bundle/dist/utility.d.ts +14 -0
  124. package/node_modules/@sigstore/bundle/dist/utility.js +2 -0
  125. package/node_modules/@sigstore/bundle/dist/validate.d.ts +7 -0
  126. package/node_modules/@sigstore/bundle/dist/validate.js +199 -0
  127. package/node_modules/@sigstore/bundle/package.json +35 -0
  128. package/node_modules/@sigstore/core/LICENSE +202 -0
  129. package/node_modules/@sigstore/core/README.md +10 -0
  130. package/node_modules/@sigstore/core/dist/asn1/error.d.ts +4 -0
  131. package/node_modules/@sigstore/core/dist/asn1/error.js +24 -0
  132. package/node_modules/@sigstore/core/dist/asn1/index.d.ts +1 -0
  133. package/node_modules/@sigstore/core/dist/asn1/index.js +20 -0
  134. package/node_modules/@sigstore/core/dist/asn1/length.d.ts +3 -0
  135. package/node_modules/@sigstore/core/dist/asn1/length.js +62 -0
  136. package/node_modules/@sigstore/core/dist/asn1/obj.d.ts +14 -0
  137. package/node_modules/@sigstore/core/dist/asn1/obj.js +155 -0
  138. package/node_modules/@sigstore/core/dist/asn1/parse.d.ts +6 -0
  139. package/node_modules/@sigstore/core/dist/asn1/parse.js +124 -0
  140. package/node_modules/@sigstore/core/dist/asn1/tag.d.ts +16 -0
  141. package/node_modules/@sigstore/core/dist/asn1/tag.js +89 -0
  142. package/node_modules/@sigstore/core/dist/crypto.d.ts +6 -0
  143. package/node_modules/@sigstore/core/dist/crypto.js +69 -0
  144. package/node_modules/@sigstore/core/dist/dsse.d.ts +1 -0
  145. package/node_modules/@sigstore/core/dist/dsse.js +29 -0
  146. package/node_modules/@sigstore/core/dist/encoding.d.ts +2 -0
  147. package/node_modules/@sigstore/core/dist/encoding.js +27 -0
  148. package/node_modules/@sigstore/core/dist/index.d.ts +9 -0
  149. package/node_modules/@sigstore/core/dist/index.js +66 -0
  150. package/node_modules/@sigstore/core/dist/json.d.ts +1 -0
  151. package/node_modules/@sigstore/core/dist/json.js +60 -0
  152. package/node_modules/@sigstore/core/dist/oid.d.ts +3 -0
  153. package/node_modules/@sigstore/core/dist/oid.js +20 -0
  154. package/node_modules/@sigstore/core/dist/pem.d.ts +2 -0
  155. package/node_modules/@sigstore/core/dist/pem.js +43 -0
  156. package/node_modules/@sigstore/core/dist/rfc3161/error.d.ts +2 -0
  157. package/node_modules/@sigstore/core/dist/rfc3161/error.js +21 -0
  158. package/node_modules/@sigstore/core/dist/rfc3161/index.d.ts +1 -0
  159. package/node_modules/@sigstore/core/dist/rfc3161/index.js +20 -0
  160. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.d.ts +36 -0
  161. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +212 -0
  162. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.d.ts +12 -0
  163. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +72 -0
  164. package/node_modules/@sigstore/core/dist/stream.d.ts +21 -0
  165. package/node_modules/@sigstore/core/dist/stream.js +117 -0
  166. package/node_modules/@sigstore/core/dist/x509/cert.d.ts +43 -0
  167. package/node_modules/@sigstore/core/dist/x509/cert.js +245 -0
  168. package/node_modules/@sigstore/core/dist/x509/ext.d.ts +41 -0
  169. package/node_modules/@sigstore/core/dist/x509/ext.js +146 -0
  170. package/node_modules/@sigstore/core/dist/x509/index.d.ts +2 -0
  171. package/node_modules/@sigstore/core/dist/x509/index.js +23 -0
  172. package/node_modules/@sigstore/core/dist/x509/sct.d.ts +25 -0
  173. package/node_modules/@sigstore/core/dist/x509/sct.js +158 -0
  174. package/node_modules/@sigstore/core/package.json +31 -0
  175. package/node_modules/@sigstore/protobuf-specs/LICENSE +202 -0
  176. package/node_modules/@sigstore/protobuf-specs/README.md +5 -0
  177. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.d.ts +44 -0
  178. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +59 -0
  179. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.d.ts +64 -0
  180. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +174 -0
  181. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.d.ts +74 -0
  182. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +141 -0
  183. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.d.ts +74 -0
  184. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +35 -0
  185. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.d.ts +1309 -0
  186. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +2191 -0
  187. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.d.ts +113 -0
  188. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +29 -0
  189. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.d.ts +23 -0
  190. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js +55 -0
  191. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.d.ts +43 -0
  192. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js +81 -0
  193. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.d.ts +22 -0
  194. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js +56 -0
  195. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.d.ts +35 -0
  196. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js +74 -0
  197. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.d.ts +146 -0
  198. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +103 -0
  199. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.d.ts +304 -0
  200. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +612 -0
  201. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.d.ts +33 -0
  202. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.js +55 -0
  203. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.d.ts +144 -0
  204. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +137 -0
  205. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.d.ts +386 -0
  206. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +284 -0
  207. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.d.ts +191 -0
  208. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +281 -0
  209. package/node_modules/@sigstore/protobuf-specs/dist/index.d.ts +6 -0
  210. package/node_modules/@sigstore/protobuf-specs/dist/index.js +37 -0
  211. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.d.ts +4 -0
  212. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js +35 -0
  213. package/node_modules/@sigstore/protobuf-specs/package.json +35 -0
  214. package/node_modules/@sigstore/verify/README.md +9 -0
  215. package/node_modules/@sigstore/verify/dist/bundle/dsse.d.ts +12 -0
  216. package/node_modules/@sigstore/verify/dist/bundle/dsse.js +44 -0
  217. package/node_modules/@sigstore/verify/dist/bundle/index.d.ts +4 -0
  218. package/node_modules/@sigstore/verify/dist/bundle/index.js +59 -0
  219. package/node_modules/@sigstore/verify/dist/bundle/message.d.ts +13 -0
  220. package/node_modules/@sigstore/verify/dist/bundle/message.js +54 -0
  221. package/node_modules/@sigstore/verify/dist/error.d.ts +16 -0
  222. package/node_modules/@sigstore/verify/dist/error.js +34 -0
  223. package/node_modules/@sigstore/verify/dist/index.d.ts +6 -0
  224. package/node_modules/@sigstore/verify/dist/index.js +28 -0
  225. package/node_modules/@sigstore/verify/dist/key/certificate.d.ts +21 -0
  226. package/node_modules/@sigstore/verify/dist/key/certificate.js +216 -0
  227. package/node_modules/@sigstore/verify/dist/key/index.d.ts +10 -0
  228. package/node_modules/@sigstore/verify/dist/key/index.js +75 -0
  229. package/node_modules/@sigstore/verify/dist/key/sct.d.ts +4 -0
  230. package/node_modules/@sigstore/verify/dist/key/sct.js +78 -0
  231. package/node_modules/@sigstore/verify/dist/policy.d.ts +5 -0
  232. package/node_modules/@sigstore/verify/dist/policy.js +50 -0
  233. package/node_modules/@sigstore/verify/dist/shared.types.d.ts +50 -0
  234. package/node_modules/@sigstore/verify/dist/shared.types.js +2 -0
  235. package/node_modules/@sigstore/verify/dist/timestamp/index.d.ts +11 -0
  236. package/node_modules/@sigstore/verify/dist/timestamp/index.js +24 -0
  237. package/node_modules/@sigstore/verify/dist/timestamp/tsa.d.ts +3 -0
  238. package/node_modules/@sigstore/verify/dist/timestamp/tsa.js +63 -0
  239. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.d.ts +11 -0
  240. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.js +154 -0
  241. package/node_modules/@sigstore/verify/dist/tlog/dsse.d.ts +6 -0
  242. package/node_modules/@sigstore/verify/dist/tlog/dsse.js +106 -0
  243. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.d.ts +6 -0
  244. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +94 -0
  245. package/node_modules/@sigstore/verify/dist/tlog/index.d.ts +5 -0
  246. package/node_modules/@sigstore/verify/dist/tlog/index.js +92 -0
  247. package/node_modules/@sigstore/verify/dist/tlog/intoto.d.ts +3 -0
  248. package/node_modules/@sigstore/verify/dist/tlog/intoto.js +62 -0
  249. package/node_modules/@sigstore/verify/dist/tlog/merkle.d.ts +3 -0
  250. package/node_modules/@sigstore/verify/dist/tlog/merkle.js +104 -0
  251. package/node_modules/@sigstore/verify/dist/tlog/set.d.ts +3 -0
  252. package/node_modules/@sigstore/verify/dist/tlog/set.js +60 -0
  253. package/node_modules/@sigstore/verify/dist/trust/filter.d.ts +8 -0
  254. package/node_modules/@sigstore/verify/dist/trust/filter.js +23 -0
  255. package/node_modules/@sigstore/verify/dist/trust/index.d.ts +5 -0
  256. package/node_modules/@sigstore/verify/dist/trust/index.js +90 -0
  257. package/node_modules/@sigstore/verify/dist/trust/trust.types.d.ts +29 -0
  258. package/node_modules/@sigstore/verify/dist/trust/trust.types.js +2 -0
  259. package/node_modules/@sigstore/verify/dist/verifier.d.ts +31 -0
  260. package/node_modules/@sigstore/verify/dist/verifier.js +160 -0
  261. package/node_modules/@sigstore/verify/package.json +36 -0
  262. package/package.json +37 -4
@@ -0,0 +1,307 @@
1
+ 'use strict';
2
+ // What loads, by module (#413 section 5.2; L2a). A module is available when
3
+ // all of these hold, the first that fails its reason:
4
+ // 1. its active version is in the module store;
5
+ // 2. the running release lists it at that version: a module no pack of it
6
+ // lists is withdrawn (section 9.7), one at another version than the
7
+ // release's pin is not loaded either (a development home is exempt);
8
+ // 3. the operator's ceiling allows it (every module, a part included:
9
+ // section 8);
10
+ // 4. (a top-level module) it is not turned off;
11
+ // 5. (every module that declares one) its credential is usable;
12
+ // 6. every module in its closure is available, for whatever reason one
13
+ // is not (to a fixed point: a cycle of available modules stays so).
14
+ // Every available top-level module is loaded, once, whichever packs record
15
+ // it; a part is loaded exactly while some loaded module's closure holds it.
16
+ //
17
+ // Rules 3 to 5 sit behind seams (the Reviewer on L2a), each by module
18
+ // (L2b: lib/module-seams.js; L5a: lib/module-credentials.js):
19
+ // seams.ceiling(module) -> null | the reason
20
+ // seams.off(module) -> null | the reason
21
+ // seams.credential(module, packs, unit) -> null | the reason | {reason, which}
22
+ // (asked of every module, a part included: lib/module-credentials.js)
23
+ // A module's closure is read from the stored manifests' countinghouse.calls,
24
+ // matched by friendly name (api.json's device.friendlyName) as the runtime
25
+ // matches it.
26
+ //
27
+ // The user's own modules (B-own-add; the own-modules design §2.2), given as
28
+ // own: {record: own.json's, sandboxOk}, are top-level, after the packs,
29
+ // each from its copy under <home>/own, its version the copy's tree hash.
30
+ // Before the seams, in this order: its copy is intact (else changed), the
31
+ // sandbox is enforced (else sandbox), and no pack module -- nor an own
32
+ // module before it -- has its device name (else collision, via that one).
33
+ // One whose package name is a pack module's is never one of the modules
34
+ // here: it is in `shadowed` (collision), apart from that module's entries.
35
+ // An own module's calls resolve to any module here; a pack module's only
36
+ // to a pack module, so a pack never calls user code that took a name it
37
+ // calls.
38
+ const fs = require('node:fs');
39
+ const path = require('node:path');
40
+ const {versionDir, looksPlaced} = require('./store-paths');
41
+ const {removeHint, packScenario, holds} = require('./packs');
42
+ const {chLocal, folderArg} = require('./command-line');
43
+ const {copyDir, copyState} = require('./own-tree');
44
+
45
+ const short = (name) => name.replace(/^@[^/]+\//, '');
46
+ // (status says it too, of a running start's own sandbox)
47
+ const SANDBOX_LINE = 'own modules run only with the sandbox enforced';
48
+
49
+ function manifestOf(dir) {
50
+ try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')); } catch (err) { return null; }
51
+ }
52
+ function friendlyOf(dir) {
53
+ try {
54
+ const api = JSON.parse(fs.readFileSync(path.join(dir, 'api.json'), 'utf8'));
55
+ return api != null && api.device != null && typeof api.device.friendlyName === 'string' ? api.device.friendlyName : null;
56
+ } catch (err) { return null; }
57
+ }
58
+ // the modules a manifest calls: the names before the slash, each once
59
+ const callsOf = (m) => {
60
+ const calls = m != null && m.countinghouse != null && Array.isArray(m.countinghouse.calls) ? m.countinghouse.calls : [];
61
+ return [...new Set(calls.filter((c) => typeof c === 'string' && c.includes('/')).map((c) => c.slice(0, c.indexOf('/'))))];
62
+ };
63
+
64
+ // where: layout(); record: modules.json's; release: the running release's
65
+ // pins (packs.<p>.packages or .modules, pins); seams: above; pins: false
66
+ // for a record of another release, which a start judges by none of its own
67
+ // pins (section 9.8): rule 2 is skipped. Each reason has a kind: missing,
68
+ // withdrawn, pin, ceiling, off, credential, calls.
69
+ // -> {units: [unit of each available top-level module, in the record's
70
+ // order, then the own modules'], unavailable: Map(module -> {kind, reason,
71
+ // line, withdrawn, via}), shadowed: Map(own module -> {kind: 'collision',
72
+ // via, reason, line}),
73
+ // states: Map(module -> {ok} | {ok: false, kind, reason}) for every
74
+ // installed module, a part included, and tops: the top-level modules
75
+ // (status, section 9.9)}. A unit: {name: the module, short, scenario: the module, version,
76
+ // modules: {m: version} over its closure, dirs: {m: store dir}, dir,
77
+ // packages: its closure's names, packs: the packs whose scenario it is;
78
+ // own: true for an own module's, and added: {<own module of its closure>:
79
+ // its entry's addedAt}}.
80
+ function availability(where, record, {release, seams, pins: byPins = true, own: ownOpt = null}) {
81
+ const modules = record.modules || {};
82
+ const packNames = Object.keys(modules);
83
+ // the own modules, a pack module's name apart (shadowed)
84
+ const ownOf = new Map();
85
+ const shadowed = new Map();
86
+ const ownRecorded = ownOpt != null && ownOpt.record != null ? ownOpt.record.modules : {};
87
+ for (const [m, e] of Object.entries(ownRecorded)) {
88
+ if (holds(modules, m)) shadowed.set(m, {kind: 'collision', via: m, reason: `pack module ${m} uses its name`, line: `not loading your own module ${short(m)}: pack module ${m} uses its name`});
89
+ else ownOf.set(m, e);
90
+ }
91
+ const isOwn = (m) => ownOf.has(m);
92
+ const sandboxOk = ownOpt != null && ownOpt.sandboxOk === true;
93
+ const names = packNames.concat([...ownOf.keys()]);
94
+ const versionOf = (m) => (isOwn(m) ? ownOf.get(m).tree : modules[m].version);
95
+ const dirOf = (m) => (isOwn(m) ? copyDir(where, m, ownOf.get(m).tree) : versionDir(where, m, modules[m].version));
96
+ // each module's placement, looked at once (the high review of L2a, 9); an
97
+ // own module's: its copy whole and hashing to the tree the user said yes to
98
+ // (and why one is not: changed, or gone -- E10)
99
+ const copies = new Map([...ownOf.keys()].map((m) => [m, copyState(where, m, ownOf.get(m).tree)]));
100
+ const placed = new Map(names.map((m) => [m, isOwn(m) ? copies.get(m) === 'intact' : looksPlaced(where, m, modules[m].version)]));
101
+ // (own properties only, as the top-level rule reads them: #449's review)
102
+ const recordedBy = (m) => Object.entries(record.packs || {}).filter(([, p]) => p != null && holds(p.modules, m)).map(([n]) => n);
103
+ // the packs whose scenario the module is (the seams' unit, today); a
104
+ // module that is some pack's scenario is top-level, whatever role it
105
+ // declares (a pack whose modules declare none: its first), and every
106
+ // other module is a part, loaded only within a closure (the medium
107
+ // review of L2a, 1: never past a pack's seams)
108
+ const scenarioOf = new Map();
109
+ for (const pack of Object.keys(record.packs || {})) {
110
+ const m = packScenario(record, pack);
111
+ if (m == null || !holds(modules, m)) continue;
112
+ if (!scenarioOf.has(m)) scenarioOf.set(m, []);
113
+ scenarioOf.get(m).push(pack);
114
+ }
115
+ const top = (m) => scenarioOf.has(m) || isOwn(m);
116
+ const listed = new Set();
117
+ for (const p of Object.values((release && release.packs) || {})) {
118
+ const list = p == null ? null : Array.isArray(p.modules) ? p.modules : Array.isArray(p.packages) ? p.packages : null;
119
+ for (const m of (list || [])) listed.add(m);
120
+ }
121
+ // withdrawn when this release does not list it, or the record's own list
122
+ // names it (an upgrade's pins wrote it: section 9.7)
123
+ const withdrawnByRecord = new Set(Array.isArray(record.withdrawn) ? record.withdrawn : []);
124
+ const pins = (release && release.pins) || {};
125
+ // each placed module's calls, read once (the closure and the check share them)
126
+ const calls = new Map();
127
+ const callsOfModule = (m) => {
128
+ if (!calls.has(m)) calls.set(m, placed.get(m) ? callsOf(manifestOf(dirOf(m))) : []);
129
+ return calls.get(m);
130
+ };
131
+ // friendly name -> module (an installed one, placed); an installed module
132
+ // whose files are missing has no friendly name to read: it is found by
133
+ // its short name, so a caller says why
134
+ // (the packs' first, then the own modules': a pack module keeps its name)
135
+ const byFriendly = new Map();
136
+ const friendly = new Map();
137
+ for (const m of names) {
138
+ const f = placed.get(m) ? friendlyOf(dirOf(m)) : null;
139
+ friendly.set(m, f);
140
+ if (typeof f === 'string' && !byFriendly.has(f)) byFriendly.set(f, m);
141
+ }
142
+ const byShort = new Map();
143
+ for (const m of packNames) if (!byShort.has(short(m))) byShort.set(short(m), m);
144
+ // the module a call of `from`'s names: a pack module's calls find only
145
+ // pack modules
146
+ const target = (c, from) => {
147
+ const t = byFriendly.get(c);
148
+ if (t != null && (isOwn(from) || !isOwn(t))) return t;
149
+ if (byShort.has(c) && !placed.get(byShort.get(c))) return byShort.get(c);
150
+ // (an own module held back as its copy changed or is gone: by the device
151
+ // name its entry has, so an own caller says why)
152
+ const held = isOwn(from) ? [...ownOf.keys()].find((m) => !placed.get(m) && ownOf.get(m).friendlyName === c) : undefined;
153
+ return held !== undefined ? held : null;
154
+ };
155
+ // each reason twice: as the module's own ("not loading m: <reason>") and
156
+ // as its caller says it ("it calls m, which <which>": section 11)
157
+ const asWhich = (kind, reason) => (reason == null ? null : {kind, reason, which: `is not available (${reason})`});
158
+ // an own module's rules: its copy, the sandbox, its device name; then
159
+ // the ceiling and off, as any top-level module's
160
+ const ownRule = (m) => {
161
+ // (gone: as the overview says it, countinghouse #534 -- the folder it
162
+ // was added from, never the copy's path)
163
+ if (copies.get(m) === 'gone') return asWhich('gone', `its copy is gone: run \`${chLocal(where, `add-module ${folderArg(ownOf.get(m).from)}`)}\` again`);
164
+ if (!placed.get(m)) return asWhich('changed', `its files changed since you added it: run \`${chLocal(where, `add-module ${folderArg(ownOf.get(m).from)}`)}\` again`);
165
+ if (!sandboxOk) return asWhich('sandbox', SANDBOX_LINE);
166
+ const holder = byFriendly.get(friendly.get(m));
167
+ if (holder != null && holder !== m) return {...asWhich('collision', `${isOwn(holder) ? 'your own module' : 'pack module'} ${holder} uses its name`), via: holder};
168
+ return asWhich('ceiling', seams.ceiling(m)) || asWhich('off', seams.off(m));
169
+ };
170
+ const own = (m) => {
171
+ if (isOwn(m)) return ownRule(m);
172
+ const v = modules[m].version;
173
+ if (!placed.get(m)) return {kind: 'missing', reason: `its files are missing; run \`${chLocal(where, 'install')}\` again`, which: `is missing from the module store; run \`${chLocal(where, 'install')}\` again`};
174
+ if (byPins && record.unreleased !== true) {
175
+ if (!listed.has(m) || withdrawnByRecord.has(m)) {
176
+ return {kind: 'withdrawn', reason: `it was withdrawn in this release and is not started; ${removeHint(recordedBy(m)[0] || '<pack>', where)}`, which: 'was withdrawn in this release'};
177
+ }
178
+ const pin = pins[m] != null ? pins[m].version : null;
179
+ if (pin !== v) {
180
+ const pinned = pin != null ? pin : 'no version of it';
181
+ return {kind: 'pin', reason: `${v} is installed and this release pins ${pinned}; run \`${chLocal(where, 'install')}\` again`, which: `is installed at ${v} and this release pins ${pinned}; run \`${chLocal(where, 'install')}\` again`};
182
+ }
183
+ }
184
+ // the ceiling for every module, a part included; off for a top-level one
185
+ return asWhich('ceiling', seams.ceiling(m)) || (top(m) ? asWhich('off', seams.off(m)) : null);
186
+ };
187
+ const credentialOf = new Map(); // module -> {credential} the seam chose
188
+ // rules 1 to 4 per module, then rule 6 to a fixed point: a module is not
189
+ // available while any module it calls is not, so a cycle of available
190
+ // modules stays available and one that reaches an unavailable module
191
+ // does not (the medium review of L2a, 2: never cached mid-cycle)
192
+ const state = new Map(names.map((m) => { const w = own(m); return [m, w == null ? {ok: true} : {ok: false, ...w}]; }));
193
+ // a blocked callee's own via when it is blocked through a call, else itself
194
+ const viaOf = (t) => (state.get(t).kind === 'calls' ? state.get(t).via : t);
195
+ const settle = () => {
196
+ for (let changed = true; changed;) {
197
+ changed = false;
198
+ for (const m of names) {
199
+ if (!state.get(m).ok) continue;
200
+ for (const c of callsOfModule(m)) {
201
+ const t = target(c, m);
202
+ // root: the kind at the bottom of the chain (a frozen record still
203
+ // unloads a caller whose callee went for a reason no pins decide)
204
+ // via: the module at the bottom of the chain, which the person acts
205
+ // on; for a callee not installed, the name called (A-firstrun d1)
206
+ const why = t == null ? {kind: 'calls', root: 'not installed', via: c, reason: `it calls ${c}, which is not installed`, which: `calls ${c}, which is not installed`}
207
+ : !state.get(t).ok ? {kind: 'calls', root: state.get(t).root || state.get(t).kind, via: viaOf(t), reason: `it calls ${c}, which ${state.get(t).which}`, which: `calls ${c}, which ${state.get(t).which}`} : null;
208
+ if (why != null) { state.set(m, {ok: false, ...why}); changed = true; break; }
209
+ }
210
+ }
211
+ }
212
+ };
213
+ settle();
214
+ // rule 5 last: asked of every module that would otherwise load, after
215
+ // every rule before it has settled, callees before their
216
+ // callers, so a caller whose callee lacks its credential reports that and
217
+ // is never asked its own (the high reviews of L2a, 1, and of its medium
218
+ // round, 8: the reason said is the real blocker)
219
+ const order = [];
220
+ const seen = new Set();
221
+ const visit = (m) => {
222
+ if (seen.has(m)) return;
223
+ seen.add(m);
224
+ for (const c of callsOfModule(m)) { const t = target(c, m); if (t != null) visit(t); }
225
+ order.push(m);
226
+ };
227
+ for (const m of names) visit(m);
228
+ // (callees first, so one step to the callees is enough here; a cycle is
229
+ // settled once after: the medium review of the high round, 8)
230
+ for (const m of order) {
231
+ if (!state.get(m).ok) continue;
232
+ const failed = callsOfModule(m).map((c) => [c, target(c, m)]).find(([, t]) => t != null && !state.get(t).ok);
233
+ if (failed != null) {
234
+ const [c, t] = failed;
235
+ state.set(m, {ok: false, kind: 'calls', root: state.get(t).root || state.get(t).kind, via: viaOf(t), reason: `it calls ${c}, which ${state.get(t).which}`, which: `calls ${c}, which ${state.get(t).which}`});
236
+ continue;
237
+ }
238
+ // every module that declares a credential is asked, a part included: a
239
+ // credential is its declaring module's (#413 section 6.1; L5a), and a
240
+ // caller of one without it says so (rule 6). The seam answers null, a
241
+ // reason, or {reason, which} (what a caller says of it)
242
+ const chose = {};
243
+ const got = seams.credential(m, scenarioOf.get(m) || [], chose);
244
+ credentialOf.set(m, chose);
245
+ if (got != null) {
246
+ const reason = typeof got === 'string' ? got : got.reason;
247
+ const which = typeof got === 'string' || got.which == null ? `is not available (${reason})` : got.which;
248
+ state.set(m, {ok: false, kind: 'credential', reason, which});
249
+ }
250
+ }
251
+ settle();
252
+ const closureOf = (m, seen = new Set()) => {
253
+ if (seen.has(m)) return seen;
254
+ seen.add(m);
255
+ for (const c of callsOfModule(m)) { const t = target(c, m); if (t != null) closureOf(t, seen); }
256
+ return seen;
257
+ };
258
+ // A caller's because (#449's moduleMessages id 10): the one module it
259
+ // calls directly that is turned off for itself, when that is all that
260
+ // keeps it from loading: every module it calls that is not available is
261
+ // that one, so the runtime's "it calls <because>, which is turned off
262
+ // (turning <because> on brings it back)" is true. Otherwise null: through
263
+ // a part, beside another blocker, or a callee not installed, the notice
264
+ // says it as given (the medium on A-reason, 1 and 2).
265
+ const becauseOffOf = (m) => {
266
+ const failing = new Set();
267
+ for (const c of callsOfModule(m)) {
268
+ const t = target(c, m);
269
+ if (t == null) return null;
270
+ if (!state.get(t).ok) failing.add(t);
271
+ }
272
+ if (failing.size !== 1) return null;
273
+ const [t] = failing;
274
+ if (!top(t) || state.get(t).kind !== 'off') return null;
275
+ // neither it nor the module turned off is asked its credential once a
276
+ // callee has failed: asked now, so "turning it on brings it back" is
277
+ // never said of one a missing key would still keep out (the medium on
278
+ // #98's high round, 1)
279
+ for (const x of [m, t]) if (seams.credential(x, scenarioOf.get(x) || [], {}) != null) return null;
280
+ return t;
281
+ };
282
+ const units = [];
283
+ const unavailable = new Map();
284
+ for (const m of names) {
285
+ if (!top(m)) continue;
286
+ const s = state.get(m);
287
+ if (!s.ok) {
288
+ // a withdrawn module is said as section 9.7 says it
289
+ const line = s.kind === 'withdrawn' ? `module ${short(m)} was withdrawn in this release and was not started; ${removeHint(recordedBy(m)[0] || '<pack>', where)}`
290
+ : `not loading ${short(m)}: ${s.reason}`;
291
+ unavailable.set(m, {kind: s.kind, root: s.root || s.kind, via: s.kind === 'calls' || s.kind === 'collision' ? s.via : null, becauseOff: s.kind === 'calls' ? becauseOffOf(m) : null, reason: s.reason, line, withdrawn: s.kind === 'withdrawn'});
292
+ continue;
293
+ }
294
+ const closure = [...closureOf(m)];
295
+ units.push({name: m, short: short(m), scenario: m, version: versionOf(m),
296
+ modules: Object.fromEntries(closure.map((n) => [n, versionOf(n)])),
297
+ dirs: Object.fromEntries(closure.map((n) => [n, dirOf(n)])),
298
+ dir: dirOf(m), packages: closure, packs: isOwn(m) ? [] : scenarioOf.get(m), ...credentialOf.get(m),
299
+ ...(isOwn(m) ? {own: true, added: Object.fromEntries(closure.filter((n) => isOwn(n)).map((n) => [n, ownOf.get(n).addedAt]))} : {})});
300
+ }
301
+ const states = new Map(names.map((m) => { const s = state.get(m); return [m, s.ok ? {ok: true} : {ok: false, kind: s.kind, reason: s.reason}]; }));
302
+ return {units, unavailable, shadowed, states, tops: new Set([...scenarioOf.keys(), ...ownOf.keys()])};
303
+ }
304
+
305
+ // (manifestOf, friendlyOf and callsOf: section 9.4's table finds callers as
306
+ // a start matches them, lib/pack-table.js)
307
+ module.exports = {availability, short, manifestOf, friendlyOf, callsOf, SANDBOX_LINE};
package/lib/ceiling.js ADDED
@@ -0,0 +1,280 @@
1
+ 'use strict';
2
+ // The operator's ceiling (countinghouse part 3, section 4): read with the
3
+ // installed runtime's own reader, lib/settings-ceiling.js (one source,
4
+ // decision b), and applied to every loosening ch-local makes: `settings set`,
5
+ // `upgrade --auto on`, and the values and flags `start` passes. An older
6
+ // runtime without the reader, with a ceiling file present, fails closed:
7
+ // every loosening is refused, and says why. No file: the hard bounds.
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const {entryOf, valueOf, shown} = require('./settings');
11
+ const {chLocal} = require('./command-line');
12
+
13
+ // Windows' ProgramData, from the known folder (CommonApplicationData), read
14
+ // through lib/win-acl.js's PowerShell, never from the environment, which a
15
+ // client's config sets (docs/development/auto-upgrade.md; the review of #48).
16
+ // Once per process; null when it can't be read. The known folder is
17
+ // ProfileList's %SystemDrive%\ProgramData, expanded in PowerShell's own
18
+ // environment, and the shim's cleared one holds no SystemDrive (libuv
19
+ // completes a child's only from its parent's): the script sets it first,
20
+ // from the system's own Windows directory, as countinghouse's reader does.
21
+ const PROGRAMDATA_SCRIPT = "$env:SystemDrive = [IO.Path]::GetPathRoot([Environment]::GetFolderPath('Windows')).TrimEnd('\\'); " +
22
+ "[Environment]::GetFolderPath('CommonApplicationData')";
23
+ let knownProgramData;
24
+ function programDataFolder() {
25
+ if (knownProgramData !== undefined) return knownProgramData;
26
+ try {
27
+ const out = String(require('./win-acl').runPowershell(PROGRAMDATA_SCRIPT)).trim();
28
+ knownProgramData = /^[A-Za-z]:\\[^\r\n]*$/.test(out) ? out : null;
29
+ } catch (err) {
30
+ knownProgramData = null;
31
+ }
32
+ return knownProgramData;
33
+ }
34
+
35
+ // Where a ceiling file may be when the runtime has no reader to ask. env is
36
+ // not read: on Windows the known folder, and C:\ProgramData as well.
37
+ // programData: a test's stand-in for the known-folder lookup.
38
+ // eslint-disable-next-line no-unused-vars
39
+ function fallbackFiles(platform, env, {programData = programDataFolder} = {}) {
40
+ if (platform !== 'win32') return ['/etc/countinghouse/ceiling.json'];
41
+ return [...new Set([programData(), 'C:\\ProgramData'].filter(Boolean))]
42
+ .map((d) => path.win32.join(d, 'countinghouse', 'ceiling.json'));
43
+ }
44
+
45
+ // -> {state: 'none'} | {state: 'trusted', file, ceiling} | {state: 'untrusted', file, problem}
46
+ // file: where to look when the runtime has no reader (a test's).
47
+ //
48
+ // The reader is the one the runtime installed now (an upgrade replaces
49
+ // it): required again only when its file changes. Its answer is kept while
50
+ // the ceiling file and its directory are unchanged, and on Windows for at
51
+ // most 5 minutes (an ACL change moves no timestamp), so a running start does
52
+ // not run PowerShell on each change it applies.
53
+ let cached = null; // {readerKey, ceilingKey, at, value}
54
+ const stampOf = (p) => { try { const st = fs.statSync(p); return `${st.ino}:${st.size}:${st.mtimeMs}:${st.mode}:${st.uid}`; } catch (err) { return err.code || 'error'; } };
55
+ function readCeiling(where, {platform = process.platform, env = process.env, file: given} = {}) {
56
+ const readerFile = path.join(where.app, 'node_modules', 'countinghouse', 'lib', 'settings-ceiling.js');
57
+ const readerKey = `${readerFile}|${stampOf(readerFile)}`;
58
+ // the home's code is loaded only from a home only this user can change
59
+ // (the reviewer's high on #126, H1): checked whenever this would load it
60
+ // (not when the reader is already loaded, so no check per call)
61
+ let loaded = false;
62
+ try { loaded = cached != null && cached.readerKey === readerKey && require.cache[require.resolve(readerFile)] != null; } catch (err) { loaded = false; }
63
+ if (!loaded) {
64
+ // (on this machine's own filesystem: never a platform a caller simulates)
65
+ const open = require('./home').openHomeLine(where.home);
66
+ if (open != null) return {state: 'untrusted', file: where.home, problem: open, home: true};
67
+ }
68
+ let reader = null;
69
+ try {
70
+ if (cached == null || cached.readerKey !== readerKey) delete require.cache[require.resolve(readerFile)];
71
+ reader = require(readerFile);
72
+ } catch (err) { reader = null; }
73
+ if (reader != null && typeof reader.readCeiling === 'function') {
74
+ let ceilingKey = 'unknown';
75
+ try {
76
+ const f = reader.ceilingFile();
77
+ ceilingKey = `${stampOf(f)}|${stampOf(path.dirname(f))}`;
78
+ } catch (err) { ceilingKey = `error:${err.code || err.message}`; }
79
+ const fresh = cached != null && cached.readerKey === readerKey && cached.ceilingKey === ceilingKey &&
80
+ !(platform === 'win32' && Date.now() - cached.at > 5 * 60 * 1000);
81
+ if (fresh) return cached.value;
82
+ let c;
83
+ try { c = reader.readCeiling(); } catch (err) { c = {state: 'untrusted', file: '(the ceiling)', problem: `it could not be read (${err.code || err.message})`}; }
84
+ // anything but a ceiling's answer fails closed
85
+ if (!(c != null && (c.state === 'none' || (c.state === 'untrusted' && typeof c.problem === 'string') ||
86
+ (c.state === 'trusted' && c.ceiling != null && Array.isArray(c.ceiling.forbid))))) {
87
+ c = {state: 'untrusted', file: '(the ceiling)', problem: 'the installed countinghouse gave an answer that is not a ceiling'};
88
+ }
89
+ cached = {readerKey, ceilingKey, at: Date.now(), value: c};
90
+ return c;
91
+ }
92
+ // No reader (an older runtime): a ceiling file at any place it could be
93
+ // fails closed. On Windows, where the known folder says, and C:\ProgramData.
94
+ for (const file of (given != null ? [given] : fallbackFiles(platform, env))) {
95
+ try {
96
+ fs.lstatSync(file);
97
+ return {state: 'untrusted', file, noReader: true, problem: `the installed countinghouse cannot read it: it is older than this ch-local; \`${chLocal(where, 'upgrade')}\` installs one that can`};
98
+ } catch (err) {
99
+ if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') return {state: 'untrusted', file, problem: `it cannot be examined (${err.code || 'error'})`};
100
+ }
101
+ }
102
+ return {state: 'none'};
103
+ }
104
+
105
+ // The ceiling as ch-local reads it (#413 section 8): the runtime's reader's
106
+ // answer, and a ceiling that still holds "packs" is not trusted: the list is
107
+ // by module now ("modules"), and an operator's old list must never quietly
108
+ // stop applying. Stricter than the runtime's reader until M6 brings it in
109
+ // line (the Reviewer's Q2 on L3).
110
+ function ceilingFor(where, opts = {}) {
111
+ const c = readCeiling(where, opts);
112
+ // (the runtime's reader answers packs: null for a file without it)
113
+ if (c != null && c.state === 'trusted' && c.ceiling != null && Array.isArray(c.ceiling.packs)) {
114
+ return {state: 'untrusted', file: c.file, problem: 'it holds "packs", which is no longer read: list each module under "modules"'};
115
+ }
116
+ return c;
117
+ }
118
+
119
+ // A module is the ceiling's allowlist's ("modules": [package names], when
120
+ // present: only those ever load, parts included), never forbid's. A ceiling
121
+ // that cannot be trusted allows NO module (the review of #18): a typo in it,
122
+ // a PowerShell that timed out or an older reader must not quietly lift the
123
+ // operator's list; it is said, naming the problem.
124
+ const short = (m) => String(m).replace(/^@[^/]+\//, '');
125
+ function moduleAllowed(ceiling, module) {
126
+ if (ceiling == null || ceiling.state === 'none') return true;
127
+ if (ceiling.state !== 'trusted') return false;
128
+ return !(Array.isArray(ceiling.ceiling.modules) && !ceiling.ceiling.modules.includes(module));
129
+ }
130
+ // (an open home is said as the home's problem, never an operator ceiling's:
131
+ // the medium on #126's round, 2)
132
+ const untrustedWhy = (ceiling) => (ceiling.home === true ? `this home can't be used: ${ceiling.problem}` : `the operator's ceiling file ${ceiling.file} cannot be trusted (${ceiling.problem})`);
133
+ const untrustedText = (ceiling) => `${untrustedWhy(ceiling)}, so no module loads`;
134
+ // Why these modules may not load, or null: the ones not on the list, named.
135
+ function modulesRefusal(ceiling, modules) {
136
+ if (ceiling == null || ceiling.state === 'none') return null;
137
+ if (ceiling.state !== 'trusted') return untrustedText(ceiling);
138
+ const out = modules.filter((m) => !moduleAllowed(ceiling, m));
139
+ return out.length === 0 ? null : `${out.length === 1 ? 'its module' : 'its modules'} ${out.map(short).join(', ')} ${out.length === 1 ? 'is' : 'are'} not on the operator's list`;
140
+ }
141
+ // A pack: allowed while its scenario module is. record: the home's
142
+ // modules.json; without one, the module the pack's name gives.
143
+ // (by its scenario module only, as enabled.<m> is judged: refusing exactly
144
+ // what start refuses. A part the scenario calls that is not on the list
145
+ // keeps it out by availability's rule 6; one it records but never calls
146
+ // does not: the Reviewer on #92. Used only for a pack.* turned on in the
147
+ // file: a set never writes one.)
148
+ function packAllowed(ceiling, pack, record = null) {
149
+ const {packScenario, packModuleName} = require('./packs');
150
+ return moduleAllowed(ceiling, (record != null && packScenario(record, pack)) || packModuleName(pack));
151
+ }
152
+ const packName = (name) => { const m = /^pack\.(.+)$/.exec(name); return m == null ? null : m[1]; };
153
+
154
+ // The operator's rule for one module setting ({fixed} | {confirm: true} |
155
+ // {conversation: false} | null), by the INSTALLED runtime's own
156
+ // moduleSettingRule (lib/settings-ceiling.js), so the ceiling's shape is
157
+ // read in one place (the Reviewer's high review of #90, 1). A ceiling that
158
+ // is not trusted has no rule to read: the caller refuses.
159
+ //
160
+ // At a terminal the ceiling's `"conversation": false` (a rule for
161
+ // conversation) never hides a setting's own fixed or confirm: the reader is
162
+ // asked with conversation on (the medium on the high round, 1). A trusted
163
+ // ceiling that holds module settings and a reader that cannot answer (an
164
+ // older runtime, or one that throws) fail closed: throws
165
+ // SETTING_CEILING_UNREADABLE (2, 3).
166
+ function moduleSettingRule(where, ceiling, pkg, setting) {
167
+ if (ceiling == null || ceiling.state !== 'trusted' || ceiling.ceiling == null || ceiling.ceiling.moduleSettings == null) return null;
168
+ const unreadable = (why) => Object.assign(new Error(`this machine's operator ceiling has rules for module settings, which the installed countinghouse cannot read (${why}); \`${chLocal(where, 'upgrade')}\` installs one that can; nothing was changed`), {code: 'SETTING_CEILING_UNREADABLE'});
169
+ let reader = null;
170
+ const readerFile = path.join(where.app, 'node_modules', 'countinghouse', 'lib', 'settings-ceiling.js');
171
+ // (the home's code only from a home only this user can change: H1)
172
+ let loaded = false;
173
+ try { loaded = require.cache[require.resolve(readerFile)] != null; } catch (err) { loaded = false; }
174
+ if (!loaded) {
175
+ const open = require('./home').openHomeLine(where.home);
176
+ if (open != null) throw Object.assign(new Error(`${open}; nothing was changed`), {code: 'SETTING_CEILING_UNREADABLE'});
177
+ }
178
+ try { reader = require(readerFile); } catch (err) { reader = null; }
179
+ if (reader == null || typeof reader.moduleSettingRule !== 'function') throw unreadable('it is older than module settings');
180
+ const m = ceiling.ceiling.moduleSettings;
181
+ const atTerminal = Object.assign({}, ceiling, {ceiling: Object.assign({}, ceiling.ceiling, {moduleSettings: Object.assign({}, m, {conversation: true})})});
182
+ try {
183
+ return reader.moduleSettingRule(atTerminal, pkg, setting);
184
+ } catch (err) {
185
+ throw unreadable(err.code || err.name || 'its reader failed');
186
+ }
187
+ }
188
+ const enabledModule = (name) => { const m = /^enabled\.(.+)$/.exec(name); return m == null ? null : m[1]; };
189
+
190
+ // The loosening of name to next (in its stored form) against the ceiling:
191
+ // null, or {code, message}. Tightening is never refused by it.
192
+ function ceilingRefusal(ceiling, name, next, record = null) {
193
+ if (ceiling == null || ceiling.state === 'none') return null;
194
+ if (ceiling.state !== 'trusted') {
195
+ return {code: 'SETTING_CEILING_UNTRUSTED', message: `${untrustedWhy(ceiling)}, so no setting is loosened; nothing was changed`};
196
+ }
197
+ const c = ceiling.ceiling;
198
+ const pack = packName(name);
199
+ const module = enabledModule(name);
200
+ // a module turned on that is not on the list (section 8: naming
201
+ // enabled.<module>); a pack by its modules (the old name, read until L2b)
202
+ const forbidden = module != null ? (next === true && !moduleAllowed(ceiling, module))
203
+ : pack != null ? (next === true && !packAllowed(ceiling, pack, record)) : c.forbid.includes(name);
204
+ if (forbidden) {
205
+ return {code: 'SETTING_FORBIDDEN_BY_CEILING', message: `${name} cannot be changed to ${shown(name, next)} on this machine: its operator's ceiling forbids it; nothing was changed`};
206
+ }
207
+ if (Number.isInteger(c[name]) && Number.isInteger(next) && next > c[name]) {
208
+ return {code: 'SETTING_ABOVE_CEILING', message: `${name} ${shown(name, next)} is above the ceiling this machine's operator set (at most ${shown(name, c[name])}); nothing was changed`};
209
+ }
210
+ return null;
211
+ }
212
+
213
+ // What start passes, under the ceiling: {values, notes} with each setting's
214
+ // value clamped (said in notes), or {problem} to refuse the start. A
215
+ // trusted ceiling clamps a cap or timeout to its maximum, a forbidden sandbox
216
+ // loosening back to enforce and forbidden automatic upgrades to off; one that
217
+ // cannot be trusted refuses a start whose settings or flags loosen past the
218
+ // hard defaults. passedAudit: --moduleSandbox audit passed through.
219
+ // forcedAudit: the installed runtime cannot run enforce here (Windows before
220
+ // countinghouse#195, lib/sandbox-support.js), so start runs audit, which is
221
+ // no loosening a setting or flag made: the sandbox is left out. where: the
222
+ // home's layout, for the command a refusal names (lib/command-line.js).
223
+ function startUnderCeiling(settings, ceiling, {passedAudit = false, forcedAudit = false, where = null} = {}) {
224
+ const values = Object.assign({}, settings.values);
225
+ const notes = [];
226
+ if (ceiling == null || ceiling.state === 'none') return {values, notes};
227
+ if (forcedAudit) passedAudit = false;
228
+ const loosened = ['maxOutputBytes', 'requestTimeout', 'autoUpgrade'].concat(forcedAudit ? [] : ['moduleSandbox'])
229
+ .filter((name) => Object.prototype.hasOwnProperty.call(values, name) && !entryOf(name).tighter(entryOf(name).default, values[name]));
230
+ if (ceiling.state !== 'trusted') {
231
+ const what = loosened.concat(passedAudit ? ['--moduleSandbox audit'] : []);
232
+ if (what.length > 0) {
233
+ return {problem: `${untrustedWhy(ceiling)}, and this start would loosen ${what.join(', ')}: not starting; the operator fixes the file, or the settings are tightened back (\`${chLocal(where, 'settings get')}\`)`};
234
+ }
235
+ return {values, notes};
236
+ }
237
+ const c = ceiling.ceiling;
238
+ if (passedAudit && c.forbid.includes('moduleSandbox')) {
239
+ return {problem: '--moduleSandbox audit is forbidden by this machine\'s operator ceiling: not starting'};
240
+ }
241
+ for (const name of ['maxOutputBytes', 'requestTimeout']) {
242
+ if (Number.isInteger(c[name]) && valueOf(settings, name) > c[name]) {
243
+ notes.push(`${name} ${shown(name, valueOf(settings, name))} is above the operator's ceiling: the runtime gets ${shown(name, c[name])}`);
244
+ values[name] = c[name];
245
+ }
246
+ }
247
+ if (!forcedAudit && c.forbid.includes('moduleSandbox') && values.moduleSandbox === 'audit') {
248
+ notes.push('moduleSandbox audit is forbidden by the operator\'s ceiling: the runtime runs under enforce');
249
+ values.moduleSandbox = 'enforce';
250
+ }
251
+ if (c.forbid.includes('autoUpgrade') && values.autoUpgrade === true) {
252
+ notes.push('automatic upgrades are forbidden by the operator\'s ceiling: they stay off');
253
+ values.autoUpgrade = false;
254
+ }
255
+ return {values, notes};
256
+ }
257
+
258
+ // An outside loosening the ceiling forbids outright (refused, not applied);
259
+ // one above a cap is clamped like any value, and an untrusted ceiling is
260
+ // start's and the applier's own refusal.
261
+ function forbiddenBy(ceiling) {
262
+ return (name, value) => { const r = ceilingRefusal(ceiling, name, value); return r != null && r.code === 'SETTING_FORBIDDEN_BY_CEILING' ? r : null; };
263
+ }
264
+
265
+ // install and add-pack: null, or why the operator's ceiling refuses pack.
266
+ // With no runtime installed yet there is no reader to ask (a first install):
267
+ // the install goes on, and start, reading the ceiling with the runtime it
268
+ // installed, loads only what the ceiling allows (none if it cannot be
269
+ // trusted).
270
+ // packages: every module of the pack (the release's), each checked before
271
+ // anything is fetched; one missing refuses the pack whole and names them
272
+ // (section 8).
273
+ function notAllowed(where, pack, io, packages = [require('./packs').packModuleName(pack)]) {
274
+ const c = ceilingFor(where, {platform: io.platform || process.platform, env: io.env});
275
+ if (c.noReader === true && !fs.existsSync(path.join(where.app, 'node_modules', 'countinghouse'))) return null;
276
+ const why = modulesRefusal(c, packages);
277
+ return why == null ? null : `the pack "${pack}" is not allowed on this machine: ${why}; nothing was installed`;
278
+ }
279
+
280
+ module.exports = {untrustedWhy, programDataFolder, PROGRAMDATA_SCRIPT, ceilingFor, ceilingRefusal, startUnderCeiling, fallbackFiles, forbiddenBy, packAllowed, moduleAllowed, modulesRefusal, moduleSettingRule, notAllowed, resetForTests: () => { cached = null; }};
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+ // Text that reaches a client's notice or the runtime from outside (a why, a
3
+ // path): cut and cleaned at the source. A hidden character (control,
4
+ // line-separator, bidi, zero-width, soft-hyphen, interlinear, tag,
5
+ // variation-selector, filler, lone surrogate: text a model reads and a person
6
+ // doesn't see) becomes a space, and the text is cut by code point, never half
7
+ // a surrogate pair.
8
+ //
9
+ // HIDDEN_CLASS is countinghouse's shared-runtime-wire conditionsWhy
10
+ // hiddenClass, the one definition both sides check against (a RegExp class
11
+ // body, u flag); test/shim-node.test.js holds it equal to the vectors' copy.
12
+ // It is spelled in escapes only, so this file holds none of those characters.
13
+ const HIDDEN_CLASS = '\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u034f\\u061c\\u115f\\u1160\\u180e\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2069\\u2800\\u3164\\ud800-\\udfff\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff9-\\ufffb\\u{1d173}-\\u{1d17a}\\u{e0000}-\\u{e007f}\\u{e0100}-\\u{e01ef}';
14
+ const HIDDEN = new RegExp(`[${HIDDEN_CLASS}]`, 'gu');
15
+
16
+ function cleanText(v, max = 200) {
17
+ return Array.from(String(v).replace(HIDDEN, ' ')).slice(0, max).join('');
18
+ }
19
+
20
+ module.exports = {cleanText, HIDDEN_CLASS};
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+ // A setting changed from the terminal (`ch-local settings set`, `upgrade
3
+ // --auto`; countinghouse part 3, section 3): a tightening is made at once; a
4
+ // loosening is bound by the operator's ceiling (lib/ceiling.js) and asked
5
+ // for at a terminal, with no --yes: that stops accidents, not an agent with
6
+ // a shell, whose consent is its client's own command-approval prompt (the
7
+ // line the spec draws). Not at a terminal, a loosening is refused. The
8
+ // answer is asked before the settings lock is taken; a value changed in
9
+ // between is not overwritten. -> {code: exit code, result}
10
+ const {planSetting, setSetting, shown} = require('./settings');
11
+ const {ceilingFor, ceilingRefusal} = require('./ceiling');
12
+
13
+ async function cliSet(where, name, value, io, {by = 'cli'} = {}) {
14
+ const fail = (code, message) => { io.stderr.write(`ch-local: ${message}\n`); return {code}; };
15
+ let plan;
16
+ try { plan = planSetting(where, name, value); } catch (err) {
17
+ if (err.code === 'SETTINGS_UNREADABLE') return fail(1, err.message);
18
+ if (typeof err.code === 'string' && err.code.startsWith('SETTING_')) return fail(2, err.message);
19
+ throw err;
20
+ }
21
+ if (plan.loosened) {
22
+ const refusal = ceilingRefusal(ceilingFor(where, {platform: io.platform, env: io.env}), name, plan.next);
23
+ if (refusal != null) return fail(2, refusal.message);
24
+ if (io.interactive !== true) return fail(2, `changing ${name} to ${shown(name, plan.next)} loosens a guarding setting, which is confirmed at a terminal: run it in one; nothing was changed`);
25
+ const answer = String(await io.ask(`Loosen ${name} from ${shown(name, plan.old)} to ${shown(name, plan.next)}? This is kept until you change it back. [y/N] `)).trim().toLowerCase();
26
+ if (answer !== 'y' && answer !== 'yes') return fail(1, `${name} was not changed`);
27
+ }
28
+ try {
29
+ const result = setSetting(where, name, value, {by, mayLoosen: true, expect: plan.old, confirmed: plan.loosened ? 'cli' : undefined});
30
+ return {code: 0, result};
31
+ } catch (err) {
32
+ if (err.code === 'SETTINGS_BUSY' || err.code === 'SETTINGS_UNREADABLE' || err.code === 'SETTINGS_CHANGED') return fail(1, err.message);
33
+ if (typeof err.code === 'string' && err.code.startsWith('SETTING_')) return fail(2, err.message);
34
+ throw err;
35
+ }
36
+ }
37
+
38
+ module.exports = {cliSet};