@osdlc/wayfinder 0.0.1-stage → 0.7.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 (53) hide show
  1. package/CHANGELOG.md +231 -0
  2. package/CONTRIBUTING.md +62 -0
  3. package/{LICENSE → LICENSE-APACHE} +1 -11
  4. package/LICENSE-MIT +21 -0
  5. package/README.md +505 -2
  6. package/SECURITY.md +44 -0
  7. package/bin/way.js +18 -0
  8. package/dist/app.d.ts +24 -0
  9. package/dist/app.js +24 -0
  10. package/dist/args.d.ts +44 -0
  11. package/dist/args.js +93 -0
  12. package/dist/cache.d.ts +7 -0
  13. package/dist/cache.js +15 -0
  14. package/dist/catalog.d.ts +38 -0
  15. package/dist/catalog.js +61 -0
  16. package/dist/clean-command.d.ts +43 -0
  17. package/dist/clean-command.js +274 -0
  18. package/dist/cli.d.ts +76 -0
  19. package/dist/cli.js +612 -0
  20. package/dist/config-command.d.ts +52 -0
  21. package/dist/config-command.js +342 -0
  22. package/dist/config.d.ts +367 -0
  23. package/dist/config.js +700 -0
  24. package/dist/devlink.d.ts +14 -0
  25. package/dist/devlink.js +30 -0
  26. package/dist/groups.d.ts +34 -0
  27. package/dist/groups.js +38 -0
  28. package/dist/guide.d.ts +32 -0
  29. package/dist/guide.js +411 -0
  30. package/dist/http.d.ts +22 -0
  31. package/dist/http.js +149 -0
  32. package/dist/origin-owner.d.ts +14 -0
  33. package/dist/origin-owner.js +69 -0
  34. package/dist/page.d.ts +15 -0
  35. package/dist/page.js +58 -0
  36. package/dist/providers-command.d.ts +40 -0
  37. package/dist/providers-command.js +132 -0
  38. package/dist/serve.d.ts +97 -0
  39. package/dist/serve.js +678 -0
  40. package/dist/tools.d.ts +46 -0
  41. package/dist/tools.js +102 -0
  42. package/dist/trust-command.d.ts +33 -0
  43. package/dist/trust-command.js +221 -0
  44. package/dist/trust-store.d.ts +18 -0
  45. package/dist/trust-store.js +46 -0
  46. package/dist/tui.d.ts +178 -0
  47. package/dist/tui.js +846 -0
  48. package/dist/web/main.js +2315 -0
  49. package/dist/web/page.html +110 -0
  50. package/dist/web/styles.css +1514 -0
  51. package/dist/xdg.d.ts +10 -0
  52. package/dist/xdg.js +17 -0
  53. package/package.json +54 -9
