@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
package/lib/packs.js ADDED
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+ // The packs a home holds, which of them a start loads, and the remote
3
+ // credentials those may use (spec §2, many packs; plan Tasks 11 and 12b).
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const {readModulesRecord, own} = require('./module-record');
7
+ const {versionDir} = require('./store-paths');
8
+ const {compareVersions} = require('./semver-order');
9
+ const {chLocal} = require('./command-line');
10
+
11
+ // where: layout(); record: readModulesRecord's, when the caller has it; io:
12
+ // the running release's pins (releaseOf). -> [{name, scenario, version,
13
+ // modules, dirs, dir, packages, credentials}] from modules.json; [] when
14
+ // nothing is installed. Still pack by pack (L2 decides by module):
15
+ // - modules: each of the pack's modules at its active version (the record's
16
+ // derived one: the highest any pack records, in a released home the pin);
17
+ // - scenario: the pack's module whose role is scenario, else its first;
18
+ // version: the scenario's; dirs: each module's store directory; dir: the
19
+ // scenario's, what start loads;
20
+ // - credentials: the variables the running release's pins describe for the
21
+ // pack's modules (version 2's modules.<package>.credentials: packVariables)
22
+ // A pack's scenario in the record: its module whose role is scenario, else
23
+ // its first, the module the pack's seams speak for (start, the applier and
24
+ // status alike); null for a pack the record has not.
25
+ // (own properties only, as countinghouse's rule reads them: a module named
26
+ // "constructor", or anything on Object.prototype, is no entry the record
27
+ // holds: #449's review; module-record's own, the one helper). Whether o
28
+ // holds its own k, not null (a key a half-written record holds as null
29
+ // holds nothing).
30
+ const holds = (o, k) => o != null && typeof o === 'object' && own(o, k) && o[k] != null;
31
+ // the record's own entry for a module, or null
32
+ const entryOf = (record, m) => (record != null && holds(record.modules, m) ? record.modules[m] : null);
33
+ function packScenario(record, pack) {
34
+ const p = record != null && holds(record.packs, pack) ? record.packs[pack] : null;
35
+ if (p == null || p.modules == null) return null;
36
+ const packages = Object.keys(p.modules);
37
+ return packages.find((m) => { const e = entryOf(record, m); return e != null && own(e, 'role') && e.role === 'scenario'; }) || packages[0] || null;
38
+ }
39
+ // the package a pack's scenario is named by, when the record has no
40
+ // scenario for it: lib/ceiling.js's fallback (packAllowed, notAllowed) for
41
+ // a pack not recorded yet
42
+ const packModuleName = (pack) => `@countinghouse/ch-pack-${pack}`;
43
+
44
+ function installedPacks(where, record = readModulesRecord(where), io = null) {
45
+ if (record == null) return [];
46
+ const release = releaseOf(io);
47
+ return Object.entries(record.packs).map(([name, p]) => {
48
+ const packages = Object.keys(p.modules);
49
+ const modules = Object.fromEntries(packages.map((m) => { const e = entryOf(record, m); return [m, e != null ? e.version : p.modules[m]]; }));
50
+ const scenario = packScenario(record, name);
51
+ const dirs = Object.fromEntries(packages.map((m) => [m, versionDir(where, m, modules[m])]));
52
+ return {
53
+ name,
54
+ scenario,
55
+ version: modules[scenario],
56
+ modules,
57
+ dirs,
58
+ dir: dirs[scenario],
59
+ packages,
60
+ credentials: packVariables(release, name)
61
+ };
62
+ });
63
+ }
64
+
65
+ // The variables a release's pins describe for a pack's modules (version 2,
66
+ // #413 section 9.3): [variable], each once, sorted; [] for a pack it does
67
+ // not list
68
+ function packVariables(release, pack) {
69
+ const own = (o, k) => o != null && Object.prototype.hasOwnProperty.call(o, k);
70
+ if (release == null || !own(release.packs, pack)) return [];
71
+ const out = new Set();
72
+ for (const m of (release.packs[pack].modules || [])) {
73
+ const d = own(release.modules, m) ? release.modules[m] : null;
74
+ for (const c of (d != null && Array.isArray(d.credentials) ? d.credentials : [])) out.add(c.variable);
75
+ }
76
+ return [...out].sort();
77
+ }
78
+
79
+ // Withdrawn packs (maintainer's decision, 2026-11-17; #413 section 9.7): a
80
+ // pack the running release does not list is never started. An upgrade to
81
+ // such a release keeps it recorded, and writes its modules into the
82
+ // record's withdrawn list (derived from that release's own pins), which a
83
+ // start still running from the release before reads, as it cannot ask its
84
+ // own pins (heldWithdrawn below). Each start tells each session once
85
+ // (withdrawnLine); nothing is removed: its files and data stay, for
86
+ // `ch-local remove-pack`.
87
+ // An unreleased (development) install is exempt: its record is marked only
88
+ // by --unreleased-pins, which needs CH_LOCAL_DEV=1 (lib/pins.js), so the dev
89
+ // intent is on record. Not CH_LOCAL_DEV at start as well: the shared
90
+ // daemon's environment is shim.json's allowlist, which never carries it.
91
+ // Every start of one says UNRELEASED_LINE, so it is never silent.
92
+ // packs: installedPacks(); allow: the running release's (ALLOWLIST);
93
+ // record: the record. -> the withdrawn packs.
94
+ function withdrawnPacks(packs, {allow, record = null} = {}) {
95
+ if (record != null && record.unreleased === true) return [];
96
+ const listed = (allow != null && allow.packs != null) ? allow.packs : {};
97
+ return packs.filter((p) => !Object.prototype.hasOwnProperty.call(listed, p.name));
98
+ }
99
+ // What the user is told: the pack and the command to run, the command in
100
+ // the home's launcher form (lib/command-line.js: the user's own home path,
101
+ // which their own agent may see, as the credential line and the overview
102
+ // already say it; the reviewer on ch-local#110, 4). where: the home's layout
103
+ const removeHint = (name, where) => `\`${chLocal(where, `remove-pack ${name}`)}\` removes it`;
104
+ const withdrawnLine = (name, where) => `pack ${name} was withdrawn in this release and was not started; ${removeHint(name, where)}`;
105
+ // ... and to a start that was serving it when the upgrade withdrew it
106
+ const withdrawnNowLine = (name, where) => `pack ${name} was withdrawn in this release and is no longer served; ${removeHint(name, where)}`;
107
+ // ... in status, and in an upgrade's preview
108
+ const withdrawnStatusLine = (name, where) => `${name}: withdrawn in this release, so it is not started; ${removeHint(name, where)}`;
109
+ // a release that lists a withdrawn pack again (lib/install.js drops it from held)
110
+ // (install --pack adds it, from npm or a release folder alike; add-pack takes
111
+ // --from only: A11)
112
+ const relistedLine = (name, where) => `pack ${name} is in this release again: \`${chLocal(where, `install --pack ${name}`)}\` adds it back`;
113
+ const relistedStatusLine = (name, where) => `${name}: in this release again, not started until added: \`${chLocal(where, `install --pack ${name}`)}\` adds it back`;
114
+ // The packs the record has withdrawn: each with a module in the record's
115
+ // withdrawn list, which the operation that wrote it derived from its own
116
+ // pins (#413 section 9.7). What a start of another release reads, since its
117
+ // own pins cannot say what the new release withdrew. -> their names.
118
+ const heldWithdrawn = (record) => {
119
+ if (record == null || !Array.isArray(record.withdrawn) || record.withdrawn.length === 0) return [];
120
+ const gone = new Set(record.withdrawn);
121
+ return Object.entries(record.packs || {}).filter(([, p]) => Object.keys(p.modules || {}).some((m) => gone.has(m))).map(([name]) => name);
122
+ };
123
+ // What a release does to the record's packs: ONE rule for upgrade and the
124
+ // automatic upgrade (#413 rev 3 sections 9.6, 9.7; the Reviewer's high on
125
+ // L4, 8). record: the home's; allow: the new release's; running: the
126
+ // release that runs now. What is running is start's own rule
127
+ // (withdrawnNames: a pack the running release does not list, or one the
128
+ // record has withdrawn, is not: the Reviewer's high on #101, round 2).
129
+ // -> {withdrawn, served, target}:
130
+ // withdrawn packs the record has not withdrawn that the release does not
131
+ // list (one the running release does not list either included:
132
+ // its modules go into the record's withdrawn list, so it is
133
+ // said: the medium on #101 round 2, 3): kept, not started
134
+ // served the packs the release lists: running ones first, then those
135
+ // not running (served again, new to the running set: their
136
+ // modules are additions)
137
+ // target install's: the first served pack (install moves every pack of
138
+ // the record the release lists: lib/install-plan.js
139
+ // touchedPacks), or the runtime only when none is served
140
+ function releaseSelection(record, allow, running) {
141
+ const packs = Object.keys((record && record.packs) || {});
142
+ const out = withdrawnNames(record, packs.map((name) => ({name})), running);
143
+ const recorded = new Set(heldWithdrawn(record));
144
+ const listed = (n) => allow != null && own(allow.packs, n);
145
+ const withdrawn = packs.filter((n) => !recorded.has(n) && !listed(n));
146
+ const served = [...packs.filter((n) => listed(n) && !out.has(n)), ...packs.filter((n) => listed(n) && out.has(n))];
147
+ return {withdrawn, served, target: served.length > 0 ? {pack: served[0]} : {runtimeOnly: true}};
148
+ }
149
+ // The running release's allowlist: a test's own through io.release.
150
+ const releaseOf = (io) => (io != null && io.release != null ? io.release : require('./allowlist').ALLOWLIST);
151
+ // Whose home this is (#413 section 9.8): ONE rule, for start and the
152
+ // applier alike (the Reviewer on L2a), asked in this order:
153
+ // stale this process was launched from the home's app, and the ch-local
154
+ // the home holds now is another version (the home was upgraded or
155
+ // rolled back under it): frozen; keep what is loaded, apply only
156
+ // what no pins decide, and staleLine said once
157
+ // same the home's ch-local, its release's record (or either unknown):
158
+ // judged as usual
159
+ // other the home's ch-local, another release's record (an install that
160
+ // did not finish, a hand-edited home): judged by this ch-local's
161
+ // pins, and installLine said once
162
+ // The home's ch-local is the record's own (runtime.versions), read with its
163
+ // release: never a file the install or rollback is moving (the medium
164
+ // review of the refinement, 3 and 6). A ch-local run from outside the home
165
+ // (a checkout, a global install) is never stale: it is judged by the record
166
+ // (1). Versions compare by full semver precedence (lib/semver-order.js); two
167
+ // that do not parse are never stale, and another release's record is then
168
+ // "other": fail closed, by these pins (2). io.selfVersion: a test's running
169
+ // version (null: not known, never stale).
170
+ const SELF_DIR = path.resolve(__dirname, '..');
171
+ const homeSelfDir = (where) => path.join(where.app, 'node_modules', '@countinghouse', 'ch-local');
172
+ // whether this process runs the home's own ch-local (launched by its launcher)
173
+ function runsFromHome(where, selfDir = SELF_DIR) {
174
+ if (where == null) return false;
175
+ const home = homeSelfDir(where);
176
+ if (selfDir === home) return true;
177
+ try { return fs.realpathSync(selfDir) === fs.realpathSync(home); } catch (err) { return false; }
178
+ }
179
+ function recordRelease(record, io, where) {
180
+ const r = releaseOf(io);
181
+ const ours = r != null && r.release != null && typeof r.release.version === 'string' ? r.release.version : null;
182
+ const theirs = record != null && record.release != null && typeof record.release.version === 'string' ? record.release.version : null;
183
+ const versions = record != null && record.runtime != null && record.runtime.versions != null ? record.runtime.versions : {};
184
+ const installed = typeof versions['@countinghouse/ch-local'] === 'string' ? versions['@countinghouse/ch-local'] : null;
185
+ const self = io != null && io.selfVersion !== undefined ? io.selfVersion
186
+ : runsFromHome(where) ? require('../package.json').version : null;
187
+ const c = self != null && installed != null ? compareVersions(installed, self) : null;
188
+ // fromHome: this process is the home's own ch-local (its app), so the
189
+ // home's launcher runs this release
190
+ const fromHome = self != null;
191
+ if (c === 1 || c === -1) return {ours, theirs, installed, fromHome, state: 'stale', how: c === 1 ? 'upgraded' : 'rolled back'};
192
+ if (ours == null || theirs == null || ours === theirs) return {ours, theirs, installed, fromHome, state: 'same'};
193
+ return {ours, theirs, installed, fromHome, state: compareVersions(theirs, ours) === 0 ? 'same' : 'other'};
194
+ }
195
+ const staleLine = (installed, how, where, shared = null) => `ch-local in this home is now ${installed} (${how}); ${where != null ? require('./command-line').restartOne(where, shared) : 'restart your client'} to use it`;
196
+ // (an install that did not finish, or a hand-edited record: the install
197
+ // that brings the record to this ch-local's release, by pack; never the
198
+ // bare install, which never changes release, nor upgrade, which goes to the
199
+ // newest published one: the reviewer's high on #124, 4). Run by the
200
+ // ch-local that said it, whose release is <ours>: the home's launcher only
201
+ // when this process is the home's own (fromHome), else this one's, with
202
+ // the home named (the reviewer on #124's round 20ab08e).
203
+ const installLine = (ours, where, record, fromHome = true) => {
204
+ const first = Object.keys((record && record.packs) || {})[0];
205
+ const pack = typeof first === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(first) ? first : '<name>';
206
+ const {chLocalSelf, homeNote} = require('./command-line');
207
+ const cmd = fromHome ? chLocal(where, `install --pack ${pack}`) : chLocalSelf(where, `install --pack ${pack}`);
208
+ return `this home's record is not this ch-local's release; run \`${cmd}\`${fromHome ? '' : homeNote(where)} to bring the home to ${ours}`;
209
+ };
210
+
211
+ // The packs not started, by name: those this release does not list, and
212
+ // those the record's withdrawn list names (one rule for start, the
213
+ // applier and the commands: #83's high review, 10).
214
+ // packs: installedPacks(); allow: the running release's.
215
+ function withdrawnNames(record, packs, allow) {
216
+ return new Set([...withdrawnPacks(packs, {allow, record}).map((p) => p.name), ...heldWithdrawn(record)]);
217
+ }
218
+
219
+ module.exports = {packVariables, packScenario, entryOf, holds, packModuleName, recordRelease, runsFromHome, homeSelfDir, staleLine, installLine, withdrawnNames, installedPacks, withdrawnPacks, withdrawnLine, withdrawnNowLine, withdrawnStatusLine, relistedLine, relistedStatusLine, removeHint, heldWithdrawn, releaseSelection, releaseOf};
package/lib/pins.js ADDED
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+ // The allowlist a command works with: the release's own, or, with
3
+ // --unreleased-pins <file> (reviewer, 2026-11-12; development only), the same
4
+ // packs with the file's pins, runtime lockfile and module descriptions in
5
+ // place of the release's (#413 section 9.3: install checks each module
6
+ // against them). The file cannot add a pack.
7
+ const fs = require('node:fs');
8
+ const {tarballName} = require('./unpack');
9
+
10
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
11
+ const SHA512 = /^sha512-[A-Za-z0-9+/]{86}==$/;
12
+
13
+ // -> {allow, unreleased} or {problem}. env: the command's environment.
14
+ function effectiveAllow(allow, unreleasedPins, env = {}) {
15
+ if (unreleasedPins == null) return {allow, unreleased: false};
16
+ // A released launcher carries the flag, so it is behind an explicit switch.
17
+ if (env.CH_LOCAL_DEV !== '1') return {problem: '--unreleased-pins is for development: set CH_LOCAL_DEV=1 to use it'};
18
+ const bad = (why) => ({problem: `--unreleased-pins ${unreleasedPins}: ${why}`});
19
+ let file;
20
+ let digest;
21
+ try {
22
+ const bytes = fs.readFileSync(unreleasedPins);
23
+ // which pins a pack came from (modules.json packs.<p>.from.unreleased,
24
+ // #413 section 9.2): the first 16 hex digits of the file's SHA-256
25
+ digest = require('node:crypto').createHash('sha256').update(bytes).digest('hex').slice(0, 16);
26
+ file = JSON.parse(bytes.toString('utf8'));
27
+ } catch (err) { return bad(`not a readable JSON file (${err.code || 'invalid JSON'})`); }
28
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
29
+ if (!isObject(file) || !isObject(file.pins) || !isObject(file.runtimeLockfile) || !isObject(file.modules)) {
30
+ return bad('must be {"pins": {...}, "runtimeLockfile": {...}, "modules": {...}} (modules: `node scripts/describe-release.js <tarballs> --unreleased-pins <file>` writes them)');
31
+ }
32
+ for (const [name, pin] of Object.entries(file.pins)) {
33
+ if (!isObject(pin) || typeof pin.version !== 'string' || !SEMVER.test(pin.version) || typeof pin.integrity !== 'string' || !SHA512.test(pin.integrity)) {
34
+ return bad(`the pin for ${name} must be {"version": "<x.y.z>", "integrity": "sha512-..."}`);
35
+ }
36
+ }
37
+ // The lockfile's rules, shared with a released one (lib/lockfile-rules.js,
38
+ // the review of #42): a runtime package from its own tarball at its pin;
39
+ // every dependency from the npm registry with a sha512; nothing linked, from
40
+ // git or another host; a bundled entry only where its runtime parent
41
+ // bundles it (its tarball's contents are checked at install, once read).
42
+ // the release's floors hold a development file's pins too (the medium on
43
+ // the floors, 3)
44
+ const {belowFloor} = require('./release-pins');
45
+ for (const [name, floor] of Object.entries(allow.floors || {})) {
46
+ const pin = file.pins[name];
47
+ if (pin != null && belowFloor(pin.version, floor)) return bad(`the pin for ${name} ${pin.version} is below its floor ${floor}`);
48
+ }
49
+ const why = require('./lockfile-rules').lockfileProblem(file.runtimeLockfile, {runtime: allow.runtime.packages, pins: file.pins});
50
+ if (why != null) return bad(why);
51
+ // its own descriptions of the pack modules it pins (the Reviewer on L5b,
52
+ // Q2): checked at install as a release's are, by the release's rule
53
+ // (a runtime package is never described: one a pack lists is refused by
54
+ // the operation itself, in its own words)
55
+ const runtime = new Set((allow.runtime && allow.runtime.packages) || []);
56
+ const pinned = Object.values(allow.packs).flatMap((p) => p.modules).filter((m) => Object.prototype.hasOwnProperty.call(file.pins, m) && !runtime.has(m));
57
+ const described = require('./release-pins').modulesProblem(file.modules, new Set(pinned));
58
+ if (described != null) return bad(described);
59
+ return {allow: {...allow, pins: file.pins, modules: file.modules, runtime: {...allow.runtime, lockfile: file.runtimeLockfile}}, unreleased: true, digest};
60
+ }
61
+
62
+ const UNRELEASED_LINE = 'this is an unreleased install (development only); upgrade is refused until a clean install from a release';
63
+
64
+ module.exports = {effectiveAllow, UNRELEASED_LINE};
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+ // Whether a named pipe read from daemon.json is this user's shared runtime
3
+ // (C4c; the review of ch-local #39, F1). daemon.json can be stale (a crashed
4
+ // daemon's, its pid reused; a restart that never listened), pipe names can
5
+ // be listed, so a freed name can be taken, and Node's own connect opens a
6
+ // pipe allowing impersonation, checking no owner. So on Windows this probe
7
+ // runs in PowerShell, as the native shim opens a pipe (shim/src/win_ffi.rs
8
+ // Pipe::open):
9
+ // - connected at TokenImpersonationLevel.Identification
10
+ // (SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION), so the server can
11
+ // learn who connects but never act as them;
12
+ // - the pipe's owner, read on the open handle, must be this user, SYSTEM
13
+ // (S-1-5-18) or Administrators (S-1-5-32-544), or nothing is sent;
14
+ // - then contract 2's HELLO, and the PROVE checked under the secret, on
15
+ // that same connection (the HMAC has no channel binding, so the owner
16
+ // check is what stops a relay). AUTH is never sent.
17
+ // The secret reaches PowerShell on its stdin, never in argv or env. Pure
18
+ // .NET, no cmdlet, as lib/win-acl.js's scripts. It runs only when a daemon
19
+ // starts and finds a daemon.json, so PowerShell's start-up cost is paid
20
+ // once. Anything unexpected is a no.
21
+ const winAcl = require('./win-acl');
22
+ const {isPipeName} = require('./session-socket');
23
+
24
+ const PROBE_SCRIPT = [
25
+ "$ErrorActionPreference = 'Stop'",
26
+ '$sidType = [System.Security.Principal.SecurityIdentifier]',
27
+ '$hex = [Console]::In.ReadToEnd().Trim()',
28
+ "if ($hex.Length -ne 64) { 'no secret'; return }",
29
+ '$secret = [byte[]]::new(32)',
30
+ 'for ($i = 0; $i -lt 32; $i++) { $secret[$i] = [System.Convert]::ToByte($hex.Substring($i * 2, 2), 16) }',
31
+ '$c = [System.IO.Pipes.NamedPipeClientStream]::new(\'.\', $env:CH_PIPE, [System.IO.Pipes.PipeDirection]::InOut, [System.IO.Pipes.PipeOptions]::None, [System.Security.Principal.TokenImpersonationLevel]::Identification)',
32
+ // a name no alias shadows (PowerShell resolves an alias before a
33
+ // function, and its names ignore case: `r` is Invoke-History's)
34
+ 'function ReadPipeExact($n) { $b = [byte[]]::new($n); $o = 0; while ($o -lt $n) { $k = $c.Read($b, $o, $n - $o); if ($k -le 0) { throw \'closed\' }; $o += $k }; return ,$b }',
35
+ 'try {',
36
+ ' $c.Connect([int]$env:CH_PROBE_MS)',
37
+ ' $owner = $c.GetAccessControl().GetOwner($sidType).Value',
38
+ ' $me = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value',
39
+ " if ($owner -ne $me -and $owner -ne 'S-1-5-18' -and $owner -ne 'S-1-5-32-544') { 'owner ' + $owner; return }",
40
+ ' $nc = [byte[]]::new(32)',
41
+ ' [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($nc)',
42
+ " $body = [System.Text.Encoding]::ASCII.GetBytes('{\"protocol\":1,\"nc\":\"' + [System.Convert]::ToBase64String($nc) + '\"}')",
43
+ ' $head = [byte[]]::new(5)',
44
+ ' $head[0] = 72',
45
+ ' $head[1] = ($body.Length -shr 24) -band 255; $head[2] = ($body.Length -shr 16) -band 255; $head[3] = ($body.Length -shr 8) -band 255; $head[4] = $body.Length -band 255',
46
+ ' $c.Write($head, 0, 5); $c.Write($body, 0, $body.Length); $c.Flush()',
47
+ ' $h = ReadPipeExact 5',
48
+ " if ($h[0] -ne 80) { 'not a prove'; return }",
49
+ ' $n = ([int]$h[1] -shl 24) -bor ([int]$h[2] -shl 16) -bor ([int]$h[3] -shl 8) -bor [int]$h[4]',
50
+ " if ($n -le 0 -or $n -gt 4096) { 'bad length'; return }",
51
+ ' $text = [System.Text.Encoding]::ASCII.GetString((ReadPipeExact $n))',
52
+ " $mns = [regex]::Match($text, '\"ns\"\\s*:\\s*\"([A-Za-z0-9+/=]+)\"')",
53
+ " $mms = [regex]::Match($text, '\"ms\"\\s*:\\s*\"([A-Za-z0-9+/=]+)\"')",
54
+ " if (-not $mns.Success -or -not $mms.Success) { 'bad prove'; return }",
55
+ ' $ns = [System.Convert]::FromBase64String($mns.Groups[1].Value)',
56
+ ' $ms = [System.Convert]::FromBase64String($mms.Groups[1].Value)',
57
+ " if ($ns.Length -ne 32 -or $ms.Length -ne 32) { 'bad prove'; return }",
58
+ ' $buf = [System.IO.MemoryStream]::new()',
59
+ " $label = [System.Text.Encoding]::ASCII.GetBytes('ch-server')",
60
+ ' $buf.Write($label, 0, $label.Length); $buf.WriteByte(1); $buf.Write($nc, 0, 32); $buf.Write($ns, 0, 32)',
61
+ ' $want = [System.Security.Cryptography.HMACSHA256]::new($secret).ComputeHash($buf.ToArray())',
62
+ ' $diff = 0',
63
+ ' for ($i = 0; $i -lt 32; $i++) { $diff = $diff -bor ($want[$i] -bxor $ms[$i]) }',
64
+ " if ($diff -eq 0) { 'ok' } else { 'wrong proof' }",
65
+ '} finally { $c.Dispose() }'
66
+ ].join('\n');
67
+
68
+ // socket (a pipe name), secret (32 bytes) -> Promise<boolean>. powershell:
69
+ // for the tests (script, env, stdin) -> stdout, or a Promise of it. Run
70
+ // without blocking: the pipe's server may be in this same process (a test's),
71
+ // and a synchronous child would keep it from ever answering.
72
+ async function probePipe(socket, secret, ms = 2000, {powershell = winAcl.runPowershellAsync} = {}) {
73
+ if (!isPipeName(socket) || !Buffer.isBuffer(secret) || secret.length !== 32) return false;
74
+ try {
75
+ const out = await powershell(PROBE_SCRIPT, {CH_PIPE: socket.slice('\\\\.\\pipe\\'.length), CH_PROBE_MS: String(ms)}, secret.toString('hex'));
76
+ return String(out).trim() === 'ok';
77
+ } catch (e) {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ module.exports = {probePipe, PROBE_SCRIPT};
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ // One way to read the shim's files (ch-shim, ch-shim.previous): only as a
3
+ // regular file under its own name, never through a link and never blocking
4
+ // on a FIFO -- lstat, then an O_NOFOLLOW | O_NONBLOCK descriptor judged and
5
+ // read on its own (Windows has no O_NOFOLLOW: lstat refuses a link there).
6
+ // lib/shim-install.js reads whole binaries with it (the reviewer's high on
7
+ // #120, 2 and 3) and lib/session.js a binary's first bytes, before it runs
8
+ // one; kept apart from shim-install so a session start loads nothing more.
9
+ const fs = require('node:fs');
10
+
11
+ const MAX_BINARY = 64 * 1024 * 1024;
12
+ // errors that mean "not a plain file here", not "could not be read"
13
+ const NOT_THERE = new Set(['ENOENT', 'ENOTDIR', 'ELOOP', 'EMLINK']);
14
+
15
+ // (file, {limit}) -> {bytes: Buffer | null, code: errno | null}. bytes null
16
+ // with code null: no plain file there (absent, a link, a FIFO, a directory,
17
+ // past MAX_BINARY); with a code: one there that could not be read. limit:
18
+ // read only the first limit bytes (whole, bounded by MAX_BINARY, without).
19
+ function readPlain(file, {limit = null} = {}) {
20
+ let st;
21
+ try { st = fs.lstatSync(file); } catch (e) { return {bytes: null, code: NOT_THERE.has(e.code) ? null : (e.code || 'EIO')}; }
22
+ if (st.isSymbolicLink() || !st.isFile() || (limit == null && st.size > MAX_BINARY)) return {bytes: null, code: null};
23
+ let fd;
24
+ try {
25
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
26
+ } catch (e) {
27
+ return {bytes: null, code: NOT_THERE.has(e.code) ? null : (e.code || 'EIO')};
28
+ }
29
+ try {
30
+ const at = fs.fstatSync(fd);
31
+ if (!at.isFile() || (limit == null && at.size > MAX_BINARY)) return {bytes: null, code: null};
32
+ if (limit == null) return {bytes: fs.readFileSync(fd), code: null};
33
+ const buf = Buffer.alloc(limit);
34
+ let got = 0;
35
+ while (got < limit) {
36
+ const n = fs.readSync(fd, buf, got, limit - got, null);
37
+ if (n <= 0) break;
38
+ got += n;
39
+ }
40
+ return {bytes: buf.subarray(0, got), code: null};
41
+ } catch (e) {
42
+ return {bytes: null, code: e.code || 'EIO'};
43
+ } finally {
44
+ fs.closeSync(fd);
45
+ }
46
+ }
47
+
48
+ // <home>/shim/versions.json, sha512 hex -> version: as lib/shim-install.js
49
+ // writes it, read only as this user's own private file (lib/own-file.js);
50
+ // anything else reads as none -> {}
51
+ function readVersions(file, platform = process.platform) {
52
+ try {
53
+ const bytes = require('./own-file').readOwnFile(file, {max: 64 * 1024, platform});
54
+ if (bytes == null) return {};
55
+ const doc = JSON.parse(bytes.toString('utf8'));
56
+ if (doc == null || typeof doc !== 'object' || Array.isArray(doc)) return {};
57
+ return Object.fromEntries(Object.entries(doc).filter(([k, v]) => /^[0-9a-f]{128}$/.test(k) && typeof v === 'string'));
58
+ } catch (e) {
59
+ return {};
60
+ }
61
+ }
62
+
63
+ module.exports = {readPlain, readVersions, MAX_BINARY};
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+ // A private file in a private directory, read exactly as the native shim
3
+ // reads one (shim/src/trust.rs open_dir and open_in; countinghouse's
4
+ // shared-runtime design, #236, section 1, "The secret"):
5
+ //
6
+ // POSIX:
7
+ // - the directory is not a symlink, is a directory, is owned by the
8
+ // effective uid, and is mode 0700 exactly;
9
+ // - the file is lstat'ed and must be a regular file; it is opened
10
+ // O_NOFOLLOW | O_NONBLOCK (a FIFO never blocks the reader) and fstat'ed;
11
+ // both stats must name the same file (device and inode); it is owned by
12
+ // the effective uid and mode 0600 exactly.
13
+ // Windows: no reparse point (a symlink or a junction), and the directory's
14
+ // and the file's owner and DACL pass countinghouse's privateProblem rule
15
+ // (lib/win-acl.js).
16
+ //
17
+ // -> the file's bytes, at most `max`; throws an Error saying what failed.
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+
21
+ const euid = () => (typeof process.geteuid === 'function' ? process.geteuid() : null);
22
+ const mode = (st) => st.mode & 0o7777;
23
+
24
+ function refuse(file, why) {
25
+ const e = new Error(`${file}: ${why}`);
26
+ e.code = 'NOT_PRIVATE';
27
+ return e;
28
+ }
29
+
30
+ // `me` is the effective uid (a test passes another)
31
+ function checkDirPosix(dir, me = euid()) {
32
+ const st = fs.lstatSync(dir);
33
+ if (st.isSymbolicLink()) throw refuse(dir, 'it is a symbolic link');
34
+ if (!st.isDirectory()) throw refuse(dir, 'it is not a directory');
35
+ if (me != null && st.uid !== me) throw refuse(dir, `it is owned by uid ${st.uid}, not this user`);
36
+ if (mode(st) !== 0o700) throw refuse(dir, `its mode is ${mode(st).toString(8).padStart(4, '0')}, not 0700`);
37
+ }
38
+
39
+ function readPosix(dir, name, max) {
40
+ checkDirPosix(dir);
41
+ const file = path.join(dir, name);
42
+ const before = fs.lstatSync(file);
43
+ if (!before.isFile()) throw refuse(file, 'it is not a regular file');
44
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
45
+ try {
46
+ const st = fs.fstatSync(fd);
47
+ if (st.dev !== before.dev || st.ino !== before.ino) throw refuse(file, 'it changed while it was checked');
48
+ if (!st.isFile()) throw refuse(file, 'it is not a regular file');
49
+ if (euid() != null && st.uid !== euid()) throw refuse(file, `it is owned by uid ${st.uid}, not this user`);
50
+ if (mode(st) !== 0o600) throw refuse(file, `its mode is ${mode(st).toString(8).padStart(4, '0')}, not 0600`);
51
+ const buf = Buffer.alloc(max + 1);
52
+ const n = fs.readSync(fd, buf, 0, max + 1, 0);
53
+ if (n > max) throw refuse(file, `it is larger than ${max} bytes`);
54
+ return buf.subarray(0, n);
55
+ } finally {
56
+ fs.closeSync(fd);
57
+ }
58
+ }
59
+
60
+ // Windows: p not a symlink or junction (what lstat reports as a link), a
61
+ // directory or a regular file as isDir says, its owner and DACL passing
62
+ // privateProblem. `acl` is {fileAcl, privateProblem} (a test passes its own).
63
+ function checkPathWindows(p, isDir, acl = require('./win-acl')) {
64
+ const st = fs.lstatSync(p);
65
+ if (st.isSymbolicLink()) throw refuse(p, 'it is a symbolic link or another reparse point');
66
+ if (isDir ? !st.isDirectory() : !st.isFile()) throw refuse(p, isDir ? 'it is not a directory' : 'it is not a regular file');
67
+ const problem = acl.privateProblem(p, acl.fileAcl(p));
68
+ if (problem != null) throw refuse(p, problem);
69
+ }
70
+
71
+ // (cold-start part 3: the folder's ACL and the file's in one PowerShell run,
72
+ // read at the moment of this read and kept for it alone, so nothing read
73
+ // earlier is used; win-acl prefetch never reads through a link, and a failed
74
+ // read gets today's single read and its error)
75
+ function readWindows(dir, name, max, acl) {
76
+ const file = path.join(dir, name);
77
+ // (a path the run couldn't answer: the caller's own single read)
78
+ const reading = typeof acl.prefetch === 'function' ? Object.assign({}, acl, {fileAcl: acl.prefetch([dir, file], {single: acl.fileAcl})}) : acl;
79
+ for (const [p, isDir] of [[dir, true], [file, false]]) checkPathWindows(p, isDir, reading);
80
+ const data = fs.readFileSync(file);
81
+ if (data.length > max) throw refuse(file, `it is larger than ${max} bytes`);
82
+ return data;
83
+ }
84
+
85
+ // acl: {fileAcl, privateProblem, prefetch} on Windows, a test's (else win-acl's)
86
+ function readPrivateIn(dir, name, max, platform = process.platform, acl = null) {
87
+ return platform === 'win32' ? readWindows(dir, name, max, acl || require('./win-acl')) : readPosix(dir, name, max);
88
+ }
89
+
90
+ module.exports = {readPrivateIn, checkDirPosix, checkPathWindows};
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+ // A small file only this user may read, written whole (the daemon's
3
+ // daemon.json and failed.json; start's held-back file, A-firstrun d1).
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ // dir/name, written whole: through a temporary file created exclusively, 0600
8
+ // (on Windows with an owner-only DACL, in the call that creates it:
9
+ // win-acl createPrivate, protected, nothing inherited from the directory),
10
+ // then renamed in place, which keeps it. `platform` and `acl` are for tests.
11
+ function writePrivate(dir, name, text, {platform = process.platform, acl = null} = {}) {
12
+ const file = path.join(dir, name);
13
+ const temp = path.join(dir, `.${name}.${process.pid}.${Date.now()}.tmp`);
14
+ let placed = false;
15
+ try {
16
+ if (platform === 'win32') (acl || require('./win-acl')).createPrivate(temp, text);
17
+ else {
18
+ const fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600);
19
+ try {
20
+ fs.fchmodSync(fd, 0o600);
21
+ fs.writeSync(fd, text);
22
+ } finally {
23
+ fs.closeSync(fd);
24
+ }
25
+ }
26
+ fs.renameSync(temp, file);
27
+ placed = true;
28
+ } finally {
29
+ if (!placed) { try { fs.unlinkSync(temp); } catch (e) { /* gone */ } }
30
+ }
31
+ }
32
+
33
+ module.exports = {writePrivate};