@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,287 @@
1
+ 'use strict';
2
+ // The shared runtime's log (C-daemon-log): <home>/run/daemon/runtime.log.
3
+ // The daemon writes its own lines there, and a shared runtime's stdout and
4
+ // stderr (under --sessionSocket countinghouse serves MCP on the session
5
+ // socket; its stdout carries only its log), each of the runtime's prefixed
6
+ // "[runtime] ". The shim starts the daemon with its output discarded, so
7
+ // without this file a shared runtime logs nowhere.
8
+ //
9
+ // - Private: in run/daemon (made private by ensureRunDir). POSIX opened
10
+ // O_APPEND|O_CREAT|O_NOFOLLOW|O_NONBLOCK at 0600 (a FIFO there never
11
+ // blocks the open); Windows created exclusively (it takes run/daemon's
12
+ // inherited owner-only DACL, with no PowerShell), or an existing one opened
13
+ // without O_CREAT after win-acl's privateProblem accepts its DACL (at the
14
+ // open only: while running, a file found at the name is set aside unread
15
+ // and made anew, so no PowerShell runs on the running path). Once
16
+ // open: a regular file, the one the name names, with one link; on POSIX
17
+ // this user's, at most 0600. One that isn't is set aside as runtime.log.1,
18
+ // never appended to, and a fresh one made; said in it.
19
+ // - Bounded by size alone: past CAP_BYTES the daemon that has the home (own())
20
+ // renames it runtime.log.1, one kept, and goes on in a fresh one; any other
21
+ // opener (a hand-over's daemon before it has the home, a second daemon that
22
+ // finds one serving) only appends. A rename that fails (on Windows a file
23
+ // another process holds) is never fatal: lines go on, it is tried again at
24
+ // the next line, and past twice the cap lines are dropped and counted. A
25
+ // log removed or moved meanwhile is opened again at its name (checked every
26
+ // CHECK_MS). Lines are cut at LINE_CAP bytes (on a character's boundary),
27
+ // with a marker; control characters but tab become "?", so no line can
28
+ // move a terminal's cursor or pass for another.
29
+ // - Never in the runtime's way: every line read from it is taken at once;
30
+ // the writes are queued, and past PENDING_MAX queued, or when a write
31
+ // fails, lines are dropped, counted, and said ("<n> lines dropped") in
32
+ // their place, before the next line kept.
33
+ const fs = require('node:fs');
34
+ const path = require('node:path');
35
+
36
+ const NAME = 'runtime.log';
37
+ const CAP_BYTES = 5 * 1024 * 1024;
38
+ const LINE_CAP = 8 * 1024;
39
+ const PENDING_MAX = 256 * 1024;
40
+ const CHECK_MS = 30 * 1000;
41
+
42
+ // a line as it is kept: control characters but tab as "?", at most lineCap
43
+ // bytes (cut on a character's boundary), the rest said as cut
44
+ function kept(line, lineCap) {
45
+ // eslint-disable-next-line no-control-regex
46
+ const clean = line.replace(/\r$/, '').replace(/[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, '?');
47
+ const b = Buffer.from(clean);
48
+ if (b.length <= lineCap) return clean;
49
+ let i = lineCap;
50
+ while (i > 0 && (b[i] & 0xc0) === 0x80) i--;
51
+ return `${b.subarray(0, i).toString('utf8')} …[cut: ${b.length - i} more bytes]`;
52
+ }
53
+
54
+ // an open fd at file: a regular file, the one the name names now (no link or
55
+ // junction swapped in), with one link; on POSIX this user's, at most 0600
56
+ // -> {fd, size} | {problem, aside} (fd closed)
57
+ function checked(file, fd, {platform, fsx}) {
58
+ let s;
59
+ let named;
60
+ try {
61
+ s = fsx.fstatSync(fd);
62
+ named = fsx.lstatSync(file);
63
+ } catch (e) {
64
+ try { fsx.closeSync(fd); } catch (e2) { /* closed */ }
65
+ return {problem: `it could not be read once open (${e.code || e.message})`};
66
+ }
67
+ const uid = platform !== 'win32' && typeof process.geteuid === 'function' ? process.geteuid() : null;
68
+ const why = !s.isFile() || named.isSymbolicLink() ? 'it is not a plain file'
69
+ : (s.ino !== named.ino || s.dev !== named.dev) ? 'it changed as it was opened'
70
+ : s.nlink !== 1 ? 'it has another name (a hard link)'
71
+ : (uid != null && s.uid !== uid) ? 'it is owned by another user'
72
+ : (platform !== 'win32' && ((s.mode & 0o777) & ~0o600) !== 0) ? `its mode is ${(s.mode & 0o777).toString(8)}, wider than 600` : null;
73
+ if (why != null) { try { fsx.closeSync(fd); } catch (e) { /* closed */ } return {problem: why, aside: true}; }
74
+ return {fd, size: s.size};
75
+ }
76
+
77
+ const C = fs.constants;
78
+ const POSIX_APPEND = C.O_WRONLY | C.O_APPEND | C.O_CREAT | (C.O_NOFOLLOW || 0) | (C.O_NONBLOCK || 0);
79
+
80
+ // file, opened for appending, private -> {fd, size} | {problem, aside}
81
+ // (aside: something is there that this must not append to)
82
+ function openPrivate(file, {platform, acl, fsx}) {
83
+ let st = null;
84
+ try { st = fsx.lstatSync(file); } catch (e) { if (e.code !== 'ENOENT') return {problem: `it could not be read (${e.code || e.message})`}; }
85
+ if (st != null && (st.isSymbolicLink() || !st.isFile())) return {problem: 'it is not a plain file', aside: true};
86
+ if (platform === 'win32') {
87
+ if (st == null) {
88
+ // (made exclusively: a second daemon that made it first is the
89
+ // existing-file case below)
90
+ try { return checked(file, fsx.openSync(file, 'ax'), {platform, fsx}); } catch (e) {
91
+ if (e.code !== 'EEXIST') return {problem: `it could not be made (${e.code || e.message})`};
92
+ }
93
+ try { st = fsx.lstatSync(file); } catch (e) { return {problem: `it could not be read (${e.code || e.message})`}; }
94
+ if (st.isSymbolicLink() || !st.isFile()) return {problem: 'it is not a plain file', aside: true};
95
+ }
96
+ const winAcl = acl || require('./win-acl');
97
+ try {
98
+ const problem = winAcl.privateProblem(NAME, winAcl.fileAcl(file));
99
+ if (problem != null) return {problem, aside: true};
100
+ } catch (e) { return {problem: `its access could not be checked (${e.code || e.message})`}; }
101
+ // (never O_CREAT: a link swapped in now makes nothing at its target)
102
+ let fd;
103
+ try { fd = fsx.openSync(file, C.O_WRONLY | C.O_APPEND); } catch (e) { return {problem: `it could not be opened (${e.code || e.message})`}; }
104
+ return checked(file, fd, {platform, fsx});
105
+ }
106
+ let fd;
107
+ try { fd = fsx.openSync(file, POSIX_APPEND, 0o600); } catch (e) {
108
+ return {problem: `it could not be opened (${e.code || e.message})`, aside: e.code === 'ELOOP' || e.code === 'ENXIO'};
109
+ }
110
+ return checked(file, fd, {platform, fsx});
111
+ }
112
+
113
+ // a file at file while the daemon runs (a rotation, a name found changed):
114
+ // created exclusively. One already there is, on POSIX, opened as any
115
+ // existing one; on Windows set aside unread and made anew, since judging its
116
+ // DACL runs PowerShell, which nothing on the running path waits for
117
+ function openFresh(file, {platform, acl, fsx, old}) {
118
+ const make = () => checked(file, platform === 'win32' ? fsx.openSync(file, 'ax') : fsx.openSync(file, POSIX_APPEND | C.O_EXCL, 0o600), {platform, fsx});
119
+ try { return make(); } catch (e) {
120
+ if (e.code !== 'EEXIST') return {problem: `a fresh one could not be made (${e.code || e.message})`};
121
+ }
122
+ if (platform !== 'win32') return openPrivate(file, {platform, acl, fsx});
123
+ try { fsx.renameSync(file, old); return make(); } catch (e) { return {problem: `a fresh one could not be made (${e.code || e.message})`}; }
124
+ }
125
+
126
+ // The log for a daemon in runDir, appended to as it is. own(): this daemon
127
+ // has the home, so it rotates at the cap. -> {file, write(text),
128
+ // forward(stream), own(), close(), note, problem}. note: something said about
129
+ // the file as it was opened; problem: it is not used (lines are taken and
130
+ // dropped).
131
+ function openRuntimeLog(runDir, {platform = process.platform, acl = null, fsx = fs, sink = null, cap = CAP_BYTES,
132
+ lineCap = LINE_CAP, pendingMax = PENDING_MAX, checkMs = CHECK_MS, now = () => new Date(), clock = () => Date.now()} = {}) {
133
+ const hardCap = 2 * cap;
134
+ const file = path.join(runDir, NAME);
135
+ const old = `${file}.1`;
136
+ const notes = [];
137
+ const stamp = (s) => `${now().toISOString()} ${s}`;
138
+ let opened = openPrivate(file, {platform, acl, fsx});
139
+ if (opened.problem != null && opened.aside) {
140
+ const why = opened.problem;
141
+ let moved = true;
142
+ try { fsx.renameSync(file, old); } catch (e) { moved = e.code === 'ENOENT'; }
143
+ opened = moved ? openPrivate(file, {platform, acl, fsx}) : {problem: `${why}, and it could not be set aside`};
144
+ if (opened.problem == null) notes.push(`the earlier ${NAME} was set aside as ${NAME}.1, unread: ${why}`);
145
+ }
146
+ let fd = opened.problem == null ? opened.fd : null;
147
+ let size = opened.problem == null ? opened.size : 0;
148
+ let owner = false;
149
+ let lastCheck = clock();
150
+ // every byte of buf, a short write going on from where it stopped
151
+ const writeAll = (d, buf, cb) => {
152
+ let off = 0;
153
+ const step = () => fsx.write(d, buf, off, buf.length - off, null, (err, n) => {
154
+ if (err) return cb(err);
155
+ off += n;
156
+ if (off >= buf.length) return cb(null);
157
+ if (n === 0) return cb(new Error('a write wrote nothing'));
158
+ step();
159
+ });
160
+ step();
161
+ };
162
+ const write = sink || writeAll;
163
+ const queue = []; // {buf, notice: the drop count it says, or 0}
164
+ let queued = 0;
165
+ let busy = false;
166
+ let dropped = 0;
167
+ let closing = null;
168
+ let ended = false; // closed: the fd is the queue's no more
169
+ let closeAfter = false; // closed while a write was out: the fd goes after it
170
+ const streams = new Set(); // (each forgotten once it ends)
171
+ const swap = (next) => { try { fsx.closeSync(fd); } catch (e) { /* closed */ } fd = next.fd; size = next.size; };
172
+ // past the cap, the owner only: the file becomes runtime.log.1 and a fresh
173
+ // one goes on; a rename that fails leaves it as it is, tried at the next
174
+ // line; one that worked, whose fresh file could not be made, is not made
175
+ // again (renamed: only the fresh file is tried next)
176
+ let renamed = false;
177
+ const rotate = () => {
178
+ if (!renamed) {
179
+ try { fsx.renameSync(file, old); } catch (e) { if (e.code !== 'ENOENT') return; }
180
+ renamed = true;
181
+ }
182
+ const next = openFresh(file, {platform, acl, fsx, old});
183
+ if (next.problem == null) { swap(next); renamed = false; }
184
+ };
185
+ // the name still names this file: one removed or moved is opened again
186
+ // (POSIX: through the checks; Windows: made anew, no PowerShell)
187
+ const recheck = () => {
188
+ lastCheck = clock();
189
+ let named = null;
190
+ let mine = null;
191
+ try { mine = fsx.fstatSync(fd); named = fsx.lstatSync(file); } catch (e) { named = null; }
192
+ if (named != null && mine != null && named.ino === mine.ino && named.dev === mine.dev) return;
193
+ const next = platform === 'win32' ? openFresh(file, {platform, acl, fsx, old}) : openPrivate(file, {platform, acl, fsx});
194
+ if (next.problem == null) swap(next);
195
+ };
196
+ const writeOne = (buf) => new Promise((resolve) => {
197
+ let done = false;
198
+ try {
199
+ write(fd, buf, (err) => { if (done) return; done = true; resolve(err == null); });
200
+ } catch (e) { done = true; resolve(false); }
201
+ });
202
+ const pump = async() => {
203
+ if (busy) return;
204
+ busy = true;
205
+ try {
206
+ while (queue.length > 0 && fd != null && !ended) {
207
+ const item = queue.shift();
208
+ queued -= item.buf.length;
209
+ if (clock() - lastCheck >= checkMs) recheck();
210
+ if (owner && (renamed || size + item.buf.length > cap)) rotate();
211
+ // (still past twice the cap: a rename that keeps failing, or a log
212
+ // this daemon may not rotate; dropped)
213
+ if (size + item.buf.length > hardCap) { dropped += item.notice || 1; continue; }
214
+ if (await writeOne(item.buf)) size += item.buf.length;
215
+ else dropped += item.notice || 1;
216
+ }
217
+ } finally {
218
+ busy = false;
219
+ // (never closed under a write still out: its fd number could be another
220
+ // file's by the time the write runs)
221
+ if (closeAfter && fd != null) { try { fsx.closeSync(fd); } catch (e) { /* closed */ } fd = null; }
222
+ if (closing != null && queue.length === 0) closing();
223
+ }
224
+ };
225
+ const push = (buf, notice) => { queue.push({buf, notice}); queued += buf.length; };
226
+ const take = (line) => {
227
+ const buf = Buffer.from(`${kept(line, lineCap)}\n`);
228
+ const notice = dropped > 0 ? Buffer.from(`${stamp(`[runtime log] ${dropped} lines dropped`)}\n`) : null;
229
+ if (fd == null || closing != null || queued + buf.length + (notice != null ? notice.length : 0) > pendingMax) { dropped++; return; }
230
+ // (the drops said where they were, before this line)
231
+ if (notice != null) { push(notice, dropped); dropped = 0; }
232
+ push(buf, 0);
233
+ pump().catch(() => { busy = false; if (closing != null) closing(); });
234
+ };
235
+ for (const n of notes) take(stamp(`[runtime log] ${n}`));
236
+ return {
237
+ file,
238
+ note: notes.length > 0 ? notes[0] : null,
239
+ problem: opened.problem != null ? `${file} is not used: ${opened.problem}` : null,
240
+ // the daemon's own lines (each stamped)
241
+ write(text) {
242
+ for (const line of String(text).split('\n')) if (line !== '') take(stamp(line));
243
+ return true;
244
+ },
245
+ // this daemon has the home: it rotates at the cap
246
+ own() { owner = true; },
247
+ // a runtime's stdout or stderr: whole lines, "[runtime] " first, each at
248
+ // most lineCap; read always, never paused; destroyed at close, so none
249
+ // keeps the daemon up, and forgotten once it ends
250
+ forward(stream) {
251
+ if (stream == null) return;
252
+ streams.add(stream);
253
+ stream.on('close', () => streams.delete(stream));
254
+ if (typeof stream.setEncoding === 'function') stream.setEncoding('utf8');
255
+ let partial = '';
256
+ let skipping = false;
257
+ const one = (p) => take(`[runtime] ${p}`);
258
+ stream.on('data', (chunk) => {
259
+ const parts = (partial + String(chunk)).split('\n');
260
+ partial = parts.pop();
261
+ for (const p of parts) { if (skipping) { skipping = false; continue; } one(p); }
262
+ if (Buffer.byteLength(partial) > lineCap) { if (!skipping) one(partial); partial = ''; skipping = true; }
263
+ });
264
+ stream.on('end', () => { if (partial !== '' && !skipping) one(partial); partial = ''; });
265
+ stream.on('error', () => { /* the runtime's end */ });
266
+ },
267
+ // the queued lines written (at most ms), then the file closed
268
+ close(ms = 1000) {
269
+ return new Promise((resolve) => {
270
+ const finish = () => {
271
+ for (const st of streams) { try { st.destroy(); } catch (e) { /* gone */ } }
272
+ ended = true;
273
+ if (busy) closeAfter = true;
274
+ else if (fd != null) { try { fsx.closeSync(fd); } catch (e) { /* closed */ } fd = null; }
275
+ resolve();
276
+ };
277
+ // (drops not yet said, said last)
278
+ if (dropped > 0 && fd != null && !ended) { push(Buffer.from(`${stamp(`[runtime log] ${dropped} lines dropped`)}\n`), dropped); dropped = 0; pump().catch(() => {}); }
279
+ const t = setTimeout(finish, ms);
280
+ closing = () => { clearTimeout(t); finish(); };
281
+ if (!busy && queue.length === 0) closing();
282
+ });
283
+ }
284
+ };
285
+ }
286
+
287
+ module.exports = {openRuntimeLog, NAME, CAP_BYTES, LINE_CAP, PENDING_MAX, CHECK_MS};
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+ // Whether the installed countinghouse runs --moduleSandbox enforce on this
3
+ // platform. Everywhere but Windows, always. On Windows, from countinghouse#195
4
+ // (#197: a module's files on a virtual drive), which brought
5
+ // lib/fs-broker/virtual-drive.js: a runtime without it refuses enforce there,
6
+ // so start runs audit, says so, and refuses an explicit enforce (ch-local
7
+ // #17), until `ch-local upgrade` installs one that can. Read from the files
8
+ // the runtime installed (what it has), not from a version number.
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+
12
+ function enforceAvailable(where, platform = process.platform) {
13
+ if (platform !== 'win32') return true;
14
+ return fs.existsSync(path.join(where.app, 'node_modules', 'countinghouse', 'lib', 'fs-broker', 'virtual-drive.js'));
15
+ }
16
+
17
+ module.exports = {enforceAvailable};
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+ // Semantic Versioning 2.0.0 precedence (section 11), prereleases included:
3
+ // 1.2.0-rc.1 < 1.2.0, 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-beta, numeric
4
+ // identifiers compare numerically and below alphanumeric ones; build
5
+ // metadata (+...) is ignored. Used to tell whose record a start holds
6
+ // (lib/packs.js recordRelease).
7
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
8
+ const NUMERIC = /^\d+$/;
9
+
10
+ function parse(v) {
11
+ const m = typeof v === 'string' ? SEMVER.exec(v) : null;
12
+ if (m == null) return null;
13
+ return {core: [m[1], m[2], m[3]].map(BigInt), pre: m[4] != null ? m[4].split('.') : []};
14
+ }
15
+
16
+ function compareIds(a, b) {
17
+ const an = NUMERIC.test(a);
18
+ const bn = NUMERIC.test(b);
19
+ if (an && bn) { const x = BigInt(a); const y = BigInt(b); return x < y ? -1 : x > y ? 1 : 0; }
20
+ if (an) return -1;
21
+ if (bn) return 1;
22
+ return a < b ? -1 : a > b ? 1 : 0;
23
+ }
24
+
25
+ // -> -1, 0 or 1 (a against b), or null when either is not a version
26
+ function compareVersions(a, b) {
27
+ const x = parse(a);
28
+ const y = parse(b);
29
+ if (x == null || y == null) return null;
30
+ for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
31
+ // a version with a prerelease is below the same version without one
32
+ if (x.pre.length === 0 || y.pre.length === 0) return x.pre.length === y.pre.length ? 0 : x.pre.length === 0 ? 1 : -1;
33
+ for (let i = 0; i < Math.min(x.pre.length, y.pre.length); i++) {
34
+ const c = compareIds(x.pre[i], y.pre[i]);
35
+ if (c !== 0) return c;
36
+ }
37
+ return x.pre.length === y.pre.length ? 0 : x.pre.length < y.pre.length ? -1 : 1;
38
+ }
39
+
40
+ module.exports = {compareVersions};
@@ -0,0 +1,69 @@
1
+ 'use strict';
2
+ // Where the shared runtime listens (countinghouse's shared-runtime design,
3
+ // section 1, "Where it listens"; C4c). ch-local daemon picks it for each
4
+ // runtime start and passes it as --sessionSocket, with --sessionDir its run
5
+ // directory (<home>/run/daemon), where the secret is (countinghouse C2).
6
+ // - Windows: a named pipe, \\.\pipe\countinghouse-<32 hex>, its name random
7
+ // (16 bytes) per runtime start: a predictable one could be taken ahead by
8
+ // another user, so the runtime would never start. It is recorded in
9
+ // daemon.json, which is owner-only.
10
+ // - POSIX: <home>/run/daemon/sessions.sock, unless that is over the
11
+ // platform's limit (107 bytes on Linux, 103 on macOS, without the NUL):
12
+ // then $TMPDIR/ch-<uid>/sessions.sock, its directory made 0700 and checked
13
+ // like the run directory (the user's, not a link). The runtime checks it
14
+ // again, and refuses a path still over the limit.
15
+ const crypto = require('node:crypto');
16
+ const fs = require('node:fs');
17
+ const os = require('node:os');
18
+ const path = require('node:path');
19
+
20
+ const SOCKET = 'sessions.sock';
21
+ const PIPE_NAME = /^\\\\\.\\pipe\\countinghouse-[0-9a-f]{32}$/;
22
+ const isPipeName = (p) => typeof p === 'string' && PIPE_NAME.test(p);
23
+ const socketPathMax = (platform) => (platform === 'darwin' ? 103 : 107);
24
+ const newPipeName = (random = crypto.randomBytes) => `\\\\.\\pipe\\countinghouse-${random(16).toString('hex')}`;
25
+
26
+ // the long-home fallback's socket: $TMPDIR (else the system's) /ch-<uid>/
27
+ function fallbackSocket({env = process.env, uid = (typeof process.geteuid === 'function' ? process.geteuid() : null)} = {}) {
28
+ const base = typeof env.TMPDIR === 'string' && path.isAbsolute(env.TMPDIR) ? env.TMPDIR : os.tmpdir();
29
+ return path.join(base, `ch-${uid}`, SOCKET);
30
+ }
31
+
32
+ // the socket for one runtime start: {socket, fallback} (fallback: the
33
+ // directory to make and check first, or null)
34
+ function socketFor(runDir, {platform = process.platform, env = process.env, uid, random} = {}) {
35
+ if (platform === 'win32') return {socket: newPipeName(random), fallback: null};
36
+ const inRun = path.join(runDir, SOCKET);
37
+ if (Buffer.byteLength(inRun) <= socketPathMax(platform)) return {socket: inRun, fallback: null};
38
+ const socket = fallbackSocket({env, ...(uid !== undefined ? {uid} : {})});
39
+ return {socket, fallback: path.dirname(socket)};
40
+ }
41
+
42
+ // $TMPDIR/ch-<uid>/: made 0700 if missing, then the user's, a directory,
43
+ // not a link, 0700 -> null or what is wrong
44
+ function socketDirProblem(dir) {
45
+ try {
46
+ fs.mkdirSync(dir, {mode: 0o700});
47
+ } catch (e) {
48
+ if (e.code !== 'EEXIST') return `its socket directory ${dir} could not be made (${e.code || e.message})`;
49
+ }
50
+ let st;
51
+ try { st = fs.lstatSync(dir); } catch (e) { return `its socket directory ${dir} could not be read (${e.code || e.message})`; }
52
+ if (st.isSymbolicLink() || !st.isDirectory()) return `its socket directory ${dir} is not a directory`;
53
+ if (typeof process.geteuid === 'function' && st.uid !== process.geteuid()) return `its socket directory ${dir} is not this user's`;
54
+ if ((st.mode & 0o777) !== 0o700) {
55
+ try { fs.chmodSync(dir, 0o700); } catch (e) { return `its socket directory ${dir} could not be made 0700 (${e.code || e.message})`; }
56
+ }
57
+ return null;
58
+ }
59
+
60
+ // a daemon.json's socket that a daemon of this home may have chosen: a pipe
61
+ // name of the form (Windows, random per start), or exactly what socketFor
62
+ // gives on POSIX
63
+ function socketOk(socket, runDir, opts = {}) {
64
+ const platform = opts.platform || process.platform;
65
+ if (platform === 'win32') return isPipeName(socket);
66
+ return typeof socket === 'string' && socket === socketFor(runDir, opts).socket;
67
+ }
68
+
69
+ module.exports = {SOCKET, PIPE_NAME, isPipeName, newPipeName, socketFor, fallbackSocket, socketDirProblem, socketOk, socketPathMax};
@@ -0,0 +1,238 @@
1
+ 'use strict';
2
+ // ch-local daemon's session table (countinghouse's shared-runtime design,
3
+ // #236, section 6, "Where session state lives"). It is in memory only and
4
+ // never on disk. The runtime tells the daemon each session's resume hash and
5
+ // state, and the daemon hands the whole table back to a restarted runtime
6
+ // ('restore', before it listens).
7
+ //
8
+ // From the runtime, over the control channel, with no id:
9
+ // {type: 'session-resume', session, hash} SHA-256 of its newest resume token
10
+ // {type: 'session-state', session, state} B2's snapshot after each change
11
+ // {type: 'session-gone', session} it ended: its row goes
12
+ // {type: 'decline', kind, at} a declined form, kept 60 minutes
13
+ // To a new runtime:
14
+ // {type: 'restore', sessions: [{session, resume, state}], declines: [{kind, at}], reset: [session]}
15
+ // reset: the sessions a re-exec handoff took loosenings from, to be told
16
+ //
17
+ // The runtime refuses a whole restore over one bad row
18
+ // (countinghouse lib/session-transport/restore.js). So the table keeps only
19
+ // what that check accepts, by the same rules:
20
+ // - a session id is 32 lowercase hex, and a hash is 64;
21
+ // - a state is B2's exact shape (#252 rev 2);
22
+ // - a decline's kind is one of the runtime's (KINDS) or of a kind's shape,
23
+ // its `at` a past epoch ms;
24
+ // - at most MAX_ROWS sessions and MAX_DECLINES declines.
25
+ // A told message that fails is refused. A refused state drops that session's
26
+ // whole row, so a restart never restores it looser than it was. Only a
27
+ // session with a resume hash is restored: without one, nothing resumes it.
28
+ const MAX_ROWS = 256;
29
+ const MAX_DECLINES = 1024;
30
+ const MAX_STATE_BYTES = 64 * 1024;
31
+ // overrides: the two caps, one each (the runtime's rule since M5a, #438:
32
+ // no pack.* override; the shared vectors' restoreRows)
33
+ const MAX_OVERRIDES = 2;
34
+ // Two 30-minute windows: countinghouse's UserWindow.load (lib/settings-
35
+ // confirm.js LOAD_KEEP_MS) counts the declines of the window a lock was
36
+ // started in as well as the current one, since a lock runs 30 minutes from
37
+ // its third decline (declines at 0, 0 and 29 min lock until 59). Keeping only
38
+ // one window would hand a restart at 31 the last decline alone, and the lock
39
+ // would end 28 minutes early.
40
+ const DECLINE_KEEP_MS = 60 * 60 * 1000;
41
+ const SESSION_ID = /^[0-9a-f]{32}$/;
42
+ const RESUME = /^[0-9a-f]{64}$/;
43
+ // the runtime's confirmation kinds (countinghouse lib/settings-confirm.js):
44
+ // the two caps, a module turned on (enabled since M5b, pack before it: both
45
+ // taken, from L3, until L6 drops pack), and every module setting
46
+ // (module.<package>.<setting>, one kind: module)
47
+ const KINDS = ['maxOutputBytes', 'requestTimeout', 'pack', 'enabled', 'module'];
48
+ // a pack.* override as the pack form wrote it (the runtime's rule since M5a,
49
+ // #438: a handoff drops one of this shape; any other pack.* shape refuses
50
+ // the row)
51
+ const PACK = /^pack\.[a-z0-9][a-z0-9-]{0,63}$/;
52
+ const VERSION = /^\d{1,9}\.\d{1,9}\.\d{1,9}(?:-[0-9A-Za-z.-]{1,64})?$/;
53
+ const isPackName = (o) => o != null && typeof o.name === 'string' && o.name.startsWith('pack.');
54
+ const oldPackOverride = (o) => isObject(o) && keysAre(o, ['loosening', 'name', 'over', 'value', 'version']) && PACK.test(o.name) &&
55
+ typeof o.value === 'boolean' && typeof o.loosening === 'boolean' && o.over === null && typeof o.version === 'string' && VERSION.test(o.version);
56
+ // A handoff keeps every kind as it was told, and ch-local never maps or drops
57
+ // one: a runtime before M5b takes pack as it is, and one with M5b
58
+ // (countinghouse #449) maps pack to enabled on restore, per row, and takes a
59
+ // kind it has none of out of its row (the Reviewer's rulings on #449 and
60
+ // #96). The table takes enabled from a runtime that sends it.
61
+ const CAPS = ['maxOutputBytes', 'requestTimeout'];
62
+ // a cap override's value within the settings tool's own bounds, as
63
+ // countinghouse's restore.js reads them from its lib/settings-tool.js
64
+ // ALLOWLIST (held to the shared vectors: test/restore-vectors.test.js)
65
+ const MIB = 1024 * 1024;
66
+ const CAP_BOUNDS = Object.freeze({maxOutputBytes: [MIB, 256 * MIB], requestTimeout: [5000, 120000]});
67
+ // a session's state before B2 has told one: the runtime's fresh one
68
+ const EMPTY_STATE = Object.freeze({overrides: Object.freeze([]), locks: Object.freeze([]), formsLeft: 3});
69
+
70
+ const isObject = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
71
+ const keysAre = (o, keys) => { const k = Object.keys(o).sort(); return k.length === keys.length && k.every((x, i) => x === keys[i]); };
72
+ const posInt = (v) => Number.isSafeInteger(v) && v > 0;
73
+
74
+ function overrideOk(o) {
75
+ if (!isObject(o) || !keysAre(o, ['loosening', 'name', 'over', 'value', 'version']) || typeof o.loosening !== 'boolean') return false;
76
+ if (CAPS.includes(o.name)) {
77
+ const [lo, hi] = CAP_BOUNDS[o.name];
78
+ return Number.isSafeInteger(o.value) && o.value >= lo && o.value <= hi && o.version === null && (o.loosening ? posInt(o.over) : o.over === null);
79
+ }
80
+ // (a pack.* override is no row's since M5a, #438: a handoff drops one,
81
+ // seed; told by a runtime, it is refused like any unknown name)
82
+ return false;
83
+ }
84
+
85
+ // A kind's shape (the runtime's restore.js): a letter, then letters and
86
+ // digits, at most 64. ch-local takes any kind of this shape in locks,
87
+ // unanswered and declines, and hands it on exactly as told: one it doesn't
88
+ // know is most likely one a newer runtime knows and enforces, and taking it
89
+ // out would lose a session's lock or decline. Dropping what it doesn't know
90
+ // is the runtime's job (the shared vectors' kindsDropped: the Reviewer's
91
+ // high review of #96). Anything else in a kind's place refuses the row.
92
+ const KIND_SHAPE = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
93
+ // (every one of KINDS is of the shape: the shape alone decides)
94
+ const kindTaken = (k) => typeof k === 'string' && KIND_SHAPE.test(k);
95
+
96
+ function stateOk(st) {
97
+ // exactly these keys, or these and `unanswered` (B's: the distinct kinds
98
+ // with one unanswered form, each of a kind's shape; no other cap, as the
99
+ // runtime's restore.js has none)
100
+ if (!isObject(st) || !(keysAre(st, ['formsLeft', 'locks', 'overrides']) || keysAre(st, ['formsLeft', 'locks', 'overrides', 'unanswered']))) return false;
101
+ if (st.unanswered !== undefined && !(Array.isArray(st.unanswered) &&
102
+ st.unanswered.every(kindTaken) && new Set(st.unanswered).size === st.unanswered.length)) return false;
103
+ if (!Array.isArray(st.overrides) || st.overrides.length > MAX_OVERRIDES || !st.overrides.every(overrideOk)) return false;
104
+ if (new Set(st.overrides.map((o) => o.name)).size !== st.overrides.length) return false;
105
+ if (!Array.isArray(st.locks) || !st.locks.every(kindTaken) || new Set(st.locks).size !== st.locks.length) return false;
106
+ if (!Number.isInteger(st.formsLeft) || st.formsLeft < 0 || st.formsLeft > 3) return false;
107
+ // as the runtime has it: a kind is locked or has one form unanswered,
108
+ // never both; and a form left unanswered was a form spent
109
+ if (st.unanswered !== undefined && (st.unanswered.some((k) => st.locks.includes(k)) || (st.unanswered.length > 0 && st.formsLeft >= 3))) return false;
110
+ try { return Buffer.byteLength(JSON.stringify(st)) <= MAX_STATE_BYTES; } catch (e) { return false; }
111
+ }
112
+
113
+ function createSessionTable({now = () => Date.now(), warn = () => {}} = {}) {
114
+ const rows = new Map(); // session id -> {resume, state}
115
+ let declines = []; // {kind, at}, oldest first
116
+ const reset = new Set(); // seeded sessions that lost loosenings, to be told once
117
+ const prune = () => { const cut = now() - DECLINE_KEEP_MS; declines = declines.filter((d) => d.at >= cut); };
118
+ const row = (id) => {
119
+ if (rows.has(id)) return rows.get(id);
120
+ if (rows.size >= MAX_ROWS) { warn(`the session table is full (${MAX_ROWS}); a new session is not kept`); return null; }
121
+ const r = {resume: null, state: null};
122
+ rows.set(id, r);
123
+ return r;
124
+ };
125
+ const idOk = (m) => typeof m.session === 'string' && SESSION_ID.test(m.session);
126
+ return {
127
+ // one message from the runtime -> whether the table took it
128
+ told(m) {
129
+ if (m == null || typeof m.type !== 'string') return false;
130
+ if (m.type === 'session-resume') {
131
+ if (!idOk(m) || !keysAre(m, ['hash', 'session', 'type']) || typeof m.hash !== 'string' || !RESUME.test(m.hash)) return false;
132
+ const r = row(m.session);
133
+ if (r == null) return false;
134
+ r.resume = m.hash;
135
+ return true;
136
+ }
137
+ if (m.type === 'session-state') {
138
+ if (!idOk(m)) return false;
139
+ const state = m.state;
140
+ if (!stateOk(state)) {
141
+ // the whole row goes: restored with no state, its tightenings and
142
+ // locks would be lost on a resume that carries no replay. Without
143
+ // it the resume is refused, and the shim replays only-tighter.
144
+ rows.delete(m.session);
145
+ warn('a session\'s state is not one the runtime would restore; its row is dropped');
146
+ return false;
147
+ }
148
+ const r = row(m.session);
149
+ if (r == null) return false;
150
+ r.state = state;
151
+ return true;
152
+ }
153
+ if (m.type === 'session-gone') { if (idOk(m)) reset.delete(m.session); return idOk(m) && rows.delete(m.session); }
154
+ if (m.type === 'decline') {
155
+ if (!keysAre(m, ['at', 'kind', 'type']) || !kindTaken(m.kind)) return false;
156
+ if (!Number.isSafeInteger(m.at) || m.at < 0 || m.at > now() + 60000) return false;
157
+ declines.push({kind: m.kind, at: m.at});
158
+ prune();
159
+ // past the cap, a decline of a kind ch-local doesn't know goes first
160
+ // (the oldest), then the oldest of any kind: one a runtime may drop
161
+ // never pushes out one that starts a lock (the medium on #96's high
162
+ // round, 2)
163
+ while (declines.length > MAX_DECLINES) {
164
+ const i = declines.findIndex((d) => !KINDS.includes(d.kind));
165
+ declines.splice(i >= 0 ? i : 0, 1);
166
+ }
167
+ return true;
168
+ }
169
+ return false;
170
+ },
171
+ // the 'restore' a new runtime is handed (empty from a fresh daemon)
172
+ restore() {
173
+ prune();
174
+ const sessions = [];
175
+ for (const [session, r] of rows) {
176
+ if (r.resume != null) sessions.push({session, resume: r.resume, state: r.state != null ? r.state : EMPTY_STATE});
177
+ }
178
+ // the sessions to tell their loosenings were reset (each a row's),
179
+ // told to the first runtime handed them, never again
180
+ const told = sessions.filter((r) => reset.has(r.session)).map((r) => r.session);
181
+ reset.clear();
182
+ return {type: 'restore', sessions, declines: declines.slice(), reset: told};
183
+ },
184
+ // a handoff from the daemon this one replaced (C3b): each row and decline
185
+ // goes through the same checks as a told one (a bad state drops its whole
186
+ // row). Anyone of this user can start a daemon with a handoff of their
187
+ // own, and a restored loosening skips its confirmation, so a handoff
188
+ // never carries one (the Reviewer's ruling on #35, within section 6's
189
+ // "nothing a same-user process could plant becomes a loosening"): a
190
+ // confirmed loosening is dropped; tightenings, locks and forms left are
191
+ // kept. Section 10 (L3): a pack.* override of the pack form's own shape is
192
+ // handed on for the runtime to drop and tell, naming the packs (any other
193
+ // pack.* shape refuses the row). Every kind is kept as it was told
194
+ // (above).
195
+ // -> {kept, loosened}: sessions kept, and of those, how many lost some
196
+ seed(t) {
197
+ if (t == null || !Array.isArray(t.sessions) || !Array.isArray(t.declines)) return {kept: 0, loosened: 0};
198
+ let kept = 0;
199
+ let loosened = 0;
200
+ for (const r of t.sessions) {
201
+ if (r == null || typeof r !== 'object') continue;
202
+ if (!this.told({type: 'session-resume', session: r.session, hash: r.resume})) continue;
203
+ let state = r.state;
204
+ let lost = false;
205
+ let stale = [];
206
+ if (state != null && typeof state === 'object' && Array.isArray(state.overrides)) {
207
+ // a pack.* override not of the pack form's own shape refuses the
208
+ // row, as the runtime refuses it (the medium on 5b, 1)
209
+ if (state.overrides.some((o) => isPackName(o) && !oldPackOverride(o))) { rows.delete(r.session); continue; }
210
+ // a well-formed pack override is handed on as it is: the runtime
211
+ // drops it at the restore and tells that session once, naming the
212
+ // packs (#438: restore.js, session-state.js packsDropped; section
213
+ // 10's sentence, the Reviewer's ruling on #90); the row is checked
214
+ // here without it
215
+ stale = state.overrides.filter((o) => oldPackOverride(o));
216
+ const tight = state.overrides.filter((o) => o != null && o.loosening !== true && !isPackName(o));
217
+ lost = tight.length !== state.overrides.length - stale.length;
218
+ state = Object.assign({}, state, {overrides: tight});
219
+ }
220
+ if (state != null && !this.told({type: 'session-state', session: r.session, state})) continue;
221
+ // its stale pack overrides go back in, for the runtime to drop and
222
+ // tell (a confirmed loosening, a cap's, is the only one dropped here)
223
+ if (stale.length > 0) rows.get(r.session).state = Object.assign({}, rows.get(r.session).state, {overrides: [...rows.get(r.session).state.overrides, ...stale]});
224
+ // (counted and marked only for a row kept: the medium on 5b, 8)
225
+ if (lost) { loosened += 1; reset.add(r.session); }
226
+ kept += 1;
227
+ }
228
+ for (const d of t.declines) if (d != null && typeof d === 'object') this.told({type: 'decline', kind: d.kind, at: d.at});
229
+ return {kept, loosened};
230
+ },
231
+ // a restore the runtime refused: its rows would be stale forever, never
232
+ // told gone, so the table starts over
233
+ clear() { rows.clear(); declines = []; reset.clear(); },
234
+ size: () => rows.size
235
+ };
236
+ }
237
+
238
+ module.exports = {createSessionTable, MAX_ROWS, MAX_DECLINES, MAX_STATE_BYTES, DECLINE_KEEP_MS, EMPTY_STATE};