@osdlc/wayfinder 0.7.0 → 0.7.2

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.
package/dist/serve.js CHANGED
@@ -1,46 +1,45 @@
1
1
  /**
2
- * The web view — the same catalog as a page you can search in a browser.
2
+ * The web view: the same catalog as a page you can search in a browser.
3
3
  *
4
- * A SERVER rather than a generated file, because a file would be a snapshot:
5
- * add a task and the page is wrong with no signal that it is. Every
6
- * `/api/catalog` request re-probes, and the page re-fetches on focus and on a
7
- * slow poll, so what is on screen is what the repository currently has.
4
+ * It is a server rather than a generated file, because a file goes out of date
5
+ * as soon as a task is added, with no sign that it has. `/api/catalog`
6
+ * re-probes (requests close together share one probe), and the page re-fetches
7
+ * on focus and on a slow poll, so the screen shows what the repository has now.
8
8
  *
9
- * Loopback is not by itself a boundary, so every route is behind a token.
9
+ * Loopback alone does not keep other callers out, so every route needs a token.
10
10
  *
11
11
  * Other local users on this machine can reach 127.0.0.1, and can read a
12
- * process's argv and environment for as long as it runs. So the session token
13
- * never appears in a URL or an argv. What does appear in a URL is the boot
14
- * token, which is single-use and expires in a minute; burning it on first use
15
- * bounds the window to the moment between opening the browser and the page
16
- * loading.
12
+ * process's argv and environment while it runs. So the session token never
13
+ * appears in a URL or an argv. The URL carries the boot token instead. It works
14
+ * once and expires after a minute, so it is only usable between opening the
15
+ * browser and the page loading.
17
16
  *
18
- * Any website the user visits can also issue cross-origin requests to
19
- * 127.0.0.1. A cookie would ride along on those — that is CSRF — while a
20
- * request header does not, and the token header is a non-simple header, so a
21
- * cross-origin fetch must first pass a CORS preflight this server never
22
- * answers. Hence header auth, and hence the boot token is accepted on the page
23
- * routes only, never on the API.
17
+ * Any website the user visits can also send cross-origin requests to
18
+ * 127.0.0.1. A cookie would be sent with those (that is CSRF), but a request
19
+ * header is not. The token header is not a CORS-safelisted header, so a
20
+ * cross-origin fetch must first pass a CORS preflight, which this server never
21
+ * answers. That is why auth uses a header, and why the boot token is accepted
22
+ * on the page routes only, never on the API.
24
23
  *
25
24
  * `/api/run` hands this server's own terminal to a task and exits. It takes a
26
- * task id and nothing else — see the note on the route.
25
+ * task id and nothing else (see the note on the route).
27
26
  *
28
- * `/api/trust` POST permits this repository's code to run from now on, so it is
29
- * gated a third time, beyond the method and the token: the grant must be
30
- * APPLICABLE — the same condition that decides whether the page may offer the
31
- * button at all. Without it a grant would override `--no-exec` or write the
32
- * store under `--exec`. DELETE revokes and carries no such gate.
27
+ * `POST /api/trust` lets this repository's code run from now on, so it has a
28
+ * third check beyond the method and the token: the grant must be applicable.
29
+ * That is the same condition that decides whether the page shows the button.
30
+ * Without it a grant would override `--no-exec` or write the store under
31
+ * `--exec`. DELETE revokes and has no such check.
33
32
  */
34
- import { homedir } from 'node:os';
35
33
  import { spawnRunner, streamRunner } from '@osdlc/command-seam';
36
34
  import { tasks as allTasks, } from '@osdlc/system-model/detect';
37
35
  import { humanAge } from '@osdlc/system-model/duration';
38
- import { trustDecision } from '@osdlc/trust-repo';
36
+ import { homeDir, trustDecision } from '@osdlc/trust-repo';
39
37
  import { APP, BIN, PROJECT_CONFIG_FILENAME, TOKEN_HEADER } from "./app.js";
40
38
  import { acceptArgs, runArgv } from "./args.js";
41
39
  import { cacheDir } from "./cache.js";
42
40
  import { collectAndCache, freshStates, fromStore, orderedCatalog, readCachedCatalog, } from "./catalog.js";
43
41
  import { CONFIG_KEYS, collectOptionsFromConfig, configLocations, loadConfig, readRawConfigFile, setConfigValue, trustPolicyFromConfig, trustPolicyOptions, validateConfig, writeConfigFile, } from "./config.js";
42
+ import { terminalSafe } from "./terminal-text.js";
44
43
  import { appTrustStore } from "./trust-store.js";
45
44
  import { serveFetch } from "./http.js";
46
45
  import { buildPage } from "./page.js";
@@ -48,7 +47,7 @@ import { buildPage } from "./page.js";
48
47
  const COALESCE_MS = 1500;
49
48
  /** How long the boot token stays usable if the browser never arrives. */
50
49
  const BOOT_TTL_MS = 60_000;
