@osdlc/wayfinder 0.7.1 → 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/CHANGELOG.md +23 -0
- package/README.md +210 -182
- package/SECURITY.md +39 -1
- package/bin/way.js +14 -9
- package/dist/args.d.ts +16 -16
- package/dist/args.js +19 -19
- package/dist/cache.js +3 -4
- package/dist/clean-command.d.ts +18 -18
- package/dist/clean-command.js +35 -36
- package/dist/cli.d.ts +19 -20
- package/dist/cli.js +76 -69
- package/dist/config-command.d.ts +15 -14
- package/dist/config-command.js +63 -59
- package/dist/config.d.ts +135 -130
- package/dist/config.js +156 -149
- package/dist/devlink.d.ts +6 -2
- package/dist/devlink.js +7 -2
- package/dist/guide.js +5 -4
- package/dist/origin-owner.d.ts +7 -2
- package/dist/origin-owner.js +20 -4
- package/dist/providers-command.d.ts +1 -1
- package/dist/providers-command.js +11 -23
- package/dist/serve.d.ts +43 -42
- package/dist/serve.js +251 -258
- package/dist/terminal-text.d.ts +57 -0
- package/dist/terminal-text.js +91 -0
- package/dist/tools.d.ts +4 -4
- package/dist/tools.js +4 -4
- package/dist/trust-command.d.ts +6 -7
- package/dist/trust-command.js +48 -50
- package/dist/trust-store.d.ts +1 -1
- package/dist/tui.d.ts +65 -66
- package/dist/tui.js +124 -130
- package/dist/web/main.js +371 -386
- package/dist/web/page.html +6 -5
- package/dist/web/styles.css +258 -271
- package/package.json +7 -7
package/dist/serve.js
CHANGED
|
@@ -1,46 +1,45 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The web view
|
|
2
|
+
* The web view: the same catalog as a page you can search in a browser.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* slow poll, so
|
|
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
|
|
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
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
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
|
|
19
|
-
* 127.0.0.1. A cookie would
|
|
20
|
-
*
|
|
21
|
-
* cross-origin fetch must first pass a CORS preflight this server never
|
|
22
|
-
* answers.
|
|
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
|
|
25
|
+
* task id and nothing else (see the note on the route).
|
|
27
26
|
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
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
|
|
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.
|
|
67
|
-
* token,
|
|
68
|
-
*
|
|
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
|
|
75
|
-
* the address bar no longer
|
|
76
|
-
*
|
|
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
|
|
79
|
-
* token, expired token
|
|
80
|
-
*
|
|
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
|
-
*
|
|
125
|
-
* The TUI's ANSI helpers are private to that module, so the
|
|
126
|
-
* and bold argv
|
|
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
|
|
133
|
-
*
|
|
134
|
-
* command
|
|
135
|
-
* without a shell
|
|
136
|
-
* `<placeholders>`
|
|
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
|
-
*
|
|
151
|
-
*
|
|
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
|
-
*
|
|
155
|
-
* - The patch is applied to the file's
|
|
156
|
-
* does not know
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
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
|
-
//
|
|
170
|
-
//
|
|
171
|
-
//
|
|
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
|
-
//
|
|
180
|
-
//
|
|
181
|
-
//
|
|
182
|
-
//
|
|
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
|
-
//
|
|
189
|
-
// pre-authorize itself (or
|
|
190
|
-
// Refused even when empty
|
|
191
|
-
//
|
|
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
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
//
|
|
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
|
-
*
|
|
219
|
+
* Catalog access that runs at most one probe at a time and uses the store.
|
|
224
220
|
*
|
|
225
|
-
* The in-flight
|
|
226
|
-
*
|
|
227
|
-
*
|
|
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
|
|
230
|
-
* starts a real probe
|
|
231
|
-
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
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
|
|
236
|
-
*
|
|
237
|
-
*
|
|
238
|
-
*
|
|
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
|
|
244
|
-
*
|
|
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
|
|
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
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
//
|
|
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
|
|
286
|
-
// falls through to the probe below,
|
|
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
|
-
//
|
|
290
|
-
//
|
|
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
|
-
//
|
|
295
|
-
//
|
|
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
|
|
307
|
-
*
|
|
308
|
-
*
|
|
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
|
|
313
|
-
*
|
|
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
|
|
317
|
-
//
|
|
318
|
-
//
|
|
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
|
|
321
|
-
//
|
|
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
|
|
324
|
-
//
|
|
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
|
|
328
|
-
//
|
|
329
|
-
//
|
|
330
|
-
const home = options.home ??
|
|
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
|
|
339
|
-
*
|
|
340
|
-
* "execution is off". It is computed
|
|
341
|
-
*
|
|
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
|
-
*
|
|
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-
|
|
338
|
+
* Re-read the config file's collect options after a save.
|
|
348
339
|
*
|
|
349
|
-
* Without this the file is written
|
|
350
|
-
* server
|
|
351
|
-
* effect
|
|
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
|
|
354
|
-
*
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
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`
|
|
360
|
-
*
|
|
361
|
-
*
|
|
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
|
-
//
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
//
|
|
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
|
|
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
|
-
*
|
|
407
|
-
*
|
|
408
|
-
*
|
|
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.
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
//
|
|
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
|
-
//
|
|
427
|
-
// may be on because of this store or because of an
|
|
428
|
-
// `--exec`, and
|
|
429
|
-
//
|
|
430
|
-
//
|
|
431
|
-
//
|
|
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
|
|
445
|
-
// a cross-origin caller
|
|
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
|
-
//
|
|
450
|
-
//
|
|
451
|
-
//
|
|
452
|
-
//
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
//
|
|
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
|
|
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
|
-
//
|
|
484
|
-
//
|
|
485
|
-
//
|
|
486
|
-
//
|
|
487
|
-
//
|
|
488
|
-
//
|
|
489
|
-
//
|
|
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
|
|
495
|
-
//
|
|
496
|
-
//
|
|
497
|
-
//
|
|
498
|
-
//
|
|
499
|
-
//
|
|
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
|
-
//
|
|
503
|
-
// for `just deploy <env>`.
|
|
504
|
-
// replace the binary
|
|
505
|
-
// arguments to a command the catalog
|
|
506
|
-
// and `runArgv` in args.ts
|
|
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
|
|
523
|
-
// authenticated and
|
|
524
|
-
//
|
|
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
|
|
527
|
-
//
|
|
528
|
-
//
|
|
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
|
|
540
|
-
//
|
|
541
|
-
// event loop
|
|
542
|
-
//
|
|
543
|
-
//
|
|
544
|
-
//
|
|
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
|
-
//
|
|
548
|
-
// response be written first.
|
|
549
|
-
// whole handler runs without
|
|
550
|
-
//
|
|
551
|
-
//
|
|
552
|
-
//
|
|
553
|
-
//
|
|
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`
|
|
569
|
-
//
|
|
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
|
-
//
|
|
575
|
-
//
|
|
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.
|
|
584
|
-
//
|
|
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
|
|
592
|
-
//
|
|
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 `{}
|
|
596
|
-
//
|
|
597
|
-
//
|
|
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
|
|
607
|
-
// covers shows as trusted
|
|
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
|
|
610
|
-
//
|
|
611
|
-
//
|
|
612
|
-
//
|
|
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
|
-
//
|
|
620
|
-
// restart. The bundle includes the matcher
|
|
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
|
|
626
|
-
//
|
|
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
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
//
|
|
638
|
-
//
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
//
|
|
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
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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
|
-
|
|
636
|
+
const aged = stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ');
|
|
637
|
+
out += ` cached ${terminalSafe(aged)} — re-probing now\n`;
|
|
659
638
|
}
|
|
660
|
-
|
|
661
|
-
|
|
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
|
|
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], {
|
|
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
|
}
|