@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,414 @@
1
+ 'use strict';
2
+ // The credentials ch-local holds, each bound to one module (#413 section
3
+ // 6.3; L5a): entered at a terminal, or on standard input with the origin it
4
+ // is for (`ch-local credentials add`). Never from the conversation, a client
5
+ // config or a client's environment; never printed, logged or recorded;
6
+ // modules never reach the ch-local home.
7
+ //
8
+ // <home>/credentials/credentials.json, version 2:
9
+ // {"v": 2, "modules": {"<package>": {"<VARIABLE>":
10
+ // {"origin": "<https origin>", "source": "gh"} |
11
+ // {"origin": "<https origin>", "source": "stored", "value": "..."}}}}
12
+ //
13
+ // An entry is the binding: this value, for this module's credential of this
14
+ // name, to this origin. At most 64 entries, the file at most 512 KiB. A file
15
+ // that is not of this form is refused, naming the entry and never a value.
16
+ //
17
+ // Version 1 ({"v": 1, "values": {"<VARIABLE>": {value, module}}}, ch-local
18
+ // before L5a) is read as it is (readStore's {version: 1, values}); what its
19
+ // entries bind is lib/module-credentials.js's to say (section 10). The first
20
+ // add or remove writes version 2.
21
+ //
22
+ // The directory and the file are this user's alone, checked, never
23
+ // repaired: one that fails a check is refused, saying the path, what was
24
+ // seen, and how to fix it, and nothing is written through it or beside it.
25
+ // - POSIX: the directory not a link, owned by this user, mode 0700 (nothing
26
+ // for group or others); the file through lib/own-file.js (no link, owned
27
+ // by this user, nothing for group or others, written by an exclusive
28
+ // temporary file renamed into place, 0600).
29
+ // - Every change (add, remove, uninstall's removal) is made under the
30
+ // store's lock, <home>/credentials.lock (lib/lock.js's protocol with its
31
+ // started and ageOtherHosts options; post-rel cred-race): bind and unbind
32
+ // take the `held` withStoreLock hands its function (branded: one it
33
+ // minted), and check it is still this holder's before credentials/ is
34
+ // made and just before the file is replaced or removed. No write without
35
+ // it. start and list only read: each write is a whole file
36
+ // renamed into place.
37
+ // - Windows: the directory's and the file's owner and DACL pass
38
+ // lib/win-acl.js privateProblem (a new directory gets a protected
39
+ // owner-only DACL, and each write is a file made private before it is
40
+ // renamed into place). Another program running as this user can read the
41
+ // file, as it can read gh's own token: the limit the docs state.
42
+ const fs = require('node:fs');
43
+ const path = require('node:path');
44
+ // (through the module object: one seam a test can stub for every read)
45
+ const ownFile = require('./own-file');
46
+
47
+ const DIR = 'credentials';
48
+ const LOCK = 'credentials.lock';
49
+ const FILE = 'credentials.json';
50
+ const MAX_BYTES = 512 * 1024;
51
+ const MAX_ENTRIES = 64;
52
+ // a variable, as the runtime reads a declaration's (countinghouse
53
+ // lib/remote/declaration.js VARIABLE, copied: test/credentials.test.js
54
+ // pins the copy), so every declaration the runtime takes can get a key (the
55
+ // Reviewer's high review of L5a, 2)
56
+ const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
57
+ // a value: 8 to 4096 visible ASCII characters, no space, so that it is a
58
+ // safe header value (section 6.2)
59
+ const VALUE = /^[\x21-\x7e]{8,4096}$/;
60
+ // version 1's own value grammar (its entries are read as they were written)
61
+ const V1_VALUE = /^[A-Za-z0-9_]{8,255}$/;
62
+ const SOURCES = ['gh', 'stored'];
63
+ // the one origin a gh login's token is ever for (section 6.8): an entry
64
+ // that pairs gh with another is refused at add, and at use for its module
65
+ // alone (lib/module-credentials.js stateOf), so one hand-written entry never
66
+ // takes the whole store down (the Fable pass on L5a, F5)
67
+ const GH_ORIGIN = 'https://api.githubcopilot.com';
68
+ // an https origin as the runtime reads a declaration's: scheme, host and
69
+ // port, nothing else (the same string URL.origin gives back)
70
+ function isOrigin(o) {
71
+ if (typeof o !== 'string') return false;
72
+ let u;
73
+ try { u = new URL(o); } catch (e) { return false; }
74
+ return u.protocol === 'https:' && u.origin === o;
75
+ }
76
+ const {PACKAGE} = require('./names');
77
+
78
+ class StoreProblem extends Error {
79
+ constructor(message, code = 'CREDENTIALS_NOT_PRIVATE') {
80
+ super(message);
81
+ this.code = code;
82
+ }
83
+ }
84
+
85
+ const paths = (home) => ({dir: path.join(home, DIR), file: path.join(home, DIR, FILE)});
86
+ const isWindows = (platform) => platform === 'win32' || process.platform === 'win32';
87
+ const euid = () => (typeof process.geteuid === 'function' ? process.geteuid() : null);
88
+
89
+ // The directory, checked as it is. -> 'ok' | 'missing'; throws StoreProblem.
90
+ // create: make it when missing (0700; on Windows a protected owner-only DACL)
91
+ function checkDir(dir, {platform = process.platform, acl = null, create = false} = {}) {
92
+ let st;
93
+ try {
94
+ st = fs.lstatSync(dir);
95
+ } catch (e) {
96
+ if (e.code !== 'ENOENT') throw new StoreProblem(`${dir} could not be read (${e.code || e.message})`);
97
+ if (!create) return 'missing';
98
+ try {
99
+ fs.mkdirSync(dir, {mode: 0o700});
100
+ } catch (made) {
101
+ // another made it meanwhile: checked as found, below
102
+ if (made.code !== 'EEXIST') throw new StoreProblem(`${dir} could not be made (${made.code || made.message})`, 'CREDENTIALS_WRITE');
103
+ }
104
+ if (isWindows(platform)) {
105
+ const [made] = (acl != null && acl.makePrivateDirs ? acl : require('./win-acl')).makePrivateDirs([dir], [dir]);
106
+ const why = (acl != null && acl.privateProblem ? acl : require('./win-acl')).privateProblem(dir, made, {directory: true});
107
+ if (why != null) throw new StoreProblem(`${dir}: ${why}`);
108
+ }
109
+ st = fs.lstatSync(dir);
110
+ }
111
+ if (st.isSymbolicLink()) throw new StoreProblem(`${dir} is a link; remove it (ch-local makes the directory itself) and run the command again`);
112
+ if (!st.isDirectory()) throw new StoreProblem(`${dir} is not a directory; remove it and run the command again`);
113
+ if (isWindows(platform)) {
114
+ const winAcl = require('./win-acl');
115
+ let read;
116
+ try { read = (acl != null && acl.fileAcl ? acl.fileAcl : winAcl.fileAcl)(dir); } catch (e) { throw new StoreProblem(`${dir}: its access list could not be read (${e.code || e.message})`); }
117
+ const why = (acl != null && acl.privateProblem ? acl.privateProblem : winAcl.privateProblem)(dir, read, {directory: true});
118
+ if (why != null) {
119
+ const hint = winAcl.fixHint(dir, read, {directory: true});
120
+ throw new StoreProblem(`${why}${hint != null ? `; to make it this user's alone, in Windows PowerShell (powershell.exe):\n ${hint}` : ''}`);
121
+ }
122
+ return 'ok';
123
+ }
124
+ // the directory itself, opened without following a link, as it is now
125
+ const fd = fs.openSync(dir, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
126
+ try {
127
+ const at = fs.fstatSync(fd);
128
+ if (!at.isDirectory()) throw new StoreProblem(`${dir} is not a directory`);
129
+ if (euid() != null && at.uid !== euid()) throw new StoreProblem(`${dir} is owned by uid ${at.uid}, not this user; remove it and run the command again`);
130
+ const mode = at.mode & 0o777;
131
+ if ((mode & 0o077) !== 0) throw new StoreProblem(`${dir} is open to others (mode ${mode.toString(8).padStart(4, '0')}); make it this user's alone: chmod 700 "${dir}"`);
132
+ } finally {
133
+ fs.closeSync(fd);
134
+ }
135
+ return 'ok';
136
+ }
137
+
138
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
139
+ const exactly = (o, keys) => JSON.stringify(Object.keys(o).sort()) === JSON.stringify([...keys].sort());
140
+
141
+ // text -> {version: 2, modules: Map(module -> Map(variable -> entry))} or
142
+ // {version: 1, values: Map(variable -> {value, module})}; throws StoreProblem
143
+ function parse(text, file) {
144
+ const bad = (why) => new StoreProblem(`${file} is not a credentials file (${why}); remove it and add the credentials again`, 'CREDENTIALS_INVALID');
145
+ let doc;
146
+ try { doc = JSON.parse(text); } catch (e) { throw bad('not JSON'); }
147
+ if (isObject(doc) && doc.v === 1) return {version: 1, values: parseV1(doc, bad)};
148
+ if (!isObject(doc) || !exactly(doc, ['v', 'modules']) || doc.v !== 2 || !isObject(doc.modules)) throw bad('not {v: 2, modules}');
149
+ const modules = new Map();
150
+ let count = 0;
151
+ for (const module of Object.keys(doc.modules)) {
152
+ if (!PACKAGE.test(module)) throw bad('an entry that is not a package name');
153
+ const vars = doc.modules[module];
154
+ if (!isObject(vars)) throw bad(`the entry for ${module} is not an object`);
155
+ const out = new Map();
156
+ for (const variable of Object.keys(vars)) {
157
+ count += 1;
158
+ if (count > MAX_ENTRIES) throw bad(`more than ${MAX_ENTRIES} entries`);
159
+ if (!VARIABLE.test(variable)) throw bad(`an entry of ${module} that is not a variable name`);
160
+ const e = vars[variable];
161
+ // the module and the name only: never the value
162
+ const at = `${module} ${variable}`;
163
+ if (!isObject(e) || !isOrigin(e.origin) || !SOURCES.includes(e.source)) throw bad(`the entry for ${at} is not {origin, source}`);
164
+ if (e.source === 'gh' && !exactly(e, ['origin', 'source'])) throw bad(`the entry for ${at} is not {origin, source: "gh"}`);
165
+ if (e.source === 'stored' && (!exactly(e, ['origin', 'source', 'value']) || typeof e.value !== 'string' || !VALUE.test(e.value))) throw bad(`the entry for ${at} is not {origin, source: "stored", value}`);
166
+ out.set(variable, e.source === 'gh' ? {origin: e.origin, source: 'gh'} : {origin: e.origin, source: 'stored', value: e.value});
167
+ }
168
+ if (out.size > 0) modules.set(module, out);
169
+ }
170
+ return {version: 2, modules};
171
+ }
172
+ function parseV1(doc, bad) {
173
+ if (!exactly(doc, ['v', 'values']) || !isObject(doc.values)) throw bad('not {v: 1, values}');
174
+ const names = Object.keys(doc.values);
175
+ if (names.length > MAX_ENTRIES) throw bad(`more than ${MAX_ENTRIES} entries`);
176
+ const out = new Map();
177
+ for (const name of names) {
178
+ const e = doc.values[name];
179
+ if (!VARIABLE.test(name)) throw bad('an entry that is not a variable name');
180
+ if (!isObject(e) || !exactly(e, ['value', 'module']) || typeof e.value !== 'string' || !V1_VALUE.test(e.value) || typeof e.module !== 'string' || !PACKAGE.test(e.module)) {
181
+ // the name only: never the value
182
+ throw bad(`the entry for ${name} is not {value, module}`);
183
+ }
184
+ out.set(name, {value: e.value, module: e.module});
185
+ }
186
+ return out;
187
+ }
188
+
189
+ // home -> parse()'s answer: {version: 2, modules} empty when there is none.
190
+ // Throws StoreProblem for a directory or file that fails a check.
191
+ const empty = () => ({version: 2, modules: new Map()});
192
+ function readStore(home, {platform = process.platform, acl = null} = {}) {
193
+ const {dir, file} = paths(home);
194
+ // Windows: the folder's ACL and the file's in one PowerShell run (cold-start
195
+ // part 3; win-acl prefetch: a link or a missing path is never read through,
196
+ // a failed read gets today's single read and its error), used for this one
197
+ // read only, so the window between the read and its use is no longer than
198
+ // today's two separate reads
199
+ let checking = acl;
200
+ let fileAcl = null;
201
+ if (isWindows(platform)) {
202
+ const prefetch = acl != null ? acl.prefetch : require('./win-acl').prefetch;
203
+ if (typeof prefetch === 'function') {
204
+ fileAcl = prefetch([dir, file], acl != null && typeof acl.fileAcl === 'function' ? {single: acl.fileAcl} : {single: (p) => require('./win-acl').fileAcl(p)});
205
+ checking = Object.assign({}, acl || {}, {fileAcl});
206
+ }
207
+ }
208
+ if (checkDir(dir, {platform, acl: checking}) === 'missing') return empty();
209
+ let bytes;
210
+ try {
211
+ // an atomic write (a racing add's rename) can swap the file between the
212
+ // check and the read: read once more, and a second race is transient
213
+ // too, never a file found wrong (the Reviewer's round 3, 1); the second
214
+ // read's ACL is read fresh, as the file is a new one
215
+ const read = (given) => ownFile.readOwnFile(file, {max: MAX_BYTES, platform, fileAcl: given});
216
+ try { bytes = read(fileAcl); } catch (e) { if (e.raced !== true) throw e; bytes = read(null); }
217
+ } catch (e) {
218
+ if (e.raced === true) throw Object.assign(new StoreProblem(`${file} was being replaced while it was read`), {transient: true});
219
+ if (e.code === 'NOT_PRIVATE') throw new StoreProblem(`${e.message}; ${isWindows(platform) ? 'remove it and add the credential again' : `make it this user's alone (chmod 600 "${file}"), or remove it and add the credential again`}`);
220
+ // a read that failed, not a file found wrong: transient (the applier
221
+ // keeps its last good states and reads again)
222
+ throw Object.assign(new StoreProblem(`${file} could not be read (${e.code || e.message})`), {transient: true});
223
+ }
224
+ if (bytes == null) return empty();
225
+ return parse(bytes.toString('utf8'), file);
226
+ }
227
+
228
+ // The home's own ownership. POSIX: lib/home.js homeOwnershipProblem (this
229
+ // user's, no group or world write). Windows: its owner and DACL by win-acl
230
+ // privateProblem (this user, SYSTEM, Administrators only), read through the
231
+ // acl seam; an unreadable DACL is a problem, never a pass.
232
+ function homeProblem(realHome, {platform, acl}) {
233
+ if (!isWindows(platform)) return require('./home').homeOwnershipProblem(realHome, platform);
234
+ const winAcl = require('./win-acl');
235
+ let read;
236
+ try { read = (acl != null && acl.fileAcl ? acl.fileAcl : winAcl.fileAcl)(realHome); } catch (e) { return `its access list could not be read (${e.code || e.message})`; }
237
+ return (acl != null && acl.privateProblem ? acl.privateProblem : winAcl.privateProblem)('it', read, {directory: true});
238
+ }
239
+
240
+ // the file written whole, this user's alone, by an exclusive temporary file
241
+ // renamed into place (never through a link, never beside one that fails)
242
+ // modules: Map(module -> Map(variable -> entry)), written as version 2
243
+ function writeStore(home, modules, {platform = process.platform, acl = null, held = null} = {}) {
244
+ // the home itself this user's alone (no other user can swap the directory
245
+ // in it between the check and the write; the same user can do anything
246
+ // the store does), and written through the real path that was checked, so
247
+ // a link re-pointed meanwhile can't redirect the write
248
+ let realHome;
249
+ try { realHome = fs.realpathSync(home); } catch (e) { throw new StoreProblem(`${home} could not be read (${e.code || e.message})`); }
250
+ const owned = homeProblem(realHome, {platform, acl});
251
+ if (owned != null) throw new StoreProblem(`${home}: ${owned}`);
252
+ const {dir, file} = paths(realHome);
253
+ try {
254
+ writeChecked(dir, file, modules, {platform, acl, held, home});
255
+ } catch (e) {
256
+ if (e instanceof StoreProblem) throw e;
257
+ throw new StoreProblem(`${file} could not be written (${e.code || e.message}); nothing was stored`, 'CREDENTIALS_WRITE');
258
+ }
259
+ // and after: the directory is still the one checked, and the file reads
260
+ // back as this user's own (a link swapped in meanwhile is refused here)
261
+ checkDir(dir, {platform, acl});
262
+ try { ownFile.readOwnFile(file, {max: MAX_BYTES, platform}); } catch (e) { throw new StoreProblem(`${file} did not read back as this user's own (${e.message}); remove ${dir} and add the credential again`); }
263
+ }
264
+
265
+ function writeChecked(dir, file, modules, {platform, acl, held, home}) {
266
+ // (before the directory is made too: a holder whose lock was taken over
267
+ // never recreates credentials/ an uninstall removed; the reviewer's high
268
+ // on #102, 4)
269
+ checkHeld(held, home);
270
+ checkDir(dir, {platform, acl, create: true});
271
+ // objects with no prototype: a variable named __proto__ (the runtime's
272
+ // grammar takes it) is an own key, written as any other
273
+ const out = Object.create(null);
274
+ const byName = (a, b) => (a[0] < b[0] ? -1 : 1);
275
+ for (const [module, vars] of [...modules].sort(byName)) {
276
+ if (vars.size === 0) continue;
277
+ out[module] = Object.create(null);
278
+ for (const [variable, e] of [...vars].sort(byName)) out[module][variable] = e.source === 'gh' ? {origin: e.origin, source: 'gh'} : {origin: e.origin, source: 'stored', value: e.value};
279
+ }
280
+ const text = `${JSON.stringify({v: 2, modules: out}, null, 2)}\n`;
281
+ const beforeRename = () => checkHeld(held, home);
282
+ if (!isWindows(platform)) return ownFile.writeOwnFile(file, text, {beforeRename});
283
+ const winAcl = acl != null && acl.createPrivate ? acl : require('./win-acl');
284
+ const temp = path.join(dir, `.${FILE}.${process.pid}.${Date.now()}.tmp`);
285
+ let placed = false;
286
+ try {
287
+ winAcl.createPrivate(temp, text);
288
+ beforeRename();
289
+ fs.renameSync(temp, file);
290
+ placed = true;
291
+ } finally {
292
+ if (!placed) { try { fs.unlinkSync(temp); } catch (e) { /* gone */ } }
293
+ }
294
+ }
295
+
296
+ // One module's binding set (add) or removed (remove), the whole file
297
+ // written as version 2. migrate(read) -> Map(module -> Map(variable ->
298
+ // entry)): a version 1 file's bindings as lib/module-credentials.js reads
299
+ // them (section 10), so its other entries carry over; without one a version
300
+ // 1 file is refused, never dropped. Neither echoes a value.
301
+ function bindingsOf(read, migrate) {
302
+ if (read.version === 2) return new Map([...read.modules].map(([m, v]) => [m, new Map(v)]));
303
+ if (typeof migrate !== 'function') throw new StoreProblem('the stored credentials are of an earlier ch-local; nothing was changed', 'CREDENTIALS_INVALID');
304
+ return migrate(read);
305
+ }
306
+ // A change made with no lock, or once the lock is no longer this
307
+ // holder's, is refused: nothing written (post-rel cred-race).
308
+ const lockLost = () => new StoreProblem('another ch-local took over the stored credentials\' lock while this change was being made; nothing was changed', 'CREDENTIALS_LOCK');
309
+ // A held is branded: withStoreLock mints each into this module's own
310
+ // WeakSet, and only one found there is taken (the reviewer's high on #102,
311
+ // 7). testOnlyHeld, for the tests' fixtures, is the one other minter;
312
+ // test/credential-lock.test.js pins that its name is nowhere else under lib/
313
+ // or bin/.
314
+ // Each held is minted for one home's lock file, by its real path, and
315
+ // taken only where the home's lock file is that same file now: a home
316
+ // spelled another way is the same home, and a home re-pointed since (a
317
+ // link, which writeStore resolves) is another, refused (the reviewer's high
318
+ // on #102's round 1, 1; the medium on it, 1 and 4). A fixture's is for any
319
+ // home.
320
+ const MINTED = new WeakMap();
321
+ const ANY_HOME = Symbol('any home');
322
+ const realLock = (home) => { try { return fs.realpathSync(path.join(home, LOCK)); } catch (e) { return null; } };
323
+ function requireHeld(held, home) {
324
+ const file = MINTED.get(held);
325
+ if (file === undefined || (file !== ANY_HOME && (home == null || file !== realLock(home)))) {
326
+ throw new StoreProblem('the stored credentials are changed only under their lock; nothing was changed', 'CREDENTIALS_LOCK');
327
+ }
328
+ }
329
+ // tests only: a branded held whose check is `check` (by default, always
330
+ // still held)
331
+ // (exported, so reachable by any module that requires the store: the
332
+ // limit, stated. The pin keeps lib/ and bin/ from naming it; a computed
333
+ // lookup would get past it, and is no pattern this codebase uses.)
334
+ function testOnlyHeld(check = () => {}) {
335
+ const held = Object.freeze({check});
336
+ MINTED.set(held, ANY_HOME);
337
+ return held;
338
+ }
339
+ // the lock still this holder's, just before a change lands: a lock taken
340
+ // over is said as that; any other failure of the check as itself
341
+ function checkHeld(held, home) {
342
+ requireHeld(held, home);
343
+ try { held.check(); } catch (e) {
344
+ if (e.code === 'LOCK_LOST') throw lockLost();
345
+ throw new StoreProblem(`the stored credentials' lock could not be checked (${e.code || e.message}); nothing was changed`, 'CREDENTIALS_LOCK');
346
+ }
347
+ }
348
+
349
+ // fn(held) -> an exit code, run under <home>/credentials.lock; 1 with a line
350
+ // on standard error when another ch-local still holds it after STALE_MS (a
351
+ // section can take seconds of ACL calls on Windows: the reviewer's high on
352
+ // #102, 6; on this host a holder that old is gone and cleared, so only a
353
+ // live one, or another host's, is waited out); io.credentialsLockWaitMs
354
+ // caps the wait, for the tests.
355
+ // doing: the command, named to whoever finds it held. missing(): the
356
+ // answer with no home (nothing installed), never fn run unlocked.
357
+ async function withStoreLock(home, io, doing, fn, {missing = () => { throw new StoreProblem('nothing is installed; nothing was changed', 'CREDENTIALS_INVALID'); }} = {}) {
358
+ const {withLockFile, STALE_MS} = require('./lock');
359
+ const file = path.join(home, LOCK);
360
+ // fn's own throw passes through as it is; a lock that can't be made (a
361
+ // home not writable) is the store's own write problem, said, never an
362
+ // unhandled error
363
+ let entered = false;
364
+ const locked = (release, held) => {
365
+ entered = true;
366
+ // (by its real path: the lock file is there now, this holder's)
367
+ const real = realLock(home);
368
+ if (real != null) MINTED.set(held, real);
369
+ return fn(held);
370
+ };
371
+ try {
372
+ return await withLockFile(file, home, io, locked, {
373
+ started: true, ageOtherHosts: false, missing, doing,
374
+ waitMs: io != null && Number.isInteger(io.credentialsLockWaitMs) ? io.credentialsLockWaitMs : STALE_MS,
375
+ what: 'to finish changing the stored credentials',
376
+ heldMessage: ({holder, who, removable}) => `ch-local: another ch-local (${who}${holder != null && typeof holder.doing === 'string' ? `, \`${holder.doing}\`` : ''}) is changing the stored credentials; nothing was changed. Try again when it is done${removable ? require('./lock').removeHint(file, holder) : ''}.`,
377
+ });
378
+ } catch (e) {
379
+ if (entered || e instanceof StoreProblem) throw e;
380
+ throw new StoreProblem(`${file} could not be made (${e.code || e.message}); nothing was changed`, 'CREDENTIALS_WRITE');
381
+ }
382
+ }
383
+
384
+ function bind(home, module, variable, entry, {migrate = null, held = null, ...opts} = {}) {
385
+ requireHeld(held, home);
386
+ if (typeof module !== 'string' || !PACKAGE.test(module)) throw new StoreProblem('that is not a package name', 'CREDENTIALS_INVALID');
387
+ if (!VARIABLE.test(String(variable))) throw new StoreProblem('that is not a variable name', 'CREDENTIALS_INVALID');
388
+ if (entry == null || !isOrigin(entry.origin) || !SOURCES.includes(entry.source)) throw new StoreProblem('that is not an https origin', 'CREDENTIALS_INVALID');
389
+ if (entry.source === 'gh' && entry.origin !== GH_ORIGIN) throw new StoreProblem(`a gh login is only ever used for ${GH_ORIGIN}`, 'CREDENTIALS_INVALID');
390
+ if (entry.source === 'stored' && (typeof entry.value !== 'string' || !VALUE.test(entry.value))) {
391
+ throw new StoreProblem('that does not look like a key (8 to 4096 visible characters, no space); nothing was stored', 'CREDENTIALS_INVALID');
392
+ }
393
+ const modules = bindingsOf(readStore(home, opts), migrate);
394
+ // a module has one credential in release 1: its binding replaces any other
395
+ const count = [...modules].filter(([m]) => m !== module).reduce((n, [, v]) => n + v.size, 0);
396
+ if (count + 1 > MAX_ENTRIES) throw new StoreProblem(`at most ${MAX_ENTRIES} credentials are held`, 'CREDENTIALS_INVALID');
397
+ modules.set(module, new Map([[variable, entry.source === 'gh' ? {origin: entry.origin, source: 'gh'} : {origin: entry.origin, source: 'stored', value: entry.value}]]));
398
+ writeStore(home, modules, {...opts, held});
399
+ }
400
+ // -> true when the module had a binding; the file goes once it holds none
401
+ function unbind(home, module, {migrate = null, held = null, ...opts} = {}) {
402
+ requireHeld(held, home);
403
+ const modules = bindingsOf(readStore(home, opts), migrate);
404
+ if (!modules.delete(module)) return false;
405
+ if ([...modules.values()].every((v) => v.size === 0)) {
406
+ checkHeld(held, home);
407
+ fs.rmSync(paths(home).file, {force: true});
408
+ return true;
409
+ }
410
+ writeStore(home, modules, {...opts, held});
411
+ return true;
412
+ }
413
+
414
+ module.exports = {readStore, bind, unbind, withStoreLock, checkHeld, testOnlyHeld, LOCK, checkDir, paths, StoreProblem, isOrigin, VARIABLE, VALUE, MAX_ENTRIES, MAX_BYTES, GH_ORIGIN};