51
- /** 128 bits, hex. `getRandomValues` is the CSPRNG; `Math.random` is not. */
50
+ /** 128 bits, hex. `getRandomValues` is cryptographically secure; `Math.random` is not. */
52
51
  function secret() {
53
52
  const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
54
53
  return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
@@ -63,22 +62,22 @@ function tokenEquals(a, b) {
63
62
  return diff === 0;
64
63
  }
65
64
  /**
66
- * One bare status line for every failure. Which check failed — no token, wrong
67
- * token, spent boot token, an API route refusing a boot token — is what an
68
- * attacker would use to aim, and the caller who is authorized never needs it.
65
+ * One bare status line for every failure. An attacker could use the knowledge
66
+ * of which check failed (no token, wrong token, used boot token, a boot token
67
+ * on an API route), and an authorized caller never needs it.
69
68
  */
70
69
  function unauthorized() {
71
70
  return new Response('unauthorized', { status: 401 });
72
71
  }
73
72
  /**
74
- * The same 401, dressed for a human, and only on the page routes. After boot
75
- * the address bar no longer carries `?boot=`, so a reload is a reflex — and a
76
- * bare status line renders as twelve bytes of plain text with no way back.
73
+ * The same 401 as a page a person can read, on the page routes only. After
74
+ * sign-in the address bar no longer has `?boot=`, so a reload fails. A bare
75
+ * status line would show one word of plain text and no way to recover.
77
76
  *
78
- * One document for every page-route failure — no token, wrong token, spent
79
- * token, expired token — so it still says nothing about which check failed.
80
- * Inline styles and no external requests: this server answers nothing else to
81
- * an unauthenticated caller.
77
+ * One document for every page-route failure (no token, wrong token, used
78
+ * token, expired token), so it still does not say which check failed. Styles
79
+ * are inline and there are no external requests, because this server serves
80
+ * nothing else to an unauthenticated caller.
82
81
  */
83
82
  function unauthorizedPage() {
84
83
  const body = `<!doctype html>
@@ -121,23 +120,23 @@ function unauthorizedPage() {
121
120
  });
122
121
  }
123
122
  /**
124
- * Painting for the one line this server echoes before the task takes over.
125
- * The TUI's ANSI helpers are private to that module, so the shape — a dim `$`
126
- * and bold argv — is restated here rather than exported across the seam.
123
+ * Colours for the one line this server prints before the task takes over.
124
+ * The TUI's ANSI helpers are private to that module, so the same style (a dim
125
+ * `$` and bold argv) is repeated here rather than exported.
127
126
  */
128
127
  const PAINT = !process.env['NO_COLOR'] && process.stdout.isTTY;
129
128
  const dim = (s) => (PAINT ? `\x1b[2m${s}\x1b[0m` : s);
130
129
  const bold = (s) => (PAINT ? `\x1b[1m${s}\x1b[0m` : s);
131
130
  /**
132
- * Hand the terminal to `argv` and take this process out of the way: the web
133
- * twin of the TUI's `runAndExit`, down to its cwd rule. It streams through the
134
- * command seam, so the task owns the terminal while it runs. `argv` runs
135
- * without a shell; `display` would be wrong to run, since its
136
- * `<placeholders>` read as redirections.
131
+ * Hand the terminal to `argv` and exit when it finishes. This matches the
132
+ * TUI's `runAndExit`, including how it picks the cwd. It streams through
133
+ * `@osdlc/command-seam`, so the task has the terminal while it runs. `argv`
134
+ * runs without a shell. Running `display` would be wrong, since a shell reads
135
+ * its `<placeholders>` as redirections.
137
136
  */
138
137
  function runAndExit(root, task, argv) {
139
138
  // Echo what actually runs, not `display`.
140
- process.stdout.write(`${dim('$')} ${bold(argv.join(' '))}\n`);
139
+ process.stdout.write(`${dim('$')} ${bold(terminalSafe(argv.join(' ')))}\n`);
141
140
  const [binary, ...rest] = argv;
142
141
  const res = streamRunner(binary).run(rest, {
143
142
  cwd: task.cwd === '.' ? root : `${root}/${task.cwd}`,
@@ -147,17 +146,16 @@ function runAndExit(root, task, argv) {
147
146
  /**
148
147
  * Apply a settings-screen edit to `<root>/wayfinder.config.json`.
149
148
  *
150
- * A PATCH of dotted keys, not a document. Two reasons, and the second is the
151
- * one that matters:
149
+ * The request is a patch of dotted keys, not a whole document, for two
150
+ * reasons. The second matters more:
152
151
  *
153
- * - `way config set` names keys the same way, so the screen and the CLI
154
- * talk about the same thing in the same words.
155
- * - The patch is applied to the file's RAW contents, so a key this version
156
- * does not know — one from a newer wayfinder, one a person added by hand —
157
- * survives the save. Writing a validated document instead would drop it
158
- * silently, because `validateConfig` returns only the keys it recognises.
159
- * `writeConfigFile` takes a raw record precisely to make this path
160
- * writable.
152
+ * - `way config set` names keys the same way, so the screen and the CLI use
153
+ * the same names.
154
+ * - The patch is applied to the file's raw contents, so a key this version
155
+ * does not know (from a newer wayfinder, or added by hand) survives the
156
+ * save. Writing a validated document would silently drop it, because
157
+ * `validateConfig` returns only the keys it knows. `writeConfigFile`
158
+ * takes a raw record for this reason.
161
159
  *
162
160
  * Returns null on success, or the Response to send on refusal.
163
161
  */
@@ -166,9 +164,9 @@ async function writeProjectConfig(req, options) {
166
164
  const body = (await req.json().catch(() => null));
167
165
  if (body === null || !isRecord(body.set))
168
166
  return bad('expected { set: { <key>: <value> } }');
169
- // An allowlist, from the single list of settable keys. A key
170
- // outside it is refused rather than dropped: this is a write path, and a
171
- // caller whose key silently vanished would believe it had been saved.
167
+ // Only settable keys are allowed. Any other key is refused rather than
168
+ // dropped, because a caller whose key silently vanished would believe it
169
+ // had been saved.
172
170
  for (const key of Object.keys(body.set)) {
173
171
  if (!CONFIG_KEYS.includes(key))
174
172
  return bad(`${key} is not a setting`);
@@ -176,19 +174,18 @@ async function writeProjectConfig(req, options) {
176
174
  // Tool modules are code. The page never edits them; `way config set` does.
177
175
  if ('tools' in body.set)
178
176
  return bad(`tools cannot be written from the page; use "${BIN} config set tools"`);
179
- // The one value a project file may never carry. `loadConfig` already strips
180
- // it after the fact, but a write path that accepted it would put it in the
181
- // file — where a reader would see it, believe it, and be wrong about the
182
- // execution boundary. A repository cannot grant itself permission to run its
183
- // own code; that is the trust store's job.
177
+ // A project file may never hold this value. `loadConfig` already drops it on
178
+ // read, but writing it would put it in the file, where a reader would take
179
+ // it as allowing execution. A repository cannot grant itself permission to
180
+ // run its own code. That is the trust store's job.
184
181
  if (body.set['allowExec'] === true) {
185
182
  return bad('allowExec: true cannot be written to a project file — a repository cannot grant itself ' +
186
183
  'permission to run subprocesses. Trust this repository instead.');
187
184
  }
188
- // Same rule, for the same reason: a project file must not be able to
189
- // pre-authorize itself (or any class of repositories, via trust.owners).
190
- // Refused even when empty — `loadConfig` drops the whole block either way,
191
- // so the write could only ever mislead a reader of the file.
185
+ // The same rule, for the same reason: a project file must not
186
+ // pre-authorize itself (or a group of repositories, through trust.owners).
187
+ // Refused even when empty. `loadConfig` drops the whole block anyway, so
188
+ // the write could only mislead a reader of the file.
192
189
  for (const key of ['trust.paths', 'trust.owners']) {
193
190
  if (key in body.set) {
194
191
  return bad(`${key} cannot be written to a project file — a repository cannot grant itself trust. ` +
@@ -197,12 +194,11 @@ async function writeProjectConfig(req, options) {
197
194
  }
198
195
  const file = configLocations(options.root, options.env, options.home).project;
199
196
  let candidate = (await readRawConfigFile(file)) ?? {};
200
- // Both steps under one guard. `setConfigValue` type-checks each value as it
201
- // goes and throws on a bad one, so a `try` around the whole-document
202
- // validation alone left a wrong type answering 500 — the caller's mistake
203
- // reported as the server's. `validateConfig` then re-checks the MERGED
204
- // document, which catches a patch that is fine in isolation and wrong
205
- // against what the file already holds.
197
+ // Both steps are inside one `try`. `setConfigValue` type-checks each value
198
+ // and throws on a bad one, so it must be caught here too, or a wrong type
199
+ // would answer 500 and report the caller's mistake as the server's.
200
+ // `validateConfig` then checks the merged document, which catches a patch
201
+ // that is valid alone but wrong against what the file already holds.
206
202
  try {
207
203
  for (const [key, value] of Object.entries(body.set)) {
208
204
  candidate = setConfigValue(candidate, key, value);
@@ -220,34 +216,34 @@ function isRecord(value) {
220
216
  return typeof value === 'object' && value !== null && !Array.isArray(value);
221
217
  }
222
218
  /**
223
- * Single-flight catalog access, cache-aware.
219
+ * Catalog access that runs at most one probe at a time and uses the store.
224
220
  *
225
- * The in-flight PROMISE is cached, not the resolved value: caching the value
226
- * would be enough only if nothing could interleave, and collection is async.
227
- * Concurrent requests await one probe instead of starting several.
221
+ * The in-flight promise is cached, not the resolved value, because collection
222
+ * is async and requests can overlap. Concurrent requests wait on one probe
223
+ * instead of starting several.
228
224
  *
229
- * The first non-forced request answers from the store when there is one and
230
- * starts a real probe behind it, so the page appears at once on a repository
231
- * whose slowest runner takes seconds. Every later request gets the freshest
232
- * thing available, and `?force` is always a real probe — an explicit refresh
233
- * that could be answered from a cache is not a refresh.
225
+ * The first non-forced request answers from the store when it has an answer,
226
+ * and starts a real probe in the background. So the page appears at once even
227
+ * when the slowest runner takes seconds. Every later request gets the newest
228
+ * result available. `?force` always runs a real probe, since a refresh
229
+ * answered from a cache is not a refresh.
234
230
  *
235
- * A forced request never joins a probe already running: that probe reads the
236
- * world as it was before whatever forced this one. It WAITS the running probe
237
- * out and then takes its own, so a force landing on a busy source costs up to
238
- * two probe durations. Only `?force` callers pay it — the poll and the
239
- * focus reload do not — and it is the price of "always re-reads".
231
+ * A forced request never joins a probe already running, because that probe
232
+ * started before whatever caused the force. It waits for the running probe to
233
+ * finish and then starts its own, so it can take up to two probe durations.
234
+ * Only `?force` callers wait this long. The poll and the focus reload do not.
240
235
  */
241
236
  function createCatalogSource(project, root, options,
242
237
  /**
243
- * Read per probe, never captured: saving `runners.order` changes it mid-run,
244
- * exactly as saving a collect option mutates `options` in place.
238
+ * Read on each probe, never captured, because saving `runners.order` changes
239
+ * it while the server runs, just as saving a collect option changes `options`
240
+ * in place.
245
241
  */
246
242
  runnerOrder, store) {
247
243
  let pending = null;
248
244
  let settledAt = 0;
249
245
  let last = null;
250
- /** The store is only ever worth asking once; after that `last` is better. */
246
+ /** The store is read at most once. After that, `last` is newer. */
251
247
  let consultedStore = false;
252
248
  const probe = () => {
253
249
  pending ??= collectAndCache(project, root, options, store)
@@ -268,11 +264,10 @@ runnerOrder, store) {
268
264
  };
269
265
  return async (force) => {
270
266
  if (force) {
271
- // Never ADOPT an in-flight probe. A forced request is made because
272
- // something just changed — a trust grant, a saved setting — and a probe
273
- // that started before the change answers from before it. Wait the
274
- // running one out (its `finally` clears `pending` as it settles, so the
275
- // call below starts a new one) rather than joining it.
267
+ // Never join an in-flight probe. A forced request follows a change (a
268
+ // trust grant, a saved setting), and a probe that started before the
269
+ // change returns the old state. Wait for the running probe to finish
270
+ // (its `finally` clears `pending`, so the call below starts a new one).
276
271
  const running = pending;
277
272
  if (running !== null)
278
273
  await running.catch(() => { });
@@ -282,17 +277,16 @@ runnerOrder, store) {
282
277
  return last;
283
278
  if (!consultedStore) {
284
279
  consultedStore = true;
285
- // Never throws and never probes — a broken store is a miss, and a miss
286
- // falls through to the probe below, which is what would have happened
287
- // with no cache at all.
280
+ // Never throws and never probes. A broken store counts as a miss, and a
281
+ // miss falls through to the probe below, as if there were no cache.
288
282
  const stored = await readCachedCatalog(project, root, options, store);
289
- // Only worth serving when something came OUT of the store: with
290
- // execution off, a cold store still yields withheld reports.
283
+ // Serve it only when something came from the store. With execution off,
284
+ // an empty store still returns withheld reports.
291
285
  if (stored.catalog !== null && fromStore(stored)) {
292
286
  last = { catalog: orderedCatalog(stored.catalog, runnerOrder()), cache: stored.runners };
293
287
  settledAt = Date.now();
294
- // Behind the answer, not in front of it. A failure there is the probe's
295
- // problem: this request has already been answered from the store.
288
+ // Probe in the background, after answering. A probe failure is ignored
289
+ // here, since this request was already answered from the store.
296
290
  void probe().catch(() => { });
297
291
  return last;
298
292
  }
@@ -303,31 +297,28 @@ runnerOrder, store) {
303
297
  /**
304
298
  * Bind the port and return the server's handle, without printing or opening anything.
305
299
  *
306
- * Split out of {@link serve} because `serve` never returns — it is the process's
307
- * last statement — and a function that never returns cannot be tested. The
308
- * mutating endpoint is the one part of this file that must not regress silently,
309
- * so it needs a caller that can bind an ephemeral port, drive real requests and
310
- * stop again.
300
+ * Split out of {@link serve} because `serve` never returns, and a function
301
+ * that never returns cannot be tested. Tests need to bind an ephemeral port,
302
+ * send real requests to the endpoints that write, and stop again.
311
303
  *
312
- * The catalog source comes back with the handle because it is the server's, not
313
- * a second one: the startup banner must report the probe the page will see.
304
+ * The catalog source is returned with the handle, so the startup banner
305
+ * reports the same probe the page will see.
314
306
  */
315
307
  export async function startServer(options) {
316
- // Mutable: granting trust changes what the next probe is allowed to do, and
317
- // saving a setting changes what it collects. Every later collect() reads this
318
- // same object, which is what makes either of them take effect in place.
308
+ // Mutable: granting trust changes what the next probe may do, and saving a
309
+ // setting changes what it collects. Every later collect() reads this same
310
+ // object, so both take effect without a restart.
319
311
  const collectOptions = { ...options.collectOptions };
320
- // Mutable for the same reason, and only ever set from the config file: no
321
- // flag names a runner order, so a save is the one thing that changes it.
312
+ // Mutable for the same reason. Only the config file sets it (no flag sets a
313
+ // runner order), so only a save changes it.
322
314
  let runnerOrder = options.runnerOrder;
323
- // The store lives under the INJECTED env and home, exactly as the trust store
324
- // does — a test that let these default would read and write the developer's
325
- // own `~/.cache/wayfinder`.
315
+ // The cache lives under the injected env and home, like the trust store, so
316
+ // a test does not read and write the developer's own `~/.cache/wayfinder`.
326
317
  const catalog = createCatalogSource(options.project, options.root, collectOptions, () => runnerOrder, cacheDir(options.env, options.home));
327
- // `home` is resolved once here (rather than passed as `options.home`
328
- // verbatim) because `trustPolicyOptions`, unlike `appTrustStore`, needs a
329
- // concrete string to expand a leading `~` against.
330
- const home = options.home ?? homedir();
318
+ // `home` is resolved here, not passed through as `options.home`, because
319
+ // `trustPolicyOptions` (unlike `appTrustStore`) needs a real string to
320
+ // expand a leading `~` against.
321
+ const home = options.home ?? homeDir();
331
322
  const trustStoreInstance = appTrustStore({
332
323
  home,
333
324
  ...(options.env !== undefined ? { env: options.env } : {}),
@@ -335,30 +326,30 @@ export async function startServer(options) {
335
326
  /**
336
327
  * Whether the page may offer a trust grant.
337
328
  *
338
- * Derived from the hint the CLI set, which it sets only when the gate came
339
- * out `untrusted` — so this says "trust is what is missing", not merely
340
- * "execution is off". It is computed here, in the process that resolved the
341
- * gate, and never from anything the scanned repository wrote.
329
+ * Derived from the hint, which the CLI sets only when the trust check
330
+ * returned `untrusted`. So it means "trust is what is missing", not just
331
+ * "execution is off". It is computed in the process that ran the check,
332
+ * never from anything the scanned repository wrote.
342
333
  *
343
- * It is not advice to the page: `POST /api/trust` refuses when it is false.
334
+ * The server enforces it too: `POST /api/trust` refuses when it is false.
344
335
  */
345
336
  const trustable = () => collectOptions.execWithheldHint !== undefined;
346
337
  /**
347
- * Re-derive the config file's slice of the collect options after a save.
338
+ * Re-read the config file's collect options after a save.
348
339
  *
349
- * Without this the file is written, the dialog says "Saved", and the running
350
- * server goes on collecting what it was told at boot — a save with no
351
- * effect, which is worse than a refusal.
340
+ * Without this, the file is written and the dialog says "Saved", but the
341
+ * running server keeps collecting what it was told at start. A save with no
342
+ * effect is worse than a refusal.
352
343
  *
353
- * `allowExec` is deliberately NOT among the keys taken: this session's
354
- * execution gate was resolved by the CLI against the trust store, and a
355
- * project file cannot raise it. A key the config no longer sets is deleted,
356
- * so unchecking a runner and checking it again both land. A key pinned by a
357
- * flag is left alone — see `ServeOptions.pinnedByFlag`.
344
+ * `allowExec` is not taken. The CLI decided this session's execution
345
+ * against the trust store, and a project file cannot raise it. A key the
346
+ * config no longer sets is deleted, so unchecking a runner and checking it
347
+ * again both take effect. A key set by a flag is left alone (see
348
+ * `ServeOptions.pinnedByFlag`).
358
349
  *
359
- * `runners.order` rides along because it is the same promise: the CLI reads
360
- * it out of the config at boot and nothing else ever sets it, so a save that
361
- * did not reach it would leave one setting silently inert.
350
+ * `runners.order` is updated too. The CLI reads it from the config at start
351
+ * and nothing else sets it, so without this a saved order would have no
352
+ * effect.
362
353
  */
363
354
  const CONFIG_OWNED = ['exclude', 'discovery', 'excludePaths'];
364
355
  const pinned = new Set(options.pinnedByFlag ?? []);
@@ -377,15 +368,15 @@ export async function startServer(options) {
377
368
  };
378
369
  const sessionToken = secret();
379
370
  let bootToken = secret();
380
- // Stamped when the URL is actually handed to the user, not here: the first
381
- // full probe runs in between, and on a cold tree it is long enough that a
382
- // clock started now would overstate the window the output promises. Until
383
- // then nothing can spend the token, because nothing has seen it.
371
+ // The timer starts when the URL is shown to the user, not here. The first
372
+ // probe runs in between, and on a cold tree it can take long enough to use
373
+ // up much of the promised minute. Until then nothing can use the token,
374
+ // because nothing has seen it.
384
375
  let bootExpiresAt = Number.POSITIVE_INFINITY;
385
376
  const armBoot = () => {
386
377
  bootExpiresAt = Date.now() + BOOT_TTL_MS;
387
378
  };
388
- /** True once: for the first request that presents the still-live boot token. */
379
+ /** True once, for the first request that presents the unexpired boot token. */
389
380
  const burnBoot = (candidate) => {
390
381
  if (candidate === null || bootToken === null)
391
382
  return false;
@@ -403,9 +394,9 @@ export async function startServer(options) {
403
394
  return header !== null && tokenEquals(header, sessionToken);
404
395
  };
405
396
  /**
406
- * Latched by the first accepted run. There is one terminal and one process,
407
- * so a second run has nothing left to be handed — every later POST is a 409
408
- * rather than a race between two spawns for the same stdin.
397
+ * Set by the first accepted run. There is one terminal and one process, so
398
+ * a second run cannot have it. Every later POST gets a 409, rather than two
399
+ * spawns racing for the same stdin.
409
400
  */
410
401
  let handedOff = false;
411
402
  const server = await serveFetch({
@@ -414,23 +405,21 @@ export async function startServer(options) {
414
405
  async fetch(req, self) {
415
406
  const url = new URL(req.url);
416
407
  if (url.pathname === '/api/trust') {
417
- // DELETE revokes. It is NOT gated on applicability the way the grant
418
- // is: refusing to grant protects a user from a standing permission
419
- // they did not ask for, and there is no matching harm in removing one.
420
- // The only rule it keeps is the method — a GET is reachable from a
421
- // link or an <img>, and revoking is a write.
408
+ // DELETE revokes. Unlike the grant, it has no applicability check.
409
+ // Refusing a grant protects a user from a lasting permission they did
410
+ // not ask for, and removing one does no matching harm. It still needs
411
+ // the right method: a GET can come from a link or an <img>, and
412
+ // revoking is a write.
422
413
  if (req.method === 'DELETE') {
423
414
  if (!hasSession(req))
424
415
  return unauthorized();
425
416
  const removed = await trustStoreInstance.untrust(options.root);
426
- // THE RUNNING SESSION'S GATE IS NOT TOUCHED, deliberately. Execution
427
- // may be on because of this store or because of an explicit
428
- // `--exec`, and this server cannot tell which without tracking
429
- // state that would be wrong the first time someone added a third
430
- // way. The store is the durable answer and it is now `false`; what
431
- // this process already resolved stands until it restarts, and the
432
- // screen says exactly that rather than implying a revoke it did not
433
- // perform.
417
+ // This session's execution setting is left as it is, on purpose.
418
+ // Execution may be on because of this store or because of an
419
+ // explicit `--exec`, and the server cannot tell which without
420
+ // tracking extra state. The store now says not trusted. What this
421
+ // process already decided stands until it restarts, and the screen
422
+ // says so rather than implying a revoke that did not happen.
434
423
  const snapshot = await catalog(false);
435
424
  return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable(), removed }, { headers: { 'cache-control': 'no-store' } });
436
425
  }
@@ -441,19 +430,18 @@ export async function startServer(options) {
441
430
  headers: { allow: 'POST, DELETE' },
442
431
  });
443
432
  }
444
- // The same session token every other route requires — header only, so
445
- // a cross-origin caller has to clear a preflight this server never
446
- // answers. See the CSRF note at the top of the file.
433
+ // The same session token every other route requires, in a header
434
+ // only, so a cross-origin caller must pass a preflight this server
435
+ // never answers. See the CSRF note at the top of the file.
447
436
  if (!hasSession(req))
448
437
  return unauthorized();
449
- // A hidden button is not a gate. The token proves WHO is asking; it
450
- // never proves that asking made sense. `--no-exec` must stay off
451
- // however trusted the repository is, and `--exec` must record nothing
452
- // — it is consent for one run, and persisting it would turn a
453
- // deliberate run into a standing grant nobody remembers giving. Both
454
- // are exactly the states in which the page would not have offered the
455
- // button, so the endpoint refuses a grant it could not have been
456
- // legitimately asked for. Nothing of the request is echoed back.
438
+ // Hiding the button is not enough. The token proves who is asking, not
439
+ // that the request makes sense. `--no-exec` must stay off however
440
+ // trusted the repository is. `--exec` must record nothing: it is
441
+ // consent for one run, and saving it would turn one run into a lasting
442
+ // grant nobody remembers giving. In both states the page hides the
443
+ // button, so the endpoint refuses a grant the page could not have
444
+ // offered. Nothing from the request is echoed back.
457
445
  if (!trustable()) {
458
446
  return new Response("a trust grant would not change this run's execution gate", {
459
447
  status: 409,
@@ -463,7 +451,7 @@ export async function startServer(options) {
463
451
  collectOptions.allowExec = true;
464
452
  // The hint told the user to trust this repository, which they just did.
465
453
  delete collectOptions.execWithheldHint;
466
- // The fresh catalog comes back with the grant, so the page re-renders
454
+ // The fresh catalog is returned with the grant, so the page re-renders
467
455
  // from one round trip rather than racing its own poll.
468
456
  const granted = await catalog(true);
469
457
  // Tool modules are code; this handler does not import them.
@@ -480,30 +468,29 @@ export async function startServer(options) {
480
468
  if (url.pathname === '/api/run' && req.method === 'POST') {
481
469
  if (!hasSession(req))
482
470
  return unauthorized();
483
- // Claimed here, before the first `await` in this route. An `await`
484
- // yields the event loop, so a check up here and a set further down are
485
- // two steps with other requests running between them: both would pass
486
- // the check, both would set the latch, and both would be told they had
487
- // been handed the terminal — one of them for a command that never ran.
488
- // Reading and setting it in one uninterrupted step is what makes the
489
- // second POST a 409. Paths below that turn out NOT to hand off release
490
- // it again, so a later legitimate POST still wins.
471
+ // Set here, before the first `await` in this route. An `await` yields
472
+ // the event loop, so a check here and a set further down would let
473
+ // other requests run in between. Two requests could both pass the
474
+ // check, and both be told they had the terminal, one for a command
475
+ // that never ran. Checking and setting in one step makes the second
476
+ // POST a 409. Paths below that do not hand off clear the flag again,
477
+ // so a later valid POST still works.
491
478
  if (handedOff)
492
479
  return new Response('conflict', { status: 409 });
493
480
  handedOff = true;
494
- // An id, plus trailing arguments — and nothing else. This port is
495
- // reachable by any process on the machine and by any website the
496
- // browser visits, so the COMMAND is never taken from the request: the
497
- // id selects a task out of a catalog this server produced itself, and
498
- // that task supplies the binary, the leading arguments and the cwd.
499
- // Accepting argv, a command string or a cwd would make this an
500
- // arbitrary-code-execution endpoint.
481
+ // An id plus trailing arguments, and nothing else. Any process on the
482
+ // machine and any website the browser visits can reach this port, so
483
+ // the command is never taken from the request. The id selects a task
484
+ // from a catalog this server built, and that task supplies the binary,
485
+ // the leading arguments and the cwd. Accepting argv, a command string
486
+ // or a cwd would let any caller run any code.
501
487
  //
502
- // What `args` adds is the tail a parameterised recipe needs — `staging`
503
- // for `just deploy <env>`. They are bound by the task's tool and never
504
- // replace the binary, so the worst a hostile caller can do is pass
505
- // arguments to a command the catalog already contains. `acceptArgs`
506
- // and `runArgv` in args.ts hold that rule and are asserted there.
488
+ // `args` adds the trailing arguments a recipe with parameters needs,
489
+ // such as `staging` for `just deploy <env>`. The task's tool places
490
+ // them, and they never replace the binary. So the worst a hostile
491
+ // caller can do is pass arguments to a command already in the catalog.
492
+ // `acceptArgs` and `runArgv` in args.ts enforce this, and its tests
493
+ // check it.
507
494
  let task;
508
495
  let argv = [];
509
496
  let snapshot;
@@ -519,14 +506,13 @@ export async function startServer(options) {
519
506
  handedOff = false;
520
507
  throw err;
521
508
  }
522
- // Not an auth failure, so not the uniform 401: the caller is
523
- // authenticated and is simply naming a task that is not in the
524
- // catalog — most likely one that was renamed since the page loaded.
509
+ // Not an auth failure, so not the uniform 401. The caller is
510
+ // authenticated and named a task that is not in the catalog, most
511
+ // likely one renamed since the page loaded.
525
512
  //
526
- // When the listing the page was served came out of the store, that is
527
- // the far more likely explanation and it is one the user can act on. A
528
- // bare "not found" would leave them looking at a row that is on screen
529
- // and being told it does not exist, with nothing connecting the two.
513
+ // When the page's listing came from the store, that is the likely
514
+ // cause, and the user can act on it. A bare "not found" would tell
515
+ // them a row on screen does not exist, with no explanation.
530
516
  if (!task) {
531
517
  handedOff = false;
532
518
  const stale = snapshot.cache.filter((c) => c.state === 'stale');
@@ -536,22 +522,21 @@ export async function startServer(options) {
536
522
  return new Response(`not found — this listing came from a cached probe (${aged}), so the task may have been ` +
537
523
  'renamed or removed since. Refresh the page.', { status: 404 });
538
524
  }
539
- // The response has to reach the browser BEFORE the terminal changes
540
- // hands, because taking it kills this server. `spawnSync` blocks the
541
- // event loop outright, so the spawn waits for `stop()`, which resolves
542
- // once open responses have finished and their connections closed.
543
- // Echo the argv that will actually run, arguments included, so the
544
- // handoff banner names the command rather than the recipe.
525
+ // The response has to reach the browser before the task takes the
526
+ // terminal, because running the task stops this server. The spawn
527
+ // blocks the event loop, so it waits for `stop()`, which resolves once
528
+ // open responses have finished and their connections have closed.
529
+ // Return the argv that will run, arguments included, so the handoff
530
+ // banner names the command rather than the recipe.
545
531
  const payload = JSON.stringify({ ok: true, display: task.display, argv });
546
532
  void (async () => {
547
- // A macrotask before the listener goes away, which also lets this
548
- // response be written first. On a warm catalog this
549
- // whole handler runs without ever yielding, so a POST already queued
550
- // on another socket has not been parsed yet — stopping here destroys
551
- // it, and the loser sees a connection reset instead of the 409 the
552
- // latch promised it. One turn of the loop is enough for those
553
- // requests to be read and answered, and it is a yield rather than a
554
- // wait: the terminal changes hands on the very next turn.
533
+ // Wait one event-loop turn before the listener goes away, which also
534
+ // lets this response be written first. With a warm catalog this
535
+ // whole handler runs without yielding, so a POST queued on another
536
+ // socket has not been parsed yet. Stopping now would drop it, and
537
+ // that caller would see a connection reset instead of a 409. One
538
+ // turn is enough for those requests to be read and answered, and
539
+ // the task starts on the next turn.
555
540
  await new Promise((resolve) => setTimeout(resolve, 0));
556
541
  await self.stop();
557
542
  runAndExit(options.root, task, argv);
@@ -565,14 +550,13 @@ export async function startServer(options) {
565
550
  if (!hasSession(req))
566
551
  return unauthorized();
567
552
  const snapshot = await catalog(url.searchParams.has('force'));
568
- // `cache` alongside `trustable`: both are the server's own reading of
569
- // something the page cannot work out for itself. The page renders the
570
- // same three states the TUI does from it.
553
+ // `cache` and `trustable` are both facts only the server knows. From
554
+ // `cache` the page shows the same three states the TUI does.
571
555
  return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable() }, { headers: { 'cache-control': 'no-store' } });
572
556
  }
573
557
  if (url.pathname === '/api/config') {
574
- // Header only, and the session token only — never the boot token. See
575
- // the CSRF note at the top of the file.
558
+ // The session token in a header, never the boot token. See the CSRF
559
+ // note at the top of the file.
576
560
  if (!hasSession(req))
577
561
  return unauthorized();
578
562
  if (req.method === 'POST') {
@@ -580,22 +564,21 @@ export async function startServer(options) {
580
564
  if (failure !== null)
581
565
  return failure;
582
566
  // Falls through to the read below, so a save answers with the state
583
- // it produced. One round trip: the screen re-renders from the file
584
- // as it now is rather than from what it hoped it wrote.
567
+ // it produced. The screen re-renders from the file as it now is, in
568
+ // one round trip.
585
569
  }
586
570
  else if (req.method !== 'GET') {
587
571
  return new Response('use GET or POST', { status: 405, headers: { allow: 'GET, POST' } });
588
572
  }
589
573
  const loaded = await loadConfig(options.root, options.env, options.home);
590
574
  // A save has to reach the running process, not just the file. Applied
591
- // after the re-read so it adopts the merged layers, exactly as the CLI
592
- // did at boot.
575
+ // after the re-read so it uses the merged layers, as the CLI did at
576
+ // start.
593
577
  if (req.method === 'POST')
594
578
  adoptConfig(loaded.effective);
595
- // `sources` is a Map, which JSON.stringify renders as `{}`. The page
596
- // needs it most of all — "this came from your user config, not this
597
- // project" is the question a settings screen exists to answer — so it
598
- // is converted rather than lost.
579
+ // `sources` is a Map, which JSON.stringify renders as `{}`, so it is
580
+ // converted to an object. The settings screen needs it to show which
581
+ // layer each value came from.
599
582
  return Response.json({
600
583
  effective: loaded.effective,
601
584
  project: loaded.layers.project,
@@ -603,47 +586,42 @@ export async function startServer(options) {
603
586
  sources: Object.fromEntries(loaded.sources),
604
587
  locations: { project: loaded.locations.project, user: loaded.locations.user },
605
588
  warnings: loaded.warnings,
606
- // Marker OR policy — a root the user file's trust.paths/trust.owners
607
- // covers shows as trusted here even with no marker at all.
589
+ // Marker or policy: a root that the user file's
590
+ // trust.paths/trust.owners covers shows as trusted with no marker.
608
591
  trusted: (await trustDecision(trustStoreInstance, options.root, trustPolicyFromConfig(loaded.effective), trustPolicyOptions(home))).trusted,
609
- // Whether a trust grant is the thing that would change execution
610
- // here, as distinct from a config file having turned it off. The
611
- // catalog route already sends this; the settings screen needs it to
612
- // avoid offering a grant that would change nothing.
592
+ // Whether a trust grant would change execution here, as opposed to
593
+ // a config file having turned it off. The catalog route sends this
594
+ // too. The settings screen needs it so it does not offer a grant
595
+ // that would change nothing.
613
596
  trustable: trustable(),
614
597
  }, { headers: { 'cache-control': 'no-store' } });
615
598
  }
616
599
  if (url.pathname === '/' || url.pathname === '/index.html') {
617
600
  if (!hasSession(req) && !burnBoot(url.searchParams.get('boot')))
618
601
  return unauthorizedPage();
619
- // Assembled per request so editing any part is a reload, not a
620
- // restart. The bundle includes the matcher, which retired /match.js.
602
+ // Built per request, so an edit to any part needs a reload, not a
603
+ // restart. The bundle includes the matcher.
621
604
  return new Response(await buildPage(sessionToken), {
622
605
  headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
623
606
  });
624
607
  }
625
- // Unknown paths answer 401 as well: a 404 would map the server's routes
626
- // for someone who cannot authenticate.
608
+ // Unknown paths also answer 401. A 404 would reveal the server's routes
609
+ // to someone who cannot authenticate.
627
610
  return unauthorized();
628
611
  },
629
612
  });
630
613
  return { server, catalog, bootToken: bootToken, armBoot };
631
614
  }
632
- export async function serve(options) {
633
- const { server, catalog, bootToken, armBoot } = await startServer(options);
634
- const address = `http://127.0.0.1:${server.port}`;
635
- const bootUrl = `${address}/?boot=${bootToken}`;
636
- // NOT forced. This is the request that decides how long the user waits for a
637
- // URL, so it takes the store's answer when there is one and lets the real
638
- // probe land behind it — the same stale-then-refresh the TUI boots with.
639
- const first = await catalog(false);
640
- armBoot();
641
- // A withheld runner is `status: "absent"` with `skippedForExec`, and printing
642
- // its status alone called it absent — the same word used for a runner this
643
- // repository genuinely does not have. The two are opposite facts: one says
644
- // there is nothing here, the other says there is something here we did not
645
- // read. The summary is the only thing a `--serve` user sees before the page
646
- // opens, so it says which.
615
+ /**
616
+ * The first lines `--serve` prints: the address, the root, what was collected
617
+ * and what came from the cache. Repository text in them is terminal-safe.
618
+ */
619
+ export function startupSummary(address, first) {
620
+ // A withheld runner has `status: "absent"` and `skippedForExec`. Printing
621
+ // only its status would call it absent, the same word used for a runner the
622
+ // repository does not have. Those are opposite facts: one means nothing is
623
+ // here, the other means something is here that was not read. This summary is
624
+ // all a `--serve` user sees before the page opens, so it says which.
647
625
  const counts = first.catalog.reports
648
626
  .map((r) => {
649
627
  const state = r.skippedForExec ? 'withheld' : r.status === 'ok' ? r.tasks.length : r.status;
@@ -651,14 +629,27 @@ export async function serve(options) {
651
629
  })
652
630
  .join(', ');
653
631
  const stale = first.cache.filter((c) => c.state === 'stale');
654
- process.stdout.write(`${APP} ${address}\n`);
655
- process.stdout.write(` root ${first.catalog.root}\n`);
656
- process.stdout.write(` collected ${counts}\n`);
632
+ let out = `${APP} ${address}\n`;
633
+ out += ` root ${terminalSafe(first.catalog.root)}\n`;
634
+ out += ` collected ${terminalSafe(counts)}\n`;
657
635
  if (stale.length > 0) {
658
- process.stdout.write(` cached ${stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ')} — re-probing now\n`);
636
+ const aged = stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ');
637
+ out += ` cached ${terminalSafe(aged)} — re-probing now\n`;
659
638
  }
660
- // Not "re-probed per request" any more: the first paint may come from the
661
- // store, which the `cached` line above says when it does.
639
+ return out;
640
+ }
641
+ export async function serve(options) {
642
+ const { server, catalog, bootToken, armBoot } = await startServer(options);
643
+ const address = `http://127.0.0.1:${server.port}`;
644
+ const bootUrl = `${address}/?boot=${bootToken}`;
645
+ // Not forced. This request decides how long the user waits for a URL, so it
646
+ // takes the store's answer when there is one and probes in the background,
647
+ // as the TUI does at start.
648
+ const first = await catalog(false);
649
+ armBoot();
650
+ process.stdout.write(startupSummary(address, first));
651
+ // The first view may come from the store. The `cached` line above says so
652
+ // when it does.
662
653
  process.stdout.write(` live the page refreshes on focus and every 15s; Refresh always re-reads\n`);
663
654
  process.stdout.write(` stop Ctrl-C\n`);
664
655
  if (options.open === false) {
@@ -666,9 +657,11 @@ export async function serve(options) {
666
657
  process.stdout.write(` signs the browser in once; the boot token expires in 60 seconds if unused\n`);
667
658
  }
668
659
  else {
669
- // Best-effort: a headless or remote shell has no browser, and that is fine.
660
+ // Best effort: a headless or remote shell has no browser.
670
661
  const opener = process.platform === 'darwin' ? 'open' : 'xdg-open';
671
- const proc = spawnRunner(opener).run([bootUrl], { cwd: options.root });
662
+ const proc = spawnRunner(opener, { absolutePathOnly: true }).run([bootUrl], {
663
+ cwd: options.root,
664
+ });
672
665
  if (proc.exitCode !== 0) {
673
666
  process.stdout.write(` (could not open a browser - visit ${bootUrl} within 60 seconds)\n`);
674
667
  }