@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,137 @@
1
+ 'use strict';
2
+ // What the release pins say of a module (#413 section 9.3; L5b): from its
3
+ // own package.json, the credential its remote declares (variable and
4
+ // origin), the modules it calls (as package names), and each setting it
5
+ // marks confirm: true with that setting's default. One pure reader, used by
6
+ // the release step that writes the description (scripts/describe-release.js),
7
+ // by install's check that a fetched package matches it, and by the upgrade
8
+ // preview, so the three never judge a manifest differently.
9
+ //
10
+ // It describes; it does not allow. The store's binding says where a key may
11
+ // go, and the runtime checks calls and settings from the manifests it loads.
12
+ // The description exists so that a release can be compared with the one
13
+ // installed before anything is fetched, and so that what was shown is what
14
+ // is installed.
15
+ const store = require('./credential-store');
16
+
17
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
18
+ const MAX_VARIABLE = 128;
19
+ // the roles the runtime knows (module-store roleOf): a scenario, a part
20
+ // (the medium on #98's high round, 10)
21
+ const ROLE = /^(?:scenario|part)$/;
22
+ // one credential the same as another: its variable and its origin
23
+ const sameCredential = (a, b) => a != null && b != null && a.variable === b.variable && a.origin === b.origin;
24
+
25
+ // {api.json of each package (or null)} -> {map: Map(friendly name ->
26
+ // package)} or {problem}: two packages with one name. A call names a module by the friendly name before its slash, as
27
+ // the runtime matches it (lib/availability.js callsOf).
28
+ function friendlyNames(apis) {
29
+ const map = new Map();
30
+ for (const [pkg, api] of Object.entries(apis)) {
31
+ const name = isObject(api) && isObject(api.device) && typeof api.device.friendlyName === 'string' && api.device.friendlyName !== '' ? api.device.friendlyName : null;
32
+ if (name == null) continue; // no friendly name: nothing can call it
33
+ if (map.has(name)) return {problem: `${name} is the friendly name of both ${map.get(name)} and ${pkg}`};
34
+ map.set(name, pkg);
35
+ }
36
+ return {map};
37
+ }
38
+
39
+ // The credential, as lib/module-credentials.js declared() reads it: the one
40
+ // remote with a credential; its variable is the string form or {env}; its
41
+ // destination the origin of the remote's url. fallbackEnv is never described
42
+ // (section 6.1: never read).
43
+ // The one reader of a module's credential (the Reviewer's high review of
44
+ // #98, 2: install's description, the runtime binding and uninstall all read
45
+ // it here). remotes: countinghouse.remotes, a list -> {credential: null |
46
+ // {variable, origin, remote, fallback}} or {problem}. The string form
47
+ // ("credential": "GITHUB_TOKEN", 0.2.0's) and the object form ({env, ...})
48
+ // both name the variable; fallbackEnv is never the variable.
49
+ function credentialOf(remotes) {
50
+ const withCredential = (Array.isArray(remotes) ? remotes : []).filter((r) => isObject(r) && r.credential != null);
51
+ if (withCredential.length === 0) return {credential: null};
52
+ if (withCredential.length > 1) return {problem: 'it declares more than one credential', code: 'multiple'};
53
+ const r = withCredential[0];
54
+ const variable = typeof r.credential === 'string' ? r.credential : (isObject(r.credential) ? r.credential.env : null);
55
+ if (typeof variable !== 'string' || variable.length > MAX_VARIABLE || !store.VARIABLE.test(variable)) return {problem: 'its credential\'s variable cannot be read', code: 'variable'};
56
+ let origin = null;
57
+ try { origin = new URL(r.url).origin; } catch (err) { origin = null; }
58
+ if (!store.isOrigin(origin)) return {problem: 'its credential\'s remote is not an https origin', code: 'origin'};
59
+ const fallback = isObject(r.credential) && typeof r.credential.fallbackEnv === 'string' ? r.credential.fallbackEnv : null;
60
+ return {credential: {variable, origin, remote: typeof r.name === 'string' ? r.name : null, fallback}};
61
+ }
62
+ // Every variable name a module's remotes mention, whether or not they make a
63
+ // credential it can hold: each remote's string form, its env and its
64
+ // fallbackEnv, each once, sorted (uninstall names them all, to be revoked:
65
+ // the Reviewer's high review of #98's round 2, 6). Lists names; never judges.
66
+ function declaredVariables(remotes) {
67
+ const out = new Set();
68
+ for (const r of (Array.isArray(remotes) ? remotes : [])) {
69
+ if (!isObject(r) || r.credential == null) continue;
70
+ const names = typeof r.credential === 'string' ? [r.credential] : isObject(r.credential) ? [r.credential.env, r.credential.fallbackEnv] : [];
71
+ for (const n of names) if (typeof n === 'string' && store.VARIABLE.test(n)) out.add(n);
72
+ }
73
+ return [...out].sort();
74
+ }
75
+ function credentialsOf(remotes) {
76
+ const c = credentialOf(remotes);
77
+ if (c.problem != null) return c;
78
+ return {list: c.credential == null ? [] : [{variable: c.credential.variable, origin: c.credential.origin}]};
79
+ }
80
+
81
+ // manifest: the package's package.json, parsed; friendly: Map(friendly name
82
+ // -> package) of the release's modules -> {credentials: [{variable,
83
+ // origin}], calls: [package], confirmSettings: {name: default | null}}, or
84
+ // {problem}
85
+ function describeModule(manifest, friendly) {
86
+ if (!isObject(manifest)) return {problem: 'it has no package.json'};
87
+ const ch = manifest.countinghouse == null ? {} : manifest.countinghouse;
88
+ if (!isObject(ch)) return {problem: 'its countinghouse field is not an object'};
89
+ if (ch.remotes != null && !Array.isArray(ch.remotes)) return {problem: 'its countinghouse.remotes is not a list'};
90
+ if (ch.calls != null && !Array.isArray(ch.calls)) return {problem: 'its countinghouse.calls is not a list'};
91
+ if (ch.settings != null && !isObject(ch.settings)) return {problem: 'its countinghouse.settings is not an object'};
92
+ // its role, recorded: a part's settings are set at a terminal only, so a
93
+ // module that stops being a part is an addition (the Reviewer's high
94
+ // review of #98, 6)
95
+ if (ch.role != null && (typeof ch.role !== 'string' || !ROLE.test(ch.role))) return {problem: 'its countinghouse.role is neither scenario nor part'};
96
+ const role = ch.role == null ? null : ch.role;
97
+ const cred = credentialsOf(ch.remotes || []);
98
+ if (cred.problem != null) return {problem: cred.problem};
99
+ const calls = new Set();
100
+ for (const c of (ch.calls || [])) {
101
+ if (typeof c !== 'string' || !c.includes('/')) continue; // as the runtime: a call names module/action
102
+ const name = c.slice(0, c.indexOf('/'));
103
+ const pkg = friendly.get(name);
104
+ // (unknownCall: the name, for install's check to tell this from a
105
+ // manifest it cannot read: the medium on L5b, 2)
106
+ if (pkg == null) return {problem: `it calls ${name}, which is no module of this release`, unknownCall: name};
107
+ calls.add(pkg);
108
+ }
109
+ const confirmSettings = {};
110
+ for (const name of Object.keys(ch.settings || {}).sort()) {
111
+ const s = ch.settings[name];
112
+ // confirm as the runtime rules it (countinghouse lib/module-settings.js
113
+ // confirmRule): marked confirm, or any string setting (the medium on
114
+ // L5b, 5)
115
+ if (isObject(s) && (s.confirm === true || s.type === 'string')) confirmSettings[name] = Object.prototype.hasOwnProperty.call(s, 'default') ? s.default : null;
116
+ }
117
+ return {role, credentials: cred.list, calls: [...calls].sort(), confirmSettings};
118
+ }
119
+
120
+ // What differs between the pins' description and a package's: null, or the
121
+ // part, as install's refusal names it.
122
+ function describeProblem(want, got) {
123
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
124
+ if (want.role !== got.role) return 'its role';
125
+ // field by field, never by serialisation (the Reviewer's high review of
126
+ // #98, 9)
127
+ if (want.credentials.length !== got.credentials.length || want.credentials.some((c, i) => !sameCredential(c, got.credentials[i]))) return 'its credential destination';
128
+ if (!same(want.calls, got.calls)) return 'its calls';
129
+ const names = [...new Set([...Object.keys(want.confirmSettings), ...Object.keys(got.confirmSettings)])].sort();
130
+ for (const n of names) {
131
+ const has = (o) => Object.prototype.hasOwnProperty.call(o, n);
132
+ if (has(want.confirmSettings) !== has(got.confirmSettings) || !same(want.confirmSettings[n], got.confirmSettings[n])) return `its confirm setting ${n}`;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ module.exports = {describeModule, friendlyNames, describeProblem, credentialOf, declaredVariables, sameCredential, ROLE};
@@ -0,0 +1,175 @@
1
+ 'use strict';
2
+ // install's and add-pack's check that each module is what the release's
3
+ // pins describe (#413 section 9.3; L5b): its credential destination, its
4
+ // calls and its confirm settings, read from the package's own package.json
5
+ // by lib/describe-module.js, the reader the release step wrote the
6
+ // description with. A difference refuses the whole operation before anything
7
+ // is placed, so what an upgrade showed (additions) is what is installed.
8
+ //
9
+ // Every module of the operation is checked: one about to be placed, from its
10
+ // fetched, integrity-checked bytes; one the store already holds whole at its
11
+ // pin, from the store (the same bytes, by its integrity; checked anyway, so
12
+ // a release whose description is wrong is refused, not trusted).
13
+ const fs = require('node:fs');
14
+ const path = require('node:path');
15
+ const {readMembers} = require('./tar');
16
+ const {versionDir} = require('./store-paths');
17
+ const {describeModule, friendlyNames, describeProblem} = require('./describe-module');
18
+
19
+ // one file of a module: from its bytes when given, else from the store at
20
+ // version -> parsed JSON, null when absent, {unreadable} when not JSON
21
+ // (a tarball's two members read together, once: the Reviewer's high review
22
+ // of #98, 8)
23
+ const MEMBERS = ['package.json', 'api.json'];
24
+ const read = new WeakMap();
25
+ const membersOf = (bytes) => {
26
+ if (!read.has(bytes)) { try { read.set(bytes, {members: readMembers(bytes, MEMBERS)}); } catch (err) { read.set(bytes, {err}); } }
27
+ const r = read.get(bytes);
28
+ if (r.err != null) throw r.err;
29
+ return r.members;
30
+ };
31
+ function fileOf(where, m, version, bytes, name) {
32
+ let raw = null;
33
+ try {
34
+ raw = bytes != null ? membersOf(bytes)[name] : fs.readFileSync(path.join(versionDir(where, m, version), name));
35
+ } catch (err) {
36
+ // the strict tar reader's own refusal is said as it is
37
+ if (bytes != null) return {unreadable: true, why: err.message};
38
+ if (err.code !== 'ENOENT') return {unreadable: true};
39
+ raw = null;
40
+ }
41
+ if (raw == null) return null;
42
+ try { return JSON.parse(raw.toString('utf8')); } catch (err) { return {unreadable: true}; }
43
+ }
44
+
45
+ // modules: the operation's modules; allow: the release (or the development
46
+ // pins file's) pins, with modules (the descriptions) and pins; bytes:
47
+ // {module: Buffer} for those about to be placed; versionOf(module): the
48
+ // version the operation records it at (#413 section 9.4's table keeps a
49
+ // module installed at another version: its pin, by default) -> null, or the
50
+ // refusal (without its "nothing was installed").
51
+ // Only a module at its pin is held to the release's description: the
52
+ // description is of the pinned bytes. One the table keeps at another
53
+ // version is read at that version, for the friendly names the others' calls
54
+ // are matched by, and is not compared. context: {module: version}, the
55
+ // home's other installed modules, read from the store for those names only
56
+ // (a pack's calls can name a module the home already holds).
57
+ // The home's modules a call may resolve to, as a start would load them: the
58
+ // packs of `record` (the home as the operation leaves it) that are not
59
+ // withdrawn, by start's own rule (packs.withdrawnNames: one the release does
60
+ // not list, or one holding a module the record withdrew), at their active
61
+ // versions. A module only a withdrawn or held pack records never loads, so
62
+ // it is not "installed" for a call (the Reviewer's high reviews of #98, 7,
63
+ // and of its round 2, 1 and 5). record, allow -> {module: version}
64
+ function activeContext(record, allow) {
65
+ if (record == null || record.packs == null) return {};
66
+ const names = Object.keys(record.packs).filter((n) => record.packs[n] != null);
67
+ const gone = require('./packs').withdrawnNames(record, names.map((name) => ({name})), allow);
68
+ const live = Object.fromEntries(names.filter((n) => !gone.has(n)).map((n) => [n, record.packs[n]]));
69
+ return {...require('./module-record').activeVersions(live, [])};
70
+ }
71
+
72
+ // live: the modules whose friendly names calls may resolve to (activeContext
73
+ // of the home after the operation); null: every module read. One of the
74
+ // operation's that would not load is still checked, never resolved to.
75
+ function descriptionRefusal(where, modules, allow, bytes = {}, versionOf = (m) => allow.pins[m].version, context = {}, {live = null} = {}) {
76
+ const described = allow != null && allow.modules != null ? allow.modules : {};
77
+ const own = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
78
+ const atPin = (m) => versionOf(m) === allow.pins[m].version;
79
+ const at = (m) => `${m} ${versionOf(m)}`;
80
+ const manifests = {};
81
+ const apis = {};
82
+ for (const m of modules) {
83
+ if (atPin(m) && !own(described, m)) return `${at(m)}: this release does not describe it`;
84
+ const version = versionOf(m);
85
+ const fromBytes = atPin(m) ? bytes[m] : undefined;
86
+ const manifest = fileOf(where, m, version, fromBytes, 'package.json');
87
+ if (manifest != null && manifest.why != null) return `${at(m)}: ${manifest.why}`;
88
+ if (manifest == null || manifest.unreadable) return `${at(m)}: its package.json cannot be read`;
89
+ manifests[m] = manifest;
90
+ const api = fileOf(where, m, version, fromBytes, 'api.json');
91
+ apis[m] = api != null && !api.unreadable ? api : null;
92
+ }
93
+ const contextApis = {};
94
+ for (const [m, version] of Object.entries(context || {})) {
95
+ if (Object.prototype.hasOwnProperty.call(apis, m) || typeof version !== 'string') continue;
96
+ const api = fileOf(where, m, version, undefined, 'api.json');
97
+ contextApis[m] = api != null && !api.unreadable ? api : null;
98
+ }
99
+ // m's described callee that is neither placed nor installed, and the pack
100
+ // of this release that holds it -> the refusal naming what to install
101
+ // first, or null
102
+ const notInstalledCallee = (m) => {
103
+ if (!atPin(m) || !own(described, m) || !Array.isArray(described[m].calls)) return null;
104
+ for (const callee of described[m].calls) {
105
+ if (own(apis, callee) || own(contextApis, callee) || allow.pins == null || !own(allow.pins, callee)) continue;
106
+ const packs = Object.keys(allow.packs || {}).filter((p) => Array.isArray(allow.packs[p].modules) && allow.packs[p].modules.includes(callee)).sort();
107
+ if (packs.length === 0) continue;
108
+ const p = packs[0];
109
+ return `${m} calls ${callee}, from pack ${p}, which isn't installed; install ${p} first`;
110
+ }
111
+ return null;
112
+ };
113
+ // The user's own modules (B-own-add; the own-modules design §2.4): a
114
+ // module's data and key are kept by its name, so a name or device name
115
+ // one holds is never brought by a pack. An own.json that can't be read
116
+ // refuses the operation (unknown is no).
117
+ let ownModules;
118
+ try {
119
+ const r = require('./own-record').readOwnRecord(where);
120
+ ownModules = r != null ? r.modules : {};
121
+ } catch (err) { return `your own modules could not be read (${err.message})`; }
122
+ const deviceOf = (api) => (api != null && typeof api === 'object' && api.device != null && typeof api.device.friendlyName === 'string' ? api.device.friendlyName : null);
123
+ const opDevices = new Set(Object.values(apis).map(deviceOf).filter((n) => n != null));
124
+ for (const [o, e] of Object.entries(ownModules)) {
125
+ const how = `remove it first (\`${require('./command-line').chLocal(where, `remove-module ${o}`)}\`), or give yours another name and add it again`;
126
+ const {nameKey} = require('./names');
127
+ const same = modules.find((m) => nameKey(m) === nameKey(o));
128
+ if (same != null) return `${same} is the name of your own module ${o}: ${how}`;
129
+ // (nor a short name that is an own module's name: the reviewer on #116)
130
+ const byShort = modules.find((m) => nameKey(String(m).replace(/^@[^/]+\//, '')) === nameKey(o));
131
+ if (byShort != null) return `${byShort}'s short name is the name of your own module ${o}: ${how}`;
132
+ if (opDevices.has(e.friendlyName)) return `${e.friendlyName} is the device name of your own module ${o}: ${how}`;
133
+ }
134
+ // The operation's own names must be one each. The home's other modules
135
+ // only add names; a name two of them share, or one shares with the
136
+ // operation, is no one's, so a call to it matches nothing and is refused
137
+ // (fails closed: the medium on L5b, 3)
138
+ const resolvable = (m) => live == null || live.has(m);
139
+ const friendly = friendlyNames(Object.fromEntries(Object.entries(apis).filter(([m]) => resolvable(m))));
140
+ if (friendly.problem != null) return friendly.problem;
141
+ // A name the operation shares with a module the home holds is no one's
142
+ // too: the check and a start must never resolve it differently (the
143
+ // Reviewer's high review of #98, 5)
144
+ const seen = new Map();
145
+ for (const [m, api] of Object.entries(contextApis)) {
146
+ if (!resolvable(m)) continue;
147
+ const one = friendlyNames({[m]: api}).map;
148
+ for (const [name] of one) {
149
+ // one of the operation's names an installed module of another package
150
+ // holds too: the operation is refused, whatever it calls (the
151
+ // Reviewer's high review of #98's round 2, 4)
152
+ if (friendly.map.has(name)) return `${name} is the friendly name of both ${friendly.map.get(name)} and ${m}, which is installed`;
153
+ seen.set(name, seen.has(name) ? null : m);
154
+ }
155
+ }
156
+ for (const [name, m] of seen) if (m != null) friendly.map.set(name, m);
157
+ for (const m of modules) {
158
+ if (!atPin(m)) continue;
159
+ const got = describeModule(manifests[m], friendly.map);
160
+ // a call that maps to no module of the operation or the home: when the
161
+ // release describes it calling a module of a pack not installed, that is
162
+ // what is wrong (release 1 resolves names only from what it places or
163
+ // holds: the Reviewer's ruling on L5b; never accepted unverified)
164
+ if (got.problem != null && got.unknownCall != null) {
165
+ const missing = notInstalledCallee(m);
166
+ if (missing != null) return missing;
167
+ }
168
+ // otherwise it differs from a description whose calls all do
169
+ const part = got.problem != null ? (got.unknownCall != null ? 'its calls' : got.problem) : describeProblem(described[m], got);
170
+ if (part != null) return `${at(m)} does not match this release's description of it (${part})`;
171
+ }
172
+ return null;
173
+ }
174
+
175
+ module.exports = {descriptionRefusal, activeContext};
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+ // failed.json read by the shim's own rule (shim/src/failed.rs; its vectors
3
+ // are shim/tests/vectors/contract-2.json failedJson), so what status and
4
+ // restart say about it is what a session does with it: a file a session
5
+ // ignores -- stale, from the future, of another shape -- is no "gave up"
6
+ // (the medium on the closing pass, 1). Exactly {v, at, exit, signal,
7
+ // reason}, none extra, missing or twice; at most 512 bytes; fresh when
8
+ // now - 600000 <= at <= now + 60000.
9
+ const MAX_BYTES = 512;
10
+ const FRESH_PAST_MS = 600000;
11
+ const FRESH_FUTURE_MS = 60000;
12
+ const KEYS = ['v', 'at', 'exit', 'signal', 'reason'];
13
+ const REASONS = ['restarts-exhausted', 'never-listened'];
14
+
15
+ // (bytes, now ms) -> the reason, or null
16
+ function parse(bytes, now) {
17
+ if (!Buffer.isBuffer(bytes) || bytes.length > MAX_BYTES) return null;
18
+ const text = bytes.toString('utf8');
19
+ let j;
20
+ try { j = JSON.parse(text); } catch (e) { return null; }
21
+ if (j == null || typeof j !== 'object' || Array.isArray(j)) return null;
22
+ const keys = Object.keys(j);
23
+ if (keys.length !== KEYS.length || !KEYS.every((k) => keys.includes(k))) return null;
24
+ // (JSON.parse keeps the last of a key twice; the shim refuses it: each
25
+ // key counted in the text, as a key -- no value can hold a quote here)
26
+ for (const k of KEYS) if ((text.match(new RegExp(`"${k}"\\s*:`, 'g')) || []).length !== 1) return null;
27
+ if (j.v !== 1) return null;
28
+ if (!Number.isSafeInteger(j.at) || j.at < 1) return null;
29
+ if (j.exit !== null && !Number.isSafeInteger(j.exit)) return null;
30
+ if (j.signal !== null && !(typeof j.signal === 'string' && /^SIG[A-Z0-9]+$/.test(j.signal))) return null;
31
+ if (!REASONS.includes(j.reason)) return null;
32
+ return now - FRESH_PAST_MS <= j.at && j.at <= now + FRESH_FUTURE_MS ? j.reason : null;
33
+ }
34
+
35
+ // <runDir>/failed.json with daemon.json's trust checks (the private read),
36
+ // judged at now -> the reason, or null
37
+ function read(runDir, now = Date.now()) {
38
+ let bytes;
39
+ try { bytes = require('./private-file').readPrivateIn(runDir, 'failed.json', MAX_BYTES + 1); } catch (e) { return null; }
40
+ return parse(bytes, now);
41
+ }
42
+
43
+ module.exports = {parse, read, MAX_BYTES, FRESH_PAST_MS, FRESH_FUTURE_MS};
package/lib/gc.js ADDED
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+ // Packs in place (part 2, plan Task B2): the pack trees no live start uses
3
+ // are collected, after every install, add-pack, remove-pack and rollback
4
+ // (under the home's lock, so no tree is being placed meanwhile). Kept:
5
+ // - the current record's trees, a held pack's, and the rollback target's
6
+ // (<home>/previous/packs.json);
7
+ // - any tree a running start names in its run.json: on this machine while
8
+ // its pid or its runtime's lives; on another machine (a home on a shared
9
+ // disk) while its heartbeat (run.json's mtime, refreshed every
10
+ // HEARTBEAT_MS) is under STALE_MS old.
11
+ // A tree is renamed aside (.trash-*) before it is deleted, so a half-deleted
12
+ // tree is never taken for a whole one.
13
+ // Removed: every other tree under <home>/packs, staging leftovers included.
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ // a pack tree's key, as an earlier ch-local named it: its scenario's version
17
+ // and a short hash of every package@version it held (once lib/pack-dir.js);
18
+ // read only to keep the trees a record from before names
19
+ const packKey = (packages) => {
20
+ const names = Object.keys(packages);
21
+ const hash = require('node:crypto').createHash('sha256').update(names.slice().sort().map((n) => `${n}@${packages[n]}`).join('\n')).digest('hex').slice(0, 8);
22
+ return `${packages[names[0]]}+${hash}`;
23
+ };
24
+ const {readModulesRecord} = require('./module-record');
25
+ const store = require('./module-store');
26
+ const {removeAside} = require('./aside');
27
+ const {SCOPE} = require('./names');
28
+
29
+ const {machineId} = require('./machine');
30
+ const {HEARTBEAT_MS, STALE_MS, hostTag} = require('./run-liveness');
31
+
32
+ // whether a run.json was written on this machine
33
+ const onThisMachine = (run, hostname, machine = machineId()) => (run.machine != null ? run.machine === machine : run.host === hostTag(hostname));
34
+
35
+ // The run.json of every start that is alive: on this machine while its pid
36
+ // or its runtime's lives; on another (a home on a shared disk) while its
37
+ // heartbeat is under STALE_MS old. -> [run], each with an object `loaded`.
38
+ // alive(pid) is required: a caller that left it out would take every start
39
+ // on this machine for dead, and collect what they loaded (#82's high review, 1).
40
+ // sameMachine: only this machine's (a home on a shared disk has others').
41
+ // unreadable(name): given the directory of a run that can't be read, which is
42
+ // then left out and not thrown for (never collection's).
43
+ function liveRuns(where, {alive, hostname, now = Date.now(), machine = machineId(), sameMachine = false, unreadable: skip = null} = {}) {
44
+ if (typeof alive !== 'function') throw new Error('liveRuns: alive is required');
45
+ // a run that cannot be read could be a live start's: unknown, which
46
+ // throws, and the caller collects nothing (#82's medium, 1). Only "not
47
+ // there" is no run: no run directory, or a run directory being removed.
48
+ const unreadable = (what, err) => Object.assign(new Error(`${what} could not be read (${err.code || err.message}); nothing was collected`), {unknown: true});
49
+ let names = [];
50
+ try { names = fs.readdirSync(where.run); } catch (err) { if (err.code !== 'ENOENT') throw unreadable(where.run, err); }
51
+ const out = [];
52
+ for (const name of names) {
53
+ let run = null;
54
+ let mtime = 0;
55
+ const file = path.join(where.run, name, 'run.json');
56
+ let raw;
57
+ try { raw = fs.readFileSync(file, 'utf8'); mtime = fs.statSync(file).mtimeMs; } catch (err) {
58
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') continue;
59
+ if (skip != null) { skip(name); continue; }
60
+ throw unreadable(file, err);
61
+ }
62
+ // written whole (writeAtomic): one that is not JSON is not a run's
63
+ try { run = JSON.parse(raw); } catch (err) {
64
+ if (skip != null) { skip(name); continue; }
65
+ throw unreadable(file, err);
66
+ }
67
+ if (run == null || typeof run.loaded !== 'object' || run.loaded == null) continue;
68
+ const thisMachine = onThisMachine(run, hostname, machine);
69
+ const live = thisMachine
70
+ ? ((Number.isInteger(run.pid) && alive(run.pid)) || (Number.isInteger(run.childPid) && alive(run.childPid)))
71
+ : now - mtime < STALE_MS;
72
+ if (live && (thisMachine || !sameMachine)) out.push(run);
73
+ }
74
+ return out;
75
+ }
76
+
77
+ // The rollback's kept record, as collection reads it (#82's medium, 3): not
78
+ // there names nothing; there but unreadable is unknown, and nothing is
79
+ // collected; readable but not a record names nothing (rollback refuses it,
80
+ // and nothing of its is needed). -> {record} or {problem}.
81
+ function keptRecord(file, read) {
82
+ try { fs.accessSync(file, fs.constants.R_OK); } catch (err) {
83
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return {record: null};
84
+ return {problem: `${file} could not be read (${err.code || err.message}); nothing was collected`};
85
+ }
86
+ try {
87
+ fs.readFileSync(file);
88
+ } catch (err) {
89
+ return {problem: `${file} could not be read (${err.code || err.message}); nothing was collected`};
90
+ }
91
+ try { return {record: read(file)}; } catch (err) { return {record: null}; }
92
+ }
93
+
94
+ // The pack trees an earlier ch-local unpacked (<home>/packs/<pack>/<key>/)
95
+ // are never deleted: the whole directory is renamed aside
96
+ // (packs.migrated-<time>) once no live start from before uses one of them
97
+ // (its run.json's loaded names a tree, {<pack>: <tree key>}); while one
98
+ // does, it stays where it is, untouched, and a later install sets it aside
99
+ // (the Reviewer's ruling on #83: nothing deleted; the medium review of it,
100
+ // 1 and 2). A rename that fails leaves it where it is.
101
+ // -> {keptAt} | {waiting: true} | {problem} | {} (nothing to keep)
102
+ function keepOldTreesAside(where, {alive, hostname, now = Date.now(), machine = machineId()} = {}) {
103
+ if (typeof alive !== 'function') throw new Error('keepOldTreesAside: alive is required');
104
+ if (!fs.existsSync(where.packsDir)) return {};
105
+ let runs;
106
+ try { runs = liveRuns(where, {alive, hostname, now, machine}); } catch (err) { return {problem: err.message}; }
107
+ // a tree key: its scenario's version, "+", 8 hex digits
108
+ const fromBefore = runs.some((r) => Object.values(r.loaded).some((v) => typeof v === 'string' && /\+[0-9a-f]{8}$/.test(v)));
109
+ if (fromBefore) return {waiting: true};
110
+ const keptAt = `${where.packsDir}.migrated-${new Date(now).toISOString().replace(/[:.]/g, '-')}`;
111
+ try { fs.renameSync(where.packsDir, keptAt); } catch (err) { return {problem: `${where.packsDir} could not be kept aside (${err.code || err.message}); it is left where it is`}; }
112
+ return {keptAt};
113
+ }
114
+
115
+ // The module store (module-level install, #413 section 9.10): a version is
116
+ // kept while any of these names it:
117
+ // - an installed or a held pack of modules.json: every version a pack
118
+ // records, not only the active one (the lower ones are what remove-pack
119
+ // goes back to);
120
+ // - the release rollback's kept record (previous/modules.json);
121
+ // - a live start's run.json, whose loaded is {<module>: <version>}. A run
122
+ // from before the store ({<pack>: <tree key>}) names no store version
123
+ // (its pack names are not package names it loaded), and keeps its old
124
+ // tree in place (keepOldTreesAside above); reading it here too only keeps more.
125
+ // Everything else under the store is renamed aside and deleted: staging and
126
+ // trash leftovers, a version not named, a version with no marker, a marker
127
+ // with no version, anything that is not a module's. Under the home's lock
128
+ // (the caller's). -> {removed: [path], kept: [{dir, why}]}
129
+ // (problem: why nothing was collected, when the record cannot be read).
130
+ function collectStore(where, {alive, hostname, now = Date.now(), machine = machineId()} = {}) {
131
+ if (typeof alive !== 'function') throw new Error('collectStore: alive is required');
132
+ const keep = new Map();
133
+ const keepRec = (r, why) => {
134
+ if (r == null) return;
135
+ for (const p of Object.values(r.packs || {})) for (const [m, v] of Object.entries(p.modules || {})) if (!keep.has(`${m}@${v}`)) keep.set(`${m}@${v}`, why);
136
+ for (const p of Object.values(r.held || {})) for (const [m, v] of Object.entries(p.modules || {})) if (!keep.has(`${m}@${v}`)) keep.set(`${m}@${v}`, 'held');
137
+ };
138
+ try { keepRec(readModulesRecord(where), 'current'); } catch (err) { return {removed: [], kept: [], problem: err.message}; }
139
+ // the kept record names what a rollback returns to (keptRecord's rules)
140
+ const kept0 = keptRecord(where.previousModulesRecord, (file) => readModulesRecord({modulesRecord: file}));
141
+ if (kept0.problem != null) return {removed: [], kept: [], problem: kept0.problem};
142
+ keepRec(kept0.record, 'rollback');
143
+ // what a live start loaded: kept even when incomplete (a failed swap left
144
+ // it in use), as placeModule refuses to replace it (#82's medium, 2)
145
+ const running = new Set();
146
+ try {
147
+ for (const run of liveRuns(where, {alive, hostname, now, machine})) {
148
+ // a version, or several (two loaded packs at different versions)
149
+ for (const [m, vs] of Object.entries(run.loaded)) {
150
+ for (const v of [].concat(vs)) {
151
+ if (typeof v !== 'string') continue;
152
+ running.add(`${m}@${v}`);
153
+ if (!keep.has(`${m}@${v}`)) keep.set(`${m}@${v}`, 'running');
154
+ }
155
+ }
156
+ }
157
+ } catch (err) { return {removed: [], kept: [], problem: err.message}; }
158
+ const removed = [];
159
+ const kept = [];
160
+ // marker: a version's, removed first, inside the same guard, so one that
161
+ // cannot be removed is reported, never thrown (medium review, 3)
162
+ const gone = (at, marker = null) => {
163
+ try {
164
+ if (marker != null) fs.rmSync(marker, {force: true});
165
+ removeAside(at);
166
+ removed.push(at);
167
+ } catch (err) { kept.push({dir: at, why: `could not remove (${err.code || err.message})`}); }
168
+ };
169
+ const list = (dir) => { try { return fs.readdirSync(dir, {withFileTypes: true}); } catch (err) { return []; } };
170
+ // one module's directory: its versions and their markers
171
+ const collectModule = (name, dir) => {
172
+ const entries = list(dir);
173
+ const versions = new Set(entries.filter((e) => e.isDirectory() && store.storeVersion(e.name)).map((e) => e.name));
174
+ for (const e of entries) {
175
+ const at = path.join(dir, e.name);
176
+ if (versions.has(e.name)) {
177
+ const why = keep.get(`${name}@${e.name}`);
178
+ // a version or marker that cannot be read is unknown, and unknown is
179
+ // kept: never deleted on a read error (#82's high review, 2)
180
+ let complete;
181
+ try { complete = store.isComplete(where, name, e.name); } catch (err) { kept.push({dir: at, why: `could not be read (${err.code || err.message})`}); continue; }
182
+ if (why != null && complete) { kept.push({dir: at, why}); continue; }
183
+ if (running.has(`${name}@${e.name}`)) { kept.push({dir: at, why: 'running (incomplete)'}); continue; }
184
+ // the marker first: an incomplete version is never taken for whole
185
+ gone(at, `${at}.json`);
186
+ continue;
187
+ }
188
+ // a version's marker stays with it, or goes with it above
189
+ const marker = /^(.+)\.json$/.exec(e.name);
190
+ if (marker != null && e.isFile() && versions.has(marker[1])) continue;
191
+ gone(at);
192
+ }
193
+ try { if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir); } catch (err) { /* in use or gone */ }
194
+ };
195
+ for (const top of list(where.moduleStore)) {
196
+ const at = path.join(where.moduleStore, top.name);
197
+ if (top.isDirectory() && SCOPE.test(top.name)) {
198
+ for (const e of list(at)) {
199
+ const name = `${top.name}/${e.name}`;
200
+ if (e.isDirectory() && store.PACKAGE.test(name)) collectModule(name, path.join(at, e.name));
201
+ else gone(path.join(at, e.name));
202
+ }
203
+ try { if (fs.readdirSync(at).length === 0) fs.rmdirSync(at); } catch (err) { /* in use or gone */ }
204
+ } else if (top.isDirectory() && !top.name.startsWith('@') && store.PACKAGE.test(top.name)) {
205
+ collectModule(top.name, at);
206
+ } else {
207
+ gone(at);
208
+ }
209
+ }
210
+ // the user's own modules' copies, by the same live runs' rule
211
+ const own = collectOwn(where, {alive, hostname, now, machine});
212
+ return {removed: removed.concat(own.removed), kept: kept.concat(own.kept), ...(own.problem != null ? {ownProblem: own.problem} : {})};
213
+ }
214
+
215
+ // The user's own modules' copies (B-own-add; the own-modules design §2.6):
216
+ // <home>/own/<name>/<tree> is kept while own.json names it or a live
217
+ // start's run.json loaded it ({<name>: <tree>}); any other copy whose
218
+ // marker (<tree>.json) names it goes, the marker first, so a copy cut short
219
+ // is never taken for whole. A folder with no such marker is not ch-local's
220
+ // to take: kept. An own.json or a run that can't be read collects nothing
221
+ // (unknown is kept). Under the home's lock (the caller's). -> {removed:
222
+ // [path], kept: [{dir, why}], problem?}
223
+ const TREE = /^[0-9a-f]{64}$/;
224
+ function collectOwn(where, {alive, hostname, now = Date.now(), machine = machineId()} = {}) {
225
+ const {readOwnRecord} = require('./own-record');
226
+ const {markerOf} = require('./own-tree');
227
+ const keep = new Set();
228
+ try {
229
+ const record = readOwnRecord(where);
230
+ if (record != null) for (const [name, e] of Object.entries(record.modules)) keep.add(`${name}\0${e.tree}`);
231
+ } catch (err) { return {removed: [], kept: [], problem: err.message}; }
232
+ try {
233
+ for (const run of liveRuns(where, {alive, hostname, now, machine})) {
234
+ for (const [m, vs] of Object.entries(run.loaded)) for (const v of [].concat(vs)) if (typeof v === 'string' && TREE.test(v)) keep.add(`${m}\0${v}`);
235
+ }
236
+ } catch (err) { return {removed: [], kept: [], problem: err.message}; }
237
+ const removed = [];
238
+ const kept = [];
239
+ const list = (dir) => { try { return fs.readdirSync(dir, {withFileTypes: true}); } catch (err) { return []; } };
240
+ const collectName = (name, dir) => {
241
+ for (const e of list(dir)) {
242
+ if (!e.isDirectory() || !TREE.test(e.name)) continue;
243
+ const at = path.join(dir, e.name);
244
+ if (keep.has(`${name}\0${e.name}`)) { kept.push({dir: at, why: 'in use'}); continue; }
245
+ const marker = markerOf(where, name, e.name);
246
+ let mine = false;
247
+ try { const m = JSON.parse(fs.readFileSync(marker, 'utf8')); mine = m != null && m.name === name && m.tree === e.name; } catch (err) { mine = false; }
248
+ if (!mine) { kept.push({dir: at, why: 'not marked as ch-local\'s'}); continue; }
249
+ try {
250
+ // (a copy is read-only: writable again before it goes, and its
251
+ // marker removed only then, so one that can't be unlocked is kept
252
+ // marked and collected later: the medium on #113's round 1)
253
+ require('./own-tree').unlockTree(at);
254
+ fs.rmSync(marker, {force: true});
255
+ removeAside(at);
256
+ removed.push(at);
257
+ } catch (err) { kept.push({dir: at, why: `could not remove (${err.code || err.message})`}); }
258
+ }
259
+ try { if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir); } catch (err) { /* in use or gone */ }
260
+ };
261
+ for (const top of list(where.own)) {
262
+ if (!top.isDirectory()) continue;
263
+ const at = path.join(where.own, top.name);
264
+ if (SCOPE.test(top.name)) {
265
+ for (const e of list(at)) if (e.isDirectory() && store.PACKAGE.test(`${top.name}/${e.name}`)) collectName(`${top.name}/${e.name}`, path.join(at, e.name));
266
+ try { if (fs.readdirSync(at).length === 0) fs.rmdirSync(at); } catch (err) { /* in use or gone */ }
267
+ } else if (!top.name.startsWith('@') && store.PACKAGE.test(top.name)) {
268
+ collectName(top.name, at);
269
+ }
270
+ }
271
+ return {removed, kept};
272
+ }
273
+
274
+ module.exports = {keepOldTreesAside, collectStore, collectOwn, liveRuns, onThisMachine, packKey, hostTag, HEARTBEAT_MS, STALE_MS};