@osdlc/wayfinder 0.7.3 → 0.8.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.
- package/CHANGELOG.md +221 -0
- package/CONTRIBUTING.md +6 -0
- package/README.md +295 -150
- package/SECURITY.md +19 -5
- package/dist/actions.d.ts +23 -0
- package/dist/actions.js +97 -0
- package/dist/app.d.ts +1 -13
- package/dist/app.js +1 -13
- package/dist/args.d.ts +11 -6
- package/dist/args.js +25 -7
- package/dist/cache.d.ts +2 -4
- package/dist/cache.js +5 -10
- package/dist/catalog.d.ts +30 -3
- package/dist/catalog.js +87 -11
- package/dist/clean-command.d.ts +65 -36
- package/dist/clean-command.js +372 -226
- package/dist/cli.d.ts +24 -57
- package/dist/cli.js +139 -568
- package/dist/commands/browse.d.ts +128 -0
- package/dist/commands/browse.js +151 -0
- package/dist/commands/index.d.ts +25 -0
- package/dist/commands/index.js +71 -0
- package/dist/commands/list.d.ts +208 -0
- package/dist/commands/list.js +127 -0
- package/dist/commands/query.d.ts +166 -0
- package/dist/commands/query.js +73 -0
- package/dist/commands/run.d.ts +114 -0
- package/dist/commands/run.js +139 -0
- package/dist/commands/shared.d.ts +152 -0
- package/dist/commands/shared.js +209 -0
- package/dist/config-command.d.ts +27 -43
- package/dist/config-command.js +129 -330
- package/dist/config-keys.d.ts +25 -0
- package/dist/config-keys.js +29 -0
- package/dist/config.d.ts +271 -257
- package/dist/config.js +610 -460
- package/dist/core/copy-text.d.ts +30 -0
- package/dist/core/copy-text.js +50 -0
- package/dist/core/filter.d.ts +55 -0
- package/dist/core/filter.js +59 -0
- package/dist/core/run.d.ts +22 -0
- package/dist/core/run.js +59 -0
- package/dist/core/saved-view.d.ts +59 -0
- package/dist/core/saved-view.js +119 -0
- package/dist/core/session.d.ts +262 -0
- package/dist/core/session.js +589 -0
- package/dist/core/skills.d.ts +53 -0
- package/dist/core/skills.js +54 -0
- package/dist/core/unknowns.d.ts +72 -0
- package/dist/core/unknowns.js +68 -0
- package/dist/devlink.d.ts +3 -0
- package/dist/devlink.js +5 -2
- package/dist/document-schemas.generated.d.ts +22 -0
- package/dist/document-schemas.generated.js +916 -0
- package/dist/documents.d.ts +432 -0
- package/dist/documents.js +163 -0
- package/dist/groups.d.ts +22 -26
- package/dist/groups.js +13 -29
- package/dist/guide.d.ts +26 -13
- package/dist/guide.js +119 -103
- package/dist/index.d.ts +112 -0
- package/dist/index.js +58 -0
- package/dist/keys.d.ts +51 -0
- package/dist/keys.js +273 -0
- package/dist/page.d.ts +18 -8
- package/dist/page.js +28 -17
- package/dist/providers-command.d.ts +81 -20
- package/dist/providers-command.js +33 -75
- package/dist/schema.d.ts +48 -0
- package/dist/schema.js +61 -0
- package/dist/serve/auth.d.ts +46 -0
- package/dist/serve/auth.js +82 -0
- package/dist/serve/catalog-share.d.ts +51 -0
- package/dist/serve/catalog-share.js +116 -0
- package/dist/serve/index.d.ts +98 -0
- package/dist/serve/index.js +251 -0
- package/dist/serve/routes.d.ts +60 -0
- package/dist/serve/routes.js +186 -0
- package/dist/serve/terminal-input.d.ts +50 -0
- package/dist/serve/terminal-input.js +108 -0
- package/dist/skills.d.ts +19 -0
- package/dist/skills.js +54 -0
- package/dist/terminal-text.d.ts +8 -0
- package/dist/terminal-text.js +19 -6
- package/dist/tool-info.d.ts +24 -0
- package/dist/tool-info.js +17 -0
- package/dist/trust-command.d.ts +15 -27
- package/dist/trust-command.js +110 -208
- package/dist/trust-store.d.ts +5 -10
- package/dist/trust-store.js +9 -42
- package/dist/tui/app.d.ts +180 -0
- package/dist/tui/app.js +1278 -0
- package/dist/tui/copy.d.ts +29 -0
- package/dist/tui/copy.js +39 -0
- package/dist/tui/index.d.ts +33 -0
- package/dist/tui/index.js +97 -0
- package/dist/tui/keys-input.d.ts +27 -0
- package/dist/tui/keys-input.js +87 -0
- package/dist/tui/settings.d.ts +94 -0
- package/dist/tui/settings.js +198 -0
- package/dist/tui/style.d.ts +62 -0
- package/dist/tui/style.js +77 -0
- package/dist/version.d.ts +6 -0
- package/dist/version.js +7 -0
- package/dist/vocabulary.d.ts +89 -0
- package/dist/vocabulary.js +153 -0
- package/dist/web/main.js +1965 -568
- package/dist/web/page.html +39 -33
- package/dist/web/styles.css +457 -329
- package/dist/xdg.d.ts +76 -4
- package/dist/xdg.js +77 -5
- package/package.json +28 -9
- package/schema/config.json +133 -0
- package/dist/http.d.ts +0 -22
- package/dist/http.js +0 -149
- package/dist/origin-owner.d.ts +0 -19
- package/dist/origin-owner.js +0 -85
- package/dist/serve.d.ts +0 -98
- package/dist/serve.js +0 -671
- package/dist/tui.d.ts +0 -177
- package/dist/tui.js +0 -840
package/dist/serve.js
DELETED
|
@@ -1,671 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The web view: the same catalog as a page you can search in a browser.
|
|
3
|
-
*
|
|
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
|
-
*
|
|
9
|
-
* Loopback alone does not keep other callers out, so every route needs 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 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.
|
|
16
|
-
*
|
|
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.
|
|
23
|
-
*
|
|
24
|
-
* `/api/run` hands this server's own terminal to a task and exits. It takes a
|
|
25
|
-
* task id and nothing else (see the note on the route).
|
|
26
|
-
*
|
|
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.
|
|
32
|
-
*/
|
|
33
|
-
import { spawnRunner, streamRunner } from '@osdlc/command-seam';
|
|
34
|
-
import { tasks as allTasks, } from '@osdlc/system-model/detect';
|
|
35
|
-
import { humanAge } from '@osdlc/system-model/duration';
|
|
36
|
-
import { homeDir, trustDecision } from '@osdlc/trust-repo';
|
|
37
|
-
import { APP, BIN, PROJECT_CONFIG_FILENAME, TOKEN_HEADER } from "./app.js";
|
|
38
|
-
import { acceptArgs, runArgv } from "./args.js";
|
|
39
|
-
import { cacheDir } from "./cache.js";
|
|
40
|
-
import { collectAndCache, freshStates, fromStore, orderedCatalog, readCachedCatalog, } from "./catalog.js";
|
|
41
|
-
import { CONFIG_KEYS, collectOptionsFromConfig, configLocations, loadConfig, readRawConfigFile, setConfigValue, trustPolicyFromConfig, trustPolicyOptions, validateConfig, writeConfigFile, } from "./config.js";
|
|
42
|
-
import { terminalSafe } from "./terminal-text.js";
|
|
43
|
-
import { appTrustStore } from "./trust-store.js";
|
|
44
|
-
import { serveFetch } from "./http.js";
|
|
45
|
-
import { buildPage } from "./page.js";
|
|
46
|
-
/** Requests inside this window share one probe; an explicit refresh skips it. */
|
|
47
|
-
const COALESCE_MS = 1500;
|
|
48
|
-
/** How long the boot token stays usable if the browser never arrives. */
|
|
49
|
-
const BOOT_TTL_MS = 60_000;
|
|
50
|
-
/** 128 bits, hex. `getRandomValues` is cryptographically secure; `Math.random` is not. */
|
|
51
|
-
function secret() {
|
|
52
|
-
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
|
|
53
|
-
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
54
|
-
}
|
|
55
|
-
/** Compared without an early exit, so a near miss is not distinguishable by timing. */
|
|
56
|
-
function tokenEquals(a, b) {
|
|
57
|
-
if (a.length !== b.length)
|
|
58
|
-
return false;
|
|
59
|
-
let diff = 0;
|
|
60
|
-
for (let i = 0; i < a.length; i++)
|
|
61
|
-
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
62
|
-
return diff === 0;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
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.
|
|
68
|
-
*/
|
|
69
|
-
function unauthorized() {
|
|
70
|
-
return new Response('unauthorized', { status: 401 });
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
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.
|
|
76
|
-
*
|
|
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.
|
|
81
|
-
*/
|
|
82
|
-
function unauthorizedPage() {
|
|
83
|
-
const body = `<!doctype html>
|
|
84
|
-
<meta charset="utf-8">
|
|
85
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
86
|
-
<title>${APP} - not signed in</title>
|
|
87
|
-
<style>
|
|
88
|
-
:root { color-scheme: light dark; }
|
|
89
|
-
body {
|
|
90
|
-
margin: 0; min-height: 100vh;
|
|
91
|
-
display: flex; align-items: center; justify-content: center;
|
|
92
|
-
font: 15px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
93
|
-
background: #fbfbfa; color: #1c1c1a;
|
|
94
|
-
}
|
|
95
|
-
main { max-width: 30rem; padding: 2rem; }
|
|
96
|
-
h1 { margin: 0 0 .75rem; font-size: 1.15rem; font-weight: 600; }
|
|
97
|
-
p { margin: 0 0 .75rem; }
|
|
98
|
-
code {
|
|
99
|
-
font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .92em;
|
|
100
|
-
padding: .1em .35em; border-radius: .25em;
|
|
101
|
-
background: rgba(127, 127, 127, .18);
|
|
102
|
-
/* Text meant to be retyped. The default face ligates a run of hyphens
|
|
103
|
-
into one long dash, and what is retyped is then not what is shown. */
|
|
104
|
-
font-variant-ligatures: none;
|
|
105
|
-
}
|
|
106
|
-
@media (prefers-color-scheme: dark) {
|
|
107
|
-
body { background: #16161a; color: #e6e6e3; }
|
|
108
|
-
}
|
|
109
|
-
</style>
|
|
110
|
-
<main>
|
|
111
|
-
<h1>This browser is not signed in.</h1>
|
|
112
|
-
<p>${APP} needs a fresh link, and only your terminal can hand one out.</p>
|
|
113
|
-
<p>Go to the terminal ${APP} is running in, stop it with <code>Ctrl-C</code> and
|
|
114
|
-
start it again: it prints a new link that signs this browser in.</p>
|
|
115
|
-
</main>
|
|
116
|
-
`;
|
|
117
|
-
return new Response(body, {
|
|
118
|
-
status: 401,
|
|
119
|
-
headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
/**
|
|
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.
|
|
126
|
-
*/
|
|
127
|
-
const PAINT = !process.env['NO_COLOR'] && process.stdout.isTTY;
|
|
128
|
-
const dim = (s) => (PAINT ? `\x1b[2m${s}\x1b[0m` : s);
|
|
129
|
-
const bold = (s) => (PAINT ? `\x1b[1m${s}\x1b[0m` : s);
|
|
130
|
-
/**
|
|
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.
|
|
136
|
-
*/
|
|
137
|
-
function runAndExit(root, task, argv) {
|
|
138
|
-
// Echo what actually runs, not `display`.
|
|
139
|
-
process.stdout.write(`${dim('$')} ${bold(terminalSafe(argv.join(' ')))}\n`);
|
|
140
|
-
const [binary, ...rest] = argv;
|
|
141
|
-
const res = streamRunner(binary).run(rest, {
|
|
142
|
-
cwd: task.cwd === '.' ? root : `${root}/${task.cwd}`,
|
|
143
|
-
});
|
|
144
|
-
process.exit(res.exitCode);
|
|
145
|
-
}
|
|
146
|
-
/**
|
|
147
|
-
* Apply a settings-screen edit to `<root>/wayfinder.config.json`.
|
|
148
|
-
*
|
|
149
|
-
* The request is a patch of dotted keys, not a whole document, for two
|
|
150
|
-
* reasons. The second matters more:
|
|
151
|
-
*
|
|
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.
|
|
159
|
-
*
|
|
160
|
-
* Returns null on success, or the Response to send on refusal.
|
|
161
|
-
*/
|
|
162
|
-
async function writeProjectConfig(req, options) {
|
|
163
|
-
const bad = (detail) => new Response(detail, { status: 400 });
|
|
164
|
-
const body = (await req.json().catch(() => null));
|
|
165
|
-
if (body === null || !isRecord(body.set))
|
|
166
|
-
return bad('expected { set: { <key>: <value> } }');
|
|
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.
|
|
170
|
-
for (const key of Object.keys(body.set)) {
|
|
171
|
-
if (!CONFIG_KEYS.includes(key))
|
|
172
|
-
return bad(`${key} is not a setting`);
|
|
173
|
-
}
|
|
174
|
-
// Tool modules are code. The page never edits them; `way config set` does.
|
|
175
|
-
if ('tools' in body.set)
|
|
176
|
-
return bad(`tools cannot be written from the page; use "${BIN} config set tools"`);
|
|
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.
|
|
181
|
-
if (body.set['allowExec'] === true) {
|
|
182
|
-
return bad('allowExec: true cannot be written to a project file — a repository cannot grant itself ' +
|
|
183
|
-
'permission to run subprocesses. Trust this repository instead.');
|
|
184
|
-
}
|
|
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.
|
|
189
|
-
for (const key of ['trust.paths', 'trust.owners']) {
|
|
190
|
-
if (key in body.set) {
|
|
191
|
-
return bad(`${key} cannot be written to a project file — a repository cannot grant itself trust. ` +
|
|
192
|
-
'Set it in your user config instead.');
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
const file = configLocations(options.root, options.env, options.home).project;
|
|
196
|
-
let candidate = (await readRawConfigFile(file)) ?? {};
|
|
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.
|
|
202
|
-
try {
|
|
203
|
-
for (const [key, value] of Object.entries(body.set)) {
|
|
204
|
-
candidate = setConfigValue(candidate, key, value);
|
|
205
|
-
}
|
|
206
|
-
validateConfig(candidate, file);
|
|
207
|
-
}
|
|
208
|
-
catch (err) {
|
|
209
|
-
return bad(err instanceof Error ? err.message : String(err));
|
|
210
|
-
}
|
|
211
|
-
await writeConfigFile(file, candidate);
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
/** A JSON object, as distinct from an array or a primitive. */
|
|
215
|
-
function isRecord(value) {
|
|
216
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* Catalog access that runs at most one probe at a time and uses the store.
|
|
220
|
-
*
|
|
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.
|
|
224
|
-
*
|
|
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.
|
|
230
|
-
*
|
|
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.
|
|
235
|
-
*/
|
|
236
|
-
function createCatalogSource(project, root, options,
|
|
237
|
-
/**
|
|
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.
|
|
241
|
-
*/
|
|
242
|
-
runnerOrder, store) {
|
|
243
|
-
let pending = null;
|
|
244
|
-
let settledAt = 0;
|
|
245
|
-
let last = null;
|
|
246
|
-
/** The store is read at most once. After that, `last` is newer. */
|
|
247
|
-
let consultedStore = false;
|
|
248
|
-
const probe = () => {
|
|
249
|
-
pending ??= collectAndCache(project, root, options, store)
|
|
250
|
-
.then((collected) => {
|
|
251
|
-
const snapshot = {
|
|
252
|
-
catalog: orderedCatalog(collected, runnerOrder()),
|
|
253
|
-
// Measured this instant, so nothing about it is stale.
|
|
254
|
-
cache: freshStates(collected),
|
|
255
|
-
};
|
|
256
|
-
last = snapshot;
|
|
257
|
-
settledAt = Date.now();
|
|
258
|
-
return snapshot;
|
|
259
|
-
})
|
|
260
|
-
.finally(() => {
|
|
261
|
-
pending = null;
|
|
262
|
-
});
|
|
263
|
-
return pending;
|
|
264
|
-
};
|
|
265
|
-
return async (force) => {
|
|
266
|
-
if (force) {
|
|
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).
|
|
271
|
-
const running = pending;
|
|
272
|
-
if (running !== null)
|
|
273
|
-
await running.catch(() => { });
|
|
274
|
-
return probe();
|
|
275
|
-
}
|
|
276
|
-
if (last !== null && Date.now() - settledAt < COALESCE_MS)
|
|
277
|
-
return last;
|
|
278
|
-
if (!consultedStore) {
|
|
279
|
-
consultedStore = true;
|
|
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.
|
|
282
|
-
const stored = await readCachedCatalog(project, root, options, store);
|
|
283
|
-
// Serve it only when something came from the store. With execution off,
|
|
284
|
-
// an empty store still returns withheld reports.
|
|
285
|
-
if (stored.catalog !== null && fromStore(stored)) {
|
|
286
|
-
last = { catalog: orderedCatalog(stored.catalog, runnerOrder()), cache: stored.runners };
|
|
287
|
-
settledAt = Date.now();
|
|
288
|
-
// Probe in the background, after answering. A probe failure is ignored
|
|
289
|
-
// here, since this request was already answered from the store.
|
|
290
|
-
void probe().catch(() => { });
|
|
291
|
-
return last;
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
return probe();
|
|
295
|
-
};
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Bind the port and return the server's handle, without printing or opening anything.
|
|
299
|
-
*
|
|
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.
|
|
303
|
-
*
|
|
304
|
-
* The catalog source is returned with the handle, so the startup banner
|
|
305
|
-
* reports the same probe the page will see.
|
|
306
|
-
*/
|
|
307
|
-
export async function startServer(options) {
|
|
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.
|
|
311
|
-
const collectOptions = { ...options.collectOptions };
|
|
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.
|
|
314
|
-
let runnerOrder = options.runnerOrder;
|
|
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`.
|
|
317
|
-
const catalog = createCatalogSource(options.project, options.root, collectOptions, () => runnerOrder, cacheDir(options.env, 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();
|
|
322
|
-
const trustStoreInstance = appTrustStore({
|
|
323
|
-
home,
|
|
324
|
-
...(options.env !== undefined ? { env: options.env } : {}),
|
|
325
|
-
});
|
|
326
|
-
/**
|
|
327
|
-
* Whether the page may offer a trust grant.
|
|
328
|
-
*
|
|
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.
|
|
333
|
-
*
|
|
334
|
-
* The server enforces it too: `POST /api/trust` refuses when it is false.
|
|
335
|
-
*/
|
|
336
|
-
const trustable = () => collectOptions.execWithheldHint !== undefined;
|
|
337
|
-
/**
|
|
338
|
-
* Re-read the config file's collect options after a save.
|
|
339
|
-
*
|
|
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.
|
|
343
|
-
*
|
|
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`).
|
|
349
|
-
*
|
|
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.
|
|
353
|
-
*/
|
|
354
|
-
const CONFIG_OWNED = ['exclude', 'discovery', 'excludePaths'];
|
|
355
|
-
const pinned = new Set(options.pinnedByFlag ?? []);
|
|
356
|
-
const adoptConfig = (config) => {
|
|
357
|
-
const derived = collectOptionsFromConfig(config);
|
|
358
|
-
const target = collectOptions;
|
|
359
|
-
for (const key of CONFIG_OWNED) {
|
|
360
|
-
if (pinned.has(key))
|
|
361
|
-
continue;
|
|
362
|
-
if (derived[key] === undefined)
|
|
363
|
-
delete target[key];
|
|
364
|
-
else
|
|
365
|
-
target[key] = derived[key];
|
|
366
|
-
}
|
|
367
|
-
runnerOrder = config.runners?.order;
|
|
368
|
-
};
|
|
369
|
-
const sessionToken = secret();
|
|
370
|
-
let bootToken = secret();
|
|
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.
|
|
375
|
-
let bootExpiresAt = Number.POSITIVE_INFINITY;
|
|
376
|
-
const armBoot = () => {
|
|
377
|
-
bootExpiresAt = Date.now() + BOOT_TTL_MS;
|
|
378
|
-
};
|
|
379
|
-
/** True once, for the first request that presents the unexpired boot token. */
|
|
380
|
-
const burnBoot = (candidate) => {
|
|
381
|
-
if (candidate === null || bootToken === null)
|
|
382
|
-
return false;
|
|
383
|
-
if (Date.now() > bootExpiresAt) {
|
|
384
|
-
bootToken = null;
|
|
385
|
-
return false;
|
|
386
|
-
}
|
|
387
|
-
if (!tokenEquals(candidate, bootToken))
|
|
388
|
-
return false;
|
|
389
|
-
bootToken = null;
|
|
390
|
-
return true;
|
|
391
|
-
};
|
|
392
|
-
const hasSession = (req) => {
|
|
393
|
-
const header = req.headers.get(TOKEN_HEADER);
|
|
394
|
-
return header !== null && tokenEquals(header, sessionToken);
|
|
395
|
-
};
|
|
396
|
-
/**
|
|
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.
|
|
400
|
-
*/
|
|
401
|
-
let handedOff = false;
|
|
402
|
-
const server = await serveFetch({
|
|
403
|
-
hostname: '127.0.0.1',
|
|
404
|
-
port: options.port ?? 0,
|
|
405
|
-
async fetch(req, self) {
|
|
406
|
-
const url = new URL(req.url);
|
|
407
|
-
if (url.pathname === '/api/trust') {
|
|
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.
|
|
413
|
-
if (req.method === 'DELETE') {
|
|
414
|
-
if (!hasSession(req))
|
|
415
|
-
return unauthorized();
|
|
416
|
-
const removed = await trustStoreInstance.untrust(options.root);
|
|
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.
|
|
423
|
-
const snapshot = await catalog(false);
|
|
424
|
-
return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable(), removed }, { headers: { 'cache-control': 'no-store' } });
|
|
425
|
-
}
|
|
426
|
-
// Anything but POST, including the GET a link or an <img> would make.
|
|
427
|
-
if (req.method !== 'POST') {
|
|
428
|
-
return new Response('use POST or DELETE', {
|
|
429
|
-
status: 405,
|
|
430
|
-
headers: { allow: 'POST, DELETE' },
|
|
431
|
-
});
|
|
432
|
-
}
|
|
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.
|
|
436
|
-
if (!hasSession(req))
|
|
437
|
-
return unauthorized();
|
|
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.
|
|
445
|
-
if (!trustable()) {
|
|
446
|
-
return new Response("a trust grant would not change this run's execution gate", {
|
|
447
|
-
status: 409,
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
await trustStoreInstance.trust(options.root);
|
|
451
|
-
collectOptions.allowExec = true;
|
|
452
|
-
// The hint told the user to trust this repository, which they just did.
|
|
453
|
-
delete collectOptions.execWithheldHint;
|
|
454
|
-
// The fresh catalog is returned with the grant, so the page re-renders
|
|
455
|
-
// from one round trip rather than racing its own poll.
|
|
456
|
-
const granted = await catalog(true);
|
|
457
|
-
// Tool modules are code; this handler does not import them.
|
|
458
|
-
const note = options.projectToolsPending
|
|
459
|
-
? `the tools ${PROJECT_CONFIG_FILENAME} names load the next time ${BIN} starts with execution allowed`
|
|
460
|
-
: undefined;
|
|
461
|
-
return Response.json({
|
|
462
|
-
...granted.catalog,
|
|
463
|
-
cache: granted.cache,
|
|
464
|
-
trustable: trustable(),
|
|
465
|
-
...(note !== undefined ? { note } : {}),
|
|
466
|
-
}, { headers: { 'cache-control': 'no-store' } });
|
|
467
|
-
}
|
|
468
|
-
if (url.pathname === '/api/run' && req.method === 'POST') {
|
|
469
|
-
if (!hasSession(req))
|
|
470
|
-
return unauthorized();
|
|
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.
|
|
478
|
-
if (handedOff)
|
|
479
|
-
return new Response('conflict', { status: 409 });
|
|
480
|
-
handedOff = true;
|
|
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.
|
|
487
|
-
//
|
|
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.
|
|
494
|
-
let task;
|
|
495
|
-
let argv = [];
|
|
496
|
-
let snapshot;
|
|
497
|
-
try {
|
|
498
|
-
const body = (await req.json().catch(() => null));
|
|
499
|
-
const id = typeof body?.id === 'string' ? body.id : null;
|
|
500
|
-
snapshot = await catalog(false);
|
|
501
|
-
task = id === null ? undefined : allTasks(snapshot.catalog).find((t) => t.id === id);
|
|
502
|
-
if (task)
|
|
503
|
-
argv = runArgv(options.project, task, acceptArgs(body?.args));
|
|
504
|
-
}
|
|
505
|
-
catch (err) {
|
|
506
|
-
handedOff = false;
|
|
507
|
-
throw err;
|
|
508
|
-
}
|
|
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.
|
|
512
|
-
//
|
|
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.
|
|
516
|
-
if (!task) {
|
|
517
|
-
handedOff = false;
|
|
518
|
-
const stale = snapshot.cache.filter((c) => c.state === 'stale');
|
|
519
|
-
if (stale.length === 0)
|
|
520
|
-
return new Response('not found', { status: 404 });
|
|
521
|
-
const aged = stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ');
|
|
522
|
-
return new Response(`not found — this listing came from a cached probe (${aged}), so the task may have been ` +
|
|
523
|
-
'renamed or removed since. Refresh the page.', { status: 404 });
|
|
524
|
-
}
|
|
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.
|
|
531
|
-
const payload = JSON.stringify({ ok: true, display: task.display, argv });
|
|
532
|
-
void (async () => {
|
|
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.
|
|
540
|
-
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
541
|
-
await self.stop();
|
|
542
|
-
runAndExit(options.root, task, argv);
|
|
543
|
-
})();
|
|
544
|
-
return new Response(payload, {
|
|
545
|
-
headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
if (url.pathname === '/api/catalog') {
|
|
549
|
-
// Header only — see the CSRF note at the top of the file.
|
|
550
|
-
if (!hasSession(req))
|
|
551
|
-
return unauthorized();
|
|
552
|
-
const snapshot = await catalog(url.searchParams.has('force'));
|
|
553
|
-
// `cache` and `trustable` are both facts only the server knows. From
|
|
554
|
-
// `cache` the page shows the same three states the TUI does.
|
|
555
|
-
return Response.json({ ...snapshot.catalog, cache: snapshot.cache, trustable: trustable() }, { headers: { 'cache-control': 'no-store' } });
|
|
556
|
-
}
|
|
557
|
-
if (url.pathname === '/api/config') {
|
|
558
|
-
// The session token in a header, never the boot token. See the CSRF
|
|
559
|
-
// note at the top of the file.
|
|
560
|
-
if (!hasSession(req))
|
|
561
|
-
return unauthorized();
|
|
562
|
-
if (req.method === 'POST') {
|
|
563
|
-
const failure = await writeProjectConfig(req, options);
|
|
564
|
-
if (failure !== null)
|
|
565
|
-
return failure;
|
|
566
|
-
// Falls through to the read below, so a save answers with the state
|
|
567
|
-
// it produced. The screen re-renders from the file as it now is, in
|
|
568
|
-
// one round trip.
|
|
569
|
-
}
|
|
570
|
-
else if (req.method !== 'GET') {
|
|
571
|
-
return new Response('use GET or POST', { status: 405, headers: { allow: 'GET, POST' } });
|
|
572
|
-
}
|
|
573
|
-
const loaded = await loadConfig(options.root, options.env, options.home);
|
|
574
|
-
// A save has to reach the running process, not just the file. Applied
|
|
575
|
-
// after the re-read so it uses the merged layers, as the CLI did at
|
|
576
|
-
// start.
|
|
577
|
-
if (req.method === 'POST')
|
|
578
|
-
adoptConfig(loaded.effective);
|
|
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.
|
|
582
|
-
return Response.json({
|
|
583
|
-
effective: loaded.effective,
|
|
584
|
-
project: loaded.layers.project,
|
|
585
|
-
user: loaded.layers.user,
|
|
586
|
-
sources: Object.fromEntries(loaded.sources),
|
|
587
|
-
locations: { project: loaded.locations.project, user: loaded.locations.user },
|
|
588
|
-
warnings: loaded.warnings,
|
|
589
|
-
// Marker or policy: a root that the user file's
|
|
590
|
-
// trust.paths/trust.owners covers shows as trusted with no marker.
|
|
591
|
-
trusted: (await trustDecision(trustStoreInstance, options.root, trustPolicyFromConfig(loaded.effective), trustPolicyOptions(home))).trusted,
|
|
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.
|
|
596
|
-
trustable: trustable(),
|
|
597
|
-
}, { headers: { 'cache-control': 'no-store' } });
|
|
598
|
-
}
|
|
599
|
-
if (url.pathname === '/' || url.pathname === '/index.html') {
|
|
600
|
-
if (!hasSession(req) && !burnBoot(url.searchParams.get('boot')))
|
|
601
|
-
return unauthorizedPage();
|
|
602
|
-
// Built per request, so an edit to any part needs a reload, not a
|
|
603
|
-
// restart. The bundle includes the matcher.
|
|
604
|
-
return new Response(await buildPage(sessionToken), {
|
|
605
|
-
headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' },
|
|
606
|
-
});
|
|
607
|
-
}
|
|
608
|
-
// Unknown paths also answer 401. A 404 would reveal the server's routes
|
|
609
|
-
// to someone who cannot authenticate.
|
|
610
|
-
return unauthorized();
|
|
611
|
-
},
|
|
612
|
-
});
|
|
613
|
-
return { server, catalog, bootToken: bootToken, armBoot };
|
|
614
|
-
}
|
|
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.
|
|
625
|
-
const counts = first.catalog.reports
|
|
626
|
-
.map((r) => {
|
|
627
|
-
const state = r.skippedForExec ? 'withheld' : r.status === 'ok' ? r.tasks.length : r.status;
|
|
628
|
-
return `${r.runner} ${state}`;
|
|
629
|
-
})
|
|
630
|
-
.join(', ');
|
|
631
|
-
const stale = first.cache.filter((c) => c.state === 'stale');
|
|
632
|
-
let out = `${APP} ${address}\n`;
|
|
633
|
-
out += ` root ${terminalSafe(first.catalog.root)}\n`;
|
|
634
|
-
out += ` collected ${terminalSafe(counts)}\n`;
|
|
635
|
-
if (stale.length > 0) {
|
|
636
|
-
const aged = stale.map((c) => `${c.runner} ${humanAge(c.ageMs)}`).join(', ');
|
|
637
|
-
out += ` cached ${terminalSafe(aged)} — re-probing now\n`;
|
|
638
|
-
}
|
|
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.
|
|
653
|
-
process.stdout.write(` live the page refreshes on focus and every 15s; Refresh always re-reads\n`);
|
|
654
|
-
process.stdout.write(` stop Ctrl-C\n`);
|
|
655
|
-
if (options.open === false) {
|
|
656
|
-
process.stdout.write(` open ${bootUrl}\n`);
|
|
657
|
-
process.stdout.write(` signs the browser in once; the boot token expires in 60 seconds if unused\n`);
|
|
658
|
-
}
|
|
659
|
-
else {
|
|
660
|
-
// Best effort: a headless or remote shell has no browser.
|
|
661
|
-
const opener = process.platform === 'darwin' ? 'open' : 'xdg-open';
|
|
662
|
-
const proc = spawnRunner(opener, { absolutePathOnly: true }).run([bootUrl], {
|
|
663
|
-
cwd: options.root,
|
|
664
|
-
});
|
|
665
|
-
if (proc.exitCode !== 0) {
|
|
666
|
-
process.stdout.write(` (could not open a browser - visit ${bootUrl} within 60 seconds)\n`);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
// Held open by the server; Ctrl-C is the exit.
|
|
670
|
-
return new Promise(() => { });
|
|
671
|
-
}
|