@basaltkit/deploy-ui 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/remote.js ADDED
@@ -0,0 +1,220 @@
1
+ import { classifySshFailure, remoteCommand, sshArgs } from './ssh.js';
2
+ import { Diagnostics, ProtocolReader } from './stream.js';
3
+ /** Failures that a retry cannot fix: the key, the host key, the server's setup, or a stream that lied. */
4
+ const PERMANENT = new Set(['ssh-missing', 'auth', 'passphrase', 'host-key', 'no-node', 'no-dir', 'no-deploy', 'corrupt', 'protocol-version', 'no-protocol', 'unsafe', 'cancelled']);
5
+ export const isPermanent = (failure) => PERMANENT.has(failure.code);
6
+ export async function execRemote(runner, target, spec, options = {}) {
7
+ const stdin = options.stdin;
8
+ let args;
9
+ try {
10
+ args = [...runner.prefix, ...sshArgs(target, remoteCommand(target, spec, options.actor))];
11
+ }
12
+ catch (error) {
13
+ stdin?.fill(0);
14
+ return { failure: { code: 'unsafe', message: error.message }, diagnostics: [], stderr: [], sshExit: null };
15
+ }
16
+ let result;
17
+ let error;
18
+ const reader = new ProtocolReader({
19
+ ...(spec.command === 'attach' ? { attach: { fromSeq: spec.fromSeq ?? 0 } } : {}),
20
+ onEvent: (event, known) => {
21
+ if (event.type === 'result')
22
+ result = event.data;
23
+ if (event.type === 'error')
24
+ error = event;
25
+ options.onEvent?.(event, known);
26
+ },
27
+ ...(options.onInner ? { onInner: options.onInner } : {}),
28
+ ...(options.onDiagnostic ? { onDiagnostic: options.onDiagnostic } : {}),
29
+ });
30
+ const stderr = new Diagnostics();
31
+ let rawStderr = '';
32
+ let timedOut = false;
33
+ let cancelled = false;
34
+ let spawnError;
35
+ const exit = await new Promise((resolve) => {
36
+ let child;
37
+ try {
38
+ child = runner.spawn(runner.program, args, {
39
+ shell: false,
40
+ windowsHide: true,
41
+ stdio: [stdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
42
+ env: runner.env,
43
+ ...(runner.cwd ? { cwd: runner.cwd } : {}),
44
+ });
45
+ }
46
+ catch (caught) {
47
+ spawnError = caught;
48
+ stdin?.fill(0);
49
+ resolve(null);
50
+ return;
51
+ }
52
+ const stop = () => { if (child.exitCode === null && child.signalCode === null)
53
+ child.kill('SIGTERM'); };
54
+ const timer = options.timeoutMs ? setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs) : undefined;
55
+ const onAbort = () => { cancelled = true; stop(); };
56
+ if (options.signal?.aborted)
57
+ onAbort();
58
+ options.signal?.addEventListener('abort', onAbort, { once: true });
59
+ child.on('error', (caught) => { spawnError = caught; });
60
+ child.stdout?.on('data', (chunk) => { if (!reader.push(chunk))
61
+ stop(); });
62
+ child.stderr?.on('data', (chunk) => {
63
+ if (rawStderr.length < 64 * 1024)
64
+ rawStderr += chunk.toString('utf8');
65
+ stderr.add(chunk.toString('utf8'));
66
+ });
67
+ if (stdin && child.stdin) {
68
+ // The reader may be gone already (a refused connection): EPIPE is not an error of ours.
69
+ child.stdin.on('error', () => undefined);
70
+ child.stdin.end(stdin, () => stdin.fill(0));
71
+ }
72
+ else
73
+ stdin?.fill(0);
74
+ child.on('close', (code) => {
75
+ if (timer)
76
+ clearTimeout(timer);
77
+ options.signal?.removeEventListener('abort', onAbort);
78
+ stdin?.fill(0);
79
+ resolve(code);
80
+ });
81
+ });
82
+ reader.end();
83
+ const stderrLines = stderr.lines.filter((line) => line.trim() !== '');
84
+ if (stderr.dropped > 0)
85
+ stderrLines.push(`(${stderr.dropped} more bytes of stderr not shown)`);
86
+ const diagnostics = [...reader.diagnostics.lines, ...stderrLines];
87
+ const outcome = {
88
+ ...(reader.hello ? { hello: reader.hello } : {}),
89
+ ...(error ? { error } : {}),
90
+ ...(result !== undefined ? { result } : {}),
91
+ ...(reader.done ? { done: reader.done } : {}),
92
+ ...(reader.innerDone ? { innerDone: reader.innerDone } : {}),
93
+ ...(reader.lastInnerSeq !== undefined ? { lastInnerSeq: reader.lastInnerSeq } : {}),
94
+ diagnostics,
95
+ stderr: stderrLines,
96
+ sshExit: exit,
97
+ };
98
+ const failure = describeFailure(reader, { spawnError, timedOut, cancelled, exit, stderr: rawStderr, destination: target.ssh });
99
+ if (failure)
100
+ outcome.failure = failure;
101
+ return outcome;
102
+ }
103
+ function describeFailure(reader, how) {
104
+ if (how.spawnError) {
105
+ return how.spawnError.code === 'ENOENT'
106
+ ? { code: 'ssh-missing', message: 'no ssh client was found', hint: 'install OpenSSH (on Windows: the OpenSSH Client optional feature), or pass --ssh=<absolute path>' }
107
+ : { code: 'ssh', message: `ssh could not start: ${how.spawnError.message}` };
108
+ }
109
+ if (reader.failure && reader.failure.kind !== 'truncated')
110
+ return { code: reader.failure.kind, message: reader.failure.message };
111
+ if (how.cancelled)
112
+ return { code: 'cancelled', message: 'stopped by the UI' };
113
+ if (how.timedOut)
114
+ return { code: 'timeout', message: 'the command took too long and was stopped' };
115
+ if (reader.done)
116
+ return undefined;
117
+ const ssh = classifySshFailure(how.exit, how.stderr, how.destination);
118
+ if (!reader.hello) {
119
+ return ssh ?? {
120
+ code: 'no-protocol',
121
+ message: 'no protocol output from the server',
122
+ hint: 'is the account\'s login shell POSIX (sh, bash, zsh)? Does the app\'s @basaltkit/deploy speak protocol 1 (the release with RFC 0008)? Upgrade it in the app and deploy once from a terminal',
123
+ };
124
+ }
125
+ const cut = reader.failure ? `${reader.failure.message}, ` : '';
126
+ return { code: 'abnormal', message: `the output ended without done (${cut}exit ${how.exit ?? 'by signal'}) — never a success`, ...(ssh ? { hint: ssh.message } : {}) };
127
+ }
128
+ /** The reply of a collected command: it succeeded only with `done` exit 0 and no failure. */
129
+ export function toReply(outcome) {
130
+ return {
131
+ ok: !outcome.failure && outcome.done?.exitCode === 0,
132
+ ...(outcome.hello ? { hello: outcome.hello } : {}),
133
+ ...(outcome.result !== undefined ? { result: outcome.result } : {}),
134
+ ...(outcome.error ? { error: outcome.error } : {}),
135
+ ...(outcome.done ? { exitCode: outcome.done.exitCode } : {}),
136
+ ...(outcome.failure ? { failure: outcome.failure } : {}),
137
+ diagnostics: outcome.diagnostics,
138
+ };
139
+ }
140
+ export const RECONNECT_FIRST_MS = 1000;
141
+ export const RECONNECT_MAX_MS = 30_000;
142
+ export const RECONNECT_WINDOW_MS = 10 * 60_000;
143
+ const abortableSleep = (ms, signal) => new Promise((resolve) => {
144
+ const timer = setTimeout(done, ms);
145
+ function done() { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); }
146
+ signal.addEventListener('abort', done, { once: true });
147
+ });
148
+ /**
149
+ * `attach --follow` that survives a dropped connection: when ssh ends without
150
+ * the run's `done`, it attaches again from the last run seq + 1 (1 s, 2 s, 4 s
151
+ * … 30 s, for up to 10 minutes without progress). The page never sees a
152
+ * duplicate or a gap: the reader checks the run's sequence on every attach.
153
+ */
154
+ export async function follow(runner, target, runId, fromSeq, emit, options) {
155
+ const sleep = options.sleep ?? abortableSleep;
156
+ const now = options.now ?? Date.now;
157
+ const windowMs = options.windowMs ?? RECONNECT_WINDOW_MS;
158
+ let next = fromSeq;
159
+ let delay = RECONNECT_FIRST_MS;
160
+ let since = now();
161
+ let greeted = false;
162
+ emit({ kind: 'state', state: 'connecting' });
163
+ for (;;) {
164
+ if (options.signal.aborted) {
165
+ emit({ kind: 'state', state: 'ended', code: 'stopped', reason: 'the UI stopped watching; the run goes on on the server' });
166
+ return;
167
+ }
168
+ let progressed = false;
169
+ const outcome = await execRemote(runner, target, { command: 'attach', runId, fromSeq: next, follow: true }, {
170
+ signal: options.signal,
171
+ onEvent: (event) => {
172
+ if (event.type === 'hello' && !greeted) {
173
+ greeted = true;
174
+ emit({ kind: 'hello', hello: event });
175
+ }
176
+ },
177
+ onInner: (event, known) => {
178
+ next = event.seq + 1;
179
+ progressed = true;
180
+ emit({ kind: 'event', event, known });
181
+ },
182
+ onDiagnostic: (text) => emit({ kind: 'diagnostic', text }),
183
+ });
184
+ if (outcome.innerDone) {
185
+ emit({ kind: 'state', state: 'ended', exitCode: outcome.innerDone.exitCode });
186
+ return;
187
+ }
188
+ if (outcome.error) {
189
+ emit({ kind: 'state', state: 'ended', code: outcome.error.code, reason: outcome.error.message, ...(outcome.error.hint ? { hint: outcome.error.hint } : {}) });
190
+ return;
191
+ }
192
+ if (outcome.done && !outcome.failure) {
193
+ // Attach ended cleanly without the run's `done` in this window: the run's
194
+ // `done` came before `fromSeq` (RFC 0008 §8.4 — attach's exit code is the
195
+ // run's). The run has finished; reconnecting would never see more.
196
+ emit({ kind: 'state', state: 'ended', exitCode: outcome.done.exitCode, reason: 'the run had already finished' });
197
+ return;
198
+ }
199
+ const failure = outcome.failure ?? { code: 'abnormal', message: 'attach ended without the run\'s done' };
200
+ if (isPermanent(failure)) {
201
+ if (failure.code === 'cancelled')
202
+ continue;
203
+ for (const text of outcome.stderr)
204
+ emit({ kind: 'diagnostic', text });
205
+ emit({ kind: 'state', state: 'ended', code: failure.code, reason: failure.message, ...(failure.hint ? { hint: failure.hint } : {}) });
206
+ return;
207
+ }
208
+ if (progressed) {
209
+ since = now();
210
+ delay = RECONNECT_FIRST_MS;
211
+ }
212
+ if (now() - since >= windowMs) {
213
+ emit({ kind: 'state', state: 'ended', code: 'disconnected', reason: `the connection kept dropping (${failure.message}); the run goes on on the server`, hint: 're-attach when the network is back' });
214
+ return;
215
+ }
216
+ emit({ kind: 'state', state: 'reconnecting', code: failure.code, reason: failure.message, retryInMs: delay });
217
+ await sleep(delay, options.signal);
218
+ delay = Math.min(delay * 2, RECONNECT_MAX_MS);
219
+ }
220
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The checks every request passes before routing (RFC 0009 §4.3), and the
3
+ * headers every response carries (§4.4). Pure: a request's method, path and
4
+ * headers in, a verdict out.
5
+ *
6
+ * The UI's server is reachable by every process on the machine and is the
7
+ * target of every page the browser opens: exact `Host` (DNS rebinding), a
8
+ * POST-only JSON API with an exact `Origin` (CSRF, cross-origin fetch), a
9
+ * bearer token no other page can read, and no CORS, ever.
10
+ */
11
+ export declare const SECURITY_HEADERS: Readonly<Record<string, string>>;
12
+ export declare const MAX_BODY_BYTES: number;
13
+ /** A static file's name under /client/: flat, lowercase, `.js` — never a path. */
14
+ export declare const CLIENT_FILE: RegExp;
15
+ export interface RequestFacts {
16
+ method: string;
17
+ /** The raw request target (`req.url`). */
18
+ url: string;
19
+ headers: Record<string, string | string[] | undefined>;
20
+ }
21
+ export type Verdict = {
22
+ kind: 'static';
23
+ file: 'index' | 'css' | {
24
+ client: string;
25
+ };
26
+ } | {
27
+ kind: 'api';
28
+ route: string;
29
+ } | {
30
+ kind: 'refuse';
31
+ status: number;
32
+ reason: string;
33
+ };
34
+ /**
35
+ * Host, method, path, content type, origin and fetch metadata. The token is
36
+ * checked by the caller (it needs the session), after this verdict.
37
+ */
38
+ export declare function checkRequest(facts: RequestFacts, port: number): Verdict;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The checks every request passes before routing (RFC 0009 §4.3), and the
3
+ * headers every response carries (§4.4). Pure: a request's method, path and
4
+ * headers in, a verdict out.
5
+ *
6
+ * The UI's server is reachable by every process on the machine and is the
7
+ * target of every page the browser opens: exact `Host` (DNS rebinding), a
8
+ * POST-only JSON API with an exact `Origin` (CSRF, cross-origin fetch), a
9
+ * bearer token no other page can read, and no CORS, ever.
10
+ */
11
+ export const SECURITY_HEADERS = {
12
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; font-src 'none'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'",
13
+ 'X-Frame-Options': 'DENY',
14
+ 'X-Content-Type-Options': 'nosniff',
15
+ 'Referrer-Policy': 'no-referrer',
16
+ 'Cache-Control': 'no-store',
17
+ 'Cross-Origin-Opener-Policy': 'same-origin',
18
+ 'Cross-Origin-Resource-Policy': 'same-origin',
19
+ 'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), clipboard-read=()',
20
+ };
21
+ export const MAX_BODY_BYTES = 1024 * 1024;
22
+ /** A static file's name under /client/: flat, lowercase, `.js` — never a path. */
23
+ export const CLIENT_FILE = /^[a-z0-9-]+\.js$/;
24
+ const header = (facts, name) => {
25
+ const value = facts.headers[name];
26
+ return Array.isArray(value) ? undefined : value;
27
+ };
28
+ /**
29
+ * Host, method, path, content type, origin and fetch metadata. The token is
30
+ * checked by the caller (it needs the session), after this verdict.
31
+ */
32
+ export function checkRequest(facts, port) {
33
+ const origin = `http://127.0.0.1:${port}`;
34
+ if (header(facts, 'host') !== `127.0.0.1:${port}`)
35
+ return { kind: 'refuse', status: 421, reason: 'wrong Host' };
36
+ // The request target is a path, nothing else: no absolute form, no query, no encoded or dot segment.
37
+ const path = facts.url;
38
+ if (!/^\/[A-Za-z0-9/._-]*$/.test(path) || path.includes('//') || path.split('/').some((s) => s === '.' || s === '..')) {
39
+ return { kind: 'refuse', status: 404, reason: 'not found' };
40
+ }
41
+ if (!path.startsWith('/api/')) {
42
+ if (facts.method !== 'GET' && facts.method !== 'HEAD')
43
+ return { kind: 'refuse', status: 405, reason: 'method not allowed' };
44
+ if (path === '/')
45
+ return { kind: 'static', file: 'index' };
46
+ if (path === '/app.css')
47
+ return { kind: 'static', file: 'css' };
48
+ const name = path.startsWith('/client/') ? path.slice('/client/'.length) : '';
49
+ if (CLIENT_FILE.test(name))
50
+ return { kind: 'static', file: { client: name } };
51
+ return { kind: 'refuse', status: 404, reason: 'not found' };
52
+ }
53
+ if (facts.method !== 'POST')
54
+ return { kind: 'refuse', status: 405, reason: 'POST only' };
55
+ const type = header(facts, 'content-type');
56
+ if (!type || !/^application\/json\s*(?:;\s*charset=utf-8\s*)?$/i.test(type))
57
+ return { kind: 'refuse', status: 415, reason: 'application/json only' };
58
+ if (header(facts, 'origin') !== origin)
59
+ return { kind: 'refuse', status: 403, reason: 'wrong Origin' };
60
+ const site = header(facts, 'sec-fetch-site');
61
+ if (site !== undefined && site !== 'same-origin')
62
+ return { kind: 'refuse', status: 403, reason: 'cross-site request' };
63
+ return { kind: 'api', route: path.slice('/api/'.length) };
64
+ }
@@ -0,0 +1,39 @@
1
+ import { type FollowOptions, type SshRunner } from './remote.js';
2
+ import { type TimerApi } from './session.js';
3
+ /**
4
+ * The UI's local server (RFC 0009 §4, §7): `node:http` on 127.0.0.1 and a
5
+ * port the OS picks, one browser session, ~10 POST routes. A request never
6
+ * carries a host, a path or a flag: it names a target, and the server builds
7
+ * everything else from the operator's targets file.
8
+ */
9
+ export interface UiServerOptions {
10
+ targetsPath: string;
11
+ runner: SshRunner;
12
+ /** The OS user name, the actor when the targets file names none (if it matches the server's pattern). */
13
+ osUser?: string;
14
+ /** Default 15, at most 240. */
15
+ idleMinutes?: number;
16
+ /** Where the compiled client modules are (default: `dist/client` next to this file); null: none. */
17
+ clientDir?: string | null;
18
+ /** One line to the terminal. Never a request body, never an answer. */
19
+ log: (line: string) => void;
20
+ /** Called once when the server stops on its own (idle, quit). */
21
+ onStop?: (reason: 'idle' | 'quit') => void;
22
+ now?: () => number;
23
+ random?: (size: number) => Buffer;
24
+ timers?: TimerApi;
25
+ /** Reconnect pacing for attach (tests). */
26
+ follow?: Pick<FollowOptions, 'sleep' | 'now' | 'windowMs'>;
27
+ timeouts?: Partial<Record<'status' | 'plan' | 'detach' | 'cancel', number>>;
28
+ }
29
+ export interface UiServer {
30
+ port: number;
31
+ /** `http://127.0.0.1:<port>/` */
32
+ url: string;
33
+ /** The URL with the one-time launch code in its fragment. */
34
+ launchUrl: string;
35
+ close(): Promise<void>;
36
+ }
37
+ export declare const MAX_SSH_SESSIONS = 4;
38
+ export declare const MAX_IDLE_MINUTES = 240;
39
+ export declare function startUiServer(options: UiServerOptions): Promise<UiServer>;