@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/session.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { createHmac, randomBytes as nodeRandomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* The one browser session of a UI process (RFC 0009 §4.2): a one-time launch
|
|
4
|
+
* code (in the URL fragment, valid 120 s) exchanged once for a session token
|
|
5
|
+
* sent as `Authorization: Bearer`. The first exchange wins; any later one —
|
|
6
|
+
* right code or not — is refused, and the terminal says so.
|
|
7
|
+
*
|
|
8
|
+
* The exchange also hands the page a server key that the page never sends
|
|
9
|
+
* back: the page checks this process with a challenge (HMAC of a fresh nonce)
|
|
10
|
+
* before any answer leaves it. Once the UI has stopped, another local process
|
|
11
|
+
* may bind the same port; it can have seen the bearer token, never the key.
|
|
12
|
+
*/
|
|
13
|
+
/** Bound into every proof, so a proof is never anything but this. */
|
|
14
|
+
export const PROOF_CONTEXT = 'basalt-deploy-ui hello v1\n';
|
|
15
|
+
export const NONCE = /^[A-Za-z0-9_-]{22,128}$/;
|
|
16
|
+
export const LAUNCH_TTL_MS = 120_000;
|
|
17
|
+
const SECRET_BYTES = 32;
|
|
18
|
+
/** Constant time for equal lengths; a length mismatch is a plain refusal (the lengths are public). */
|
|
19
|
+
export function safeEqual(given, expected) {
|
|
20
|
+
const a = Buffer.from(given, 'utf8');
|
|
21
|
+
const b = Buffer.from(expected, 'utf8');
|
|
22
|
+
if (a.length !== b.length) {
|
|
23
|
+
// Same work either way: compare b with itself.
|
|
24
|
+
timingSafeEqual(b, b);
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
return timingSafeEqual(a, b);
|
|
28
|
+
}
|
|
29
|
+
export class Session {
|
|
30
|
+
now;
|
|
31
|
+
launchCode;
|
|
32
|
+
token;
|
|
33
|
+
serverKey;
|
|
34
|
+
createdAt;
|
|
35
|
+
claimed = false;
|
|
36
|
+
constructor(now = Date.now, random = nodeRandomBytes) {
|
|
37
|
+
this.now = now;
|
|
38
|
+
this.launchCode = random(SECRET_BYTES).toString('base64url');
|
|
39
|
+
this.token = random(SECRET_BYTES).toString('base64url');
|
|
40
|
+
this.serverKey = random(SECRET_BYTES).toString('base64url');
|
|
41
|
+
this.createdAt = now();
|
|
42
|
+
}
|
|
43
|
+
get isClaimed() {
|
|
44
|
+
return this.claimed;
|
|
45
|
+
}
|
|
46
|
+
exchange(code) {
|
|
47
|
+
if (this.claimed)
|
|
48
|
+
return { ok: false, status: 409, reason: 'this UI already has its browser session; restart basalt-deploy-ui for a new one' };
|
|
49
|
+
if (typeof code !== 'string' || !safeEqual(code, this.launchCode))
|
|
50
|
+
return { ok: false, status: 401, reason: 'wrong launch code' };
|
|
51
|
+
if (this.now() - this.createdAt > LAUNCH_TTL_MS)
|
|
52
|
+
return { ok: false, status: 401, reason: 'the launch code expired (120 s); restart basalt-deploy-ui' };
|
|
53
|
+
this.claimed = true;
|
|
54
|
+
return { ok: true, token: this.token, serverKey: this.serverKey };
|
|
55
|
+
}
|
|
56
|
+
/** HMAC-SHA256(serverKey, context + nonce), base64url; undefined for a malformed nonce. */
|
|
57
|
+
prove(nonce) {
|
|
58
|
+
if (typeof nonce !== 'string' || !NONCE.test(nonce))
|
|
59
|
+
return undefined;
|
|
60
|
+
return createHmac('sha256', Buffer.from(this.serverKey, 'base64url')).update(`${PROOF_CONTEXT}${nonce}`).digest('base64url');
|
|
61
|
+
}
|
|
62
|
+
/** `Authorization: Bearer <token>`, exactly. */
|
|
63
|
+
authorizes(header) {
|
|
64
|
+
if (!this.claimed || header === undefined)
|
|
65
|
+
return false;
|
|
66
|
+
const match = /^Bearer ([A-Za-z0-9_-]{1,128})$/.exec(header);
|
|
67
|
+
return match !== null && safeEqual(match[1], this.token);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const realTimers = {
|
|
71
|
+
set: (callback, ms) => setTimeout(callback, ms),
|
|
72
|
+
clear: (handle) => clearTimeout(handle),
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Idle shutdown (RFC 0009 §4.5): fires after `ms` with no authenticated
|
|
76
|
+
* request, no open stream and no remote command in flight. Each of those
|
|
77
|
+
* holds it; releasing the last hold restarts the count.
|
|
78
|
+
*/
|
|
79
|
+
export class IdleTimer {
|
|
80
|
+
ms;
|
|
81
|
+
onIdle;
|
|
82
|
+
timers;
|
|
83
|
+
handle;
|
|
84
|
+
holds = 0;
|
|
85
|
+
stopped = false;
|
|
86
|
+
constructor(ms, onIdle, timers = realTimers) {
|
|
87
|
+
this.ms = ms;
|
|
88
|
+
this.onIdle = onIdle;
|
|
89
|
+
this.timers = timers;
|
|
90
|
+
this.arm();
|
|
91
|
+
}
|
|
92
|
+
touch() {
|
|
93
|
+
this.arm();
|
|
94
|
+
}
|
|
95
|
+
/** An open stream or a remote command in flight: the UI is not idle. */
|
|
96
|
+
hold() {
|
|
97
|
+
this.holds++;
|
|
98
|
+
this.disarm();
|
|
99
|
+
}
|
|
100
|
+
release() {
|
|
101
|
+
this.holds = Math.max(0, this.holds - 1);
|
|
102
|
+
this.arm();
|
|
103
|
+
}
|
|
104
|
+
stop() {
|
|
105
|
+
this.stopped = true;
|
|
106
|
+
this.disarm();
|
|
107
|
+
}
|
|
108
|
+
disarm() {
|
|
109
|
+
if (this.handle !== undefined)
|
|
110
|
+
this.timers.clear(this.handle);
|
|
111
|
+
this.handle = undefined;
|
|
112
|
+
}
|
|
113
|
+
arm() {
|
|
114
|
+
this.disarm();
|
|
115
|
+
if (this.stopped || this.holds > 0)
|
|
116
|
+
return;
|
|
117
|
+
this.handle = this.timers.set(() => {
|
|
118
|
+
this.handle = undefined;
|
|
119
|
+
if (!this.stopped && this.holds === 0)
|
|
120
|
+
this.onIdle();
|
|
121
|
+
}, this.ms);
|
|
122
|
+
}
|
|
123
|
+
}
|
package/dist/ssh.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type Target } from './targets.js';
|
|
2
|
+
/**
|
|
3
|
+
* The system `ssh` (RFC 0009 §6): an argv array, never a shell; options that
|
|
4
|
+
* win over the operator's `~/.ssh/config` for everything that could prompt,
|
|
5
|
+
* forward or run something locally; `--` before the destination; and a
|
|
6
|
+
* remote command built from validated pieces, each single-quoted for the
|
|
7
|
+
* remote POSIX shell.
|
|
8
|
+
*/
|
|
9
|
+
/** Command-line `-o` values win over ssh_config (ssh keeps the first value it obtains). */
|
|
10
|
+
export declare const SSH_OPTIONS: readonly ['BatchMode=yes', 'StrictHostKeyChecking=yes', 'ConnectTimeout=10', 'ServerAliveInterval=15', 'ServerAliveCountMax=3', 'ForwardAgent=no', 'ForwardX11=no', 'ClearAllForwardings=yes', 'PermitLocalCommand=no', 'RequestTTY=no', 'LogLevel=ERROR'];
|
|
11
|
+
/** The app's lockfile-pinned copy of the deploy, the invocation the CLI documents — never npx. */
|
|
12
|
+
export declare const DEPLOY_BIN = "node_modules/@basaltkit/deploy/dist/bin.js";
|
|
13
|
+
export declare const REMOTE_COMMANDS: readonly ['status', 'plan', 'env', 'run', 'rollback', 'attach', 'cancel'];
|
|
14
|
+
export type RemoteCommand = typeof REMOTE_COMMANDS[number];
|
|
15
|
+
/** The commands that change the server (one at a time per target). */
|
|
16
|
+
export declare const MUTATING: ReadonlySet<RemoteCommand>;
|
|
17
|
+
export declare const SHA: RegExp;
|
|
18
|
+
/** What a remote invocation may carry: every flag is built here, never copied from a request. */
|
|
19
|
+
export interface RemoteSpec {
|
|
20
|
+
command: RemoteCommand;
|
|
21
|
+
/** attach, cancel. */
|
|
22
|
+
runId?: string;
|
|
23
|
+
/** env, run: the answers come on stdin. */
|
|
24
|
+
answers?: boolean;
|
|
25
|
+
/** run, rollback. */
|
|
26
|
+
detach?: boolean;
|
|
27
|
+
/** run. */
|
|
28
|
+
unhold?: boolean;
|
|
29
|
+
/** rollback. */
|
|
30
|
+
to?: string;
|
|
31
|
+
/** attach. */
|
|
32
|
+
fromSeq?: number;
|
|
33
|
+
/** attach. */
|
|
34
|
+
follow?: boolean;
|
|
35
|
+
/** cancel: refused by the server when the run was already cancelled once. */
|
|
36
|
+
firstOnly?: boolean;
|
|
37
|
+
}
|
|
38
|
+
export declare class UnsafeValueError extends Error {
|
|
39
|
+
}
|
|
40
|
+
/** One word for a POSIX shell: `'` … `'`, an embedded `'` as `'\''`. */
|
|
41
|
+
export declare function shQuote(word: string): string;
|
|
42
|
+
/**
|
|
43
|
+
* The remote command line: `cd '<dir>' && exec '<node>' '<bin>' '<cmd>' '--json=1' …`.
|
|
44
|
+
* Every value is checked again here — the target grammar is the first wall,
|
|
45
|
+
* this is the second — and then quoted.
|
|
46
|
+
*/
|
|
47
|
+
export declare function remoteCommand(target: Target, spec: RemoteSpec, actor?: string): string;
|
|
48
|
+
/** `%SystemRoot%` when it is an absolute drive path, else `C:\Windows`. */
|
|
49
|
+
export declare function windowsSystemRoot(env: NodeJS.ProcessEnv): string;
|
|
50
|
+
/**
|
|
51
|
+
* The ssh client: `--ssh=<absolute path>`; else `ssh` through PATH on POSIX
|
|
52
|
+
* (execvp never looks in the working directory unless PATH says so). On
|
|
53
|
+
* Windows a bare name is looked up in the working directory BEFORE PATH, so
|
|
54
|
+
* a planted `ssh.exe` in the folder the operator started from would get the
|
|
55
|
+
* answers: there it is always an absolute path — the OpenSSH Client feature
|
|
56
|
+
* (`%SystemRoot%\System32\OpenSSH\ssh.exe`) or the first `ssh.exe` in an
|
|
57
|
+
* absolute PATH entry (never `.`, a relative or an empty one).
|
|
58
|
+
*/
|
|
59
|
+
export declare function sshProgram(platform: NodeJS.Platform, explicit?: string, env?: NodeJS.ProcessEnv, exists?: (path: string) => boolean): string;
|
|
60
|
+
/** The ssh argv, without the program. */
|
|
61
|
+
export declare function sshArgs(target: Target, remote: string): string[];
|
|
62
|
+
export interface SshFailure {
|
|
63
|
+
code: 'ssh-missing' | 'auth' | 'passphrase' | 'host-key' | 'timeout' | 'resolve' | 'refused' | 'network' | 'no-node' | 'no-dir' | 'no-deploy' | 'ssh';
|
|
64
|
+
message: string;
|
|
65
|
+
hint?: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The common ways an ssh invocation fails, from its exit code and stderr, as
|
|
69
|
+
* something the operator can act on. The UI never offers to fix them itself.
|
|
70
|
+
*/
|
|
71
|
+
export declare function classifySshFailure(exitCode: number | null, stderr: string, destination: string): SshFailure | undefined;
|
package/dist/ssh.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
import { RUN_ID } from '@basaltkit/deploy/protocol';
|
|
4
|
+
import { ACTOR, validConfig, validDir, validSsh } from './targets.js';
|
|
5
|
+
/**
|
|
6
|
+
* The system `ssh` (RFC 0009 §6): an argv array, never a shell; options that
|
|
7
|
+
* win over the operator's `~/.ssh/config` for everything that could prompt,
|
|
8
|
+
* forward or run something locally; `--` before the destination; and a
|
|
9
|
+
* remote command built from validated pieces, each single-quoted for the
|
|
10
|
+
* remote POSIX shell.
|
|
11
|
+
*/
|
|
12
|
+
/** Command-line `-o` values win over ssh_config (ssh keeps the first value it obtains). */
|
|
13
|
+
export const SSH_OPTIONS = [
|
|
14
|
+
'BatchMode=yes',
|
|
15
|
+
'StrictHostKeyChecking=yes',
|
|
16
|
+
'ConnectTimeout=10',
|
|
17
|
+
'ServerAliveInterval=15',
|
|
18
|
+
'ServerAliveCountMax=3',
|
|
19
|
+
'ForwardAgent=no',
|
|
20
|
+
'ForwardX11=no',
|
|
21
|
+
'ClearAllForwardings=yes',
|
|
22
|
+
'PermitLocalCommand=no',
|
|
23
|
+
'RequestTTY=no',
|
|
24
|
+
'LogLevel=ERROR',
|
|
25
|
+
];
|
|
26
|
+
/** The app's lockfile-pinned copy of the deploy, the invocation the CLI documents — never npx. */
|
|
27
|
+
export const DEPLOY_BIN = 'node_modules/@basaltkit/deploy/dist/bin.js';
|
|
28
|
+
export const REMOTE_COMMANDS = ['status', 'plan', 'env', 'run', 'rollback', 'attach', 'cancel'];
|
|
29
|
+
/** The commands that change the server (one at a time per target). */
|
|
30
|
+
export const MUTATING = new Set(['env', 'run', 'rollback', 'cancel']);
|
|
31
|
+
export const SHA = /^[0-9a-f]{7,40}$/;
|
|
32
|
+
export class UnsafeValueError extends Error {
|
|
33
|
+
}
|
|
34
|
+
/** One word for a POSIX shell: `'` … `'`, an embedded `'` as `'\''`. */
|
|
35
|
+
export function shQuote(word) {
|
|
36
|
+
return `'${word.replaceAll("'", "'\\''")}'`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The remote command line: `cd '<dir>' && exec '<node>' '<bin>' '<cmd>' '--json=1' …`.
|
|
40
|
+
* Every value is checked again here — the target grammar is the first wall,
|
|
41
|
+
* this is the second — and then quoted.
|
|
42
|
+
*/
|
|
43
|
+
export function remoteCommand(target, spec, actor) {
|
|
44
|
+
const refuse = (what) => { throw new UnsafeValueError(`refused to build the remote command: ${what}`); };
|
|
45
|
+
if (!REMOTE_COMMANDS.includes(spec.command))
|
|
46
|
+
refuse(`unknown command ${JSON.stringify(spec.command)}`);
|
|
47
|
+
if (!validDir(target.dir))
|
|
48
|
+
refuse('the target dir');
|
|
49
|
+
const node = target.node ?? 'node';
|
|
50
|
+
if (target.node !== undefined && !validDir(target.node))
|
|
51
|
+
refuse('the target node');
|
|
52
|
+
const words = [spec.command];
|
|
53
|
+
if (spec.command === 'attach' || spec.command === 'cancel') {
|
|
54
|
+
if (spec.runId === undefined || !RUN_ID.test(spec.runId))
|
|
55
|
+
refuse('the run id');
|
|
56
|
+
words.push(spec.runId);
|
|
57
|
+
}
|
|
58
|
+
words.push('--json=1');
|
|
59
|
+
if (spec.answers) {
|
|
60
|
+
if (spec.command !== 'env' && spec.command !== 'run')
|
|
61
|
+
refuse('answers on a command that asks nothing');
|
|
62
|
+
words.push('--answers=stdin');
|
|
63
|
+
}
|
|
64
|
+
if (spec.detach) {
|
|
65
|
+
if (spec.command !== 'run' && spec.command !== 'rollback')
|
|
66
|
+
refuse('--detach on a command that does not detach');
|
|
67
|
+
words.push('--detach');
|
|
68
|
+
}
|
|
69
|
+
if (spec.unhold) {
|
|
70
|
+
if (spec.command !== 'run')
|
|
71
|
+
refuse('--unhold off run');
|
|
72
|
+
words.push('--unhold');
|
|
73
|
+
}
|
|
74
|
+
if (spec.to !== undefined) {
|
|
75
|
+
if (spec.command !== 'rollback' || !SHA.test(spec.to))
|
|
76
|
+
refuse('the rollback commit');
|
|
77
|
+
words.push(`--to=${spec.to}`);
|
|
78
|
+
}
|
|
79
|
+
if (spec.firstOnly) {
|
|
80
|
+
if (spec.command !== 'cancel')
|
|
81
|
+
refuse('--first-only off cancel');
|
|
82
|
+
words.push('--first-only');
|
|
83
|
+
}
|
|
84
|
+
if (spec.command === 'attach') {
|
|
85
|
+
const from = spec.fromSeq ?? 0;
|
|
86
|
+
if (!Number.isSafeInteger(from) || from < 0)
|
|
87
|
+
refuse('the attach seq');
|
|
88
|
+
if (spec.follow)
|
|
89
|
+
words.push('--follow');
|
|
90
|
+
words.push(`--from-seq=${from}`);
|
|
91
|
+
}
|
|
92
|
+
if (spec.command === 'env' || spec.command === 'run' || spec.command === 'rollback') {
|
|
93
|
+
words.push('--via=ui');
|
|
94
|
+
if (actor !== undefined) {
|
|
95
|
+
if (!ACTOR.test(actor))
|
|
96
|
+
refuse('the actor');
|
|
97
|
+
words.push(`--actor=${actor}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (target.config !== undefined) {
|
|
101
|
+
if (!validConfig(target.config))
|
|
102
|
+
refuse('the target config');
|
|
103
|
+
words.push(`--config=${target.config}`);
|
|
104
|
+
}
|
|
105
|
+
return `cd ${shQuote(target.dir)} && exec ${shQuote(node)} ${shQuote(DEPLOY_BIN)} ${words.map(shQuote).join(' ')}`;
|
|
106
|
+
}
|
|
107
|
+
/** `%SystemRoot%` when it is an absolute drive path, else `C:\Windows`. */
|
|
108
|
+
export function windowsSystemRoot(env) {
|
|
109
|
+
const root = env['SystemRoot'] ?? env['SYSTEMROOT'];
|
|
110
|
+
return root && /^[A-Za-z]:[\\/]/.test(root) ? root : 'C:\\Windows';
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* The ssh client: `--ssh=<absolute path>`; else `ssh` through PATH on POSIX
|
|
114
|
+
* (execvp never looks in the working directory unless PATH says so). On
|
|
115
|
+
* Windows a bare name is looked up in the working directory BEFORE PATH, so
|
|
116
|
+
* a planted `ssh.exe` in the folder the operator started from would get the
|
|
117
|
+
* answers: there it is always an absolute path — the OpenSSH Client feature
|
|
118
|
+
* (`%SystemRoot%\System32\OpenSSH\ssh.exe`) or the first `ssh.exe` in an
|
|
119
|
+
* absolute PATH entry (never `.`, a relative or an empty one).
|
|
120
|
+
*/
|
|
121
|
+
export function sshProgram(platform, explicit, env = {}, exists = existsSync) {
|
|
122
|
+
if (explicit)
|
|
123
|
+
return explicit;
|
|
124
|
+
if (platform !== 'win32')
|
|
125
|
+
return 'ssh';
|
|
126
|
+
const builtIn = win32.join(windowsSystemRoot(env), 'System32', 'OpenSSH', 'ssh.exe');
|
|
127
|
+
const path = env['Path'] ?? env['PATH'] ?? '';
|
|
128
|
+
const fromPath = path.split(';')
|
|
129
|
+
.map((entry) => entry.trim().replace(/^"(.*)"$/, '$1'))
|
|
130
|
+
.filter((entry) => /^[A-Za-z]:[\\/]/.test(entry))
|
|
131
|
+
.map((entry) => win32.join(entry, 'ssh.exe'));
|
|
132
|
+
// Not found anywhere: the built-in path, so the error is "no ssh client" and never a lookup in the working directory.
|
|
133
|
+
return [builtIn, ...fromPath].find((candidate) => exists(candidate)) ?? builtIn;
|
|
134
|
+
}
|
|
135
|
+
/** The ssh argv, without the program. */
|
|
136
|
+
export function sshArgs(target, remote) {
|
|
137
|
+
if (!validSsh(target.ssh))
|
|
138
|
+
throw new UnsafeValueError('refused to run ssh: the destination is not [user@]host or an alias');
|
|
139
|
+
if (target.port !== undefined && (!Number.isInteger(target.port) || target.port < 1 || target.port > 65535))
|
|
140
|
+
throw new UnsafeValueError('refused to run ssh: the port');
|
|
141
|
+
return [
|
|
142
|
+
'-T',
|
|
143
|
+
...SSH_OPTIONS.flatMap((option) => ['-o', option]),
|
|
144
|
+
'-e', 'none',
|
|
145
|
+
...(target.port === undefined ? [] : ['-p', String(target.port)]),
|
|
146
|
+
'--',
|
|
147
|
+
target.ssh,
|
|
148
|
+
remote,
|
|
149
|
+
];
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The common ways an ssh invocation fails, from its exit code and stderr, as
|
|
153
|
+
* something the operator can act on. The UI never offers to fix them itself.
|
|
154
|
+
*/
|
|
155
|
+
export function classifySshFailure(exitCode, stderr, destination) {
|
|
156
|
+
const has = (pattern) => pattern.test(stderr);
|
|
157
|
+
// Line by line with plain substring tests: stderr is the server's text, and
|
|
158
|
+
// wildcard-heavy patterns over it backtrack polynomially (CodeQL js/polynomial-redos).
|
|
159
|
+
const lines = stderr.split('\n');
|
|
160
|
+
const line = (test) => lines.some(test);
|
|
161
|
+
if (has(/passphrase/i))
|
|
162
|
+
return { code: 'passphrase', message: 'your SSH key needs its passphrase, and ssh runs here in batch mode', hint: 'add the key to your agent first: ssh-add' };
|
|
163
|
+
if (has(/Permission denied \(publickey/))
|
|
164
|
+
return { code: 'auth', message: 'the server refused your SSH key', hint: 'is the key loaded in your agent (ssh-add -l)? Can you `ssh ' + destination + '` from a terminal?' };
|
|
165
|
+
if (has(/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No \S+ host key is known/)) {
|
|
166
|
+
return { code: 'host-key', message: 'this host\'s key is not in your known_hosts, or it changed', hint: `connect once from a terminal (ssh ${destination}) and check the fingerprint` };
|
|
167
|
+
}
|
|
168
|
+
if (has(/Could not resolve hostname|Name or service not known|nodename nor servname/i))
|
|
169
|
+
return { code: 'resolve', message: 'the host name does not resolve', hint: 'check the target\'s ssh field, or the Host alias in ~/.ssh/config' };
|
|
170
|
+
if (has(/timed out|Connection timed out|Operation timed out/i))
|
|
171
|
+
return { code: 'timeout', message: 'the connection timed out', hint: 'is the server up, and port 22 (or the target\'s port) reachable from here?' };
|
|
172
|
+
if (has(/Connection refused/i))
|
|
173
|
+
return { code: 'refused', message: 'the connection was refused', hint: 'is sshd listening on that port?' };
|
|
174
|
+
if (has(/No route to host|Network is unreachable/i))
|
|
175
|
+
return { code: 'network', message: 'the network cannot reach the host' };
|
|
176
|
+
if (line((l) => l.includes('Cannot find module') && (l.includes('@basaltkit/deploy') || l.includes('@basaltkit\\deploy'))))
|
|
177
|
+
return { code: 'no-deploy', message: 'the checkout has no installed @basaltkit/deploy', hint: 'install the app\'s dependencies on the server (pnpm install) once from a terminal' };
|
|
178
|
+
if (line((l) => /\bcd\b/.test(l) && (l.includes('No such file or directory') || l.includes("can't cd"))))
|
|
179
|
+
return { code: 'no-dir', message: 'the target\'s dir does not exist on the server', hint: 'check the target\'s dir (the app\'s checkout)' };
|
|
180
|
+
if (exitCode === 127 || line((l) => /node: (command )?not found/.test(l) || (l.includes('exec:') && l.includes('node') && l.includes('not found')))) {
|
|
181
|
+
return { code: 'no-node', message: 'node was not found on the server for a non-interactive shell', hint: 'set the target\'s node to an absolute path (for example the output of `command -v node` in a login shell)' };
|
|
182
|
+
}
|
|
183
|
+
if (exitCode === 255)
|
|
184
|
+
return { code: 'ssh', message: 'ssh failed (exit 255)' };
|
|
185
|
+
return undefined;
|
|
186
|
+
}
|
package/dist/stream.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type DeployEvent, type DoneEvent, type HelloEvent } from '@basaltkit/deploy/protocol';
|
|
2
|
+
/**
|
|
3
|
+
* Reading a `--json` stream from ssh's stdout (RFC 0009 §6.5): lines split on
|
|
4
|
+
* `\n` with a 1 MiB cap; text before `hello` is foreign (a chatty `.bashrc`)
|
|
5
|
+
* and kept as a diagnostic; after `hello` every line must pass `parseEvent`
|
|
6
|
+
* with `seq` exactly one more than the last, and nothing may follow `done`.
|
|
7
|
+
* Anything else ends the stream as corrupt — never skipped, never guessed.
|
|
8
|
+
*/
|
|
9
|
+
export declare const MAX_LINE_BYTES: number;
|
|
10
|
+
export declare const MAX_DIAGNOSTIC_BYTES: number;
|
|
11
|
+
/** ANSI/VT sequences, C0/C1 controls but tab and newline, and bidi controls: text a terminal or a browser could misrender. */
|
|
12
|
+
export declare function sanitizeText(text: string): string;
|
|
13
|
+
export type StreamFailure = {
|
|
14
|
+
kind: 'corrupt';
|
|
15
|
+
message: string;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'protocol-version';
|
|
18
|
+
message: string;
|
|
19
|
+
}
|
|
20
|
+
/** The output stopped mid-line before `done`: a cut connection, not a lying server (a retry may help). */
|
|
21
|
+
| {
|
|
22
|
+
kind: 'truncated';
|
|
23
|
+
message: string;
|
|
24
|
+
};
|
|
25
|
+
export interface ReaderOptions {
|
|
26
|
+
/** `attach`: the outer stream wraps the run's events; both sequences are checked. */
|
|
27
|
+
attach?: {
|
|
28
|
+
fromSeq: number;
|
|
29
|
+
};
|
|
30
|
+
onEvent?: (event: DeployEvent, known: boolean) => void;
|
|
31
|
+
/** A run event unwrapped from `attach` (its `seq` is the resume key). */
|
|
32
|
+
onInner?: (event: DeployEvent, known: boolean) => void;
|
|
33
|
+
onDiagnostic?: (text: string) => void;
|
|
34
|
+
}
|
|
35
|
+
/** Collects text up to a byte budget, counting what it drops. */
|
|
36
|
+
export declare class Diagnostics {
|
|
37
|
+
private readonly budget;
|
|
38
|
+
readonly lines: string[];
|
|
39
|
+
private bytes;
|
|
40
|
+
dropped: number;
|
|
41
|
+
constructor(budget?: number);
|
|
42
|
+
add(text: string): string | undefined;
|
|
43
|
+
}
|
|
44
|
+
export declare class ProtocolReader {
|
|
45
|
+
private readonly options;
|
|
46
|
+
hello?: HelloEvent;
|
|
47
|
+
done?: DoneEvent;
|
|
48
|
+
/** attach: the run's own `done`, unwrapped. */
|
|
49
|
+
innerDone?: DoneEvent;
|
|
50
|
+
/** attach: the run's last seq seen. */
|
|
51
|
+
lastInnerSeq?: number;
|
|
52
|
+
failure?: StreamFailure;
|
|
53
|
+
readonly diagnostics: Diagnostics;
|
|
54
|
+
private pending;
|
|
55
|
+
private lineNo;
|
|
56
|
+
private nextSeq;
|
|
57
|
+
constructor(options?: ReaderOptions);
|
|
58
|
+
/** False once the stream is corrupt: the caller stops reading (and ends the ssh). */
|
|
59
|
+
push(chunk: Buffer): boolean;
|
|
60
|
+
/**
|
|
61
|
+
* The end of stdout: a partial last line is foreign before `hello`, corrupt
|
|
62
|
+
* after `done` (nothing may follow it), and otherwise a cut stream — a TCP
|
|
63
|
+
* or SSH drop can end the output at any byte, and an attach resumes from
|
|
64
|
+
* the last complete run event.
|
|
65
|
+
*/
|
|
66
|
+
end(): void;
|
|
67
|
+
private fail;
|
|
68
|
+
private foreign;
|
|
69
|
+
private line;
|
|
70
|
+
}
|
package/dist/stream.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { parseEvent } from '@basaltkit/deploy/protocol';
|
|
2
|
+
/**
|
|
3
|
+
* Reading a `--json` stream from ssh's stdout (RFC 0009 §6.5): lines split on
|
|
4
|
+
* `\n` with a 1 MiB cap; text before `hello` is foreign (a chatty `.bashrc`)
|
|
5
|
+
* and kept as a diagnostic; after `hello` every line must pass `parseEvent`
|
|
6
|
+
* with `seq` exactly one more than the last, and nothing may follow `done`.
|
|
7
|
+
* Anything else ends the stream as corrupt — never skipped, never guessed.
|
|
8
|
+
*/
|
|
9
|
+
export const MAX_LINE_BYTES = 1024 * 1024;
|
|
10
|
+
export const MAX_DIAGNOSTIC_BYTES = 64 * 1024;
|
|
11
|
+
/** ANSI/VT sequences, C0/C1 controls but tab and newline, and bidi controls: text a terminal or a browser could misrender. */
|
|
12
|
+
export function sanitizeText(text) {
|
|
13
|
+
return text
|
|
14
|
+
.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, '')
|
|
15
|
+
.replace(/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/g, '')
|
|
16
|
+
.replace(/\u001b[@-_]?/g, '')
|
|
17
|
+
.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g, '');
|
|
18
|
+
}
|
|
19
|
+
/** Collects text up to a byte budget, counting what it drops. */
|
|
20
|
+
export class Diagnostics {
|
|
21
|
+
budget;
|
|
22
|
+
lines = [];
|
|
23
|
+
bytes = 0;
|
|
24
|
+
dropped = 0;
|
|
25
|
+
constructor(budget = MAX_DIAGNOSTIC_BYTES) {
|
|
26
|
+
this.budget = budget;
|
|
27
|
+
}
|
|
28
|
+
add(text) {
|
|
29
|
+
const clean = sanitizeText(text);
|
|
30
|
+
const size = Buffer.byteLength(clean);
|
|
31
|
+
if (this.bytes + size > this.budget) {
|
|
32
|
+
this.dropped += size;
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
this.bytes += size;
|
|
36
|
+
this.lines.push(clean);
|
|
37
|
+
return clean;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export class ProtocolReader {
|
|
41
|
+
options;
|
|
42
|
+
hello;
|
|
43
|
+
done;
|
|
44
|
+
/** attach: the run's own `done`, unwrapped. */
|
|
45
|
+
innerDone;
|
|
46
|
+
/** attach: the run's last seq seen. */
|
|
47
|
+
lastInnerSeq;
|
|
48
|
+
failure;
|
|
49
|
+
diagnostics = new Diagnostics();
|
|
50
|
+
pending = Buffer.alloc(0);
|
|
51
|
+
lineNo = 0;
|
|
52
|
+
nextSeq = 0;
|
|
53
|
+
constructor(options = {}) {
|
|
54
|
+
this.options = options;
|
|
55
|
+
}
|
|
56
|
+
/** False once the stream is corrupt: the caller stops reading (and ends the ssh). */
|
|
57
|
+
push(chunk) {
|
|
58
|
+
if (this.failure)
|
|
59
|
+
return false;
|
|
60
|
+
this.pending = this.pending.length === 0 ? chunk : Buffer.concat([this.pending, chunk]);
|
|
61
|
+
let newline;
|
|
62
|
+
while ((newline = this.pending.indexOf(0x0a)) !== -1) {
|
|
63
|
+
if (newline > MAX_LINE_BYTES)
|
|
64
|
+
return this.fail({ kind: 'corrupt', message: `a line longer than ${MAX_LINE_BYTES} bytes at line ${this.lineNo + 1}` });
|
|
65
|
+
const line = this.pending.subarray(0, newline).toString('utf8');
|
|
66
|
+
this.pending = this.pending.subarray(newline + 1);
|
|
67
|
+
this.lineNo++;
|
|
68
|
+
if (!this.line(line))
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
if (this.pending.length > MAX_LINE_BYTES)
|
|
72
|
+
return this.fail({ kind: 'corrupt', message: `a line longer than ${MAX_LINE_BYTES} bytes at line ${this.lineNo + 1}` });
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The end of stdout: a partial last line is foreign before `hello`, corrupt
|
|
77
|
+
* after `done` (nothing may follow it), and otherwise a cut stream — a TCP
|
|
78
|
+
* or SSH drop can end the output at any byte, and an attach resumes from
|
|
79
|
+
* the last complete run event.
|
|
80
|
+
*/
|
|
81
|
+
end() {
|
|
82
|
+
if (this.failure || this.pending.length === 0)
|
|
83
|
+
return;
|
|
84
|
+
const rest = this.pending.toString('utf8');
|
|
85
|
+
this.pending = Buffer.alloc(0);
|
|
86
|
+
if (!this.hello)
|
|
87
|
+
this.foreign(rest);
|
|
88
|
+
else if (this.done)
|
|
89
|
+
this.fail({ kind: 'corrupt', message: `output after done at line ${this.lineNo + 1}` });
|
|
90
|
+
else
|
|
91
|
+
this.fail({ kind: 'truncated', message: `the output was cut mid-line at line ${this.lineNo + 1}` });
|
|
92
|
+
}
|
|
93
|
+
fail(failure) {
|
|
94
|
+
this.failure = failure;
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
foreign(line) {
|
|
98
|
+
const text = this.diagnostics.add(line);
|
|
99
|
+
if (text !== undefined)
|
|
100
|
+
this.options.onDiagnostic?.(text);
|
|
101
|
+
}
|
|
102
|
+
line(line) {
|
|
103
|
+
if (!this.hello) {
|
|
104
|
+
const parsed = parseEvent(line);
|
|
105
|
+
if (parsed.ok && parsed.value.type === 'hello' && parsed.value.seq === 0) {
|
|
106
|
+
this.hello = parsed.value;
|
|
107
|
+
this.nextSeq = 1;
|
|
108
|
+
this.options.onEvent?.(parsed.value, true);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
if (!parsed.ok && looksLikeHello(line)) {
|
|
112
|
+
return this.fail({ kind: 'protocol-version', message: 'this server\'s @basaltkit/deploy does not speak protocol 1' });
|
|
113
|
+
}
|
|
114
|
+
// A login script's echo, a MOTD: data, never parsed further.
|
|
115
|
+
this.foreign(line);
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
if (this.done)
|
|
119
|
+
return this.fail({ kind: 'corrupt', message: `output after done at line ${this.lineNo}` });
|
|
120
|
+
const parsed = parseEvent(line);
|
|
121
|
+
if (!parsed.ok)
|
|
122
|
+
return this.fail({ kind: 'corrupt', message: `the server's output is corrupt at line ${this.lineNo}: ${parsed.error}` });
|
|
123
|
+
const event = parsed.value;
|
|
124
|
+
if (event.seq !== this.nextSeq)
|
|
125
|
+
return this.fail({ kind: 'corrupt', message: `the server's output is corrupt at line ${this.lineNo}: seq ${event.seq}, expected ${this.nextSeq}` });
|
|
126
|
+
this.nextSeq++;
|
|
127
|
+
if (event.type === 'done')
|
|
128
|
+
this.done = event;
|
|
129
|
+
if (this.options.attach && event.type === 'event') {
|
|
130
|
+
const inner = event.event;
|
|
131
|
+
const expected = this.lastInnerSeq === undefined ? this.options.attach.fromSeq : this.lastInnerSeq + 1;
|
|
132
|
+
if (this.innerDone)
|
|
133
|
+
return this.fail({ kind: 'corrupt', message: `a run event after the run's done at line ${this.lineNo}` });
|
|
134
|
+
if (inner.seq !== expected)
|
|
135
|
+
return this.fail({ kind: 'corrupt', message: `the run's events are not continuous at line ${this.lineNo}: seq ${inner.seq}, expected ${expected}` });
|
|
136
|
+
this.lastInnerSeq = inner.seq;
|
|
137
|
+
if (inner.type === 'done')
|
|
138
|
+
this.innerDone = inner;
|
|
139
|
+
this.options.onInner?.(inner, parsed.known !== false);
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
this.options.onEvent?.(event, parsed.known !== false);
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** A `hello` of a protocol this UI does not speak (another `v` or `protocol`). */
|
|
147
|
+
function looksLikeHello(line) {
|
|
148
|
+
try {
|
|
149
|
+
const value = JSON.parse(line);
|
|
150
|
+
return typeof value === 'object' && value !== null && value['type'] === 'hello' && value['tool'] === '@basaltkit/deploy';
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
}
|