@rarog/server 1.0.1 → 1.1.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 (140) hide show
  1. package/README.md +18 -5
  2. package/node_modules/@rarog/shared/package.json +1 -1
  3. package/node_modules/@rarog/shared/src/decode.js +64 -3
  4. package/node_modules/@rarog/shared/src/protocol/files.js +33 -0
  5. package/node_modules/@rarog/shared/src/protocol/folders.js +27 -0
  6. package/node_modules/@rarog/shared/src/protocol/herdr.js +23 -0
  7. package/node_modules/@rarog/shared/src/protocol/inbox.js +38 -0
  8. package/node_modules/@rarog/shared/src/protocol/notes.js +7 -1
  9. package/node_modules/@rarog/shared/src/protocol.js +20 -47
  10. package/node_modules/@rarog/shared/src/rest.js +106 -12
  11. package/node_modules/@rarog/shared/src/sentences/herdr.js +0 -4
  12. package/node_modules/@rarog/shared/src/sentences/index.js +7 -1
  13. package/node_modules/@rarog/shared/src/sentences/rest.js +21 -0
  14. package/package.json +3 -3
  15. package/server/src/auth/admin.js +3 -1
  16. package/server/src/bootstrap/consent.js +99 -2
  17. package/server/src/bootstrap/folder-gate.js +55 -0
  18. package/server/src/bootstrap/http.js +3 -2
  19. package/server/src/bootstrap/inbox.js +29 -4
  20. package/server/src/bootstrap/sse.js +2 -1
  21. package/server/src/cli/doctor-no-hook.js +162 -0
  22. package/server/src/cli/doctor.js +2 -0
  23. package/server/src/cli/service-log.js +27 -0
  24. package/server/src/cli/service.js +5 -2
  25. package/server/src/cli/templates/launchd.plist +1 -1
  26. package/server/src/cli/templates/rarog.service +1 -1
  27. package/server/src/cli/update-channel.js +100 -0
  28. package/server/src/cli/update-provenance.js +37 -19
  29. package/server/src/cli/update-registry.js +160 -62
  30. package/server/src/cli/update.js +13 -3
  31. package/server/src/companion/turns-settle.js +4 -1
  32. package/server/src/companion/turns.js +36 -5
  33. package/server/src/config/files.js +32 -0
  34. package/server/src/config/flags.js +10 -1
  35. package/server/src/config/protected-dirs.js +2 -0
  36. package/server/src/config/roots.js +13 -8
  37. package/server/src/config/work-area.js +36 -12
  38. package/server/src/config-env.js +33 -0
  39. package/server/src/config.js +22 -2
  40. package/server/src/demo/control.js +9 -1
  41. package/server/src/demo/files.js +49 -0
  42. package/server/src/demo/inbox.js +73 -0
  43. package/server/src/demo/review-routes.js +6 -1
  44. package/server/src/device-effects.js +3 -1
  45. package/server/src/drivers/herdr/consent-no-hook-io.js +89 -0
  46. package/server/src/drivers/herdr/consent-no-hook.js +411 -0
  47. package/server/src/drivers/herdr/refusals.js +226 -0
  48. package/server/src/drivers/herdr/returned-prompt.js +172 -0
  49. package/server/src/drivers/herdr/screen-fallback.js +246 -0
  50. package/server/src/drivers/herdr-driver.js +193 -295
  51. package/server/src/files/file-index.js +248 -0
  52. package/server/src/files/ignored.js +119 -0
  53. package/server/src/files/listing.js +82 -0
  54. package/server/src/files/path-rule.js +199 -0
  55. package/server/src/files/refusals.js +50 -0
  56. package/server/src/files/send-file.js +115 -0
  57. package/server/src/files/session-download.js +51 -0
  58. package/server/src/files/session-files.js +38 -0
  59. package/server/src/files/session-gate.js +53 -0
  60. package/server/src/folder-gate/client.js +314 -0
  61. package/server/src/folder-gate/disk.js +455 -0
  62. package/server/src/folder-gate/folders.js +23 -0
  63. package/server/src/folder-gate/gate.js +220 -0
  64. package/server/src/folder-gate/helper.js +118 -0
  65. package/server/src/folder-gate/install.js +27 -0
  66. package/server/src/folder-gate/relay-worker.js +147 -0
  67. package/server/src/folder-gate/types.js +115 -0
  68. package/server/src/folder-gate/wire.js +170 -0
  69. package/server/src/fs-browse.js +55 -23
  70. package/server/src/fs-mkdir.js +3 -1
  71. package/server/src/git-status.js +16 -7
  72. package/server/src/git-watch.js +130 -19
  73. package/server/src/git-work-tree.js +3 -3
  74. package/server/src/herdr/audit.js +1 -1
  75. package/server/src/herdr/client.js +2 -2
  76. package/server/src/herdr/commands/discover.js +21 -9
  77. package/server/src/herdr/dialogs/consent-gate.js +28 -8
  78. package/server/src/herdr/dialogs/decide/sources.js +5 -2
  79. package/server/src/herdr/dialogs/hook/contract.js +16 -9
  80. package/server/src/herdr/dialogs/index.js +12 -2
  81. package/server/src/herdr/dialogs/layer1/cycle.js +43 -7
  82. package/server/src/herdr/dialogs/layer1/hook-list/hook-list.js +166 -86
  83. package/server/src/herdr/dialogs/layer1/hook-list/session-facts.js +135 -0
  84. package/server/src/herdr/dialogs/layer1/screen-key.js +52 -0
  85. package/server/src/herdr/dialogs/layer1/version-gate.js +13 -5
  86. package/server/src/herdr/dialogs/no-hook.js +63 -0
  87. package/server/src/herdr/dialogs/router.js +21 -6
  88. package/server/src/herdr/dialogs/screen/block.js +10 -0
  89. package/server/src/herdr/dialogs/screen/parse.js +33 -3
  90. package/server/src/herdr/dialogs/screen/resolve.js +9 -7
  91. package/server/src/herdr/dialogs/screen-fallback.js +55 -0
  92. package/server/src/herdr/dialogs/shadow/alive.js +9 -8
  93. package/server/src/herdr/jsonl-follow.js +55 -14
  94. package/server/src/herdr/jsonl-pending.js +25 -1
  95. package/server/src/herdr/provenance.js +3 -3
  96. package/server/src/herdr/socket.js +25 -28
  97. package/server/src/herdr/supervisor.js +13 -10
  98. package/server/src/herdr/transcript-path.js +36 -0
  99. package/server/src/herdr/trust.js +11 -8
  100. package/server/src/herdr/uploads-registry.js +3 -2
  101. package/server/src/herdr/uploads.js +170 -47
  102. package/server/src/inbox/card.js +18 -9
  103. package/server/src/inbox/dialogs.js +40 -12
  104. package/server/src/inbox/heads.js +55 -0
  105. package/server/src/inbox/inbox.js +24 -2
  106. package/server/src/inbox/index.js +3 -1
  107. package/server/src/index.js +44 -21
  108. package/server/src/install/repair.js +8 -0
  109. package/server/src/iroh/listener.js +3 -0
  110. package/server/src/iroh/log-budget.js +1 -0
  111. package/server/src/iroh/socket.js +2 -1
  112. package/server/src/log-timestamps.js +9 -4
  113. package/server/src/notes/store.js +3 -2
  114. package/server/src/router.js +20 -2
  115. package/server/src/routes/devices.js +2 -2
  116. package/server/src/routes/inbox.js +91 -0
  117. package/server/src/routes/projects.js +5 -1
  118. package/server/src/routes/sessions.js +145 -18
  119. package/server/src/routes/system.js +9 -4
  120. package/server/src/safe-read.js +86 -1
  121. package/server/src/sessions/companion-scope.js +16 -7
  122. package/server/src/sessions/demo-modules.js +16 -0
  123. package/server/src/sessions/diff-measure.js +30 -0
  124. package/server/src/sessions/done-retention.js +57 -0
  125. package/server/src/sessions/launch-gate.js +2 -2
  126. package/server/src/sessions/manager.js +78 -190
  127. package/server/src/sessions/project-scan.js +9 -3
  128. package/server/src/sessions/ring-buffer.js +5 -3
  129. package/server/src/sessions/seen-marks.js +9 -6
  130. package/server/src/sessions/session-git.js +31 -2
  131. package/server/src/sessions/session-scope.js +30 -0
  132. package/server/src/sessions/session.js +19 -0
  133. package/server/src/sessions/state-sentences.js +1 -1
  134. package/server/src/sessions/waiting-line.js +72 -0
  135. package/server/src/sse.js +143 -10
  136. package/server/src/term/herdr-backend.js +2 -2
  137. package/server/src/term/index.js +2 -15
  138. package/server/src/term/registry.js +4 -3
  139. package/server/src/term/ws.js +9 -1
  140. package/server/src/version.js +30 -0
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The channel rules of `rarog update`: the shapes of a release and a beta version, which version `rarog update --beta`
3
+ * targets from the npm dist-tags (the higher of `beta` and `latest`), and whether npm's `min-release-age-exclude`
4
+ * lets this package past the release age gate. Pure functions over what npm prints; the npm calls stay in
5
+ * `update-registry.ts`.
6
+ */
7
+ const STABLE = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u;
8
+ const BETA = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)-beta\.(?:0|[1-9]\d*)$/u;
9
+ /** A release: `X.Y.Z`, numbers without leading zeros. */
10
+ export function isStableVersion(value) {
11
+ return typeof value === 'string' && STABLE.test(value);
12
+ }
13
+ /** A beta: a release followed by `-beta.N`, `N` without leading zeros, and nothing after it. */
14
+ export function isBetaVersion(value) {
15
+ return typeof value === 'string' && BETA.test(value);
16
+ }
17
+ /** A version with a pre-release part (`1.1.0-beta.2`, `1.1.0-rc.0`): `X.Y.Z` followed by `-`. */
18
+ export function isPrerelease(version) {
19
+ return /^\d+\.\d+\.\d+-/u.test(version);
20
+ }
21
+ /** `X.Y.Z` and `X.Y.Z-beta.N` in semver order (a beta below its release). */
22
+ function order(a, b) {
23
+ const parts = (version) => {
24
+ const [core = '', beta] = version.split('-beta.');
25
+ return [...core.split('.').map(Number), beta === undefined ? Number.POSITIVE_INFINITY : Number(beta)];
26
+ };
27
+ const x = parts(a);
28
+ const y = parts(b);
29
+ for (let i = 0; i < 4; i += 1) {
30
+ const diff = (x[i] ?? 0) - (y[i] ?? 0);
31
+ if (diff !== 0)
32
+ return diff;
33
+ }
34
+ return 0;
35
+ }
36
+ /**
37
+ * The target of `rarog update --beta` from the value of `npm view @rarog/server dist-tags --json`: `latest` must be a
38
+ * release, and the `beta` tag counts when it names a beta, because nobody moves it after a release and a release above
39
+ * it is the newer code. `null` = another shape or no release under `latest`.
40
+ */
41
+ export function channelTarget(tags) {
42
+ if (tags === null || typeof tags !== 'object' || Array.isArray(tags))
43
+ return null;
44
+ const { latest, beta } = tags;
45
+ if (!isStableVersion(latest))
46
+ return null;
47
+ if (!isBetaVersion(beta)) {
48
+ return { latest, beta: null, target: latest, note: beta === undefined ? 'npm has no beta tag'
49
+ : 'npm\'s beta tag is not a beta version' };
50
+ }
51
+ return { latest, beta, target: order(beta, latest) > 0 ? beta : latest, note: null };
52
+ }
53
+ /**
54
+ * A pattern of `min-release-age-exclude` as npm matches it against a package name (a name, or a glob in which `*` and
55
+ * `?` stay inside one path segment and `**` crosses them, also zero of them; a leading `!` or `#` is a plain
56
+ * character). A pattern with a character class or braces counts as a match: this module does not evaluate those, and
57
+ * a wrong "no" would print an admission date for a package npm does not hold back.
58
+ */
59
+ function globMatches(pattern, name) {
60
+ if (pattern === name)
61
+ return true;
62
+ if (/[[\]{}]/u.test(pattern))
63
+ return true;
64
+ let source = '';
65
+ for (let i = 0; i < pattern.length; i += 1) {
66
+ const char = pattern[i] ?? '';
67
+ if (char === '*' && pattern[i + 1] === '*') {
68
+ if (pattern[i + 2] === '/') {
69
+ source += '(?:.*/)?';
70
+ i += 2;
71
+ }
72
+ else {
73
+ source += '.*';
74
+ i += 1;
75
+ }
76
+ }
77
+ else if (char === '*') {
78
+ source += '[^/]*';
79
+ }
80
+ else if (char === '?') {
81
+ source += '[^/]';
82
+ }
83
+ else {
84
+ source += char.replace(/[\\^$.|+()[\]{}]/gu, '\\$&');
85
+ }
86
+ }
87
+ return new RegExp(`^${source}$`, 'u').test(name);
88
+ }
89
+ /**
90
+ * Whether `npm config get … min-release-age-exclude …` (`key=value` lines; npm prints the list joined with commas)
91
+ * names `name`: npm then installs it however young, so a release age gate stop is a dependency's.
92
+ */
93
+ export function gateExcludes(stdout, name) {
94
+ const line = stdout.split('\n').map((text) => text.trim())
95
+ .find((text) => text.startsWith('min-release-age-exclude='));
96
+ if (line === undefined)
97
+ return false;
98
+ return line.slice('min-release-age-exclude='.length).split(',').map((pattern) => pattern.trim())
99
+ .filter((pattern) => pattern !== '' && pattern !== 'null').some((pattern) => globMatches(pattern, name));
100
+ }
@@ -24,6 +24,19 @@ export const RELEASE_SOURCE = {
24
24
  };
