@basaltkit/deploy-ui 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +167 -2
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/cli.d.ts +34 -0
- package/dist/cli.js +124 -0
- package/dist/client/api.js +203 -0
- package/dist/client/app.js +235 -0
- package/dist/client/dialog.js +47 -0
- package/dist/client/dom.js +51 -0
- package/dist/client/main.js +81 -0
- package/dist/client/messages.d.ts +58 -0
- package/dist/client/messages.js +1 -0
- package/dist/client/reply.js +40 -0
- package/dist/client/sanitize.js +16 -0
- package/dist/client/view-history.js +52 -0
- package/dist/client/view-plan.js +154 -0
- package/dist/client/view-run.js +311 -0
- package/dist/client/view-status.js +38 -0
- package/dist/client/view-targets.js +132 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +14 -0
- package/dist/open.d.ts +13 -0
- package/dist/open.js +31 -0
- package/dist/page.d.ts +7 -0
- package/dist/page.js +101 -0
- package/dist/remote.d.ts +68 -0
- package/dist/remote.js +220 -0
- package/dist/security.d.ts +38 -0
- package/dist/security.js +64 -0
- package/dist/server.d.ts +39 -0
- package/dist/server.js +513 -0
- package/dist/session.d.ts +66 -0
- package/dist/session.js +123 -0
- package/dist/ssh.d.ts +71 -0
- package/dist/ssh.js +186 -0
- package/dist/stream.d.ts +70 -0
- package/dist/stream.js +155 -0
- package/dist/targets.d.ts +80 -0
- package/dist/targets.js +242 -0
- package/package.json +51 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
import { readdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { ANSWER_ID, MAX_ANSWER_LINES, parseAnswerLine, RUN_ID } from '@basaltkit/deploy/protocol';
|
|
6
|
+
import { APP_CSS, INDEX_HTML } from './page.js';
|
|
7
|
+
import { execRemote, follow, toReply } from './remote.js';
|
|
8
|
+
import { CLIENT_FILE, checkRequest, MAX_BODY_BYTES, SECURITY_HEADERS } from './security.js';
|
|
9
|
+
import { IdleTimer, Session } from './session.js';
|
|
10
|
+
import { MUTATING, SHA } from './ssh.js';
|
|
11
|
+
import { ACTOR, checkTarget, NAME, readTargets, TargetsFileError, writeTargets } from './targets.js';
|
|
12
|
+
export const MAX_SSH_SESSIONS = 4;
|
|
13
|
+
export const MAX_IDLE_MINUTES = 240;
|
|
14
|
+
const DEFAULT_TIMEOUTS = { status: 60_000, plan: 300_000, detach: 120_000, cancel: 60_000 };
|
|
15
|
+
class HttpError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
body;
|
|
18
|
+
constructor(status, message, body) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.body = body;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
async function loadClientFiles(dir) {
|
|
25
|
+
const files = new Map();
|
|
26
|
+
if (dir === null)
|
|
27
|
+
return files;
|
|
28
|
+
let names;
|
|
29
|
+
try {
|
|
30
|
+
names = await readdir(dir);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return files;
|
|
34
|
+
}
|
|
35
|
+
// Read once, at start: no path from a request ever reaches the filesystem.
|
|
36
|
+
for (const name of names)
|
|
37
|
+
if (CLIENT_FILE.test(name))
|
|
38
|
+
files.set(name, await readFile(join(dir, name)));
|
|
39
|
+
return files;
|
|
40
|
+
}
|
|
41
|
+
export async function startUiServer(options) {
|
|
42
|
+
const idleMinutes = Math.min(Math.max(options.idleMinutes ?? 15, 1), MAX_IDLE_MINUTES);
|
|
43
|
+
const session = new Session(options.now, options.random);
|
|
44
|
+
const clientFiles = await loadClientFiles(options.clientDir === undefined ? fileURLToPath(new URL('./client/', import.meta.url)) : options.clientDir);
|
|
45
|
+
const timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };
|
|
46
|
+
const osActor = options.osUser && ACTOR.test(options.osUser) ? options.osUser : undefined;
|
|
47
|
+
/** The questions of each target's last plan: answers to anything else are refused. */
|
|
48
|
+
const questions = new Map();
|
|
49
|
+
const busy = new Set();
|
|
50
|
+
const controllers = new Set();
|
|
51
|
+
let sshSessions = 0;
|
|
52
|
+
let stopped = false;
|
|
53
|
+
const server = createServer((req, res) => {
|
|
54
|
+
handle(req, res).catch((error) => {
|
|
55
|
+
if (!res.headersSent)
|
|
56
|
+
refuse(res, 500, 'internal error');
|
|
57
|
+
else
|
|
58
|
+
res.end();
|
|
59
|
+
options.log(`internal error: ${error.message}`);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
// No slow-loris on a loopback tool either.
|
|
63
|
+
server.headersTimeout = 10_000;
|
|
64
|
+
await new Promise((resolve, reject) => {
|
|
65
|
+
server.once('error', reject);
|
|
66
|
+
server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve(); });
|
|
67
|
+
});
|
|
68
|
+
const port = server.address().port;
|
|
69
|
+
const url = `http://127.0.0.1:${port}/`;
|
|
70
|
+
const idle = new IdleTimer(idleMinutes * 60_000, () => { void stop('idle'); }, options.timers);
|
|
71
|
+
async function stop(reason) {
|
|
72
|
+
if (stopped)
|
|
73
|
+
return;
|
|
74
|
+
await close();
|
|
75
|
+
options.onStop?.(reason);
|
|
76
|
+
}
|
|
77
|
+
async function close() {
|
|
78
|
+
if (stopped)
|
|
79
|
+
return;
|
|
80
|
+
stopped = true;
|
|
81
|
+
idle.stop();
|
|
82
|
+
for (const controller of controllers)
|
|
83
|
+
controller.abort();
|
|
84
|
+
await new Promise((resolve) => {
|
|
85
|
+
server.close(() => resolve());
|
|
86
|
+
server.closeAllConnections();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function headers(res, type) {
|
|
90
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS))
|
|
91
|
+
res.setHeader(name, value);
|
|
92
|
+
res.setHeader('Content-Type', type);
|
|
93
|
+
}
|
|
94
|
+
function refuse(res, status, reason) {
|
|
95
|
+
headers(res, 'text/plain; charset=utf-8');
|
|
96
|
+
res.statusCode = status;
|
|
97
|
+
res.end(`${reason}\n`);
|
|
98
|
+
}
|
|
99
|
+
function json(res, status, value) {
|
|
100
|
+
headers(res, 'application/json; charset=utf-8');
|
|
101
|
+
res.statusCode = status;
|
|
102
|
+
res.end(JSON.stringify(value));
|
|
103
|
+
}
|
|
104
|
+
async function readBody(req) {
|
|
105
|
+
const chunks = [];
|
|
106
|
+
let size = 0;
|
|
107
|
+
try {
|
|
108
|
+
for await (const chunk of req) {
|
|
109
|
+
size += chunk.length;
|
|
110
|
+
chunks.push(chunk);
|
|
111
|
+
if (size > MAX_BODY_BYTES)
|
|
112
|
+
throw new HttpError(413, `the body is larger than ${MAX_BODY_BYTES} bytes`);
|
|
113
|
+
}
|
|
114
|
+
const buffer = Buffer.concat(chunks);
|
|
115
|
+
let value;
|
|
116
|
+
try {
|
|
117
|
+
value = buffer.length === 0 ? {} : JSON.parse(buffer.toString('utf8'));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw new HttpError(400, 'the body is not JSON');
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
buffer.fill(0);
|
|
124
|
+
}
|
|
125
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
126
|
+
throw new HttpError(400, 'the body is not a JSON object');
|
|
127
|
+
return value;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
// The answers travel in request bodies: the buffers this process owns are wiped.
|
|
131
|
+
for (const chunk of chunks)
|
|
132
|
+
chunk.fill(0);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function handle(req, res) {
|
|
136
|
+
const verdict = checkRequest({ method: req.method ?? '', url: req.url ?? '', headers: req.headers }, port);
|
|
137
|
+
if (verdict.kind === 'refuse')
|
|
138
|
+
return refuse(res, verdict.status, verdict.reason);
|
|
139
|
+
if (verdict.kind === 'static') {
|
|
140
|
+
let content;
|
|
141
|
+
let type;
|
|
142
|
+
if (verdict.file === 'index') {
|
|
143
|
+
content = INDEX_HTML;
|
|
144
|
+
type = 'text/html; charset=utf-8';
|
|
145
|
+
}
|
|
146
|
+
else if (verdict.file === 'css') {
|
|
147
|
+
content = APP_CSS;
|
|
148
|
+
type = 'text/css; charset=utf-8';
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
content = clientFiles.get(verdict.file.client);
|
|
152
|
+
type = 'text/javascript; charset=utf-8';
|
|
153
|
+
}
|
|
154
|
+
if (content === undefined)
|
|
155
|
+
return refuse(res, 404, 'not found');
|
|
156
|
+
headers(res, type);
|
|
157
|
+
res.statusCode = 200;
|
|
158
|
+
res.end(req.method === 'HEAD' ? undefined : content);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (verdict.route !== 'session' && !session.authorizes(req.headers.authorization))
|
|
162
|
+
return refuse(res, 401, 'no session');
|
|
163
|
+
let body;
|
|
164
|
+
try {
|
|
165
|
+
body = await readBody(req);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
if (error instanceof HttpError) {
|
|
169
|
+
refuse(res, error.status, error.message);
|
|
170
|
+
req.destroy();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
if (verdict.route !== 'session')
|
|
176
|
+
idle.touch();
|
|
177
|
+
try {
|
|
178
|
+
await route(verdict.route, body, res);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
if (!(error instanceof HttpError))
|
|
182
|
+
throw error;
|
|
183
|
+
if (error.body)
|
|
184
|
+
json(res, error.status, { error: error.message, ...error.body });
|
|
185
|
+
else
|
|
186
|
+
json(res, error.status, { error: error.message });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// ── targets ──────────────────────────────────────────────────────────────
|
|
190
|
+
async function loadFile() {
|
|
191
|
+
try {
|
|
192
|
+
return await readTargets(options.targetsPath);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error instanceof TargetsFileError)
|
|
196
|
+
throw new HttpError(409, error.message);
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function target(body) {
|
|
201
|
+
const name = body['target'];
|
|
202
|
+
if (typeof name !== 'string' || !NAME.test(name))
|
|
203
|
+
throw new HttpError(400, 'target: a target name');
|
|
204
|
+
const { file } = await loadFile();
|
|
205
|
+
const found = file.targets.find((t) => t.name === name);
|
|
206
|
+
if (!found)
|
|
207
|
+
throw new HttpError(404, `no target "${name}"`);
|
|
208
|
+
return { target: found, actor: file.actor ?? osActor };
|
|
209
|
+
}
|
|
210
|
+
async function targetsReply() {
|
|
211
|
+
try {
|
|
212
|
+
const { file, exists } = await readTargets(options.targetsPath);
|
|
213
|
+
const actor = file.actor ?? osActor;
|
|
214
|
+
return { path: options.targetsPath, exists, ...(actor ? { actor } : {}), targets: file.targets };
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
if (error instanceof TargetsFileError)
|
|
218
|
+
return { path: options.targetsPath, exists: true, targets: [], error: error.message };
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// ── remote commands ──────────────────────────────────────────────────────
|
|
223
|
+
function claim(name, command) {
|
|
224
|
+
if (sshSessions >= MAX_SSH_SESSIONS)
|
|
225
|
+
throw new HttpError(429, `at most ${MAX_SSH_SESSIONS} ssh sessions at a time`);
|
|
226
|
+
const mutating = MUTATING.has(command);
|
|
227
|
+
if (mutating && busy.has(name))
|
|
228
|
+
throw new HttpError(409, `a change to ${name} is already in progress from this UI`);
|
|
229
|
+
sshSessions++;
|
|
230
|
+
if (mutating)
|
|
231
|
+
busy.add(name);
|
|
232
|
+
let released = false;
|
|
233
|
+
return () => {
|
|
234
|
+
if (released)
|
|
235
|
+
return;
|
|
236
|
+
released = true;
|
|
237
|
+
sshSessions--;
|
|
238
|
+
if (mutating)
|
|
239
|
+
busy.delete(name);
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
async function collect(t, actor, spec, timeoutMs, stdin) {
|
|
243
|
+
const release = claim(t.name, spec.command);
|
|
244
|
+
const controller = new AbortController();
|
|
245
|
+
controllers.add(controller);
|
|
246
|
+
// A slow plan or a run --detach still detaching is not idleness: stopping
|
|
247
|
+
// now would SIGTERM it and lose its runId.
|
|
248
|
+
idle.hold();
|
|
249
|
+
try {
|
|
250
|
+
options.log(`${t.name}: ${spec.command}`);
|
|
251
|
+
const outcome = await execRemote(options.runner, t, spec, {
|
|
252
|
+
timeoutMs, signal: controller.signal,
|
|
253
|
+
...(actor ? { actor } : {}),
|
|
254
|
+
...(stdin ? { stdin } : {}),
|
|
255
|
+
});
|
|
256
|
+
return toReply(outcome);
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
controllers.delete(controller);
|
|
260
|
+
idle.release();
|
|
261
|
+
release();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function openStream(res) {
|
|
265
|
+
headers(res, 'application/x-ndjson; charset=utf-8');
|
|
266
|
+
res.statusCode = 200;
|
|
267
|
+
res.flushHeaders();
|
|
268
|
+
const controller = new AbortController();
|
|
269
|
+
controllers.add(controller);
|
|
270
|
+
idle.hold();
|
|
271
|
+
let open = true;
|
|
272
|
+
// The page went away: an attended command stops (its ssh session ends), a follow stops watching.
|
|
273
|
+
res.on('close', () => { if (open)
|
|
274
|
+
controller.abort(); });
|
|
275
|
+
// A write to a page that is gone is dropped, never a crash.
|
|
276
|
+
res.on('error', () => controller.abort());
|
|
277
|
+
return {
|
|
278
|
+
controller,
|
|
279
|
+
send: (message) => { if (open && !res.writableEnded && !res.destroyed)
|
|
280
|
+
res.write(`${JSON.stringify(message)}\n`); },
|
|
281
|
+
end: () => {
|
|
282
|
+
if (!open)
|
|
283
|
+
return;
|
|
284
|
+
open = false;
|
|
285
|
+
controllers.delete(controller);
|
|
286
|
+
idle.release();
|
|
287
|
+
res.end();
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
async function streamRemote(res, t, actor, spec, stdin) {
|
|
292
|
+
const release = claim(t.name, spec.command);
|
|
293
|
+
const stream = openStream(res);
|
|
294
|
+
try {
|
|
295
|
+
options.log(`${t.name}: ${spec.command} (attended)`);
|
|
296
|
+
stream.send({ kind: 'state', state: 'connecting' });
|
|
297
|
+
const outcome = await execRemote(options.runner, t, spec, {
|
|
298
|
+
signal: stream.controller.signal,
|
|
299
|
+
...(actor ? { actor } : {}),
|
|
300
|
+
...(stdin ? { stdin } : {}),
|
|
301
|
+
onEvent: (event, known) => stream.send(event.type === 'hello' ? { kind: 'hello', hello: event } : { kind: 'event', event, known }),
|
|
302
|
+
onDiagnostic: (text) => stream.send({ kind: 'diagnostic', text }),
|
|
303
|
+
});
|
|
304
|
+
for (const text of outcome.stderr)
|
|
305
|
+
stream.send({ kind: 'diagnostic', text });
|
|
306
|
+
const failure = outcome.failure;
|
|
307
|
+
stream.send(failure
|
|
308
|
+
? { kind: 'state', state: 'ended', code: failure.code, reason: failure.message, ...(failure.hint ? { hint: failure.hint } : {}) }
|
|
309
|
+
: { kind: 'state', state: 'ended', ...(outcome.done ? { exitCode: outcome.done.exitCode } : {}) });
|
|
310
|
+
}
|
|
311
|
+
finally {
|
|
312
|
+
release();
|
|
313
|
+
stream.end();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** The answers, checked and serialised as the protocol's answer lines; only ids the target's last plan asked. */
|
|
317
|
+
function answerLines(name, input) {
|
|
318
|
+
if (input === undefined)
|
|
319
|
+
return undefined;
|
|
320
|
+
if (!Array.isArray(input) || input.length > MAX_ANSWER_LINES)
|
|
321
|
+
throw new HttpError(400, `answers: a list of at most ${MAX_ANSWER_LINES}`);
|
|
322
|
+
if (input.length === 0)
|
|
323
|
+
return undefined;
|
|
324
|
+
const asked = questions.get(name);
|
|
325
|
+
if (!asked)
|
|
326
|
+
throw new HttpError(409, `run plan for ${name} first: answers are checked against its questions`);
|
|
327
|
+
const seen = new Set();
|
|
328
|
+
const lines = [];
|
|
329
|
+
for (const item of input) {
|
|
330
|
+
const id = item?.id;
|
|
331
|
+
const value = item?.value;
|
|
332
|
+
if (typeof id !== 'string' || !ANSWER_ID.test(id))
|
|
333
|
+
throw new HttpError(400, 'answers: each id is env.<KEY>');
|
|
334
|
+
if (!asked.has(id))
|
|
335
|
+
throw new HttpError(400, `answers: ${id} is not one of the questions of the last plan`, { field: id });
|
|
336
|
+
if (seen.has(id))
|
|
337
|
+
throw new HttpError(400, `answers: ${id} twice`, { field: id });
|
|
338
|
+
seen.add(id);
|
|
339
|
+
if (typeof value !== 'string')
|
|
340
|
+
throw new HttpError(400, `answers: the value of ${id} is not a string`, { field: id });
|
|
341
|
+
const line = JSON.stringify({ v: 1, type: 'answer', id, value });
|
|
342
|
+
// Never quotes the value: the parser's errors name the id only.
|
|
343
|
+
const parsed = parseAnswerLine(line);
|
|
344
|
+
if (!parsed.ok)
|
|
345
|
+
throw new HttpError(400, parsed.error, { field: id });
|
|
346
|
+
lines.push(line);
|
|
347
|
+
}
|
|
348
|
+
return Buffer.from(`${lines.join('\n')}\n`, 'utf8');
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* The operator confirmed a destination their page showed; the file is read
|
|
352
|
+
* again for each request. Both must be the same target, field for field, or
|
|
353
|
+
* nothing is sent: a file changed in between never redirects the answers.
|
|
354
|
+
*/
|
|
355
|
+
function confirmed(body, t, what) {
|
|
356
|
+
if (body['confirm'] !== true)
|
|
357
|
+
throw new HttpError(428, `${what} needs a confirmation`);
|
|
358
|
+
if (t.protected && body['confirmName'] !== t.name)
|
|
359
|
+
throw new HttpError(428, `${t.name} is protected: type its name to confirm ${what}`);
|
|
360
|
+
const shown = checkTarget(body['confirmedTarget']);
|
|
361
|
+
if (!shown.ok)
|
|
362
|
+
throw new HttpError(400, 'confirmedTarget: the target as the confirmation showed it');
|
|
363
|
+
if (JSON.stringify(shown.value) !== JSON.stringify(t)) {
|
|
364
|
+
throw new HttpError(409, `${t.name} changed in the targets file after you confirmed (${shown.value.ssh} · ${shown.value.dir} → ${t.ssh} · ${t.dir}): nothing was sent — check it and confirm again`, { changed: true });
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function runIdOf(body) {
|
|
368
|
+
const runId = body['runId'];
|
|
369
|
+
if (typeof runId !== 'string' || !RUN_ID.test(runId))
|
|
370
|
+
throw new HttpError(400, 'runId: a run id');
|
|
371
|
+
return runId;
|
|
372
|
+
}
|
|
373
|
+
async function route(name, body, res) {
|
|
374
|
+
switch (name) {
|
|
375
|
+
case 'session': {
|
|
376
|
+
const exchange = session.exchange(body['code']);
|
|
377
|
+
if (exchange.ok) {
|
|
378
|
+
idle.touch();
|
|
379
|
+
options.log('the browser session is open');
|
|
380
|
+
return json(res, 200, { token: exchange.token, serverKey: exchange.serverKey });
|
|
381
|
+
}
|
|
382
|
+
if (exchange.status === 409)
|
|
383
|
+
options.log('a second browser tried to claim the session: refused (if that was not you, quit and restart)');
|
|
384
|
+
else
|
|
385
|
+
options.log(`a session request was refused: ${exchange.reason}`);
|
|
386
|
+
return refuse(res, exchange.status, exchange.reason);
|
|
387
|
+
}
|
|
388
|
+
case 'hello': {
|
|
389
|
+
// The page's check that it still talks to this process (see Session).
|
|
390
|
+
const proof = session.prove(body['nonce']);
|
|
391
|
+
if (!proof)
|
|
392
|
+
throw new HttpError(400, 'nonce: 22 to 128 base64url characters');
|
|
393
|
+
return json(res, 200, { proof });
|
|
394
|
+
}
|
|
395
|
+
case 'targets':
|
|
396
|
+
return json(res, 200, await targetsReply());
|
|
397
|
+
case 'targets/save': {
|
|
398
|
+
const { file } = await loadFile();
|
|
399
|
+
let targets = file.targets;
|
|
400
|
+
if (body['target'] !== undefined) {
|
|
401
|
+
const checked = checkTarget(body['target']);
|
|
402
|
+
if (!checked.ok)
|
|
403
|
+
throw new HttpError(422, 'the target is refused', { errors: checked.errors });
|
|
404
|
+
const previous = typeof body['previousName'] === 'string' ? body['previousName'] : checked.value.name;
|
|
405
|
+
if (checked.value.name !== previous && targets.some((t) => t.name === checked.value.name)) {
|
|
406
|
+
throw new HttpError(422, 'the target is refused', { errors: { name: `"${checked.value.name}" is already a target` } });
|
|
407
|
+
}
|
|
408
|
+
const index = targets.findIndex((t) => t.name === previous);
|
|
409
|
+
targets = index === -1 ? [...targets, checked.value] : targets.map((t, i) => (i === index ? checked.value : t));
|
|
410
|
+
}
|
|
411
|
+
let actor = file.actor;
|
|
412
|
+
if (body['actor'] !== undefined) {
|
|
413
|
+
const given = body['actor'];
|
|
414
|
+
if (given === null || given === '')
|
|
415
|
+
actor = undefined;
|
|
416
|
+
else if (typeof given !== 'string' || !ACTOR.test(given))
|
|
417
|
+
throw new HttpError(422, 'the actor is refused', { errors: { actor: 'letters, digits and ._@+-, at most 64' } });
|
|
418
|
+
else
|
|
419
|
+
actor = given;
|
|
420
|
+
}
|
|
421
|
+
await writeTargets(options.targetsPath, { version: 1, ...(actor ? { actor } : {}), targets });
|
|
422
|
+
options.log(`targets saved to ${options.targetsPath}`);
|
|
423
|
+
return json(res, 200, await targetsReply());
|
|
424
|
+
}
|
|
425
|
+
case 'targets/remove': {
|
|
426
|
+
const removed = body['name'];
|
|
427
|
+
if (typeof removed !== 'string' || !NAME.test(removed))
|
|
428
|
+
throw new HttpError(400, 'name: a target name');
|
|
429
|
+
const { file } = await loadFile();
|
|
430
|
+
await writeTargets(options.targetsPath, { ...file, targets: file.targets.filter((t) => t.name !== removed) });
|
|
431
|
+
questions.delete(removed);
|
|
432
|
+
return json(res, 200, await targetsReply());
|
|
433
|
+
}
|
|
434
|
+
case 'status': {
|
|
435
|
+
const { target: t, actor } = await target(body);
|
|
436
|
+
return json(res, 200, await collect(t, actor, { command: 'status' }, timeouts.status));
|
|
437
|
+
}
|
|
438
|
+
case 'plan': {
|
|
439
|
+
const { target: t, actor } = await target(body);
|
|
440
|
+
const reply = await collect(t, actor, { command: 'plan' }, timeouts.plan);
|
|
441
|
+
const result = reply.result;
|
|
442
|
+
if (reply.hello && Array.isArray(result?.questions))
|
|
443
|
+
questions.set(t.name, new Set(result.questions.map((q) => q.id)));
|
|
444
|
+
return json(res, 200, reply);
|
|
445
|
+
}
|
|
446
|
+
case 'env': {
|
|
447
|
+
const { target: t, actor } = await target(body);
|
|
448
|
+
confirmed(body, t, 'writing the .env');
|
|
449
|
+
const stdin = answerLines(t.name, body['answers']);
|
|
450
|
+
return streamRemote(res, t, actor, { command: 'env', ...(stdin ? { answers: true } : {}) }, stdin);
|
|
451
|
+
}
|
|
452
|
+
case 'run': {
|
|
453
|
+
const { target: t, actor } = await target(body);
|
|
454
|
+
confirmed(body, t, 'a deploy');
|
|
455
|
+
const stdin = answerLines(t.name, body['answers']);
|
|
456
|
+
const spec = { command: 'run', ...(stdin ? { answers: true } : {}), ...(body['unhold'] === true ? { unhold: true } : {}) };
|
|
457
|
+
if (body['attended'] === true)
|
|
458
|
+
return streamRemote(res, t, actor, spec, stdin);
|
|
459
|
+
return json(res, 200, await collect(t, actor, { ...spec, detach: true }, timeouts.detach, stdin));
|
|
460
|
+
}
|
|
461
|
+
case 'rollback': {
|
|
462
|
+
const { target: t, actor } = await target(body);
|
|
463
|
+
confirmed(body, t, 'a rollback');
|
|
464
|
+
const to = body['to'];
|
|
465
|
+
if (to !== undefined && (typeof to !== 'string' || !SHA.test(to)))
|
|
466
|
+
throw new HttpError(400, 'to: a commit sha (7 to 40 lowercase hex)');
|
|
467
|
+
return json(res, 200, await collect(t, actor, { command: 'rollback', detach: true, ...(to === undefined ? {} : { to }) }, timeouts.detach));
|
|
468
|
+
}
|
|
469
|
+
case 'attach': {
|
|
470
|
+
const { target: t } = await target(body);
|
|
471
|
+
const runId = runIdOf(body);
|
|
472
|
+
const fromSeq = body['fromSeq'] ?? 0;
|
|
473
|
+
if (typeof fromSeq !== 'number' || !Number.isSafeInteger(fromSeq) || fromSeq < 0)
|
|
474
|
+
throw new HttpError(400, 'fromSeq: a whole number');
|
|
475
|
+
const release = claim(t.name, 'attach');
|
|
476
|
+
const stream = openStream(res);
|
|
477
|
+
try {
|
|
478
|
+
options.log(`${t.name}: attach ${runId} from ${fromSeq}`);
|
|
479
|
+
await follow(options.runner, t, runId, fromSeq, stream.send, { signal: stream.controller.signal, ...options.follow });
|
|
480
|
+
}
|
|
481
|
+
finally {
|
|
482
|
+
release();
|
|
483
|
+
stream.end();
|
|
484
|
+
}
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
case 'cancel': {
|
|
488
|
+
const { target: t, actor } = await target(body);
|
|
489
|
+
const runId = runIdOf(body);
|
|
490
|
+
if (body['confirm'] !== true)
|
|
491
|
+
throw new HttpError(428, 'cancel needs a confirmation');
|
|
492
|
+
// First or second is the server's state (`<runId>.cancel`), not this
|
|
493
|
+
// process's: a cancel from a terminal or an earlier UI session counts.
|
|
494
|
+
// Without the explicit `second`, the server refuses rather than sending
|
|
495
|
+
// the immediate second signal.
|
|
496
|
+
const second = body['second'] === true;
|
|
497
|
+
const reply = await collect(t, actor, { command: 'cancel', runId, ...(second ? {} : { firstOnly: true }) }, timeouts.cancel);
|
|
498
|
+
if (!second && reply.error?.code === 'already-cancelled') {
|
|
499
|
+
throw new HttpError(428, 'this run was already cancelled once (from a terminal, another session or this page): a second cancel ends it at once, mid-step — confirm that explicitly', { second: true });
|
|
500
|
+
}
|
|
501
|
+
return json(res, 200, reply);
|
|
502
|
+
}
|
|
503
|
+
case 'quit':
|
|
504
|
+
json(res, 200, { ok: true });
|
|
505
|
+
options.log('quit from the page');
|
|
506
|
+
setImmediate(() => { void stop('quit'); });
|
|
507
|
+
return;
|
|
508
|
+
default:
|
|
509
|
+
throw new HttpError(404, 'no such route');
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return { port, url, launchUrl: `${url}#launch=${session.launchCode}`, close };
|
|
513
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one browser session of a UI process (RFC 0009 §4.2): a one-time launch
|
|
3
|
+
* code (in the URL fragment, valid 120 s) exchanged once for a session token
|
|
4
|
+
* sent as `Authorization: Bearer`. The first exchange wins; any later one —
|
|
5
|
+
* right code or not — is refused, and the terminal says so.
|
|
6
|
+
*
|
|
7
|
+
* The exchange also hands the page a server key that the page never sends
|
|
8
|
+
* back: the page checks this process with a challenge (HMAC of a fresh nonce)
|
|
9
|
+
* before any answer leaves it. Once the UI has stopped, another local process
|
|
10
|
+
* may bind the same port; it can have seen the bearer token, never the key.
|
|
11
|
+
*/
|
|
12
|
+
/** Bound into every proof, so a proof is never anything but this. */
|
|
13
|
+
export declare const PROOF_CONTEXT = "basalt-deploy-ui hello v1\n";
|
|
14
|
+
export declare const NONCE: RegExp;
|
|
15
|
+
export declare const LAUNCH_TTL_MS = 120000;
|
|
16
|
+
/** Constant time for equal lengths; a length mismatch is a plain refusal (the lengths are public). */
|
|
17
|
+
export declare function safeEqual(given: string, expected: string): boolean;
|
|
18
|
+
export type Exchange = {
|
|
19
|
+
ok: true;
|
|
20
|
+
token: string;
|
|
21
|
+
serverKey: string;
|
|
22
|
+
} | {
|
|
23
|
+
ok: false;
|
|
24
|
+
status: 401 | 409;
|
|
25
|
+
reason: string;
|
|
26
|
+
};
|
|
27
|
+
export declare class Session {
|
|
28
|
+
private readonly now;
|
|
29
|
+
readonly launchCode: string;
|
|
30
|
+
private readonly token;
|
|
31
|
+
private readonly serverKey;
|
|
32
|
+
private readonly createdAt;
|
|
33
|
+
private claimed;
|
|
34
|
+
constructor(now?: () => number, random?: (size: number) => Buffer);
|
|
35
|
+
get isClaimed(): boolean;
|
|
36
|
+
exchange(code: unknown): Exchange;
|
|
37
|
+
/** HMAC-SHA256(serverKey, context + nonce), base64url; undefined for a malformed nonce. */
|
|
38
|
+
prove(nonce: unknown): string | undefined;
|
|
39
|
+
/** `Authorization: Bearer <token>`, exactly. */
|
|
40
|
+
authorizes(header: string | undefined): boolean;
|
|
41
|
+
}
|
|
42
|
+
export interface TimerApi {
|
|
43
|
+
set: (callback: () => void, ms: number) => unknown;
|
|
44
|
+
clear: (handle: unknown) => void;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Idle shutdown (RFC 0009 §4.5): fires after `ms` with no authenticated
|
|
48
|
+
* request, no open stream and no remote command in flight. Each of those
|
|
49
|
+
* holds it; releasing the last hold restarts the count.
|
|
50
|
+
*/
|
|
51
|
+
export declare class IdleTimer {
|
|
52
|
+
private readonly ms;
|
|
53
|
+
private readonly onIdle;
|
|
54
|
+
private readonly timers;
|
|
55
|
+
private handle;
|
|
56
|
+
private holds;
|
|
57
|
+
private stopped;
|
|
58
|
+
constructor(ms: number, onIdle: () => void, timers?: TimerApi);
|
|
59
|
+
touch(): void;
|
|
60
|
+
/** An open stream or a remote command in flight: the UI is not idle. */
|
|
61
|
+
hold(): void;
|
|
62
|
+
release(): void;
|
|
63
|
+
stop(): void;
|
|
64
|
+
private disarm;
|
|
65
|
+
private arm;
|
|
66
|
+
}
|