package/dist/serve.js ADDED
@@ -0,0 +1,678 @@
1
+ /**
2
+ * The web view — the same catalog as a page you can search in a browser.
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.
8
+ *
9
+ * Loopback is not by itself a boundary, so every route is behind a token.
10
+ *
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.
17
+ *
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.
24
+ *
25
+ * `/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.
27
+ *
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.
33
+ */
34
+ import { homedir } from 'node:os';
35
+ import { spawnRunner, streamRunner } from '@osdlc/command-seam';
36
+ import { tasks as allTasks, } from '@osdlc/system-model/detect';
37
+ import { humanAge } from '@osdlc/system-model/duration';
38
+ import { trustDecision } from '@osdlc/trust-repo';
39
+ import { APP, BIN, PROJECT_CONFIG_FILENAME, TOKEN_HEADER } from "./app.js";
40
+ import { acceptArgs, runArgv } from "./args.js";
41
+ import { cacheDir } from "./cache.js";
42
+ import { collectAndCache, freshStates, fromStore, orderedCatalog, readCachedCatalog, } from "./catalog.js";
43
+ import { CONFIG_KEYS, collectOptionsFromConfig, configLocations, loadConfig, readRawConfigFile, setConfigValue, trustPolicyFromConfig, trustPolicyOptions, validateConfig, writeConfigFile, } from "./config.js";
44
+ import { appTrustStore } from "./trust-store.js";
45
+ import { serveFetch } from "./http.js";
46
+ import { buildPage } from "./page.js";
47
+ /** Requests inside this window share one probe; an explicit refresh skips it. */
48
+ const COALESCE_MS = 1500;
49
+ /** How long the boot token stays usable if the browser never arrives. */
50
+ const BOOT_TTL_MS = 60_000;
51
+ /** 128 bits, hex. `getRandomValues` is the CSPRNG; `Math.random` is not. */
52
+ function secret() {
53
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
54
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
55
+ }
56
+ /** Compared without an early exit, so a near miss is not distinguishable by timing. */
57
+ function tokenEquals(a, b) {
58
+ if (a.length !== b.length)
59
+ return false;
60
+ let diff = 0;
61
+ for (let i = 0; i < a.length; i++)
62
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
63
+ return diff === 0;
64
+ }
65
+ /**
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.
69
+ */
70
+ function unauthorized() {
71
+ return new Response('unauthorized', { status: 401 });
72
+ }
73
+ /**
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.
77
+ *
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.
82
+ */
83
+ function unauthorizedPage() {
84
+ const body = `<!doctype html>
85
+ <meta charset="utf-8">
86
+ <meta name="viewport" content="width=device-width, initial-scale=1">
87
+ <title>${APP} - not signed in</title>
88
+ <style>
89
+ :root { color-scheme: light dark; }
90
+ body {
91
+ margin: 0; min-height: 100vh;
92
+ display: flex; align-items: center; justify-content: center;
93
+ font: 15px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
94
+ background: #fbfbfa; color: #1c1c1a;
95
+ }
96
+ main { max-width: 30rem; padding: 2rem; }
97
+ h1 { margin: 0 0 .75rem; font-size: 1.15rem; font-weight: 600; }
98
+ p { margin: 0 0 .75rem; }
99
+ code {
100
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .92em;
101
+ padding: .1em .35em; border-radius: .25em;
102
+ background: rgba(127, 127, 127, .18);
103
+ /* Text meant to be retyped. The default face ligates a run of hyphens
104
+ into one long dash, and what is retyped is then not what is shown. */
105
+ font-variant-ligatures: none;
106
+ }
107
+ @media (prefers-color-scheme: dark) {
108
+ body { background: #16161a; color: #e6e6e3; }
109
+ }
110
+ </style>
111
+ <main>
112
+ <h1>This browser is not signed in.</h1>
113
+ <p>${APP} needs a fresh link, and only your terminal can hand one out.</p>
114
+ <p>Go to the terminal ${APP} is running in, stop it with <code>Ctrl-C</code> and
115
+ start it again: it prints a new link that signs this browser in.</p>
116
+ </main>
117
+ `;
118
+ return new Response(body, {
119
+ status: 401,
120
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
121
+ });
122
+ }
123
+ /**
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.
127
+ */
128
+ const PAINT = !process.env['NO_COLOR'] && process.stdout.isTTY;
129
+ const dim = (s) => (PAINT ? `\x1b[2m${s}\x1b[0m` : s);
130
+ const bold = (s) => (PAINT ? `\x1b[1m${s}\x1b[0m` : s);
131
+ /**
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.
137
+ */
138
+ function runAndExit(root, task, argv) {
139
+ // Echo what actually runs, not `display`.
140
+ process.stdout.write(`${dim('$')} ${bold(argv.join(' '))}\n`);
141
+ const [binary, ...rest] = argv;
142
+ const res = streamRunner(binary).run(rest, {
143
+ cwd: task.cwd === '.' ? root : `${root}/${task.cwd}`,
144
+ });
145
+ process.exit(res.exitCode);
146
+ }
147
+ /**
148
+ * Apply a settings-screen edit to `<root>/wayfinder.config.json`.
149
+ *
150
+ * A PATCH of dotted keys, not a document. Two reasons, and the second is the
151
+ * one that matters:
152
+ *
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.
161
+ *
162
+ * Returns null on success, or the Response to send on refusal.
163
+ */
164
+ async function writeProjectConfig(req, options) {
165
+ const bad = (detail) => new Response(detail, { status: 400 });
166
+ const body = (await req.json().catch(() => null));
167
+ if (body === null || !isRecord(body.set))
168
+ 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.
172
+ for (const key of Object.keys(body.set)) {
173
+ if (!CONFIG_KEYS.includes(key))
174
+ return bad(`${key} is not a setting`);
175
+ }
176
+ // Tool modules are code. The page never edits them; `way config set` does.
177
+ if ('tools' in body.set)
178
+ 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.
184
+ if (body.set['allowExec'] === true) {
185
+ return bad('allowExec: true cannot be written to a project file — a repository cannot grant itself ' +
186
+ 'permission to run subprocesses. Trust this repository instead.');
187
+ }
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.
192
+ for (const key of ['trust.paths', 'trust.owners']) {
193
+ if (key in body.set) {
194
+ return bad(`${key} cannot be written to a project file — a repository cannot grant itself trust. ` +
195
+ 'Set it in your user config instead.');
196
+ }
197
+ }
198
+ const file = configLocations(options.root, options.env, options.home).project;
199
+ 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.
206
+ try {
207
+ for (const [key, value] of Object.entries(body.set)) {
208
+ candidate = setConfigValue(candidate, key, value);
209
+ }
210
+ validateConfig(candidate, file);
211
+ }
212
+ catch (err) {
213
+ return bad(err instanceof Error ? err.message : String(err));
214
+ }
215
+ await writeConfigFile(file, candidate);
216
+ return null;
217
+ }
218
+ /** A JSON object, as distinct from an array or a primitive. */
219
+ function isRecord(value) {
220
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
221
+ }
222
+ /**
223
+ * Single-flight catalog access, cache-aware.
224
+ *
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.
228
+ *
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.
234
+ *
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".
240
+ */
241
+ function createCatalogSource(project, root, options,
242
+ /**
243
+ * Read per probe, never captured: saving `runners.order` changes it mid-run,
244
+ * exactly as saving a collect option mutates `options` in place.
245
+ */
246
+ runnerOrder, store) {
247
+ let pending = null;
248
+ let settledAt = 0;
249
+ let last = null;
250
+ /** The store is only ever worth asking once; after that `last` is better. */
251
+ let consultedStore = false;
252
+ const probe = () => {
253
+ pending ??= collectAndCache(project, root, options, store)
254
+ .then((collected) => {
255
+ const snapshot = {
256
+ catalog: orderedCatalog(collected, runnerOrder()),
257
+ // Measured this instant, so nothing about it is stale.
258
+ cache: freshStates(collected),
259
+ };
260
+ last = snapshot;
261
+ settledAt = Date.now();
262
+ return snapshot;
263
+ })
264
+ .finally(() => {
265
+ pending = null;
266
+ });
267
+ return pending;
268
+ };
269
+ return async (force) => {
270
+ 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.
276
+ const running = pending;
277
+ if (running !== null)
278
+ await running.catch(() => { });
279
+ return probe();
280
+ }
281
+ if (last !== null && Date.now() - settledAt < COALESCE_MS)
282
+ return last;
283
+ if (!consultedStore) {
284
+ 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.
288
+ 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.
291
+ if (stored.catalog !== null && fromStore(stored)) {
292
+ last = { catalog: orderedCatalog(stored.catalog, runnerOrder()), cache: stored.runners };
293
+ 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.
296
+ void probe().catch(() => { });
297
+ return last;
298
+ }
299
+ }
300
+ return probe();
301
+ };
302
+ }
303
+ /**
304
+ * Bind the port and return the server's handle, without printing or opening anything.
305
+ *
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.
311
+ *
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.
314
+ */
315
+ 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.
319
+ 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.
322
+ 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`.
326
+ 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();
331
+ const trustStoreInstance = appTrustStore({
332
+ home,
333
+ ...(options.env !== undefined ? { env: options.env } : {}),
334
+ });
335
+ /**
336
+ * Whether the page may offer a trust grant.
337
+ *
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.
342
+ *
343
+ * It is not advice to the page: `POST /api/trust` refuses when it is false.
344
+ */
345
+ const trustable = () => collectOptions.execWithheldHint !== undefined;
346
+ /**
347
+ * Re-derive the config file's slice of the collect options after a save.
348
+ *
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.
352
+ *
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`.
358
+ *
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.
362
+ */
363
+ const CONFIG_OWNED = ['exclude', 'discovery', 'excludePaths'];
364
+ const pinned = new Set(options.pinnedByFlag ?? []);
365
+ const adoptConfig = (config) => {
366
+ const derived = collectOptionsFromConfig(config);
367
+ const target = collectOptions;
368
+ for (const key of CONFIG_OWNED) {
369
+ if (pinned.has(key))
370
+ continue;
371
+ if (derived[key] === undefined)
372
+ delete target[key];
373
+ else
374
+ target[key] = derived[key];
375
+ }
376
+ runnerOrder = config.runners?.order;
377
+ };
378
+ const sessionToken = secret();
379
+ 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.
384
+ let bootExpiresAt = Number.POSITIVE_INFINITY;
385
+ const armBoot = () => {
386
+ bootExpiresAt = Date.now() + BOOT_TTL_MS;
387
+ };
388
+ /** True once: for the first request that presents the still-live boot token. */
389
+ const burnBoot = (candidate) => {
390
+ if (candidate === null || bootToken === null)
391
+ return false;
392
+ if (Date.now() > bootExpiresAt) {
393
+ bootToken = null;
394
+ return false;
395
+ }
396
+ if (!tokenEquals(candidate, bootToken))
397
+ return false;
398
+ bootToken = null;
399
+ return true;
400
+ };
401
+ const hasSession = (req) => {
402
+ const header = req.headers.get(TOKEN_HEADER);
403
+ return header !== null && tokenEquals(header, sessionToken);
404
+ };
405
+ /**
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.
409
+ */
410
+ let handedOff = false;
411
+ const server = await serveFetch({
412
+ hostname: '127.0.0.1',
413
+ port: options.port ?? 0,
414
+ async fetch(req, self) {
415
+ const url = new URL(req.url);
416
+ 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.
422
+ if (req.method === 'DELETE') {
423
+ if (!hasSession(req))
424
+ return unauthorized();
425
+ 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.
434
+ const snapshot = await catalog(false);
435
+ return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable(), removed }, { headers: { 'cache-control': 'no-store' } });
436
+ }
437
+ // Anything but POST, including the GET a link or an <img> would make.
438
+ if (req.method !== 'POST') {
439
+ return new Response('use POST or DELETE', {
440
+ status: 405,
441
+ headers: { allow: 'POST, DELETE' },
442
+ });
443
+ }
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.
447
+ if (!hasSession(req))
448
+ 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.
457
+ if (!trustable()) {
458
+ return new Response("a trust grant would not change this run's execution gate", {
459
+ status: 409,
460
+ });
461
+ }
462
+ await trustStoreInstance.trust(options.root);
463
+ collectOptions.allowExec = true;
464
+ // The hint told the user to trust this repository, which they just did.
465
+ delete collectOptions.execWithheldHint;
466
+ // The fresh catalog comes back with the grant, so the page re-renders
467
+ // from one round trip rather than racing its own poll.
468
+ const granted = await catalog(true);
469
+ // Tool modules are code; this handler does not import them.
470
+ const note = options.projectToolsPending
471
+ ? `the tools ${PROJECT_CONFIG_FILENAME} names load the next time ${BIN} starts with execution allowed`
472
+ : undefined;
473
+ return Response.json({
474
+ ...granted.catalog,
475
+ cache: granted.cache,
476
+ trustable: trustable(),
477
+ ...(note !== undefined ? { note } : {}),
478
+ }, { headers: { 'cache-control': 'no-store' } });
479
+ }
480
+ if (url.pathname === '/api/run' && req.method === 'POST') {
481
+ if (!hasSession(req))
482
+ 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.
491
+ if (handedOff)
492
+ return new Response('conflict', { status: 409 });
493
+ 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.
501
+ //
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.
507
+ let task;
508
+ let argv = [];
509
+ let snapshot;
510
+ try {
511
+ const body = (await req.json().catch(() => null));
512
+ const id = typeof body?.id === 'string' ? body.id : null;
513
+ snapshot = await catalog(false);
514
+ task = id === null ? undefined : allTasks(snapshot.catalog).find((t) => t.id === id);
515
+ if (task)
516
+ argv = runArgv(options.project, task, acceptArgs(body?.args));
517
+ }
518
+ catch (err) {
519
+ handedOff = false;
520
+ throw err;
521
+ }
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.
525
+ //
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.
530
+ if (!task) {
531
+ handedOff = false;
532
+ const stale = snapshot.cache.filter((c) => c.state === 'stale');
533
+ if (stale.length === 0)
534
+ return new Response('not found', { status: 404 });
535
+ const aged = stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ');
536
+ return new Response(`not found — this listing came from a cached probe (${aged}), so the task may have been ` +
537
+ 'renamed or removed since. Refresh the page.', { status: 404 });
538
+ }
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.
545
+ const payload = JSON.stringify({ ok: true, display: task.display, argv });
546
+ 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.
555
+ await new Promise((resolve) => setTimeout(resolve, 0));
556
+ await self.stop();
557
+ runAndExit(options.root, task, argv);
558
+ })();
559
+ return new Response(payload, {
560
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
561
+ });
562
+ }
563
+ if (url.pathname === '/api/catalog') {
564
+ // Header only — see the CSRF note at the top of the file.
565
+ if (!hasSession(req))
566
+ return unauthorized();
567
+ 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.
571
+ return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable() }, { headers: { 'cache-control': 'no-store' } });
572
+ }
573
+ 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.
576
+ if (!hasSession(req))
577
+ return unauthorized();
578
+ if (req.method === 'POST') {
579
+ const failure = await writeProjectConfig(req, options);
580
+ if (failure !== null)
581
+ return failure;
582
+ // 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.
585
+ }
586
+ else if (req.method !== 'GET') {
587
+ return new Response('use GET or POST', { status: 405, headers: { allow: 'GET, POST' } });
588
+ }
589
+ const loaded = await loadConfig(options.root, options.env, options.home);
590
+ // 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.
593
+ if (req.method === 'POST')
594
+ 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.
599
+ return Response.json({
600
+ effective: loaded.effective,
601
+ project: loaded.layers.project,
602
+ user: loaded.layers.user,
603
+ sources: Object.fromEntries(loaded.sources),
604
+ locations: { project: loaded.locations.project, user: loaded.locations.user },
605
+ 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.
608
+ 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.
613
+ trustable: trustable(),
614
+ }, { headers: { 'cache-control': 'no-store' } });
615
+ }
616
+ if (url.pathname === '/' || url.pathname === '/index.html') {
617
+ if (!hasSession(req) && !burnBoot(url.searchParams.get('boot')))
618
+ 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.
621
+ return new Response(await buildPage(sessionToken), {
622
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
623
+ });
624
+ }
625
+ // Unknown paths answer 401 as well: a 404 would map the server's routes
626
+ // for someone who cannot authenticate.
627
+ return unauthorized();
628
+ },
629
+ });
630
+ return { server, catalog, bootToken: bootToken, armBoot };
631
+ }
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.
647
+ const counts = first.catalog.reports
648
+ .map((r) => {
649
+ const state = r.skippedForExec ? 'withheld' : r.status === 'ok' ? r.tasks.length : r.status;
650
+ return `${r.runner} ${state}`;
651
+ })
652
+ .join(', ');
653
+ 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`);
657
+ if (stale.length > 0) {
658
+ process.stdout.write(` cached ${stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ')} — re-probing now\n`);
659
+ }
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.
662
+ process.stdout.write(` live the page refreshes on focus and every 15s; Refresh always re-reads\n`);
663
+ process.stdout.write(` stop Ctrl-C\n`);
664
+ if (options.open === false) {
665
+ process.stdout.write(` open ${bootUrl}\n`);
666
+ process.stdout.write(` signs the browser in once; the boot token expires in 60 seconds if unused\n`);
667
+ }
668
+ else {
669
+ // Best-effort: a headless or remote shell has no browser, and that is fine.
670
+ const opener = process.platform === 'darwin' ? 'open' : 'xdg-open';
671
+ const proc = spawnRunner(opener).run([bootUrl], { cwd: options.root });
672
+ if (proc.exitCode !== 0) {
673
+ process.stdout.write(` (could not open a browser - visit ${bootUrl} within 60 seconds)\n`);
674
+ }
675
+ }
676
+ // Held open by the server; Ctrl-C is the exit.
677
+ return new Promise(() => { });
678
+ }