@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,380 @@
1
+ 'use strict';
2
+ // `ch-local add-module <dir>`: the user's own module, added by the user's
3
+ // own act in their own terminal (B-own-add; the own-modules design, §2.1,
4
+ // §5). Asked
5
+ // at a terminal only (an agent's shell is not one; its consent would be its
6
+ // client's command prompt: R6), never with --yes. The folder is judged and
7
+ // hashed (lib/own-tree.js); its name and device name must be no other
8
+ // module's; each module it calls must be installed here (composition with
9
+ // the packs: start passes those modules along); a key or data already kept
10
+ // for its name is said. The question makes no claim about what its calls
11
+ // reach through other modules (a pack's keys): R7/R8, accepted for release
12
+ // 1 (the maintainer's decision). On yes the folder is copied into the home under its
13
+ // hash -- the code that runs is the code the user saw -- and recorded in
14
+ // own.json (lib/own-record.js). The last line waits for the runtimes that run
15
+ // now to apply it, and says how that ended (lib/own-applied.js); an interrupt
16
+ // meanwhile ends the command, the change recorded and no line said. Every
17
+ // line is business-checked text (§5).
18
+ const fs = require('node:fs');
19
+ const path = require('node:path');
20
+ const {layout} = require('./home');
21
+ const {chLocal, folderArg, terminalText, hintCommand} = require('./command-line');
22
+ const {withLock} = require('./lock');
23
+ const {checkFolder, treeHash, placeCopy, copyDir, copyIntact, readPlain} = require('./own-tree');
24
+ const {readOwnRecord, writeOwnRecord} = require('./own-record');
25
+ const {readModulesRecord} = require('./module-record');
26
+ const {versionDir} = require('./store-paths');
27
+ const {PACKAGE, SCOPE, nameKey} = require('./names');
28
+ const {credentialOf} = require('./describe-module');
29
+ const {readSettings, valueOf} = require('./settings');
30
+ const {enforceAvailable} = require('./sandbox-support');
31
+
32
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
33
+ const callsOf = (pkg) => (isObject(pkg) && isObject(pkg.countinghouse) && Array.isArray(pkg.countinghouse.calls) ? pkg.countinghouse.calls.filter((c) => typeof c === 'string') : []);
34
+ const ADDRESS = /^([^/\s]{1,214})\/([^.\s/]{1,128})\.([^.\s/]{1,128})$/;
35
+ const MAX_JSON = 4 * 1024 * 1024;
36
+ const readJson = (file) => JSON.parse(readPlain(file, MAX_JSON).toString('utf8'));
37
+
38
+ // a spec's action names: a scenario's tools, by their bare names
39
+ const actionNames = (spec) => {
40
+ const list = isObject(spec) && isObject(spec.device) && isObject(spec.device.serviceList) ? Object.values(spec.device.serviceList) : [];
41
+ return list.flatMap((s) => (isObject(s) && Array.isArray(s.actionList) ? s.actionList : [])).map((a) => (isObject(a) ? a.name : null)).filter((n) => typeof n === 'string');
42
+ };
43
+
44
+ // Every name the home holds (§2.4): {byName: Map(name -> m), byDevice:
45
+ // Map(friendlyName -> m), unreadable: [name] (an installed pack module whose
46
+ // files can't be read: the names it holds are not known), calledBy:
47
+ // Map(device name -> the pack module that calls it)}, m = {name, kind:
48
+ // 'pack'|'held'|'store'|'own', dir, pkg, spec, friendlyName, tools}. The
49
+ // record's modules and its held packs' from the store; any other name the
50
+ // store holds (a leftover version); an own module's from its copy, or by
51
+ // its recorded device name when the copy can't be read.
52
+ function installedModules(where) {
53
+ const byName = new Map();
54
+ const byDevice = new Map();
55
+ const unreadable = [];
56
+ const calledBy = new Map();
57
+ const add = (name, kind, dir, recordedDevice = null) => {
58
+ if (byName.has(name)) return;
59
+ let pkg = null;
60
+ let spec = null;
61
+ try { pkg = readJson(path.join(dir, 'package.json')); spec = readJson(path.join(dir, 'api.json')); } catch (e) {
62
+ if (kind === 'pack') unreadable.push(name);
63
+ const m = {name, kind, dir, pkg: null, spec: null, friendlyName: recordedDevice, tools: []};
64
+ byName.set(name, m);
65
+ if (recordedDevice != null && !byDevice.has(recordedDevice)) byDevice.set(recordedDevice, m);
66
+ return;
67
+ }
68
+ const friendlyName = isObject(spec) && isObject(spec.device) && typeof spec.device.friendlyName === 'string' ? spec.device.friendlyName : null;
69
+ // (a scenario's tools: every own module's, a pack module's that says so)
70
+ const scenario = kind === 'own' || (isObject(pkg) && isObject(pkg.countinghouse) && pkg.countinghouse.role === 'scenario');
71
+ const m = {name, kind, dir, pkg, spec, friendlyName, tools: scenario ? actionNames(spec) : []};
72
+ byName.set(name, m);
73
+ if (friendlyName != null && !byDevice.has(friendlyName)) byDevice.set(friendlyName, m);
74
+ // the device names a pack module calls, installed or not
75
+ if (kind !== 'own') for (const c of callsOf(pkg)) { const d = c.slice(0, c.indexOf('/')); if (d !== '' && !calledBy.has(d)) calledBy.set(d, name); }
76
+ };
77
+ const record = readModulesRecord(where);
78
+ if (record != null) {
79
+ for (const [name, e] of Object.entries(record.modules)) add(name, 'pack', versionDir(where, name, e.version));
80
+ for (const p of Object.values(record.held || {})) for (const [name, v] of Object.entries((p && p.modules) || {})) if (typeof v === 'string') add(name, 'held', versionDir(where, name, v));
81
+ }
82
+ // every name the store holds
83
+ const list = (d) => { try { return fs.readdirSync(d, {withFileTypes: true}); } catch (e) { return []; } };
84
+ for (const top of list(where.moduleStore)) {
85
+ if (!top.isDirectory()) continue;
86
+ const names = SCOPE.test(top.name) ? list(path.join(where.moduleStore, top.name)).filter((e) => e.isDirectory()).map((e) => `${top.name}/${e.name}`) : [top.name];
87
+ for (const n of names) if (PACKAGE.test(n) && !byName.has(n)) byName.set(n, {name: n, kind: 'store', dir: null, pkg: null, spec: null, friendlyName: null, tools: []});
88
+ }
89
+ const own = readOwnRecord(where);
90
+ if (own != null) for (const [name, e] of Object.entries(own.modules)) add(name, 'own', copyDir(where, name, e.tree), e.friendlyName);
91
+ // (and by each name's key: two names Windows lays out as one are one)
92
+ // (every holder of a key, not the first: the medium on #113's round 1)
93
+ const byKey = new Map();
94
+ for (const m of byName.values()) { const k = nameKey(m.name); if (!byKey.has(k)) byKey.set(k, []); byKey.get(k).push(m); }
95
+ return {byName, byDevice, byKey, unreadable, calledBy};
96
+ }
97
+
98
+ // the keys stored for a module: Map(variable -> {origin, ...}) | null (the
99
+ // store's modules is a map; a version 1 store holds none of an own module's)
100
+ const keysFor = (where, name, platform) => {
101
+ try {
102
+ const m = require('./credential-store').readStore(where.home, {platform}).modules;
103
+ return m instanceof Map && m.get(name) instanceof Map && m.get(name).size > 0 ? m.get(name) : null;
104
+ } catch (e) { return null; }
105
+ };
106
+ // text from the module's package.json, as the terminal shows it: no
107
+ // character that can move the cursor or hide a line, no run of spaces, and
108
+ // cut short, so nothing can push the question's own lines away
109
+ const plain = (s) => terminalText(s, 80);
110
+ // the permissions it declares (countinghouse.permissions: fs, net, env), as
111
+ // one line, or null: under ch-local's enforce, with no operator policy,
112
+ // none is granted (countinghouse lib/module-permissions.js narrow)
113
+ function permissionsLine(pkg) {
114
+ const p = isObject(pkg.countinghouse) && isObject(pkg.countinghouse.permissions) ? pkg.countinghouse.permissions : null;
115
+ if (p == null) return null;
116
+ const few = (list) => `${list.slice(0, 5).join(', ')}${list.length > 5 ? ', …' : ''}`;
117
+ const s = (list) => (list.length > 1 ? 's' : '');
118
+ const parts = [];
119
+ const paths = (Array.isArray(p.fs) ? p.fs : []).filter(isObject).map((e) => `${plain(e.path)} (${e.access === 'rw' ? 'read and write' : 'read'})`);
120
+ if (paths.length > 0) parts.push(`the path${s(paths)} ${few(paths)}`);
121
+ const hosts = (Array.isArray(p.net) ? p.net : []).filter(isObject).map((e) => plain(e.host));
122
+ if (hosts.length > 0) parts.push(`the network host${s(hosts)} ${few(hosts)}`);
123
+ const envs = (Array.isArray(p.env) ? p.env : []).map(plain);
124
+ if (envs.length > 0) parts.push(`the environment variable${s(envs)} ${few(envs)}`);
125
+ return parts.length > 0 ? `It asks for ${parts.join(', ')}; under the enforced sandbox it gets none of them.` : null;
126
+ }
127
+ // the settings stored for a module's name (module.<name>.<setting>): the
128
+ // setting names, [] when none or when the settings file can't be read
129
+ const storedSettingsOf = (where, name) => {
130
+ const read = require('./settings').readSettings(where);
131
+ if (read.error != null || read.kept == null) return [];
132
+ return require('./module-values').storedNamesOf(read.kept, name).map((n) => n.slice(`module.${name}.`.length));
133
+ };
134
+ // a module's own declared credential's origin, or null
135
+ const credentialOfPkg = (pkg) => {
136
+ const c = credentialOf(isObject(pkg) && isObject(pkg.countinghouse) ? pkg.countinghouse.remotes : []);
137
+ return c.credential != null ? c.credential.origin : null;
138
+ };
139
+
140
+ // The module's declared calls resolved against what is installed (a pack's
141
+ // scenarios and parts, other own modules), each to one of the callee's
142
+ // actions as the runtime resolves it (lib/call-address.js: the service by
143
+ // its URN's last label, once) -> {unknown: [address] | null, wrong:
144
+ // {address, callee} | null, callees: [name] (in order)}. What those callees
145
+ // reach in turn -- a pack's keys -- is not walked: R7/R8, release 1.1
146
+ // (the maintainer's decision).
147
+ function resolveCalls(calls, installed) {
148
+ const unknown = [];
149
+ let wrong = null;
150
+ const callees = [];
151
+ for (const address of calls) {
152
+ const m = ADDRESS.exec(address);
153
+ const callee = m != null ? installed.byDevice.get(m[1]) : null;
154
+ if (callee == null) { unknown.push(address); continue; }
155
+ const list = isObject(callee.spec) && isObject(callee.spec.device) && isObject(callee.spec.device.serviceList) ? callee.spec.device.serviceList : {};
156
+ const services = Object.keys(list).filter((urn) => urn.split(':').pop() === m[2]);
157
+ const actions = services.length === 1 && isObject(list[services[0]]) && Array.isArray(list[services[0]].actionList) ? list[services[0]].actionList.map((a) => (isObject(a) ? a.name : null)) : [];
158
+ if (!actions.includes(m[3])) { if (wrong == null) wrong = {address, callee: callee.name}; continue; }
159
+ if (!callees.includes(callee.name)) callees.push(callee.name);
160
+ }
161
+ return {unknown: unknown.length > 0 ? unknown : null, wrong, callees};
162
+ }
163
+
164
+ const short = (name) => name.replace(/^@[^/]+\//, '');
165
+
166
+ // options: where; now; ceiling (the operator's, read when not given);
167
+ // afterRead (a test's seam: called once the folder's files were read)
168
+ async function addModule({dir}, io, {where = layout(io.env, io.homedir), now = () => new Date(), ceiling = undefined, afterRead = () => {}} = {}) {
169
+ const fail = (code, message) => { io.stderr.write(`ch-local: ${message}\n`); return code; };
170
+ const shownDir = typeof dir === 'string' ? path.resolve(dir) : '';
171
+ // the user's own act, at their own terminal, its lines seen (line 1)
172
+ if (io.interactive !== true || io.stdoutTTY !== true) return fail(2, `add-module asks you, in your own terminal: run ${hintCommand(where, `add-module ${folderArg(shownDir, io.platform)}`, io.platform)} there.`);
173
+ // only under enforce (line 7; §2.1 step 7): start holds one back under
174
+ // audit, so adding one there is refused first
175
+ if (!enforceAvailable(where, io.platform || process.platform)) return fail(2, 'Own modules run only with the sandbox enforced, and the installed runtime can\'t enforce it on this computer.');
176
+ // (as a start decides it: the settings under the operator's ceiling)
177
+ const settings = readSettings(where);
178
+ if (settings.error != null) return fail(1, `${settings.error}: nothing was added`);
179
+ const {ceilingFor, startUnderCeiling} = require('./ceiling');
180
+ const bounded = startUnderCeiling(settings, ceiling !== undefined ? ceiling : ceilingFor(where, {platform: io.platform || process.platform, env: io.env}), {where});
181
+ if (bounded.problem != null) return fail(1, `${bounded.problem}; nothing was added`);
182
+ if (valueOf({values: bounded.values}, 'moduleSandbox') === 'audit') return fail(2, `Own modules run only with the sandbox enforced: run ${hintCommand(where, 'settings set moduleSandbox enforce', io.platform)} first.`);
183
+ // an own module runs with what an install placed: none without one (the
184
+ // reviewer's high on #113, 3)
185
+ let installedRecord;
186
+ try { installedRecord = readModulesRecord(where); } catch (err) { return fail(1, `${err.message}; nothing was added`); }
187
+ if (installedRecord == null) return fail(2, `nothing is installed yet: run ${hintCommand(where, 'install --pack <name>', io.platform)} first; your own modules run with what it installs.`);
188
+ const checked = checkFolder(shownDir, where.home);
189
+ if (checked.problems != null) return fail(2, `${terminalText(shownDir, 512)}: ${checked.problems.join('; ')}`);
190
+ const {real, pkg, spec, entries} = checked;
191
+ const name = pkg.name;
192
+ const friendlyName = spec.device.friendlyName;
193
+ const calls = callsOf(pkg);
194
+ afterRead();
195
+ // what the question shows is what is hashed, and so what loads: the
196
+ // package.json and api.json read above must be the bytes hashed now
197
+ const hashed = {'package.json': null, 'api.json': null};
198
+ const tree = treeHash(real, entries, hashed);
199
+ if (hashed['package.json'] == null || hashed['api.json'] == null || !hashed['package.json'].equals(checked.pkgBytes) || !hashed['api.json'].equals(checked.specBytes)) {
200
+ return fail(1, 'the folder changed while it was being added: run add-module again');
201
+ }
202
+ let installed;
203
+ let own;
204
+ try {
205
+ installed = installedModules(where);
206
+ own = readOwnRecord(where);
207
+ } catch (err) {
208
+ return fail(1, err.message);
209
+ }
210
+ // an installed module whose files can't be read: the names it holds are
211
+ // not known, so none is taken (§2.4)
212
+ if (installed.unreadable.length > 0) return fail(1, `${installed.unreadable[0]}'s files can't be read here, so the names it holds are not known: run \`${chLocal(where, 'install')}\` again first.`);
213
+ const previous = own != null ? own.modules[name] : undefined;
214
+ // the same code already added, its copy whole: nothing to ask (line 10).
215
+ // With a runtime here it is asked all the same: what it runs may not be this
216
+ // (a copy put right by hand, a module it stopped), and adding it again loads it
217
+ let running = true;
218
+ try { running = require('./gc').liveRuns(where, {alive: io.alive, hostname: io.hostname, sameMachine: true}).length > 0; } catch (err) { /* a run that can't be read may be a live one's */ }
219
+ const already = previous != null && previous.tree === tree && copyIntact(where, name, tree);
220
+ const ALREADY = `${short(name)} ${tree.slice(0, 12)} is already added: nothing changed.\n`;
221
+ if (already && !running) {
222
+ io.stdout.write(ALREADY);
223
+ return 0;
224
+ }
225
+ // no name this release holds: its runtime's packages, its pinned modules
226
+ // (§2.4; their data and keys are kept by name)
227
+ const allow = require('./packs').releaseOf(io);
228
+ const held = new Set([...((allow.runtime && allow.runtime.packages) || []), ...Object.keys(allow.pins || {})].map(nameKey));
229
+ if (held.has(nameKey(name))) return fail(2, `${name} is a name this release holds: give your module another name in its package.json.`);
230
+ // no other module's name or device name (lines 4, 5)
231
+ // (any holder of its key but this own module itself)
232
+ const taken = (installed.byKey.get(nameKey(name)) || []).find((m) => !(m.kind === 'own' && m.name === name));
233
+ if (taken != null) return fail(2, `${name} is already used here by ${taken.kind === 'own' ? 'your own module' : 'pack module'} ${terminalText(taken.name)}: give your module another name in its package.json.`);
234
+ const device = installed.byDevice.get(friendlyName);
235
+ if (device != null && device.name !== name) return fail(2, `${name}'s device name ${terminalText(friendlyName)} is already used by ${device.name}: change it in its api.json.`);
236
+ // nor another module's short name: one name, one module, in every command
237
+ // (the reviewer on #116: `settings reset <name>` reset a pack's setting)
238
+ const shortOf = [...installed.byName.values()].find((m) => m.name !== name && short(m.name) === name);
239
+ if (shortOf != null) return fail(2, `${name} is the short name of ${shortOf.name} here: give your module another name in its package.json.`);
240
+ // nor one a pack module calls, installed or not: a pack never calls user
241
+ // code that took the name it calls
242
+ const caller = installed.calledBy.get(friendlyName);
243
+ if (caller != null) return fail(2, `${name}'s device name ${terminalText(friendlyName)} is one ${caller} calls: change it in its api.json.`);
244
+ // no tool name another scenario lists (§2.4: the runtime would refuse it,
245
+ // TOOL_NAME_TAKEN; the runtime's own tools it refuses at load)
246
+ for (const t of actionNames(spec)) {
247
+ const holder = [...installed.byName.values()].find((m) => m.name !== name && m.tools.includes(t));
248
+ if (holder != null) return fail(2, `${name}'s tool ${terminalText(t)} is already a tool of ${holder.name}: rename the action in its api.json.`);
249
+ }
250
+ // each call listed once, at most 256 (own.json's bounds, said before the
251
+ // yes: the reviewer's high on #113, 4)
252
+ // (the bound first, then one pass: the medium on #113's round 1)
253
+ if (calls.length > 256) return fail(2, `${name} lists more than 256 calls: an own module lists at most 256.`);
254
+ const seenCalls = new Set();
255
+ const twice = calls.find((c) => (seenCalls.has(c) ? true : (seenCalls.add(c), false)));
256
+ if (twice != null) return fail(2, `${name} lists the call ${terminalText(twice)} twice: list each call once in its package.json.`);
257
+ // what it calls: each one installed here (line 8c)
258
+ const resolved = resolveCalls(calls, installed);
259
+ if (resolved.unknown != null) return fail(2, `${name} calls ${terminalText(resolved.unknown[0])}, and nothing installed here answers it: install the pack it belongs to, or remove the call.`);
260
+ if (resolved.wrong != null) return fail(2, `${name} calls ${terminalText(resolved.wrong.address)}, and ${short(resolved.wrong.callee)} has no such action: correct the call in its package.json.`);
261
+ // the question (lines 8, 8a, 8c)
262
+ const lines = [`Add your own module ${name} ${pkg.version} (code ${tree.slice(0, 12)}, ${entries.filter((e) => e.kind === 'file').length} files)?`,
263
+ 'It runs inside the same countinghouse runtime as your packs.',
264
+ 'It can connect to the internet and send what it is given.'];
265
+ for (const callee of resolved.callees) lines.push(`It calls ${short(callee)}.`);
266
+ const ownOrigin = credentialOfPkg(pkg);
267
+ if (ownOrigin != null) lines.push(`It calls ${ownOrigin}; add its key with \`${chLocal(where, `credentials add ${name}`)}\`.`);
268
+ const asks = permissionsLine(pkg);
269
+ if (asks != null) lines.push(asks);
270
+ // a key or data kept for this name (a remove-module keeps them; line 8a)
271
+ const keptKey = keysFor(where, name, io.platform);
272
+ const dataDir = path.join(where.moduleData, ...name.split('/'));
273
+ const keptData = fs.existsSync(dataDir);
274
+ // (and its settings: a re-add, or a new module under a removed one's
275
+ // name, takes them as it takes a key or data -- B-own-settings)
276
+ const keptSettings = storedSettingsOf(where, name);
277
+ // (only what is kept is named, each with its own remedy: the medium on
278
+ // B-own-settings, 9)
279
+ const uses = [];
280
+ const remedies = [];
281
+ if (keptKey != null) {
282
+ const origins = [...new Set([...keptKey.values()].map((b) => b != null && b.origin).filter(Boolean))];
283
+ uses.push(`the key already stored for ${name}${origins.length > 0 ? ` (sent only to ${origins.join(', ')})` : ''}`);
284
+ remedies.push(`\`${chLocal(where, `credentials remove ${name}`)}\``);
285
+ }
286
+ if (keptData) { uses.push(`the data kept in ${dataDir}`); remedies.push(`delete ${dataDir}`); }
287
+ if (keptSettings.length > 0) {
288
+ uses.push(`the settings stored for ${name} (${keptSettings.map((s) => terminalText(s, 40)).slice(0, 8).join(', ')}${keptSettings.length > 8 ? ', …' : ''})`);
289
+ remedies.push(`\`${chLocal(where, `settings reset ${name}`)}\``);
290
+ }
291
+ const listed = (xs) => (xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : xs[0]);
292
+ if (uses.length > 0) lines.push(`It will use ${listed(uses)}. Remove ${uses.length > 1 ? 'them' : 'it'} first if this is a different module: ${remedies.join(', and ')}.`);
293
+ io.stdout.write(`${lines.join('\n')}\n`);
294
+ const answer = String(await io.ask('Add it? [y/N] ')).trim().toLowerCase();
295
+ if (answer !== 'y' && answer !== 'yes') {
296
+ if (!already) return fail(1, `${short(name)} was not added`);
297
+ io.stdout.write(ALREADY);
298
+ return 0;
299
+ }
300
+ // the copy and the record, under the home's lock
301
+ const addedAt = now().toISOString();
302
+ const code = await withLock(where, io, () => {
303
+ let current;
304
+ try { current = readOwnRecord(where); } catch (err) { return fail(1, err.message); }
305
+ try {
306
+ placeCopy(where, name, real, entries, tree, {now});
307
+ } catch (err) {
308
+ if (err.code === 'OWN_TREE_CHANGED') return fail(1, err.message);
309
+ // (after the yes, never a crash: the old copy, if any, stays marked)
310
+ return fail(1, `your module's copy could not be replaced (${err.code || 'an error'}): nothing was added`);
311
+ }
312
+ const modules = current != null ? current.modules : Object.create(null);
313
+ modules[name] = {tree, version: pkg.version, friendlyName, addedAt, from: real, calls};
314
+ writeOwnRecord(where, {v: 1, modules});
315
+ return 0;
316
+ });
317
+ if (code !== 0) return code;
318
+ // (line 9, once the running runtimes have applied it)
319
+ const ended = await require('./own-applied').addApplied(where, io, {name, tree, addedAt});
320
+ const why = `\`${chLocal(where, 'status')}\` says why.`;
321
+ const line = {
322
+ loaded: ': your clients see it now.',
323
+ none: ': your clients see it when they next start.',
324
+ kept: `, but the running runtime has not loaded it: ${why}`,
325
+ refused: `, but the running runtime refused it (${ended.code}): ${why}`,
326
+ restart: ended.shared ? `. The running runtime takes it up when it restarts: \`${chLocal(where, 'restart')}\` asks for that.` : '. The running runtime takes it up when your client restarts.',
327
+ late: '. The running runtime has not taken it up yet: your clients see it once it has.'
328
+ }[ended.state];
329
+ io.stdout.write(`Added ${short(name)} (own, ${tree.slice(0, 12)})${line}\n`);
330
+ return 0;
331
+ }
332
+
333
+ // `ch-local remove-module <name>` (the own-modules design §2.6, §5 line
334
+ // 15): the module dropped from own.json, by its package name or, when one
335
+ // own module has it, its short name; its copies no live start runs
336
+ // collected (the rest at the next collection). A tightening: asked of no
337
+ // one. Its data and its key are kept, and said, with how to remove them.
338
+ async function removeModule({name}, io, {where = layout(io.env, io.homedir)} = {}) {
339
+ const fail = (code, message) => { io.stderr.write(`ch-local: ${message}\n`); return code; };
340
+ let removed = null;
341
+ let stamp = null;
342
+ let entry = null;
343
+ const code = await withLock(where, io, () => {
344
+ let record;
345
+ try { record = readOwnRecord(where); } catch (err) { return fail(1, err.message); }
346
+ const names = record != null ? Object.keys(record.modules) : [];
347
+ const matches = names.includes(name) ? [name] : names.filter((n) => short(n) === name);
348
+ if (matches.length === 0) return fail(2, `${name} is not one of your own modules: \`${chLocal(where, 'status')}\` lists them.`);
349
+ if (matches.length > 1) return fail(2, `${name} names more than one of your own modules (${matches.join(', ')}): name it in full.`);
350
+ removed = matches[0];
351
+ entry = record.modules[removed];
352
+ delete record.modules[removed];
353
+ writeOwnRecord(where, record);
354
+ stamp = require('./own-applied').stampOf(where);
355
+ require('./gc').collectOwn(where, {alive: io.alive, hostname: io.hostname});
356
+ return 0;
357
+ });
358
+ if (code !== 0) return code;
359
+ const hasKey = keysFor(where, removed, io.platform) != null;
360
+ const dataDir = path.join(where.moduleData, ...removed.split('/'));
361
+ const hasData = fs.existsSync(dataDir);
362
+ const keyCmd = `\`${chLocal(where, `credentials remove ${removed}`)}\``;
363
+ const tail = hasData && hasKey ? ` Its data is kept in ${dataDir}, and its key with it: ${keyCmd} removes the key.`
364
+ : hasData ? ` Its data is kept in ${dataDir}.`
365
+ : hasKey ? ` Its key is kept: ${keyCmd} removes it.` : '';
366
+ // (its settings stay stored, as its data and key: B-own-settings)
367
+ const settingsTail = storedSettingsOf(where, removed).length > 0 ? ` Its settings stay stored: \`${chLocal(where, `settings reset ${removed}`)}\` resets them.` : '';
368
+ // (said once the running runtimes have applied it)
369
+ const ended = await require('./own-applied').removeApplied(where, io, {name: removed, stamp, tree: entry.tree, addedAt: entry.addedAt});
370
+ const line = {
371
+ removed: '.',
372
+ none: '.',
373
+ still: `, but the running runtime still serves it: ${ended.shared ? `\`${chLocal(where, 'restart')}\` stops it` : 'restart your client to stop it'}.`,
374
+ late: '. The running runtime has not dropped it yet: your clients see it go once it has.'
375
+ }[ended.state];
376
+ io.stdout.write(`Removed ${short(removed)}${line}${tail}${settingsTail}\n`);
377
+ return 0;
378
+ }
379
+
380
+ module.exports = {addModule, removeModule, installedModules, resolveCalls, folderArg};
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+ // A file in the home that only this user can have written, read and written
3
+ // so (the review of #48): what the automatic upgrade keeps between runs
4
+ // (upgrade-check.json) decides when new code runs, so it is not taken from a
5
+ // file another user could have planted or a link to one.
6
+ // - read: missing is null. Otherwise it must not be a link (on Windows, no
7
+ // reparse point), must be a regular file, and at most `max` bytes. On
8
+ // POSIX it is opened O_NOFOLLOW, both stats must name the same file, and it
9
+ // must be owned by this user with nothing for group or others
10
+ // (mode & 0o077 == 0). On Windows its owner and DACL pass privateProblem
11
+ // (lib/win-acl.js). Anything else throws NOT_PRIVATE.
12
+ // - write: a temp file beside it, created exclusively (never through a
13
+ // link), 0600, then renamed over it (a link there is replaced, not
14
+ // followed).
15
+ const fs = require('node:fs');
16
+ const path = require('node:path');
17
+
18
+ const refuse = (file, why) => Object.assign(new Error(`${file}: ${why}`), {code: 'NOT_PRIVATE'});
19
+ const euid = () => (typeof process.geteuid === 'function' ? process.geteuid() : null);
20
+
21
+ // platform: as the caller sees it; the checks are the Windows ones whenever
22
+ // either it or the system this runs on is Windows (a POSIX mode on Windows
23
+ // means nothing, and a caller's platform can be a test's)
24
+ // fileAcl: the caller's reader of a path's ACL (Windows: a session's, read
25
+ // once for every path it checks -- the medium on A3, 1), else win-acl's
26
+ function readOwnFile(file, {max = 1024 * 1024, platform = process.platform, fileAcl = null} = {}) {
27
+ let before;
28
+ try { before = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
29
+ if (before.isSymbolicLink()) throw refuse(file, 'it is a link');
30
+ if (!before.isFile()) throw refuse(file, 'it is not a regular file');
31
+ if (platform === 'win32' || process.platform === 'win32') {
32
+ const winAcl = require('./win-acl');
33
+ const problem = winAcl.privateProblem(file, (fileAcl || winAcl.fileAcl)(file));
34
+ if (problem != null) throw refuse(file, problem);
35
+ const data = fs.readFileSync(file);
36
+ if (data.length > max) throw refuse(file, `it is larger than ${max} bytes`);
37
+ return data;
38
+ }
39
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
40
+ try {
41
+ const st = fs.fstatSync(fd);
42
+ if (st.dev !== before.dev || st.ino !== before.ino) throw Object.assign(refuse(file, 'it changed while it was checked'), {raced: true});
43
+ if (!st.isFile()) throw refuse(file, 'it is not a regular file');
44
+ if (euid() != null && st.uid !== euid()) throw refuse(file, `it is owned by uid ${st.uid}, not this user`);
45
+ if ((st.mode & 0o077) !== 0) throw refuse(file, `its mode is ${(st.mode & 0o777).toString(8).padStart(4, '0')}: group or others have access`);
46
+ const buf = Buffer.alloc(max + 1);
47
+ const n = fs.readSync(fd, buf, 0, max + 1, 0);
48
+ if (n > max) throw refuse(file, `it is larger than ${max} bytes`);
49
+ return buf.subarray(0, n);
50
+ } finally {
51
+ fs.closeSync(fd);
52
+ }
53
+ }
54
+
55
+ // A file read whole, at most `max` bytes, that need not be private (an
56
+ // app's own files: lib/installed-description.js reads the home's own
57
+ // release's pins so): a regular file, not a link, the one checked (dev and
58
+ // inode as bigints: Windows file ids exceed a double), opened without
59
+ // following a link or blocking on a FIFO swapped in, read to its end (a
60
+ // short read is never taken for the whole). The file itself is never a
61
+ // link; links in the directories above it are followed, as the launcher
62
+ // that runs those files follows them. -> its bytes, or null when it is
63
+ // missing, not a regular file, a link (found at the check, or swapped in
64
+ // before the open: ELOOP), under a path that is not a directory (ENOTDIR),
65
+ // swapped (a socket swapped in: ENXIO), or over max. Any other I/O error
66
+ // (EACCES, say) throws.
67
+ // (the codes each step can give for a path that is not a readable file)
68
+ const REFUSED_LSTAT = new Set(['ENOENT', 'ENOTDIR', 'ELOOP']);
69
+ const REFUSED_OPEN = new Set(['ENOENT', 'ENOTDIR', 'ELOOP', 'EISDIR', 'ENXIO']);
70
+ function readBoundedFile(file, {max}) {
71
+ let before;
72
+ try { before = fs.lstatSync(file, {bigint: true}); } catch (e) { if (REFUSED_LSTAT.has(e.code)) return null; throw e; }
73
+ if (before.isSymbolicLink() || !before.isFile()) return null;
74
+ let fd;
75
+ try {
76
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
77
+ } catch (e) {
78
+ if (REFUSED_OPEN.has(e.code)) return null;
79
+ throw e;
80
+ }
81
+ try {
82
+ const st = fs.fstatSync(fd, {bigint: true});
83
+ if (!st.isFile() || st.dev !== before.dev || st.ino !== before.ino) return null;
84
+ const buf = Buffer.alloc(max + 1);
85
+ let n = 0;
86
+ for (;;) {
87
+ const got = fs.readSync(fd, buf, n, max + 1 - n, n);
88
+ if (got === 0) break;
89
+ n += got;
90
+ if (n > max) return null;
91
+ }
92
+ return buf.subarray(0, n);
93
+ } finally {
94
+ fs.closeSync(fd);
95
+ }
96
+ }
97
+
98
+ // beforeRename: called once the temporary file is whole, just before it is
99
+ // renamed into place; a throw leaves the file as it was (the stored
100
+ // credentials' lock checked there: post-rel cred-race)
101
+ function writeOwnFile(file, data, {beforeRename = null} = {}) {
102
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
103
+ let placed = false;
104
+ try {
105
+ const fd = fs.openSync(temp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600);
106
+ try {
107
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
108
+ fs.writeSync(fd, data);
109
+ } finally {
110
+ fs.closeSync(fd);
111
+ }
112
+ if (typeof beforeRename === 'function') beforeRename();
113
+ fs.renameSync(temp, file);
114
+ placed = true;
115
+ } finally {
116
+ if (!placed) { try { fs.unlinkSync(temp); } catch (e) { /* gone */ } }
117
+ }
118
+ }
119
+
120
+ module.exports = {readOwnFile, readBoundedFile, writeOwnFile};
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+ // The user's own modules, recorded (B-own-add; the own-modules design,
3
+ // §2.1-2.2):
4
+ // <home>/own.json, apart from modules.json (the pinned record, whose readers
5
+ // all assume a release's pins). Written whole and atomically, under
6
+ // packs.lock, by add-module and remove-module; read by start, the applier,
7
+ // status, credentials, gc and uninstall, and by the runtime's overview
8
+ // (countinghouse settings-tool installedOwn).
9
+ //
10
+ // {"v": 1,
11
+ // "modules": {"<package>": {
12
+ // "tree": "<sha256 of the confirmed copy's tree, 64 hex>",
13
+ // "version": "<package.json version>",
14
+ // "friendlyName": "<api.json device.friendlyName>",
15
+ // "addedAt": "<ISO instant of the user's yes>",
16
+ // "from": "<the absolute folder it was added from>",
17
+ // "calls": ["<address>", ...] its declared countinghouse.calls
18
+ // }}}
19
+ //
20
+ // (What its calls can reach through other modules -- a pack's keys -- is
21
+ // neither listed at the yes nor recorded: accepted for release 1 as R7 and
22
+ // R8, the maintainer's decision, for 1.1.)
23
+ //
24
+ // The shape is versioned and kept stable: the release-1 -> next upgrade
25
+ // test pins it (C), and the 1.1 host process takes it unchanged (§2.7).
26
+ const fs = require('node:fs');
27
+ const path = require('node:path');
28
+ const {PACKAGE, endsTrimmed} = require('./names');
29
+ const {writeAtomic} = require('./atomic');
30
+ const {chLocal} = require('./command-line');
31
+
32
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
33
+ const TREE = /^[0-9a-f]{64}$/;
34
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
35
+ // a call address as a module declares it: <module>/<service>.<action>
36
+ const ADDRESS = /^[^/\s]{1,214}\/[^.\s/]{1,128}\.[^.\s/]{1,128}$/;
37
+ const MAX_LIST = 256;
38
+ const isString = (x, max) => typeof x === 'string' && x.length > 0 && x.length <= max;
39
+ const listOf = (x, rule) => Array.isArray(x) && x.length <= MAX_LIST && x.every((v) => typeof v === 'string' && rule.test(v)) && new Set(x).size === x.length;
40
+
41
+ // -> why m is not one own module's entry, or null
42
+ function entryProblem(m) {
43
+ if (!isObject(m)) return 'an entry is not an object';
44
+ const keys = Object.keys(m).sort().join(',');
45
+ if (keys !== 'addedAt,calls,friendlyName,from,tree,version') return 'an entry has other fields than tree, version, friendlyName, addedAt, from and calls';
46
+ if (!TREE.test(m.tree)) return 'tree is not a sha256';
47
+ if (!isString(m.version, 64)) return 'version is not a string';
48
+ if (!isString(m.friendlyName, 64)) return 'friendlyName is not a string';
49
+ if (typeof m.addedAt !== 'string' || !ISO.test(m.addedAt)) return 'addedAt is not an instant';
50
+ if (!isString(m.from, 4096) || !path.isAbsolute(m.from)) return 'from is not an absolute path';
51
+ if (!listOf(m.calls, ADDRESS)) return 'calls is not a list of addresses';
52
+ return null;
53
+ }
54
+
55
+ // -> why r is not an own-modules record, or null
56
+ function shapeProblem(r) {
57
+ if (!isObject(r) || r.v !== 1 || !isObject(r.modules) || Object.keys(r).sort().join(',') !== 'modules,v') return 'it is not {"v": 1, "modules": {...}}';
58
+ for (const [name, m] of Object.entries(r.modules)) {
59
+ if (!PACKAGE.test(name) || name.startsWith('@countinghouse/') || endsTrimmed(name)) return `${JSON.stringify(name.slice(0, 80))} is not an own module's package name`;
60
+ const p = entryProblem(m);
61
+ if (p != null) return `${name}: ${p}`;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ const ownError = (where, reason, code) => Object.assign(new Error(`${reason}; run \`${chLocal(where, 'status')}\` to see the own modules`), {code, reason});
67
+
68
+ // -> the record ({v: 1, modules}, a map with no prototype), or null with
69
+ // none. Throws OWN_RECORD_IO / OWN_RECORD_FORMAT for one that is there and
70
+ // can't be read as one: never taken for "none".
71
+ function readOwnRecord(where) {
72
+ let raw;
73
+ try {
74
+ raw = fs.readFileSync(where.ownRecord, 'utf8');
75
+ } catch (err) {
76
+ if (err.code === 'ENOENT') return null;
77
+ throw ownError(where, `${where.ownRecord} is not readable (${err.code})`, 'OWN_RECORD_IO');
78
+ }
79
+ let r;
80
+ try { r = JSON.parse(raw); } catch (err) { r = null; }
81
+ const problem = shapeProblem(r);
82
+ if (problem != null) throw ownError(where, `${where.ownRecord} is not ch-local's own-modules record (${problem})`, 'OWN_RECORD_FORMAT');
83
+ const modules = Object.create(null);
84
+ for (const [name, m] of Object.entries(r.modules)) modules[name] = {...m, calls: [...m.calls]};
85
+ return {v: 1, modules};
86
+ }
87
+
88
+ // Writes the record whole, atomically; refuses one it would refuse to read.
89
+ // The caller holds packs.lock.
90
+ function writeOwnRecord(where, record) {
91
+ const problem = shapeProblem(record);
92
+ if (problem != null) throw new Error(`refused to write the own-modules record: ${problem}`);
93
+ writeAtomic(where.ownRecord, `${JSON.stringify({v: 1, modules: record.modules}, null, 2)}\n`);
94
+ }
95
+
96
+ module.exports = {readOwnRecord, writeOwnRecord, shapeProblem, entryProblem, TREE};