25
25
  /** Where to report a version that fails the check (the repository's security policy). */
26
26
  export const REPORT_FIX = `do not install it by hand; report it at ${RELEASE_SOURCE.repository}/security`;
27
+ /**
28
+ * The clause of {@link attestationSigner} for a certificate the pinned authority did not issue. From here a new
29
+ * Sigstore certificate and a forged attestation look the same, so the clause names both.
30
+ */
31
+ export const OTHER_AUTHORITY = 'has a certificate from another authority than the pinned one: Sigstore changed its'
32
+ + ' certificate, or the attestation is forged';
33
+ /**
34
+ * The fix of {@link OTHER_AUTHORITY}: a version that pins Sigstore's new certificate is announced on the releases
35
+ * page of the repository. No install command: one typed from here would install without this check.
36
+ */
37
+ export const OTHER_AUTHORITY_FIX = `check ${RELEASE_SOURCE.repository}/releases for a release with Sigstore's new`
38
+ + ` certificate before you install a version by hand; if there is none, report it at ${RELEASE_SOURCE.repository}`
39
+ + '/security';
27
40
  /** The predicate type of the SLSA provenance npm keeps next to a version published from a CI run. */
28
41
  const PROVENANCE = 'https://slsa.dev/provenance/v1';
29
42
  /** The payload type of an in-toto statement in a DSSE envelope. */
