@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,344 @@
1
+ 'use strict';
2
+ // ch-local credentials add <module> (at a terminal)
3
+ // ch-local credentials add <module> --to <origin> (the value on standard input)
4
+ // ch-local credentials list
5
+ // ch-local credentials remove <module>
6
+ //
7
+ // A credential is bound to one module (#413 sections 6.2, 6.3 and 6.8; L5a):
8
+ // the value, for this module's credential of this name, to this origin
9
+ // (lib/credential-store.js). The module must be installed and must declare
10
+ // a credential; add reads the declaration from its active version in the
11
+ // module store (lib/module-credentials.js) and shows the variable and the
12
+ // origin before it asks anything: what the user sees before typing is where
13
+ // the key will go.
14
+ //
15
+ // - At a terminal, the gh login is offered only for exactly
16
+ // https://api.githubcopilot.com (whole origin: scheme, host and port), only
17
+ // when gh has one, default No; a yes stores no value (the source gh: each
18
+ // start asks gh). Otherwise the value is read with nothing echoed.
19
+ // - On standard input (not a terminal): --to <origin> is required and must
20
+ // equal the declared origin; it never replaces a binding for another
21
+ // origin or variable (a rotated key for the same destination is fine);
22
+ // one line, at most 4096 bytes, no gh offer and no question.
23
+ // - A value is never taken from an argument or the environment, never
24
+ // printed, logged or recorded. An argument that is not an installed
25
+ // module's name is never shown back (a token typed in its place would be).
26
+ // - add and remove ask a running daemon to restart its runtime (it drains
27
+ // first), and say what a session on a runtime of its own sees.
28
+ const {layout} = require('./home');
29
+ const store = require('./credential-store');
30
+ const mc = require('./module-credentials');
31
+ const {readModulesRecord} = require('./module-record');
32
+ const {chLocal, hintCommand} = require('./command-line');
33
+
34
+ class Refused extends Error {}
35
+ const short = (name) => String(name).replace(/^@[^/]+\//, '');
36
+ // (where: the home's layout, for the commands' launcher form:
37
+ // lib/command-line.js)
38
+ const notOne = (where, platform) => `that is not an installed module that declares a credential; \`${chLocal(where, 'credentials list', platform)}\` and \`${chLocal(where, 'status', platform)}\` show them. Nothing was changed.`;
39
+ const MAX_LINE = 4096;
40
+
41
+ // The installed module an argument names: its package name, or a short name
42
+ // one installed module has. -> name | null; throws Refused for a short name
43
+ // two share (the full names are the user's to give).
44
+ // where: the home, whose own modules count too (B-own-add)
45
+ function moduleNamed(record, arg, where = null) {
46
+ const packNames = Object.keys((record && record.modules) || {});
47
+ const names = packNames.concat(where != null ? Object.keys(mc.ownModules(where)).filter((n) => !packNames.includes(n)) : []);
48
+ if (names.includes(arg)) return arg;
49
+ const matches = names.filter((n) => short(n) === arg);
50
+ if (matches.length > 1) throw new Refused(`more than one installed module is named ${arg}: ${matches.join(', ')}; give the full name`);
51
+ return matches.length === 1 ? matches[0] : null;
52
+ }
53
+
54
+ // a version 1 file is migrated as it is written (section 10), so its other
55
+ // entries carry over
56
+ const migrateFor = (where, record) => (read) => mc.migrateV1(read, mc.declarations(where, record));
57
+
58
+ // {action: 'list' | 'add' | 'remove', name?, to?}, io -> exit code
59
+ // After a change: a running daemon is asked to restart its runtime (it
60
+ // drains first), and what a session on a runtime of its own sees is said.
61
+ async function restartAfter(where, io, say, change) {
62
+ let asked = false;
63
+ try { asked = await require('./daemon-requests').requestRestart(where.home, {io}); } catch (e) { asked = false; }
64
+ // (the shared runtime named only when one serves this home: never sending
65
+ // a home with none, a first install's included, to a restart that answers
66
+ // "no shared runtime" -- the reviewer's high on #147, M4)
67
+ let serving = false;
68
+ try { serving = (await require('./daemon').daemonServing(where.home, {platform: io.platform, probePipe: io.probePipe || null})).serving; } catch (e) { serving = false; }
69
+ if (serving && asked) say('The shared runtime restarts once its calls finish (it drains first).');
70
+ // (not asked: its way said, never left on the old key -- the medium on A5, 9)
71
+ else if (serving) say(`The shared runtime was not asked to restart: run \`${require('./command-line').chLocal(where, 'restart')}\` to make it take the change.`);
72
+ // (a key left by a module no longer installed: no session has the module)
73
+ if (change === 'removed, not installed') return;
74
+ say(change === 'removed'
75
+ ? 'A session on a runtime of its own unloads the module at once; adding the key it started with loads it again there, another one at its client\'s next start.'
76
+ : 'A session on a runtime of its own takes it at its client\'s next start (a changed key unloads the module there at once).');
77
+ }
78
+
79
+ // restart: false leaves the restart to the caller (install's end asks once,
80
+ // after every module: the Reviewer's high review of L5a, 7)
81
+ async function credentials({action, name, to = null, restart: restartNow = true}, io) {
82
+ const where = layout(io.env, io.homedir);
83
+ const opts = {platform: io.platform || process.platform};
84
+ const fail = (text, code = 1) => { io.stderr.write(`ch-local credentials: ${text}\n`); return code; };
85
+ const say = (text) => io.stdout.write(`${text}\n`);
86
+ // where a key goes reaches the person, beside the prompts: standard
87
+ // error, never standard output (`install > log` would hide it; the Fable
88
+ // pass on L5a, F2)
89
+ const show = (text) => io.stderr.write(`${text}\n`);
90
+ const history = (entry) => {
91
+ try { require('./history').appendHistory(where, {by: 'credentials', ...entry}, {host: io.hostname, pid: io.pid}); } catch (e) { /* history is a record, never in the way */ }
92
+ };
93
+ const restart = async(change) => { if (restartNow) await restartAfter(where, io, say, change); };
94
+ try {
95
+ let record;
96
+ try { record = readModulesRecord(where); } catch (e) { return fail(`${e.message}. Nothing was changed.`); }
97
+ // list and remove work with nothing installed: a key a removed module
98
+ // left is still listed, and still removable (the /code-review medium on
99
+ // L5a, 2)
100
+ if (record == null && action === 'add') return fail(`nothing is installed; run ${hintCommand(where, 'install --pack <name>', opts.platform)} first. Nothing was changed.`);
101
+ const rec = record != null ? record : {modules: {}};
102
+ if (action === 'list') return list(where, rec, opts, say);
103
+ // an argument that is not an installed module is never shown back
104
+ const module = name != null ? moduleNamed(rec, name, where) : null;
105
+ const how = io.terminal === true ? 'terminal' : 'stdin';
106
+ if (action === 'remove') {
107
+ // read, judged and written under the store's lock, the record read
108
+ // again there (post-rel cred-race: a remove made beside another add
109
+ // or remove is never undone by it)
110
+ let removed = null;
111
+ const code = await store.withStoreLock(where.home, io, 'ch-local credentials remove', async(held) => {
112
+ let now;
113
+ try { now = readModulesRecord(where); } catch (e) { return fail(`${e.message}. Nothing was changed.`); }
114
+ const r = now != null ? now : {modules: {}};
115
+ const before = mc.bindings(where, r, opts);
116
+ if (before.problem != null) return fail(`the stored credentials are not used (${before.problem}). Nothing was changed.`);
117
+ // an installed module, or one the store still holds a key for (by
118
+ // its full name, or a short name one stored module has)
119
+ const installedName = name != null ? moduleNamed(r, name, where) : null;
120
+ const removing = installedName != null ? installedName : moduleNamed({modules: Object.fromEntries([...before.bindings.keys()].map((m) => [m, {}]))}, name);
121
+ if (removing == null) return fail(notOne(where, opts.platform), 2);
122
+ const had = before.bindings.get(removing);
123
+ if (!store.unbind(where.home, removing, {...opts, held, migrate: migrateFor(where, r)})) { say(`no credential is stored for ${short(removing)}`); return 0; }
124
+ // (the name it was stored under: a key read from GitHub's earlier
125
+ // name is recorded as removed under that name, the medium on #98's
126
+ // cut, 6)
127
+ const storedAs = new Map((before.carried || []).filter((c) => c.module === removing).map((c) => [c.to, c.from]));
128
+ for (const [variable, b] of had || []) history({module: removing, variable: storedAs.has(variable) ? storedAs.get(variable) : variable, origin: b.origin, source: b.source, how, change: 'removed'});
129
+ say(`the stored credential for ${short(removing)} is removed`);
130
+ removed = installedName != null ? 'removed' : 'removed, not installed';
131
+ return 0;
132
+ // (no home: never the argument shown back, which may be a pasted key;
133
+ // the reviewer's high on #102, 1)
134
+ }, {missing: () => fail(notOne(where, opts.platform), 2)});
135
+ if (removed != null) await restart(removed);
136
+ return code;
137
+ }
138
+ if (action !== 'add') return fail('the actions are list, add and remove', 2);
139
+ const decl = module != null ? mc.declared(where, record, module) : null;
140
+ if (module == null || decl == null) return fail(notOne(where, opts.platform), 2);
141
+ if (decl.problem != null) return fail(`${short(module)}: ${decl.problem}. Nothing was changed.`, 2);
142
+ // a pack module's version, an own module's code (B-own-add)
143
+ const at = mc.installedAt(where, record, module);
144
+ const version = at.label;
145
+ // the directory and any file there checked before anything is typed
146
+ const before = mc.bindings(where, record, opts);
147
+ if (before.problem != null) return fail(`the stored credentials are not used (${before.problem}). Nothing was changed.`);
148
+ const vars = before.bindings.get(module);
149
+ const other = vars != null ? [...vars].find(([v, b]) => v !== decl.variable || b.origin !== decl.origin) : null;
150
+
151
+ // The key is asked for before the lock (no lock held while a person
152
+ // types); under it, everything judged above is judged again on what is
153
+ // there now, and the store read there is the one written (post-rel
154
+ // cred-race). A module uninstalled meanwhile: nothing stored (uninstall
155
+ // removes the record under this lock). A version changed meanwhile:
156
+ // install, add-pack and rollback hold packs.lock only, so the check here
157
+ // is not atomic against them; a binding that no longer matches what the
158
+ // module declares is refused at start (the reviewer's high on #102, 5).
159
+ const keep = async(entry) => {
160
+ const code = await store.withStoreLock(where.home, io, 'ch-local credentials add', async(held) => {
161
+ let now;
162
+ try { now = readModulesRecord(where); } catch (e) { return fail(`${e.message}. Nothing was stored.`); }
163
+ const changed = `changed while the key was being entered; run \`${addCommand(where, module, opts.platform)}\` again. Nothing was stored.`;
164
+ const atNow = now != null ? mc.installedAt(where, now, module) : null;
165
+ if (atNow == null) return fail(`${short(module)} is no longer installed; nothing was stored`);
166
+ if (atNow.id !== at.id) return fail(`${short(module)} ${changed}`);
167
+ const declNow = mc.declared(where, now, module);
168
+ if (declNow == null || declNow.problem != null || declNow.variable !== decl.variable || declNow.origin !== decl.origin) return fail(`${short(module)}'s declared credential ${changed}`);
169
+ const read = mc.bindings(where, now, opts);
170
+ if (read.problem != null) return fail(`the stored credentials are not used (${read.problem}). Nothing was changed.`);
171
+ const varsNow = read.bindings.get(module);
172
+ const otherNow = varsNow != null ? [...varsNow].find(([v, b]) => v !== decl.variable || b.origin !== decl.origin) : null;
173
+ // on standard input, never re-bind another destination: judged on
174
+ // the store as it is now
175
+ if (how === 'stdin' && otherNow != null) {
176
+ return fail(`the credential stored for ${short(module)} does not match this version: ${mc.declarationChange(decl, otherNow[0], otherNow[1].origin).reason}; run \`${addCommand(where, module, opts.platform)}\` at a terminal to allow that. Nothing was changed.`, 2);
177
+ }
178
+ const hadNow = varsNow != null ? varsNow.get(decl.variable) : null;
179
+ store.bind(where.home, module, decl.variable, entry, {...opts, held, migrate: migrateFor(where, now)});
180
+ history({module, variable: decl.variable, origin: decl.origin, source: entry.source, how, change: hadNow != null || otherNow != null ? 'replaced' : 'added'});
181
+ return 0;
182
+ }, {missing: () => fail(`nothing is installed; run ${hintCommand(where, 'install --pack <name>', opts.platform)} first. Nothing was stored.`)});
183
+ if (code !== 0) return code;
184
+ show(entry.source === 'gh'
185
+ ? `stored for ${short(module)}: your gh login's token, asked at each start, sent to ${decl.origin}`
186
+ : `stored for ${short(module)}: ${decl.variable}, sent to ${decl.origin}; readable by this user only (another program running as this user can read it, as it can read gh's own token)`);
187
+ await restart('added');
188
+ return 0;
189
+ };
190
+
191
+ // an origin given is checked wherever the key comes from (the
192
+ // /code-review medium on L5a, 4)
193
+ if (to != null && to !== decl.origin) return fail(`${short(module)} ${version} sends its credential to ${decl.origin}, not the address given. Nothing was stored.`, 2);
194
+ if (io.terminal === true && typeof io.readHidden === 'function') {
195
+ show(`${short(module)} ${version} declares one credential:`);
196
+ show(` ${decl.variable}, sent to ${decl.origin}${decl.remote != null ? ` (its remote "${decl.remote}")` : ''}`);
197
+ if (other != null) show(`the stored credential for ${short(module)}: ${mc.declarationChange(decl, other[0], other[1].origin).reason}`);
198
+ if (decl.origin === mc.GH_ORIGIN) {
199
+ const gh = await require('./github-token').ghToken(io, where.home);
200
+ if (gh.token != null) {
201
+ // the y/N read hidden, as the key is: a key pasted here is never
202
+ // echoed (the reviewer's targeted high, 11-21); anything but y or n
203
+ // is no, said without showing it
204
+ let answer;
205
+ try {
206
+ answer = String(await io.readHidden(`Use your gh login's token for ${short(module)}? [y/N] (input hidden): `)).trim();
207
+ } catch (e) {
208
+ // any read that failed ends here: a paste too long leaves its
209
+ // tail for the next hidden read, which would take it as the key
210
+ // (the medium on B-shim-allow)
211
+ if (e.code === 'ABORTED') return fail('nothing was entered; nothing was stored');
212
+ return fail(`the answer could not be read (${e.code || 'an error'}); nothing was stored`);
213
+ }
214
+ if (/^y(es)?$/i.test(answer)) return await keep({origin: decl.origin, source: 'gh'});
215
+ if (!/^(n(o)?)?$/i.test(answer)) show('that was not y or n, so your gh login\'s token is not used (what was typed is not kept or shown)');
216
+ }
217
+ }
218
+ let value;
219
+ try {
220
+ value = await io.readHidden(`${decl.variable} for ${short(module)} (input hidden): `);
221
+ } catch (e) {
222
+ return fail(e.code === 'ABORTED' ? 'nothing was entered; nothing was stored' : e.code === 'TOO_LONG' ? `that was ${e.message}; nothing was stored` : 'the input could not be read; nothing was stored');
223
+ }
224
+ // an empty answer stores nothing (install's end skips the module)
225
+ if (value === '') return fail('nothing was entered; nothing was stored');
226
+ return await keep({origin: decl.origin, source: 'stored', value});
227
+ }
228
+ // on standard input nobody is looking at a prompt: the caller states the
229
+ // destination, and ch-local checks it
230
+ // a terminal on standard input but not both ways (its output
231
+ // redirected): the key would echo as it is typed (the /code-review
232
+ // medium on L5a, 3)
233
+ if (io.stdinIsTTY === true) return fail('a key is typed only at a terminal both ways (its prompt seen, its typing hidden), or piped in; standard input is a terminal here but the output is not. Nothing was stored.', 2);
234
+ if (to == null) return fail(`a key on standard input needs \`--to <origin>\`: the address it is for (\`${chLocal(where, 'credentials list', opts.platform)}\` shows what ${short(module)} declares). Nothing was stored.`, 2);
235
+ if (other != null) {
236
+ return fail(`the credential stored for ${short(module)} does not match this version: ${mc.declarationChange(decl, other[0], other[1].origin).reason}; run \`${addCommand(where, module, opts.platform)}\` at a terminal to allow that. Nothing was changed.`, 2);
237
+ }
238
+ if (typeof io.readStdin !== 'function') return fail('standard input could not be read; nothing was stored');
239
+ let text;
240
+ try {
241
+ text = await io.readStdin(MAX_LINE + 2);
242
+ } catch (e) {
243
+ if (e.code === 'TOO_LONG') return fail(`a key on standard input is one line of at most ${MAX_LINE} bytes; nothing was stored`, 2);
244
+ return fail(e.code === 'TIMEOUT' ? `${e.message}: pipe the key in, one line, and close the input. Nothing was stored.` : 'standard input could not be read; nothing was stored');
245
+ }
246
+ const line = String(text == null ? '' : text).replace(/\r?\n$/, '');
247
+ // an input that ended with nothing in it (/dev/null, an empty pipe)
248
+ if (line === '') return fail('standard input held no key; pipe it in, one line. Nothing was stored.', 2);
249
+ if (line.includes('\n') || Buffer.byteLength(line) > MAX_LINE) return fail(`a key on standard input is one line of at most ${MAX_LINE} bytes; nothing was stored`, 2);
250
+ return await keep({origin: decl.origin, source: 'stored', value: line});
251
+ } catch (e) {
252
+ if (e instanceof store.StoreProblem || e instanceof Refused) return fail(`${e.message.replace(/[;.]? *[Nn]othing was (changed|stored)\.?$/, '')}. Nothing was changed.`);
253
+ throw e;
254
+ }
255
+ }
256
+
257
+ // A module's binding as a start would use it: for its declared variable and
258
+ // origin (a gh one counts: gh is asked at start). -> the binding or null.
259
+ function bindingFor(read, module, decl) {
260
+ if (read.bindings == null || decl == null || decl.problem != null) return null;
261
+ const vars = read.bindings.get(module);
262
+ const b = vars != null ? vars.get(decl.variable) : null;
263
+ // a gh login only ever for GitHub's origin: a hand-written pairing is no
264
+ // usable binding here either (the Reviewer's round 3, 6)
265
+ if (b != null && b.source === 'gh' && decl.origin !== store.GH_ORIGIN) return null;
266
+ return b != null && b.origin === decl.origin ? b : null;
267
+ }
268
+
269
+ // install's and add-pack's end (#413 section 6.2; L5a): each of `modules`
270
+ // (installed now) that declares a credential and has none stored for it. At
271
+ // a terminal the add conversation runs for it (the gh offer first where it
272
+ // applies; nothing entered skips it); otherwise one line says how to add
273
+ // it. Never fails the install. -> nothing.
274
+ // The command that adds a module's credential, as the person runs it in
275
+ // their own terminal: the home's own launcher, which runs as printed
276
+ // (nothing puts ch-local on PATH after an npx or a folder install;
277
+ // A-firstrun d1, the fixed text business checked)
278
+ // The launcher as the runtime's overview names it too (lib/home.js
279
+ // safeLauncher: a real path a shell reads as written, or none); with none,
280
+ // the bare form, which still names the command
281
+ const addCommand = (where, m, platform) => chLocal(where, `credentials add ${short(m)}`, platform);
282
+ const credentialLine = (where, m, platform) => `${short(m)} needs a credential: in your own terminal run \`${addCommand(where, m, platform)}\``;
283
+ // a line askMissing printed for a module with none (auto-apply carries them
284
+ // into its result)
285
+ // (the npx form too, a home's hint before its launcher exists, built from
286
+ // the one NPX form, with the home before it when it isn't the default; the
287
+ // bare form kept: A11 and its medium, 6, and the follow-up's medium, 2)
288
+ const NPX_RE = require('./command-line').NPX.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
289
+ const CREDENTIAL_LINE = new RegExp(`^\\S+ needs a credential: in your own terminal run \`(?:node "[^"]+" |(?:COUNTINGHOUSE_HOME="[^"]+" )?${NPX_RE} |ch-local )credentials add [^\`]+\`$`);
290
+ const isCredentialLine = (l) => CREDENTIAL_LINE.test(l);
291
+
292
+ async function askMissing(io, modules) {
293
+ // (standard error: what a module needs reaches the person: F2)
294
+ const say = (text) => io.stderr.write(`${text}\n`);
295
+ const where = layout(io.env, io.homedir);
296
+ let record;
297
+ try { record = readModulesRecord(where); } catch (e) { return; }
298
+ if (record == null) return;
299
+ const opts = {platform: io.platform || process.platform};
300
+ const read = mc.bindings(where, record, opts);
301
+ if (read.problem != null) { say(`the stored credentials are not used (${read.problem}); \`${chLocal(where, 'credentials list', opts.platform)}\` shows them`); return; }
302
+ const atTerminal = io.terminal === true && typeof io.readHidden === 'function';
303
+ let added = 0;
304
+ for (const m of modules) {
305
+ const decl = mc.declared(where, record, m);
306
+ if (decl == null || decl.problem != null || bindingFor(read, m, decl) != null) continue;
307
+ if (!atTerminal) { say(credentialLine(where, m, opts.platform)); continue; }
308
+ if (await credentials({action: 'add', name: m, restart: false}, io) === 0) added += 1;
309
+ else say(`${short(m)} is not loaded until it has one: in your own terminal run \`${addCommand(where, m, opts.platform)}\``);
310
+ }
311
+ // one restart, and one pair of sentences, for all of them
312
+ if (added > 0) await restartAfter(where, io, (text) => io.stdout.write(`${text}\n`), 'added');
313
+ }
314
+
315
+ // list (section 6.2): per binding, the module, the variable, the origin, the
316
+ // source and whether the installed version still declares that destination;
317
+ // for an installed module with none, what it declares (so --to can be
318
+ // written). Never a value.
319
+ function list(where, record, opts, say) {
320
+ const decls = mc.declarations(where, record);
321
+ const read = mc.bindings(where, record, opts);
322
+ if (read.problem != null) say(`the stored credentials are not used (${read.problem})`);
323
+ const bound = read.bindings != null ? read.bindings : new Map();
324
+ const byName = ([a], [b]) => (a < b ? -1 : 1);
325
+ let any = false;
326
+ for (const [m, vars] of [...bound].sort(byName)) {
327
+ const d = decls.get(m);
328
+ for (const [variable, b] of vars) {
329
+ any = true;
330
+ const still = d != null && d.problem == null && d.variable === variable && d.origin === b.origin;
331
+ const state = d == null ? 'not installed, or it declares no credential now' : still ? 'its installed version sends it here' : `its installed version sends ${d.variable} to ${d.origin} instead`;
332
+ say(`${short(m)} ${variable} ${b.origin} ${b.source === 'gh' ? 'gh login' : 'stored'} (${state})`);
333
+ }
334
+ }
335
+ for (const [m, d] of [...decls].sort(byName)) {
336
+ if (bound.has(m) || d.problem != null) continue;
337
+ any = true;
338
+ say(`${short(m)} ${d.variable} ${d.origin} none stored (\`${addCommand(where, m, opts.platform)}\`)`);
339
+ }
340
+ if (!any) say('no installed module declares a credential');
341
+ return 0;
342
+ }
343
+
344
+ module.exports = {credentials, moduleNamed, askMissing, addCommand, credentialLine, isCredentialLine};
@@ -0,0 +1,137 @@
1
+ 'use strict';
2
+ // <home>/run/daemon/requests (countinghouse's shared-runtime design, #236,
3
+ // section 6, "Upgrade"): an install or upgrade that changed the home appends
4
+ // one JSON line, {"op": "upgrade", "at": <epoch ms>}, which a running daemon
5
+ // watches. It then restarts its runtime, or itself, onto what was installed.
6
+ //
7
+ // - Written only into a private daemon directory (0700, this user's, not a
8
+ // link), appended at 0600, opened O_NOFOLLOW, so never through a link.
9
+ // - Read with the same private-file checks as the secret (lib/private-file.js),
10
+ // from an offset. A line not yet ended waits, and a bad line or an unknown op
11
+ // is skipped.
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+ // (as the module, so the read can be counted: test/daemon-requests.test.js)
15
+ const privateFile = require('./private-file');
16
+
17
+ const NAME = 'requests';
18
+ const MAX_BYTES = 1024 * 1024;
19
+ // upgrade: what is installed changed; restart: a stored credential changed,
20
+ // or `ch-local restart` (A5)
21
+ const OPS = ['upgrade', 'restart'];
22
+
23
+ // on Windows the directory's owner and DACL by privateProblem, as a
24
+ // directory (the review of #39); platform and fileAcl: for the tests
25
+ function privateDir(dir, {platform = process.platform, fileAcl = null} = {}) {
26
+ try {
27
+ const st = fs.lstatSync(dir);
28
+ if (!st.isDirectory() || st.isSymbolicLink()) return false;
29
+ if (platform === 'win32') {
30
+ const winAcl = require('./win-acl');
31
+ return winAcl.privateProblem(dir, (fileAcl || winAcl.fileAcl)(dir), {directory: true}) == null;
32
+ }
33
+ return (st.mode & 0o777) === 0o700 && (typeof process.geteuid !== 'function' || st.uid === process.geteuid());
34
+ } catch (e) {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ // -> Promise<whether the request was written> (no daemon directory: nothing
40
+ // to tell). Appended under start.lock, which the daemon holds while it
41
+ // empties the file, so a request is never lost between its read and the
42
+ // truncation.
43
+ // signal: ends a wait on start.lock (a command's bound: the reviewer's high
44
+ // on #147, L3); underLock: run after the line is appended, still under the
45
+ // lock (restart reads its baseline there: M2). -> whether it was written
46
+ async function requestUpgrade(home, {now = () => Date.now(), io = {stderr: {write: () => {}}}, op = 'upgrade', platform, fileAcl, signal = null, underLock = null} = {}) {
47
+ const dir = path.join(home, 'run', 'daemon');
48
+ if (!privateDir(dir, {platform, fileAcl})) return false;
49
+ const {withLockFile} = require('./lock');
50
+ let written = false;
51
+ await withLockFile(path.join(dir, 'start.lock'), dir, io, async() => {
52
+ written = append(dir, now, op);
53
+ if (written && typeof underLock === 'function') underLock();
54
+ return 0;
55
+ }, {wait: true, what: 'to finish its start or stop', signal});
56
+ return written;
57
+ }
58
+
59
+ function append(dir, now, op = 'upgrade') {
60
+ let fd = null;
61
+ try {
62
+ fd = fs.openSync(path.join(dir, NAME), fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW || 0), 0o600);
63
+ if (process.platform !== 'win32') fs.fchmodSync(fd, 0o600);
64
+ fs.writeSync(fd, `${JSON.stringify({op: OPS.includes(op) ? op : 'upgrade', at: now()})}\n`);
65
+ return true;
66
+ } catch (e) {
67
+ return false;
68
+ } finally {
69
+ if (fd != null) fs.closeSync(fd);
70
+ }
71
+ }
72
+
73
+ // the daemon, under start.lock, once it has read every whole line: the file
74
+ // emptied (only if nothing was appended after `offset`) -> whether it was
75
+ function emptyRequests(home, offset) {
76
+ const file = path.join(home, 'run', 'daemon', NAME);
77
+ let fd = null;
78
+ try {
79
+ fd = fs.openSync(file, fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW || 0));
80
+ if (fs.fstatSync(fd).size !== offset) return false;
81
+ fs.ftruncateSync(fd, 0);
82
+ return true;
83
+ } catch (e) {
84
+ return false;
85
+ } finally {
86
+ if (fd != null) fs.closeSync(fd);
87
+ }
88
+ }
89
+
90
+ // -> {requests: [{op, at}], offset, size}: the whole lines after `offset`;
91
+ // on any check that fails, none, and the offset unchanged. size: the file's,
92
+ // as stat saw it; seen: the size the last read saw, when its read was
93
+ // refused or left a partial line (the daemon passes it back) -- a file at
94
+ // that size again isn't read again until it changes (the medium on A2, 1)
95
+ function readRequests(home, offset, seen = null) {
96
+ // (a stat first: the daemon polls every second, and on Windows each
97
+ // private read is a synchronous PowerShell run -- A2. A file not there,
98
+ // at the offset, or at the size the last read already saw is not read;
99
+ // any other size is read by every check. A stat decides only whether to
100
+ // read: a same-size replacement waits for its next append, as before)
101
+ let st;
102
+ try { st = fs.lstatSync(path.join(home, 'run', 'daemon', NAME)); } catch (e) { return {requests: [], offset, size: null}; }
103
+ if (st.size === offset || st.size === seen) return {requests: [], offset, size: st.size};
104
+ let bytes;
105
+ // (a read refused -- on Windows, a PowerShell run timed out -- is said as
106
+ // refused: the daemon tries it again, never waiting for the size to
107
+ // change, or a request written once is ignored -- the closing pass, M2)
108
+ try {
109
+ bytes = privateFile.readPrivateIn(path.join(home, 'run', 'daemon'), NAME, MAX_BYTES);
110
+ } catch (e) {
111
+ return {requests: [], offset, size: st.size, refused: true, why: e.code || 'unreadable'};
112
+ }
113
+ let replaced = false;
114
+ if (bytes.length < offset) { offset = 0; replaced = true; } // the file was replaced
115
+ // (lines found in the bytes themselves, so every offset is a byte
116
+ // position whatever a line holds -- the medium on #147's last round, 9)
117
+ const end = bytes.lastIndexOf(0x0a);
118
+ if (end < offset) return {requests: [], offset, size: st.size};
119
+ // (each request with the byte offset its line ends at: the daemon tells a
120
+ // request written before its runtime last started without a clock -- the
121
+ // reviewer's high on #147, R3)
122
+ const requests = [];
123
+ for (let from = offset; from <= end;) {
124
+ const nl = bytes.indexOf(0x0a, from);
125
+ const line = bytes.subarray(from, nl).toString('utf8');
126
+ from = nl + 1;
127
+ let m = null;
128
+ try { m = JSON.parse(line); } catch (e) { continue; }
129
+ if (m != null && typeof m === 'object' && OPS.includes(m.op) && Number.isSafeInteger(m.at)) requests.push({op: m.op, at: m.at, end: from});
130
+ }
131
+ return {requests, offset: end + 1, size: st.size, replaced};
132
+ }
133
+
134
+ // a running daemon restarts its runtime (a credential stored or removed)
135
+ const requestRestart = (home, opts = {}) => requestUpgrade(home, {...opts, op: 'restart'});
136
+
137
+ module.exports = {requestUpgrade, requestRestart, readRequests, emptyRequests, NAME};