@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,334 @@
1
+ 'use strict';
2
+ // A module's settings at a terminal (#413 sections 4.2 and 4.3; L3):
3
+ //
4
+ // ch-local settings modules [<m>]
5
+ // ch-local settings set <m>.<setting> [<value>] (no value: prompted)
6
+ // ch-local settings reset <m>[.<setting>]
7
+ //
8
+ // <m> is a package name or the short name one installed module has -- a
9
+ // pack's, or one of the user's own (B-own-settings, the maintainer's decision: own
10
+ // modules' settings are adjustable in release 1; the declaration read from
11
+ // the module's copy, by own.json's tree, and only from a copy that still
12
+ // hashes to it);
13
+ // `module.` may be left out. The stored name is always
14
+ // module.<package>.<setting> (the last dot splits it: a setting name has
15
+ // none). The declaration is read from the module's active version in the
16
+ // module store, and a value is checked with the INSTALLED runtime's own
17
+ // reader (its lib/module-settings.js: parseDeclaration and checkValue), as
18
+ // lib/ceiling.js reads the ceiling with the runtime's, so the grammar has one
19
+ // source. A running start or daemon sees the file change and has its
20
+ // runtime read the values again (`reread`, section 7.3).
21
+ const fs = require('node:fs');
22
+ const path = require('node:path');
23
+ const {versionDir} = require('./store-paths');
24
+ const {readModulesRecord} = require('./module-record');
25
+ const settingsLib = require('./settings');
26
+ const {chLocal, folderArg, terminalText, hintCommand} = require('./command-line');
27
+ const {copyDir, readIntact} = require('./own-tree');
28
+
29
+ const short = (m) => String(m).replace(/^@[^/]+\//, '');
30
+ const refuse = (code, message) => Object.assign(new Error(message), {code});
31
+
32
+ // The installed runtime's reader, required again only when its file
33
+ // changes. -> its exports, or null (none installed, or one older than
34
+ // module settings).
35
+ let cached = null;
36
+ function runtimeReader(where) {
37
+ const file = path.join(where.app, 'node_modules', 'countinghouse', 'lib', 'module-settings.js');
38
+ let stamp;
39
+ try { const st = fs.statSync(file); stamp = `${st.ino}:${st.size}:${st.mtimeMs}`; } catch (err) { return null; }
40
+ if (cached != null && cached.file === file && cached.stamp === stamp) return cached.reader;
41
+ // (the home's code only from a home only this user can change: the
42
+ // reviewer's high on #126, H1; noReader says why)
43
+ if (require('./home').openHomeLine(where.home) != null) return null;
44
+ let reader = null;
45
+ try {
46
+ delete require.cache[require.resolve(file)];
47
+ reader = require(file);
48
+ } catch (err) { reader = null; }
49
+ if (reader == null || typeof reader.parseDeclaration !== 'function' || typeof reader.checkValue !== 'function') reader = null;
50
+ cached = {file, stamp, reader};
51
+ return reader;
52
+ }
53
+ // (where: the home's layout, for the commands' launcher form:
54
+ // lib/command-line.js)
55
+ const noReader = (where) => {
56
+ // (a home another user could change: that, never "upgrade": H1)
57
+ const open = require('./home').openHomeLine(where.home);
58
+ if (open != null) return `${open}; nothing was changed`;
59
+ return `the installed countinghouse cannot check a module's setting: run \`${chLocal(where, 'upgrade')}\` to install one that can; nothing was changed`;
60
+ };
61
+
62
+ // Every module whose settings a terminal adjusts: Map(name -> {own, dir,
63
+ // tree?, from?}) -- the record's, from its active version in the store,
64
+ // then the user's own, from its copy (a pack module of its name keeps it).
65
+ // An own.json that can't be read adds none of them.
66
+ // (ownProblem on the map: why own.json could not be read, said where a
67
+ // name is not found -- never taken for "no own module": the medium on
68
+ // B-own-settings, 5)
69
+ function modulesOf(where, record) {
70
+ const out = new Map();
71
+ for (const [m, e] of Object.entries((record && record.modules) || {})) out.set(m, {own: false, dir: versionDir(where, m, e.version)});
72
+ let own = null;
73
+ try { own = require('./own-record').readOwnRecord(where); } catch (err) { own = null; out.ownProblem = err.message; }
74
+ if (own != null) for (const [m, e] of Object.entries(own.modules)) if (!out.has(m)) out.set(m, {own: true, dir: copyDir(where, m, e.tree), tree: e.tree, from: e.from});
75
+ return out;
76
+ }
77
+ const ownProblemText = (mods) => (mods.ownProblem != null ? ` (your own modules could not be read (${mods.ownProblem}))` : '');
78
+ // the stored names of one module's settings: module.<module>.<setting>, the
79
+ // setting names (one rule for reset, add-module and remove-module)
80
+ const storedNamesOf = (kept, module) => {
81
+ const prefix = `module.${module}.`;
82
+ return Object.keys(kept || {}).filter((n) => n.startsWith(prefix) && !n.slice(prefix.length).includes('.'));
83
+ };
84
+
85
+ // An installed module by its package name or the short name one installed
86
+ // module has. -> package name; throws SETTING_UNKNOWN.
87
+ // (an exact installed full name wins over another module's same short name;
88
+ // exact: the module.<full name> form, which never takes a short name -- the
89
+ // reviewer on #116)
90
+ function moduleNamed(record, given, where, mods = modulesOf(where, record), {exact = false} = {}) {
91
+ const names = [...mods.keys()];
92
+ if (names.includes(given)) return given;
93
+ const byShort = exact ? [] : names.filter((n) => short(n) === given);
94
+ const ambiguous = (list) => refuse('SETTING_AMBIGUOUS', `more than one installed module is named ${given}: ${list.join(', ')}; give the full name`);
95
+ if (byShort.length > 1) throw ambiguous(byShort);
96
+ if (byShort.length === 1) return byShort[0];
97
+ throw refuse('SETTING_UNKNOWN', `no installed module is named ${given}${ownProblemText(mods)}; \`${chLocal(where, 'settings modules')}\` lists them`);
98
+ }
99
+
100
+ // "<m>.<setting>", "module.<package>.<setting>" or "<package>.<setting>":
101
+ // -> {module, setting, stored}. The last dot splits it.
102
+ function resolve(record, name, where, mods = modulesOf(where, record)) {
103
+ const bare = String(name).replace(/^module\./, '');
104
+ const dot = bare.lastIndexOf('.');
105
+ if (dot <= 0 || dot === bare.length - 1) throw refuse('SETTING_UNKNOWN', `${name} is not <module>.<setting>; \`${chLocal(where, 'settings modules')}\` lists them`);
106
+ const module = moduleNamed(record, bare.slice(0, dot), where, mods, {exact: /^module\./.test(String(name))});
107
+ const setting = bare.slice(dot + 1);
108
+ return {module, setting, stored: `module.${module}.${setting}`};
109
+ }
110
+
111
+ // The module's declared settings, from its active version's package.json in
112
+ // the store: -> {settings: map name -> declaration, net} (settings null
113
+ // when it declares none).
114
+ function declarationOf(where, record, module, reader, mods = modulesOf(where, record)) {
115
+ const at = mods.get(module);
116
+ // (gone meanwhile: a remove-module beside this command -- the medium, 6)
117
+ if (at == null) throw refuse('SETTING_UNKNOWN', `no installed module is named ${short(module)}${ownProblemText(mods)}; nothing was changed`);
118
+ let pkg;
119
+ if (at.own) {
120
+ // an own module's declaration: the package.json bytes hashed with its
121
+ // whole copy, only while it still hashes to the user's yes (the
122
+ // medium on B-own-settings, 3)
123
+ const bytes = readIntact(where, module, at.tree, 'package.json');
124
+ try { pkg = bytes != null ? JSON.parse(bytes.toString('utf8')) : null; } catch (err) { pkg = null; }
125
+ if (pkg == null) throw refuse('SETTING_UNKNOWN', `${short(module)}'s files changed since you added it: run \`${chLocal(where, `add-module ${folderArg(at.from)}`)}\` again; nothing was changed`);
126
+ } else {
127
+ try { pkg = JSON.parse(fs.readFileSync(path.join(at.dir, 'package.json'), 'utf8')); } catch (err) {
128
+ throw refuse('SETTING_UNKNOWN', `${short(module)}'s files are missing from the module store; run \`${chLocal(where, 'install')}\` again; nothing was changed`);
129
+ }
130
+ }
131
+ const parsed = reader.parseDeclaration(pkg);
132
+ if (parsed.problems != null && parsed.problems.length > 0) {
133
+ throw refuse('SETTING_UNKNOWN', `${short(module)}'s settings declaration cannot be read (${parsed.problems[0].message}); nothing was changed`);
134
+ }
135
+ const perms = pkg.countinghouse != null && pkg.countinghouse.permissions != null ? pkg.countinghouse.permissions : {};
136
+ return {settings: parsed.settings, net: Array.isArray(perms.net) ? perms.net : null};
137
+ }
138
+
139
+ // A raw terminal value in the declared type's form.
140
+ function typed(decl, raw) {
141
+ if (decl.type === 'boolean') return raw === 'true' || raw === 'on' ? true : raw === 'false' || raw === 'off' ? false : raw;
142
+ if (decl.type === 'integer' || decl.type === 'number') return /^-?\d+(\.\d+)?$/.test(String(raw).trim()) ? Number(raw) : raw;
143
+ return raw;
144
+ }
145
+ // what a declaration allows, said (never a value)
146
+ function allowedOf(decl) {
147
+ if (decl.type === 'enum') return decl.values.join(' or ');
148
+ if (decl.type === 'boolean') return 'true or false';
149
+ if (decl.type === 'integer' || decl.type === 'number') return `${decl.type === 'integer' ? 'a whole number' : 'a number'}${decl.min != null ? ` from ${decl.min}` : ''}${decl.max != null ? ` to ${decl.max}` : ''}`;
150
+ if (decl.format === 'repo') return 'owner/name';
151
+ return decl.format != null ? `a ${decl.format}` : `text of at most ${decl.maxLength} characters`;
152
+ }
153
+ const shownValue = (v) => (v === true ? 'on' : v === false ? 'off' : v === undefined ? '(not set)' : String(v));
154
+
155
+ // The operator's rule for one setting (section 8 moduleSettings): {fixed} |
156
+ // {confirm} | {conversation: false} | null, read with the installed
157
+ // runtime's own moduleSettingRule (lib/ceiling.js). A ceiling that cannot
158
+ // be trusted fails closed, as ch-local's own settings do: its rules are not
159
+ // known, so no module setting is changed under it (the Reviewer's high
160
+ // review of #90, 2). Throws SETTING_CEILING_UNTRUSTED.
161
+ // (the ceiling read once: -> (module, setting) -> rule)
162
+ function rulesFor(where, io) {
163
+ const ceiling = require('./ceiling');
164
+ const c = ceiling.ceilingFor(where, {platform: io.platform || process.platform, env: io.env});
165
+ if (c.state === 'untrusted') throw refuse('SETTING_CEILING_UNTRUSTED', `${ceiling.untrustedWhy(c)}, so no module setting is changed; nothing was changed`);
166
+ return (module, setting) => ceiling.moduleSettingRule(where, c, module, setting);
167
+ }
168
+ const ceilingRule = (where, io, module, setting) => rulesFor(where, io)(module, setting);
169
+
170
+ // What a set would do, before the lock (to ask first): -> {stored, module,
171
+ // setting, decl, old, next, confirm}; throws SETTING_*.
172
+ function planModuleSetting(where, io, name, raw) {
173
+ const reader = runtimeReader(where);
174
+ if (reader == null) throw refuse('SETTING_NO_READER', noReader(where));
175
+ const record = readModulesRecord(where);
176
+ if (record == null) throw refuse('SETTING_UNKNOWN', `nothing is installed; run ${hintCommand(where, 'install --pack <name>')} first; nothing was changed`);
177
+ const mods = modulesOf(where, record);
178
+ const r = resolve(record, name, where, mods);
179
+ const {settings, net} = declarationOf(where, record, r.module, reader, mods);
180
+ const decl = settings != null ? settings[r.setting] : null;
181
+ if (decl == null) {
182
+ const names = settings != null ? Object.keys(settings) : [];
183
+ throw refuse('SETTING_UNKNOWN', `${short(r.module)} declares no setting ${r.setting}${names.length > 0 ? `; it declares ${names.join(', ')}` : ''}; nothing was changed`);
184
+ }
185
+ const rule = ceilingRule(where, io, r.module, r.setting);
186
+ if (rule != null && Object.prototype.hasOwnProperty.call(rule, 'fixed')) {
187
+ throw refuse('SETTING_FORBIDDEN_BY_CEILING', `${r.setting} for ${short(r.module)} is fixed by this machine's operator ceiling; nothing was changed`);
188
+ }
189
+ const checked = reader.checkValue(decl, typed(decl, raw), {net});
190
+ if (checked.ok !== true) throw refuse(checked.code || 'SETTING_OUT_OF_BOUNDS', `${checked.reason}; nothing was changed`);
191
+ const read = settingsLib.readSettings(where);
192
+ if (read.error != null) throw refuse('SETTINGS_UNREADABLE', `${read.error}; fix or remove it first; nothing was changed`);
193
+ const has = Object.prototype.hasOwnProperty.call(read.kept, r.stored);
194
+ return {...r, decl, old: has ? read.kept[r.stored] : decl.default, stored0: has ? read.kept[r.stored] : undefined,
195
+ next: checked.value, confirm: decl.confirm === true || (rule != null && rule.confirm === true)};
196
+ }
197
+
198
+ // ch-local settings set <m>.<setting> [<value>] -> exit code
199
+ async function setModuleSetting(where, io, name, raw) {
200
+ const fail = (code, message) => { io.stderr.write(`ch-local: ${message}\n`); return code; };
201
+ const say = (s) => io.stdout.write(`${s}\n`);
202
+ try {
203
+ if (raw === undefined) {
204
+ // no value: asked at a terminal (what is allowed shown first)
205
+ const reader = runtimeReader(where);
206
+ if (reader == null) return fail(2, noReader(where));
207
+ const record = readModulesRecord(where);
208
+ const mods = modulesOf(where, record);
209
+ const r = resolve(record, name, where, mods);
210
+ const {settings} = declarationOf(where, record, r.module, reader, mods);
211
+ const decl = settings != null ? settings[r.setting] : null;
212
+ if (decl == null) return fail(2, `${short(r.module)} declares no setting ${r.setting}; nothing was changed`);
213
+ // the ceiling before anything is asked: a fixed or untrusted one
214
+ // refuses at once (the medium on the high round, 7)
215
+ const rule = ceilingRule(where, io, r.module, r.setting);
216
+ if (rule != null && Object.prototype.hasOwnProperty.call(rule, 'fixed')) return fail(2, `${r.setting} for ${short(r.module)} is fixed by this machine's operator ceiling; nothing was changed`);
217
+ if (io.interactive !== true || typeof io.ask !== 'function') return fail(2, `${r.setting} for ${short(r.module)} needs a value: give the value, or run it at a terminal to be asked; nothing was changed`);
218
+ raw = String(await io.ask(`${r.setting} for ${short(r.module)} (${allowedOf(decl)}): `)).trim();
219
+ }
220
+ const plan = planModuleSetting(where, io, name, raw);
221
+ if (plan.confirm) {
222
+ if (io.interactive !== true || typeof io.ask !== 'function') return fail(2, `${plan.setting} for ${short(plan.module)} is confirmed at a terminal: run it in one; nothing was changed`);
223
+ const answer = String(await io.ask(`Change ${plan.setting} for ${short(plan.module)} from ${JSON.stringify(plan.old) || 'unset'} to ${JSON.stringify(plan.next)}? [y/N] `)).trim().toLowerCase();
224
+ if (answer !== 'y' && answer !== 'yes') return fail(1, `${plan.setting} for ${short(plan.module)} was not changed`);
225
+ }
226
+ settingsLib.writeModuleValues(where, {[plan.stored]: plan.next}, {by: 'cli', expect: {[plan.stored]: plan.stored0}, inEffect: {[plan.stored]: plan.old}});
227
+ say(`${short(plan.module)}.${plan.setting}: ${shownValue(plan.old)} -> ${shownValue(plan.next)}; a running client applies it now, and the next load otherwise`);
228
+ return 0;
229
+ } catch (err) {
230
+ if (err.code === 'SETTINGS_BUSY' || err.code === 'SETTINGS_UNREADABLE' || err.code === 'SETTINGS_CHANGED') return fail(1, err.message);
231
+ if (typeof err.code === 'string' && err.code.startsWith('SETTING')) return fail(2, err.message);
232
+ throw err;
233
+ }
234
+ }
235
+
236
+ // ch-local settings reset <m>[.<setting>] -> exit code: the stored values
237
+ // removed (each back to its default), recorded; other names kept.
238
+ function resetModuleSetting(where, io, target) {
239
+ const fail = (code, message) => { io.stderr.write(`ch-local: ${message}\n`); return code; };
240
+ try {
241
+ const record = readModulesRecord(where);
242
+ if (record == null) return fail(2, 'nothing is installed; nothing was changed');
243
+ const read = settingsLib.readSettings(where);
244
+ if (read.error != null) return fail(1, `${read.error}; fix or remove it first; nothing was changed`);
245
+ const mods = modulesOf(where, record);
246
+ // module.<full name>: that exact name, never a short one
247
+ const explicit = /^module\./.test(String(target));
248
+ const bareTarget = String(target).replace(/^module\./, '');
249
+ let module = null;
250
+ let setting = null;
251
+ if (mods.has(bareTarget)) {
252
+ // an installed module by its exact full name
253
+ module = bareTarget;
254
+ } else if (storedNamesOf(read.kept, bareTarget).length > 0) {
255
+ // a module no longer installed -- an own module removed, its settings
256
+ // kept and said so -- by its full name (the medium on B-own-settings,
257
+ // 1); never when an installed module's short name is the same name:
258
+ // ambiguous, so the advice never resets another's (the reviewer on #116)
259
+ const shorts = explicit ? [] : [...mods.keys()].filter((n) => short(n) === bareTarget);
260
+ if (shorts.length > 0) return fail(2, `${bareTarget} names more than one module: ${bareTarget} (no longer installed; its settings stored) and ${shorts.join(', ')}; give module.<full name>; nothing was changed`);
261
+ module = bareTarget;
262
+ } else if (!explicit) {
263
+ try { module = moduleNamed(record, bareTarget, where, mods); } catch (err) {
264
+ // two installed modules share that short name: said as it is (the
265
+ // Reviewer's high review of #90, 7), never taken for <m>.<setting>
266
+ if (err.code === 'SETTING_AMBIGUOUS') return fail(2, `${err.message}; nothing was changed`);
267
+ }
268
+ }
269
+ if (module == null) {
270
+ const r = resolve(record, target, where, mods);
271
+ module = r.module;
272
+ setting = r.setting;
273
+ }
274
+ const prefix = `module.${module}.`;
275
+ const names = setting != null ? Object.keys(read.kept).filter((n) => n === `${prefix}${setting}`) : storedNamesOf(read.kept, module);
276
+ // a setting the operator's ceiling fixes is never changed, by a reset
277
+ // either (the medium on L3, 8)
278
+ const rules = rulesFor(where, io);
279
+ const fixed = names.map((n) => n.slice(prefix.length)).filter((s) => { const rule = rules(module, s); return rule != null && Object.prototype.hasOwnProperty.call(rule, 'fixed'); });
280
+ if (fixed.length > 0) return fail(2, `${fixed.join(', ')} for ${short(module)} ${fixed.length === 1 ? 'is' : 'are'} fixed by this machine's operator ceiling; nothing was changed`);
281
+ const done = settingsLib.writeModuleValues(where, Object.fromEntries(names.map((n) => [n, settingsLib.REMOVE])), {by: 'cli', change: 'reset'});
282
+ io.stdout.write(done.changed.length === 0 ? 'nothing to reset\n'
283
+ : `${done.changed.length} setting${done.changed.length === 1 ? '' : 's'} of ${short(module)} back to the default; a running client applies it now, and the next load otherwise\n`);
284
+ return 0;
285
+ } catch (err) {
286
+ if (typeof err.code === 'string' && (err.code.startsWith('SETTING') || err.code.startsWith('SETTINGS'))) return fail(2, err.message);
287
+ throw err;
288
+ }
289
+ }
290
+
291
+ // ch-local settings modules [<m>] -> exit code: every installed module's
292
+ // declared settings (loaded or not), one line each; with <m>, its
293
+ // descriptions too.
294
+ function listModuleSettings(where, io, given = null) {
295
+ const say = (s) => io.stdout.write(`${s}\n`);
296
+ const reader = runtimeReader(where);
297
+ if (reader == null) { io.stderr.write(`ch-local: ${noReader(where).replace(/; nothing was changed$/, '')}\n`); return 2; }
298
+ const record = readModulesRecord(where);
299
+ if (record == null) { say('nothing is installed'); return 0; }
300
+ const mods = modulesOf(where, record);
301
+ if (mods.ownProblem != null) io.stderr.write(`ch-local: your own modules could not be read (${mods.ownProblem}); they are not listed\n`);
302
+ let only = null;
303
+ try { only = given != null ? moduleNamed(record, given, where, mods) : null; } catch (err) { io.stderr.write(`ch-local: ${err.message}\n`); return 2; }
304
+ const read = settingsLib.readSettings(where);
305
+ // a file that is not valid is said, never listed as defaults (as
306
+ // `settings get` does: the Reviewer's high review of #90, 6)
307
+ if (read.error != null) { io.stderr.write(`ch-local: ${read.error}; ch-local start refuses to start until it is fixed\n`); return 1; }
308
+ const kept = read.kept || {};
309
+ let any = false;
310
+ for (const m of [...mods.keys()].sort()) {
311
+ if (only != null && m !== only) continue;
312
+ let decl;
313
+ try { decl = declarationOf(where, record, m, reader, mods).settings; } catch (err) { say(`${short(m)}: ${err.message.replace(/; nothing was changed$/, '')}`); continue; }
314
+ if (decl == null) continue;
315
+ for (const [name, d] of Object.entries(decl)) {
316
+ any = true;
317
+ const stored = kept[`module.${m}.${name}`];
318
+ const value = stored !== undefined ? stored : d.default;
319
+ // (a module's own words, as a terminal shows them: nothing that moves
320
+ // the cursor -- the medium on B-own-settings, 2)
321
+ const parts = [d.title != null ? terminalText(d.title, 120) : null, d.default !== undefined ? `default ${terminalText(shownValue(d.default), 120)}` : null, terminalText(allowedOf(d), 240), d.confirm === true ? 'asks before a change' : null].filter((x) => x != null);
322
+ say(`${short(m)}.${terminalText(name, 120)} = ${terminalText(shownValue(value), 120)} (${parts.join('; ')})`);
323
+ if (only != null && d.description != null) say(` ${terminalText(d.description, 400)}`);
324
+ }
325
+ }
326
+ if (!any) say(only != null ? `${short(only)} declares no settings` : 'no installed module declares a setting');
327
+ return 0;
328
+ }
329
+
330
+ // Whether a name is a module's setting (not one of ch-local's own, an
331
+ // enabled.* or a pack.*): what the settings command routes here.
332
+ const isModuleName = (name) => settingsLib.entryOf(name) == null && /\./.test(String(name)) && !/^(enabled|pack)\./.test(String(name));
333
+
334
+ module.exports = {storedNamesOf, setModuleSetting, resetModuleSetting, listModuleSettings, planModuleSetting, isModuleName, runtimeReader, resolve, resetForTests: () => { cached = null; }};
package/lib/names.js ADDED
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ // Names and versions as a release writes them. They become directory names
3
+ // (the pack trees, the module store), so nothing else passes: one copy, read
4
+ // by both records (lib/record.js, lib/module-record.js) and the store.
5
+ const VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,64})?$/;
6
+ const PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]{0,63}\/)?[a-z0-9][a-z0-9._-]{0,127}$/;
7
+ // a package's scope directory: PACKAGE's part before the slash
8
+ const SCOPE = /^@[a-z0-9][a-z0-9._-]{0,63}$/;
9
+ const PACK = /^[a-z0-9][a-z0-9-]{0,63}$/;
10
+
11
+ // A module version the store holds as a directory, beside its marker
12
+ // (<version>.json) and its staging and trash names (<version>.new-*,
13
+ // .trash-*). Refused (each could share another version's path):
14
+ // - one that ends in .json or holds .new- or .trash- (the medium review of
15
+ // L1a-1, 4);
16
+ // - one with an upper-case letter: on a case-insensitive file system
17
+ // (Windows, macOS by default) 1.0.0-RC.1 and 1.0.0-rc.1 share a directory
18
+ // (#82's high review, 3);
19
+ // - one that ends in a dot, or holds an empty identifier (..): Windows drops
20
+ // a trailing dot, so 1.0.0-a. is 1.0.0-a's directory (#82's medium, 4).
21
+ const storeVersion = (v) => typeof v === 'string' && VERSION.test(v) && !/[A-Z]/.test(v) && !/\.json$/.test(v) &&
22
+ !/\.(?:new|trash)-/.test(v) && !/\.$/.test(v) && !/[.+-]{2}/.test(v.replace(/^\d+\.\d+\.\d+/, ''));
23
+
24
+ // A name as Windows lays it out: each part's trailing dots and spaces
25
+ // dropped (Windows drops them, so "my-tool." is my-tool's directory, and its
26
+ // data). Two names with one key are one name (the reviewer's high on
27
+ // ch-local#113, 1); an own module's name ends in neither.
28
+ const nameKey = (name) => String(name).split('/').map((p) => p.replace(/[. ]+$/, '')).join('/');
29
+ const endsTrimmed = (name) => nameKey(name) !== String(name);
30
+
31
+ module.exports = {VERSION, PACKAGE, SCOPE, PACK, storeVersion, nameKey, endsTrimmed};
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+ // What a person is told to do next once install or add-pack has put a pack
3
+ // in place (A-firstrun d1, the first-run design): one fixed line, the last on
4
+ // stdout, true whatever is still missing (it looks at nothing). A change to
5
+ // it is a change to checked text.
6
+ const READY_LINE = 'Next: add any credential still missing and connect your client; then ask it what countinghouse can do for you.';
7
+
8
+ module.exports = {READY_LINE};
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ // The Node floor, checked before anything else is loaded (spec §2, "Node").
3
+ // It requires nothing, so even a Node far below the floor gets this far.
4
+ var FLOOR = '22.16.0';
5
+
6
+ function parts(v) {
7
+ return String(v).replace(/^v/, '').split('.').map(function (x) { return parseInt(x, 10) || 0; });
8
+ }
9
+
10
+ function check(version) {
11
+ var have = parts(version);
12
+ var need = parts(FLOOR);
13
+ var ok = have[0] > need[0] || (have[0] === need[0] && (have[1] > need[1] || (have[1] === need[1] && have[2] >= need[2])));
14
+ return {ok: ok, floor: FLOOR};
15
+ }
16
+
17
+ // The routes the install pages give (docs/install/README.md, "Before you
18
+ // start", as they land),
19
+ // never "whatever is current": Homebrew's node@24 is keg-only, so it goes on
20
+ // the PATH as `brew info node@24` prints; winget has no per-major id for 24,
21
+ // so Windows takes the installer from latest-v24.x -- the x64 one, while
22
+ // ch-local's own end-to-end Windows runs are x64 only (the shim's own tests
23
+ // run on arm64 too); x64 emulation is Windows 11 on Arm's, not 10's. An arm64
24
+ // end-to-end run, once it exists, names both. Each command and address
25
+ // stands on its own indented line with nothing after it, so a copy of it is
26
+ // whole (CMD); the prose around it is indented under the header (MORE), broken
27
+ // to fit an 80-column terminal.
28
+ var MORE = '\n ';
29
+ var CMD = '\n ';
30
+ var INSTALL = {
31
+ darwin: 'the macOS installer (.pkg) from' + CMD + 'https://nodejs.org/dist/latest-v24.x/'
32
+ + MORE + 'or Homebrew:' + CMD + 'brew install node@24'
33
+ + MORE + 'then add the PATH line that brew info node@24 prints to your shell\'s'
34
+ + MORE + 'startup file (~/.zshrc for zsh, the default; ~/.bash_profile for bash),'
35
+ + MORE + 'and open a new terminal',
36
+ win32: 'the Windows installer (.msi, x64; our end-to-end Windows checks run'
37
+ + MORE + 'on x64, and x64 Node also runs on arm64 Windows 11) from' + CMD + 'https://nodejs.org/dist/latest-v24.x/'
38
+ + MORE + 'then open a new terminal',
39
+ linux: 'your distribution\'s package if node -v' + MORE + 'then prints v24.x; otherwise' + CMD + 'https://nodejs.org/en/download'
40
+ + MORE + 'choose v24 and Linux, and it shows the commands to run',
41
+ // (any other system: FreeBSD, and the rest)
42
+ other: 'your system\'s package manager or ports,' + MORE + 'for Node 24'
43
+ };
44
+
45
+ // The route a person takes, in plain text: the install pages' own, under
46
+ // its header (bin/ch-local.js has said what is needed and what was found). ch-local's own fetch of Node (24 from
47
+ // nodejs.org, its SHA-256 checked against SHASUMS256.txt) is not built, so
48
+ // none is offered and nothing is asked or downloaded. -> 'install-yourself'
49
+ async function offerNode(io) {
50
+ // (under bin's own line, "needs Node 22.16 or later; this is <version>")
51
+ io.stderr.write('Install Node 24 yourself:' + MORE
52
+ + (Object.prototype.hasOwnProperty.call(INSTALL, io.platform) ? INSTALL[io.platform] : INSTALL.other) + '\n');
53
+ return 'install-yourself';
54
+ }
55
+
56
+ module.exports = {FLOOR: FLOOR, check: check, offerNode: offerNode};
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+ // The registry fetch for upgrades from npm (docs/development/auto-upgrade.md,
3
+ // "The trust chain", step 2): a package's packument and one version's
4
+ // tarball, from https://registry.npmjs.org/ only.
5
+ // - The tarball URL must be the registry's own path for that name and
6
+ // version, with nothing after it, on the registry's origin. Anything else is
7
+ // NOT_ON_REGISTRY, and nothing is fetched.
8
+ // - dist.integrity must be a sha512 (NO_SHA512 otherwise), and the tarball's
9
+ // own sha512 must equal it (INTEGRITY_MISMATCH).
10
+ // - With a pin ({version, integrity}), the pin must name that version and
11
+ // integrity, or it is PIN_MISMATCH before the tarball is fetched.
12
+ // - Every answer is bounded: a packument at most 16 MB, a tarball at most
13
+ // 50 MB (FETCH_TOO_LARGE), and each fetch 15 s or 60 s (FETCH_FAILED, as is
14
+ // a failed connection or an error status).
15
+ // Each failure is an Error with one of those codes, which the announcements
16
+ // name. Nothing here runs or unpacks what it fetches.
17
+
18
+ const {integrityOf} = require('./integrity');
19
+ const REGISTRY = 'https://registry.npmjs.org/';
20
+ const PACKUMENT_MAX = 16 * 1024 * 1024;
21
+ const TARBALL_MAX = 50 * 1024 * 1024;
22
+ const ATTESTATIONS_MAX = 1024 * 1024;
23
+ const PACKUMENT_MS = 15000;
24
+ const TARBALL_MS = 60000;
25
+ const SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/;
26
+
27
+ const failure = (code, message) => Object.assign(new Error(message), {code});
28
+
29
+ // The registry is always registry.npmjs.org. A test's fake one reaches these
30
+ // functions only as their `registry` argument, passed by the test's own code:
31
+ // no variable, argument or file selects another (docs/development/
32
+ // auto-upgrade.md, "Development overrides never reach a real upgrade").
33
+
34
+ // body of a fetch, at most maxBytes, within the AbortController's time
35
+ async function readBounded(res, maxBytes, what) {
36
+ const declared = Number(res.headers.get('content-length'));
37
+ if (Number.isFinite(declared) && declared > maxBytes) throw failure('FETCH_TOO_LARGE', `${what} is ${declared} bytes, over ${maxBytes}`);
38
+ const chunks = [];
39
+ let size = 0;
40
+ for await (const chunk of res.body) {
41
+ size += chunk.length;
42
+ if (size > maxBytes) throw failure('FETCH_TOO_LARGE', `${what} is over ${maxBytes} bytes`);
43
+ chunks.push(Buffer.from(chunk));
44
+ }
45
+ return Buffer.concat(chunks);
46
+ }
47
+
48
+ // GET url -> its bytes, bounded in size and time
49
+ async function get(url, io, {maxBytes, timeoutMs, accept, what}) {
50
+ const abort = new AbortController();
51
+ const timer = setTimeout(() => abort.abort(), timeoutMs);
52
+ try {
53
+ let res;
54
+ try {
55
+ res = await io.fetch(url, {headers: accept != null ? {accept} : {}, signal: abort.signal, redirect: 'error'});
56
+ } catch (e) {
57
+ // (unreachable: no answer at all, which a reinstall says with the
58
+ // --from line that needs no network; the medium on the install hints, 4)
59
+ throw Object.assign(failure('FETCH_FAILED', `${what} could not be fetched (${abort.signal.aborted ? `no answer in ${timeoutMs / 1000} s` : (e.cause && e.cause.code) || e.message})`), {unreachable: true});
60
+ }
61
+ if (res.status === 404) return null;
62
+ if (!res.ok) throw failure('FETCH_FAILED', `the registry answered ${res.status} for ${what}`);
63
+ try {
64
+ return await readBounded(res, maxBytes, what);
65
+ } catch (e) {
66
+ if (e.code === 'FETCH_TOO_LARGE') throw e;
67
+ // (a body cut after the registry answered is not "no network": the
68
+ // reviewer's high on #124, 7)
69
+ throw failure('FETCH_FAILED', `${what} could not be read (${abort.signal.aborted ? `no answer in ${timeoutMs / 1000} s` : e.message})`);
70
+ }
71
+ } finally {
72
+ clearTimeout(timer);
73
+ }
74
+ }
75
+
76
+ const encoded = (name) => name.replace('/', '%2F');
77
+
78
+ // name -> its packument (JSON), or null when the registry has no such package
79
+ async function packument(name, io, {registry = REGISTRY, maxBytes = PACKUMENT_MAX, timeoutMs = PACKUMENT_MS} = {}) {
80
+ const body = await get(`${registry}${encoded(name)}`, io, {maxBytes, timeoutMs, accept: 'application/json', what: `${name}'s packument`});
81
+ if (body == null) return null;
82
+ try {
83
+ return JSON.parse(body.toString('utf8'));
84
+ } catch (e) {
85
+ throw failure('FETCH_FAILED', `${name}'s packument is not JSON`);
86
+ }
87
+ }
88
+
89
+ // name@version's attestations (provenance, lib/provenance.js), as JSON, at
90
+ // most 1 MB -> the document, or null when the registry has none
91
+ async function attestations(name, version, io, {registry = REGISTRY, maxBytes = ATTESTATIONS_MAX, timeoutMs = PACKUMENT_MS} = {}) {
92
+ const body = await get(`${registry}-/npm/v1/attestations/${encoded(name)}@${version}`, io, {maxBytes, timeoutMs, accept: 'application/json', what: `${name}@${version}'s attestations`});
93
+ if (body == null) return null;
94
+ try {
95
+ return JSON.parse(body.toString('utf8'));
96
+ } catch (e) {
97
+ throw failure('FETCH_FAILED', `${name}@${version}'s attestations are not JSON`);
98
+ }
99
+ }
100
+
101
+ // the registry's own tarball URL for name@version
102
+ const tarballUrl = (registry, name, version) => `${registry}${name}/-/${name.split('/').pop()}-${version}.tgz`;
103
+
104
+ // name@version's tarball -> {bytes, integrity}. pin: {version, integrity},
105
+ // when this ch-local's pins name the package.
106
+ async function fetchTarball(name, version, io, {registry = REGISTRY, pin = null, maxBytes = TARBALL_MAX, timeoutMs = TARBALL_MS} = {}) {
107
+ const doc = await packument(name, io, {registry});
108
+ const entry = doc != null && doc.versions != null && Object.prototype.hasOwnProperty.call(doc.versions, version) ? doc.versions[version] : null;
109
+ if (entry == null || entry.dist == null) throw failure('NOT_PUBLISHED', `${name}@${version} is not on the registry`);
110
+ const {tarball, integrity} = entry.dist;
111
+ if (tarball !== tarballUrl(registry, name, version)) throw failure('NOT_ON_REGISTRY', `${name}@${version} is not served from ${registry}`);
112
+ if (typeof integrity !== 'string' || !SHA512.test(integrity)) throw failure('NO_SHA512', `${name}@${version} has no sha512 integrity on the registry`);
113
+ if (pin != null && (pin.version !== version || pin.integrity !== integrity)) {
114
+ throw failure('PIN_MISMATCH', `${name}@${version} on the registry is not the one this ch-local pins`);
115
+ }
116
+ const bytes = await get(tarball, io, {maxBytes, timeoutMs, what: `${name}@${version}'s tarball`});
117
+ if (bytes == null) throw failure('NOT_PUBLISHED', `${name}@${version}'s tarball is not on the registry`);
118
+ const got = integrityOf(bytes);
119
+ if (got !== integrity) throw failure('INTEGRITY_MISMATCH', `${name}@${version} did not match its integrity`);
120
+ return {bytes, integrity};
121
+ }
122
+
123
+ module.exports = {REGISTRY, PACKUMENT_MAX, TARBALL_MAX, ATTESTATIONS_MAX, packument, fetchTarball, attestations, tarballUrl};