@@ -31,7 +44,8 @@ const STATEMENT_TYPE = 'application/vnd.in-toto+json';
31
44
  /**
32
45
  * The certificate authority that issues the signing certificate of a GitHub Actions run: the intermediate of
33
46
  * Sigstore's public Fulcio (`O=sigstore.dev, CN=sigstore-intermediate`, valid until October 2031), DER in base64 as
34
- * Sigstore's trust root (`trusted_root.json`) carries it. A provenance signed under another authority is refused.
47
+ * Sigstore's trust root (`trusted_root.json`) carries it. A provenance signed under another authority is refused
48
+ * ({@link OTHER_AUTHORITY}); `scripts/sigstore-pin.ts` tells whether Sigstore still issues under this one.
35
49
  */
36
50
  const FULCIO_INTERMEDIATE = [
37
51
  'MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREw',
@@ -168,9 +182,8 @@ export function attestationSigner(signed, authority) {
168
182
  ]);
169
183
  try {
170
184
  const issuer = new X509Certificate(authority);
171
- if (!certificate.checkIssued(issuer) || !certificate.verify(issuer.publicKey)) {
172
- return 'has a certificate Sigstore did not issue';
173
- }
185
+ if (!certificate.checkIssued(issuer) || !certificate.verify(issuer.publicKey))
186
+ return OTHER_AUTHORITY;
174
187
  if (!verify('sha256', signedBytes, certificate.publicKey, Buffer.from(signature.sig, 'base64'))) {
175
188
  return 'has a signature its certificate did not make';
176
189
  }
@@ -192,17 +205,20 @@ export function attestationSigner(signed, authority) {
192
205
  * provenance of this version passes {@link attestationSigner} under `authority`, its certificate's only subject
193
206
  * alternative name is {@link releaseIdentity}, and the signed statement is a provenance that names this package
194
207
  * version, this file's sha512 and the same repository, workflow and tag. The certificate decides, because the
195
- * statement is text the signing run wrote.
208
+ * statement is text the signing run wrote. Every refusal has {@link REPORT_FIX}, except a certificate of another
209
+ * authority ({@link OTHER_AUTHORITY_FIX}): that one can be a new Sigstore certificate.
196
210
  */
197
211
  export function provenanceProblem(audit, expected, authority = fulcioAuthority()) {
212
+ const problem = (summary) => ({ summary, fix: REPORT_FIX });
198
213
  const id = `${RAROG_PACKAGE_NAME} ${expected.version}`;
199
214
  if (!isRecord(audit))
200
- return `npm gave no signature check result for ${id}`;
215
+ return problem(`npm gave no signature check result for ${id}`);
201
216
  const { invalid, missing, verified } = audit;
202
- if (Array.isArray(invalid) && invalid.length > 0)
203
- return `npm found an invalid signature or attestation of ${id}`;
217
+ if (Array.isArray(invalid) && invalid.length > 0) {
218
+ return problem(`npm found an invalid signature or attestation of ${id}`);
219
+ }
204
220
  if (Array.isArray(missing) && missing.length > 0)
205
- return `npm found no registry signature of ${id}`;
221
+ return problem(`npm found no registry signature of ${id}`);
206
222
  const thisVersion = (one) => isRecord(one) && one.name === RAROG_PACKAGE_NAME
207
223
  && one.version === expected.version;
208
224
  const entry = Array.isArray(verified) ? verified.find(thisVersion) : undefined;
@@ -212,27 +228,29 @@ export function provenanceProblem(audit, expected, authority = fulcioAuthority()
212
228
  : [];
213
229
  const [provenance] = provenances;
214
230
  if (!isRecord(provenance))
215
- return `${id} has no verified provenance`;
231
+ return problem(`${id} has no verified provenance`);
216
232
  if (provenances.length !== 1)
217
- return `${id} has more than one provenance`;
233
+ return problem(`${id} has more than one provenance`);
218
234
  const signer = attestationSigner(provenance.bundle, authority);
235
+ if (signer === OTHER_AUTHORITY)
236
+ return { summary: `the provenance of ${id} ${signer}`, fix: OTHER_AUTHORITY_FIX };
219
237
  if (typeof signer === 'string')
220
- return `the provenance of ${id} ${signer}`;
238
+ return problem(`the provenance of ${id} ${signer}`);
221
239
  const identity = releaseIdentity(expected.version);
222
240
  if (signer.names !== `URI:${identity}`) {
223
241
  const single = /^URI:([^,\s]+)$/u.exec(signer.names)?.[1];
224
242
  const shown = single === undefined ? 'a certificate with other names' : printable(single);
225
- return `${id} was signed by ${shown}, not by ${identity}`;
243
+ return problem(`${id} was signed by ${shown}, not by ${identity}`);
226
244
  }
227
245
  const { statement } = signer;
228
246
  if (statement.predicateType !== PROVENANCE)
229
- return `the provenance of ${id} is another kind of statement`;
247
+ return problem(`the provenance of ${id} is another kind of statement`);
230
248
  const subjects = statement.subject;
231
249
  const purl = `pkg:npm/${RAROG_PACKAGE_NAME.replace(/^@/u, '%40')}@${expected.version}`;
232
250
  const subject = Array.isArray(subjects) && subjects.length === 1 ? subjects[0] : undefined;
233
251
  if (!isRecord(subject) || subject.name !== purl || !isRecord(subject.digest)
234
252
  || subject.digest.sha512 !== expected.sha512) {
235
- return `the provenance of ${id} names another tarball`;
253
+ return problem(`the provenance of ${id} names another tarball`);
236
254
  }
237
255
  const { predicate } = statement;
238
256
  const definition = isRecord(predicate) ? predicate.buildDefinition : undefined;
@@ -240,7 +258,7 @@ export function provenanceProblem(audit, expected, authority = fulcioAuthority()
240
258
  const workflow = isRecord(parameters) ? parameters.workflow : undefined;
241
259
  if (!isRecord(workflow) || workflow.repository !== RELEASE_SOURCE.repository
242
260
  || workflow.path !== RELEASE_SOURCE.workflow || workflow.ref !== `refs/tags/v${expected.version}`) {
243
- return `the provenance of ${id} names another workflow than ${identity}`;
261
+ return problem(`the provenance of ${id} names another workflow than ${identity}`);
244
262
  }
245
263
  return null;
246
264
  }
@@ -295,9 +313,9 @@ export async function verifyTarball(input) {
295
313
  // which says nothing about the package.
296
314
  if (isRecord(report) && !found && !Array.isArray(report.verified))
297
315
  return { kind: 'old-npm' };
298
- const problem = provenanceProblem(report, { version, sha512 }, input.authority);
299
- if (problem !== null)
300
- return { kind: 'refused', summary: problem, fix: REPORT_FIX };
316
+ const refusal = provenanceProblem(report, { version, sha512 }, input.authority);
317
+ if (refusal !== null)
318
+ return { kind: 'refused', ...refusal };
301
319
  input.log(` npm: ${id} provenance verified: ${releaseIdentity(version)}`);
302
320
  return { kind: 'verified' };
303
321
  }
@@ -5,21 +5,24 @@
5
5
  * installation's or when the new version needs a newer Node. Then npm downloads the tarball of the highest version
6
6
  * above this one up to it into a temporary directory (npm's release age gate holds, also from the environment, and
7
7
  * never gives an older version; a gate that holds every version back is a warning that names the day npm lets the next
8
- * one in), `update-provenance.ts` checks that one file, and npm installs exactly that file with
9
- * `--ignore-scripts`. It finishes nothing: `update.ts` hands a new version to that version's own `rarog update
10
- * --finish`. After npm has replaced the package files this process only reads one file and starts a child, so it never
11
- * loads a module from the new files (no dynamic import).
8
+ * one in); a pre-release in that range is refused. With `--beta` the target is the higher of the dist-tags `beta` and
9
+ * `latest` (`update-channel.ts`), read with its `engines` and `deprecated` and downloaded as that exact version.
10
+ * `update-provenance.ts` checks that one file, and npm installs exactly that file with `--ignore-scripts`. It finishes
11
+ * nothing: `update.ts` hands a new version to that version's own `rarog update --finish`. After npm has replaced the
12
+ * package files this process only reads one file and starts a child, so it never loads a module from the new files
13
+ * (no dynamic import).
12
14
  */
13
15
  import { spawn } from 'node:child_process';
14
16
  import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';
15
17
  import os from 'node:os';
16
18
  import path from 'node:path';
17
- import { PACKAGE_INSTALL, RAROG_PACKAGE_NAME, isPackageName, npmBinDir, npmSelfUpdate, npmUpdateInstallArgs, npmUpdatePackArgs, otherPackageFix, packageCommands, packageManagerOf, } from '../install/repair.js';
19
+ import { PACKAGE_INSTALL, RAROG_PACKAGE_NAME, isPackageName, npmBinDir, npmSelfUpdate, npmUpdateExactPackArgs, npmUpdateInstallArgs, npmUpdatePackArgs, otherPackageFix, packageCommands, packageManagerOf, } from '../install/repair.js';
18
20
  import { NPM_AGE_GATE_CONFIG, firstNpmError, npmCliOf, npmEnv } from '../install/sdk.js';
19
21
  import { readRegularFileSync } from '../safe-read.js';
20
22
  import { VERSION_RE } from '../version.js';
21
23
  import { trackChild } from './child-output.js';
22
24
  import { SetupInterrupted } from './setup.js';
25
+ import { channelTarget, gateExcludes, isPrerelease } from './update-channel.js';
23
26
  import { packedTarball, verifyTarball } from './update-provenance.js';
24
27
  /** `npm prefix -g`: where npm installs global packages. */
25
28
  const PREFIX_ARGS = ['prefix', '-g'];
@@ -30,6 +33,12 @@ const VIEW_ARGS = ['view', `${RAROG_PACKAGE_NAME}@latest`, 'version', 'engines',
30
33
  * prints `<key>=<value>` per key when it gets more than one, `null` for a key that is not set).
31
34
  */
32
35
  const GATE_CONFIG_ARGS = ['config', 'get', 'min-release-age', 'before', '-g'];
36
+ /** {@link GATE_CONFIG_ARGS} of `--beta` with `min-release-age-exclude` (npm prints the list joined with commas). */
37
+ const BETA_GATE_CONFIG_ARGS = ['config', 'get', 'min-release-age', 'before', 'min-release-age-exclude', '-g'];
38
+ /** `npm view` of the dist-tags: one object, tag → version (`rarog update --beta`). */
39
+ const TAGS_ARGS = ['view', RAROG_PACKAGE_NAME, 'dist-tags', '--json'];
40
+ /** `npm view` of the exact target of `--beta`: its version, the Node it needs, and its deprecation when it has one. */
41
+ const targetViewArgs = (version) => ['view', `${RAROG_PACKAGE_NAME}@${version}`, 'version', 'engines', 'deprecated', '--json'];
33
42
  /**
34
43
  * `npm view` with two fields, so one JSON object `{ time, versions }`: the publication time of every version ever
35
44
  * published (`{ "<version>": "<ISO>", created, modified }`) and the versions the registry still has.
@@ -172,7 +181,7 @@ function isRecord(value) {
172
181
  * `npm unpublish` removes a version from `versions` and keeps its `time`. `null` for another shape (`time` not an
173
182
  * object of strings, `versions` not an array of strings, a date that does not parse, a version of the range without a
174
183
  * time), for no version in the range, and for a publication in the future or a day already past, which the gate would
175
- * not have held back.
184
+ * not have held back. With `only` (the exact target of `--beta`) that version alone counts, not the range.
176
185
  */
177
186
  export function ageGateWait(answer, gate) {
178
187
  if (!isRecord(answer))
@@ -186,7 +195,7 @@ export function ageGateWait(answer, gate) {
186
195
  for (const version of versions) {
187
196
  if (typeof version !== 'string')
188
197
  return null;
189
- if (!inInstallRange(version, gate.above, gate.upTo))
198
+ if (gate.only === undefined ? !inInstallRange(version, gate.above, gate.upTo) : version !== gate.only)
190
199
  continue;
191
200
  const published = time[version];
192
201
  const at = typeof published === 'string' ? Date.parse(published) : Number.NaN;
@@ -374,59 +383,133 @@ export async function downloadStep(input) {
374
383
  return stop({ state: 'problem', summary: `npm installs into ${npmPrefix}, not into ${prefix} of this installation`,
375
384
  fix: manual });
376
385
  }
377
- const viewRun = await runNpm(npm, VIEW_ARGS, () => { });
378
- if (viewRun.code !== 0) {
379
- header(`Rarog update ${current}`);
380
- return failed('registry check', 'view', viewRun, 'check the network, then rarog update');
381
- }
382
- let latest = null;
383
- let engines;
384
- try {
385
- const parsed = JSON.parse(viewRun.stdout);
386
- latest = typeof parsed?.version === 'string' && VERSION_RE.test(parsed.version) ? parsed.version : null;
387
- engines = parsed?.engines;
388
- }
389
- catch {
390
- latest = null;
391
- }
392
- if (latest === null) {
393
- header(`Rarog update ${current}`);
394
- view.detail(` npm view: ${viewRun.stdout.trim().slice(0, 300)}`);
395
- return stop({ state: 'problem', summary: `npm gave no version of ${RAROG_PACKAGE_NAME}`,
396
- fix: 'rarog update again later' });
397
- }
398
- view.detail(` npm: ${RAROG_PACKAGE_NAME}@latest is ${latest}; this installation is ${current}`);
399
- const order = compareVersions(latest, current);
400
- if (latest === current || (order !== null && order <= 0)) {
401
- header(`Rarog update ${current}`);
402
- view.endStep({
403
- title: TITLE, state: 'warn', skipped: true,
404
- summary: latest === current ? `rarog ${current} is the latest` : `rarog ${current} is newer than ${latest} on npm`,
405
- }, input.home);
406
- return { kind: 'finish-here' };
407
- }
408
- header(`Rarog update ${current} → ${latest}`);
386
+ const beta = input.beta === true;
387
+ /** The command a fix runs again: the same channel. */
388
+ const again = beta ? 'rarog update --beta' : 'rarog update';
389
+ const network = `check the network, then ${again}`;
390
+ const noVersion = (run, summary) => {
391
+ view.detail(` npm view: ${run.stdout.trim().slice(0, 300)}`);
392
+ return stop({ state: 'problem', summary, fix: `${again} again later` });
393
+ };
394
+ /** Without a flag: the newest release from `@latest`, installed through npm's range above this version. */
395
+ const readLatest = async () => {
396
+ const viewRun = await runNpm(npm, VIEW_ARGS, () => { });
397
+ if (viewRun.code !== 0) {
398
+ header(`Rarog update ${current}`);
399
+ return failed('registry check', 'view', viewRun, network);
400
+ }
401
+ let latest = null;
402
+ let engines;
403
+ try {
404
+ const parsed = JSON.parse(viewRun.stdout);
405
+ latest = typeof parsed?.version === 'string' && VERSION_RE.test(parsed.version) ? parsed.version : null;
406
+ engines = parsed?.engines;
407
+ }
408
+ catch {
409
+ latest = null;
410
+ }
411
+ if (latest === null) {
412
+ header(`Rarog update ${current}`);
413
+ return noVersion(viewRun, `npm gave no version of ${RAROG_PACKAGE_NAME}`);
414
+ }
415
+ view.detail(` npm: ${RAROG_PACKAGE_NAME}@latest is ${latest}; this installation is ${current}`);
416
+ const order = compareVersions(latest, current);
417
+ if (latest === current || (order !== null && order <= 0)) {
418
+ header(`Rarog update ${current}`);
419
+ view.endStep({
420
+ title: TITLE, state: 'warn', skipped: true,
421
+ summary: latest === current ? `rarog ${current} is the latest` : `rarog ${current} is newer than ${latest} on npm`,
422
+ }, input.home);
423
+ return { kind: 'finish-here' };
424
+ }
425
+ header(`Rarog update ${current} → ${latest}`);
426
+ return { version: latest, engines, note: null };
427
+ };
428
+ /**
429
+ * `--beta`: the higher of the dist-tags `beta` and `latest`, then that exact version's `engines` and deprecation.
430
+ * A deprecated target is not installed: npm would install an exact version whatever its deprecation.
431
+ */
432
+ const readChannel = async () => {
433
+ const tagsRun = await runNpm(npm, TAGS_ARGS, () => { });
434
+ if (tagsRun.code !== 0) {
435
+ header(`Rarog update ${current}`);
436
+ return failed('registry check', 'view', tagsRun, network);
437
+ }
438
+ let channel = null;
439
+ try {
440
+ channel = channelTarget(JSON.parse(tagsRun.stdout));
441
+ }
442
+ catch {
443
+ channel = null;
444
+ }
445
+ if (channel === null) {
446
+ header(`Rarog update ${current}`);
447
+ return noVersion(tagsRun, `npm gave no version of ${RAROG_PACKAGE_NAME}`);
448
+ }
449
+ const { target, note } = channel;
450
+ view.detail(` npm: ${RAROG_PACKAGE_NAME}@latest is ${channel.latest}, @beta is ${channel.beta ?? 'none'}; this`
451
+ + ` installation is ${current}`);
452
+ const order = compareVersions(target, current);
453
+ if (order === null) {
454
+ header(`Rarog update ${current}`);
455
+ return stop({ state: 'problem', fix: manual,
456
+ summary: `rarog ${current} has no version order against ${target}` });
457
+ }
458
+ if (order <= 0) {
459
+ header(`Rarog update ${current}`);
460
+ const summary = order === 0 ? `rarog ${current} is the newest on npm`
461
+ : `rarog ${current} is newer than ${target} on npm`;
462
+ view.endStep({
463
+ title: TITLE, state: 'warn', skipped: note === null, summary: note === null ? summary : `${summary}; ${note}`,
464
+ }, input.home);
465
+ return { kind: 'finish-here' };
466
+ }
467
+ header(`Rarog update ${current} → ${target}`);
468
+ const targetRun = await runNpm(npm, targetViewArgs(target), () => { });
469
+ if (targetRun.code !== 0)
470
+ return failed('registry check', 'view', targetRun, network);
471
+ let manifest = null;
472
+ try {
473
+ const parsed = JSON.parse(targetRun.stdout);
474
+ manifest = isRecord(parsed) ? parsed : null;
475
+ }
476
+ catch {
477
+ manifest = null;
478
+ }
479
+ if (manifest?.version !== target) {
480
+ return noVersion(targetRun, `npm gave no version ${target} of ${RAROG_PACKAGE_NAME}`);
481
+ }
482
+ if (typeof manifest.deprecated === 'string' && manifest.deprecated !== '') {
483
+ // The deprecation message is the publisher's text: neither the screen nor the log repeats it.
484
+ view.detail(` npm: ${RAROG_PACKAGE_NAME}@${target} is deprecated`);
485
+ return stop({ state: 'warn', summary: `rarog ${target} is deprecated on npm, so ${current} stays` }, 0);
486
+ }
487
+ return { version: target, engines: manifest.engines, note };
488
+ };
489
+ const chosen = beta ? await readChannel() : await readLatest();
490
+ if ('kind' in chosen)
491
+ return chosen;
492
+ const { version: target, engines, note } = chosen;
409
493
  const range = engines !== null && typeof engines === 'object' && 'node' in engines ? engines.node : undefined;
410
494
  if (typeof range === 'string') {
411
495
  const fits = nodeSatisfies(process.versions.node, range);
412
496
  if (fits === false) {
413
497
  return stop({
414
- state: 'problem', summary: `rarog ${latest} needs Node ${range}; this is ${process.versions.node}`,
498
+ state: 'problem', summary: `rarog ${target} needs Node ${range}; this is ${process.versions.node}`,
415
499
  fix: `nvm install --lts, ${PACKAGE_INSTALL.npm}, then rarog setup`,
416
500
  });
417
501
  }
418
502
  if (fits === null)
419
503
  view.detail(` engines.node ${range}: a form this check does not read, so the install goes on`);
420
504
  }
421
- view.screen.progress(`downloading ${latest}…`);
422
- const newest = latest;
505
+ view.screen.progress(`downloading ${target}…`);
423
506
  /**
424
- * When npm's age gate lets a version above `above` in: `min-release-age` from npm's own config, the
425
- * publication times from the registry; `null` = no date (`before` set, a failed call, another shape), and the text
426
- * stays without one.
507
+ * When npm's age gate lets a version above `above` in (with `--beta`: the target alone): `min-release-age` from
508
+ * npm's own config, the publication times from the registry; `null` = no date (`before` set, with `--beta` this
509
+ * package in `min-release-age-exclude`, a failed call, another shape), and the text stays without one.
427
510
  */
428
511
  const gateWait = async (above) => {
429
- const config = await runNpm(npm, GATE_CONFIG_ARGS, log);
512
+ const config = await runNpm(npm, beta ? BETA_GATE_CONFIG_ARGS : GATE_CONFIG_ARGS, log);
430
513
  if (config.interrupted)
431
514
  throw new SetupInterrupted('npm config was interrupted (Ctrl-C)');
432
515
  const days = config.code === 0 ? gateDaysOf(config.stdout) : null;
@@ -434,6 +517,11 @@ export async function downloadStep(input) {
434
517
  view.detail(' npm age gate: no date (min-release-age not read, or before is set)');
435
518
  return null;
436
519
  }
520
+ if (beta && gateExcludes(config.stdout, RAROG_PACKAGE_NAME)) {
521
+ // npm lets an excluded package in however young: what it held back is a dependency.
522
+ view.detail(` npm age gate: no date (${RAROG_PACKAGE_NAME} is in min-release-age-exclude)`);
523
+ return null;
524
+ }
437
525
  const timeRun = await runNpm(npm, TIME_ARGS, () => { });
438
526
  if (timeRun.interrupted)
439
527
  throw new SetupInterrupted('npm view was interrupted (Ctrl-C)');
@@ -444,7 +532,7 @@ export async function downloadStep(input) {
444
532
  catch {
445
533
  answer = null;
446
534
  }
447
- const wait = ageGateWait(answer, { days, above, upTo: newest, now: Date.now() });
535
+ const wait = ageGateWait(answer, { days, above, upTo: target, now: Date.now(), ...(beta ? { only: target } : {}) });
448
536
  const why = timeRun.code === 0 ? 'no version to date' : firstNpmError(timeRun.stderr);
449
537
  view.detail(wait === null ? ` npm age gate: no date (npm view time: ${why})`
450
538
  : ` npm age gate: ${String(days)} days; ${wait.version} is in from ${wait.from}`);
@@ -454,7 +542,7 @@ export async function downloadStep(input) {
454
542
  const heldBack = async (detail) => {
455
543
  view.detail(` ${detail}`);
456
544
  const wait = await gateWait(current);
457
- const summary = wait === null ? `rarog ${latest} not installed yet (npm age gate)` : ageGateText(wait);
545
+ const summary = wait === null ? `rarog ${target} not installed yet (npm age gate)` : ageGateText(wait);
458
546
  return stop({ state: 'warn', summary }, 0);
459
547
  };
460
548
  /** stderr of a call whose stdout is JSON for this process, to the run log. */
@@ -463,7 +551,8 @@ export async function downloadStep(input) {
463
551
  if (text.trim() !== '')
464
552
  log(` npm: ${text.trimEnd()}`);
465
553
  };
466
- const tooYoung = `npm found no version above ${current} old enough for its release age gate; ${current} stays`;
554
+ const tooYoung = beta ? `npm found ${target} not old enough for its release age gate; ${current} stays`
555
+ : `npm found no version above ${current} old enough for its release age gate; ${current} stays`;
467
556
  // The tarball and the audit project live in a directory of this run only, removed on every way out.
468
557
  const work = mkdtempSync(path.join(os.tmpdir(), 'rarog-update-'));
469
558
  try {
@@ -471,30 +560,37 @@ export async function downloadStep(input) {
471
560
  const auditDir = path.join(work, 'audit');
472
561
  mkdirSync(tarballDir);
473
562
  mkdirSync(auditDir);
474
- const pack = await runNpm(npm, npmUpdatePackArgs(current, latest, tarballDir), () => { });
563
+ const packArgs = beta ? npmUpdateExactPackArgs(target, tarballDir) : npmUpdatePackArgs(current, target, tarballDir);
564
+ const pack = await runNpm(npm, packArgs, () => { });
475
565
  logStderr(pack);
476
566
  if (pack.code !== 0 && !pack.interrupted && NO_VERSION_OLD_ENOUGH.test(pack.stderr))
477
567
  return await heldBack(tooYoung);
478
568
  if (pack.code !== 0)
479
- return failed('download', 'pack', pack, 'check the network, then rarog update');
569
+ return failed('download', 'pack', pack, network);
480
570
  const tarball = packedTarball(pack.stdout, tarballDir);
481
- if (tarball === null || !inInstallRange(tarball.version, current, latest)) {
571
+ if (tarball === null || (beta ? tarball.version !== target : !inInstallRange(tarball.version, current, target))) {
482
572
  view.detail(` npm pack: ${pack.stdout.trim().slice(0, 300)}`);
483
- return stop({ state: 'problem', summary: `npm gave no tarball of ${RAROG_PACKAGE_NAME} above ${current}`,
484
- fix: 'rarog update again later' });
573
+ return stop({ state: 'problem', fix: `${again} again later`, summary: tarball === null || !beta
574
+ ? `npm gave no tarball of ${RAROG_PACKAGE_NAME} ${beta ? target : `above ${current}`}`
575
+ : `npm gave ${tarball.version}, not ${target}` });
576
+ }
577
+ // Without --beta the range admits a pre-release of the latest's own version (npm's range rule), and the age gate
578
+ // can pick one; rarog update never installs a pre-release without the flag.
579
+ if (!beta && isPrerelease(tarball.version)) {
580
+ return stop({ state: 'problem', fix: 'rarog update --beta, or rarog update again later',
581
+ summary: `npm gave the pre-release ${tarball.version}; rarog update without --beta installs only releases` });
485
582
  }
486
583
  const check = await verifyTarball({
487
584
  npm: (args, cwd) => runNpm({ ...npm, cwd }, args, () => { }), tarball, auditDir, cwd: input.home, log,
488
585
  ...(input.provenanceAuthority === undefined ? {} : { authority: input.provenanceAuthority }),
489
586
  });
490
- if (check.kind === 'npm-failed') {
491
- return failed(check.what, check.command, check.result, 'check the network, then rarog update');
492
- }
587
+ if (check.kind === 'npm-failed')
588
+ return failed(check.what, check.command, check.result, network);
493
589
  if (check.kind === 'old-npm') {
494
590
  // The npm to update is the one this step runs, next to this node.
495
591
  const selfUpdate = npmSelfUpdate(npmCli) ?? `update the npm next to ${input.execPath} to 11.12 or newer`;
496
592
  return stop({ state: 'problem', summary: 'this npm does not list attestations (it needs npm 11.12 or newer)',
497
- fix: `${selfUpdate}, then rarog update` });
593
+ fix: `${selfUpdate}, then ${again}` });
498
594
  }
499
595
  if (check.kind === 'refused')
500
596
  return stop({ state: 'problem', summary: check.summary, fix: check.fix });
@@ -505,22 +601,24 @@ export async function downloadStep(input) {
505
601
  return await heldBack(tooYoung);
506
602
  }
507
603
  if (install.code !== 0)
508
- return failed('install', 'install', install, 'check the network, then rarog update');
604
+ return failed('install', 'install', install, network);
509
605
  const after = readInstalledVersion(root);
510
606
  if (after !== tarball.version) {
511
607
  return stop({ state: 'problem', fix: manual, summary: after === null
512
608
  ? `after npm there is no readable package.json in ${root}`
513
609
  : `after npm, ${root} has ${after}, not ${tarball.version}` });
514
610
  }
515
- if (after !== latest) {
611
+ if (after !== target) {
516
612
  const wait = await gateWait(after);
517
- const summary = wait === null ? `rarog ${after} installed, ${latest} not yet (npm age gate)`
613
+ const summary = wait === null ? `rarog ${after} installed, ${target} not yet (npm age gate)`
518
614
  : ageGateText(wait, after);
519
615
  view.endStep({ title: TITLE, state: 'warn', summary }, input.home);
520
616
  }
521
617
  else {
522
618
  // The finish runs in a new process with its own screen: a line counted here would never be shown.
523
- view.endStep({ title: TITLE, state: 'ok', summary: `rarog ${latest} from npm`, changed: true }, input.home);
619
+ const summary = `rarog ${target} from npm`;
620
+ view.endStep(note === null ? { title: TITLE, state: 'ok', summary, changed: true }
621
+ : { title: TITLE, state: 'warn', summary: `${summary}; ${note}`, changed: true }, input.home);
524
622
  }
525
623
  return { kind: 'finish-new', installed: { version: after, root } };
526
624
  }
@@ -36,11 +36,13 @@ import { unitFilePath } from './systemd-unit.js';
36
36
  import { downloadStep } from './update-registry.js';
37
37
  import { UPDATE_LOCK_TOKEN, markInstalled, takeUpdateLock, updateLockOf } from './update-lock.js';
38
38
  import { sentenceFor, usageFor } from './screen/prose.js';
39
- export const UPDATE_USAGE = ` rarog update [--data-dir <dir>] [--verbose]
40
- Updates the npm package on this machine, in a terminal: the newest version from the npm registry (npm next
39
+ export const UPDATE_USAGE = ` rarog update [--beta] [--data-dir <dir>] [--verbose]
40
+ Updates the npm package on this machine, in a terminal: the newest release from the npm registry (npm next
41
41
  to this installation's node, without install scripts), then the finish below by the new version itself. A
42
42
  version npm holds back (release age gate) is reported and nothing else changes. One update runs at a time
43
43
  (the update lock in ~/.config/rarog). Details go to the log <data directory>/logs/update-<time>.log.
44
+ --beta: the newer of the newest beta and the newest release (npm dist-tags beta and latest); without it a
45
+ beta is never installed.
44
46
  rarog update --finish [--data-dir <dir>] [--verbose]
45
47
  Finishes the version installed on this machine, without the registry: the Claude SDK it pins (downloaded
46
48
  without a question), the hook copy (after its diff and a question, as in setup; without the question when the
@@ -60,6 +62,7 @@ const DEFAULT_DEPS = {
60
62
  };
61
63
  function parseFlags(argv) {
62
64
  let finish = false;
65
+ let beta = false;
63
66
  let dataDir = null;
64
67
  let verbose = false;
65
68
  for (let i = 1; i < argv.length; i += 1) {
@@ -67,6 +70,9 @@ function parseFlags(argv) {
67
70
  if (arg === '--finish') {
68
71
  finish = true;
69
72
  }
73
+ else if (arg === '--beta') {
74
+ beta = true;
75
+ }
70
76
  else if (arg === '--verbose') {
71
77
  verbose = true;
72
78
  }
@@ -85,7 +91,10 @@ function parseFlags(argv) {
85
91
  throw new Usage(`rarog update: unknown argument "${arg}".`);
86
92
  }
87
93
  }
88
- return { finish, dataDir, verbose };
94
+ if (finish && beta) {
95
+ throw new Usage('rarog update: --beta chooses what rarog update downloads, and --finish downloads nothing.');
96
+ }
97
+ return { finish, beta, dataDir, verbose };
89
98
  }
90
99
  /** The environment of the steps and their child processes: without the lock token, which only this process checks. */
91
100
  function withoutToken(env) {
@@ -261,6 +270,7 @@ async function run(io, update, deps) {
261
270
  if (!update.flags.finish) {
262
271
  const outcome = await downloadStep({
263
272
  io: stepIo, view, home, root: update.root, execPath: process.execPath, refused: EXIT_REFUSED,
273
+ beta: update.flags.beta,
264
274
  stepHeader: `[1/${String(STEPS + offset)}] Download`, ...(deps.npmCli === undefined ? {} : { npmCli: deps.npmCli }),
265
275
  ...(deps.provenanceAuthority === undefined ? {} : { provenanceAuthority: deps.provenanceAuthority }),
266
276
  });
@@ -3,7 +3,10 @@ export const TURNS_MAX_READS = 3;
3
3
  /**
4
4
  * Takes the session, reads its turns and takes it again until the conversation holds still across a read. `finish`
5
5
  * runs synchronously right after the last take, with no `await` in between, so the route answers for the session as
6
- * it was taken. A body carries the token and `stateSince` of the target it was read for, never of a later take.
6
+ * it was taken. A body carries the token, `stateSince` and `readMark` of the target it was read for, taken before
7
+ * that read, never of a take after it: a message that reaches the session during the read gives the body an older
8
+ * mark. A body with no messages or with a trimmed message carries the mark that names no read instead (`NO_READ_MARK`
9
+ * in `turns.ts`).
7
10
  */
8
11
  export async function readSettledTurns(reader, take, count, finish) {
9
12
  let taken = take();