@celljs/ta-exec 4.6.0 → 4.7.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/README.en.md +43 -0
- package/README.md +5 -1
- package/esm/node/exec-client.d.ts +28 -11
- package/esm/node/exec-client.js +89 -33
- package/esm/node/exec-client.js.map +1 -1
- package/esm/node/exec-peer.d.ts +40 -0
- package/esm/node/exec-peer.js +167 -0
- package/esm/node/exec-peer.js.map +1 -0
- package/esm/node/exec-protocol.d.ts +14 -0
- package/esm/node/exec-remote-source.d.ts +5 -0
- package/esm/node/exec-remote-source.js +9 -0
- package/esm/node/exec-remote-source.js.map +1 -0
- package/esm/node/exec-rpc.d.ts +21 -3
- package/esm/node/exec-rpc.js +14 -3
- package/esm/node/exec-rpc.js.map +1 -1
- package/esm/node/exec-server.d.ts +2 -26
- package/esm/node/exec-server.js +3 -132
- package/esm/node/exec-server.js.map +1 -1
- package/esm/node/exec-stdio.d.ts +27 -0
- package/esm/node/exec-stdio.js +60 -0
- package/esm/node/exec-stdio.js.map +1 -0
- package/esm/node/index.d.ts +8 -0
- package/esm/node/index.js +8 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/local-exec-environment.js +8 -8
- package/esm/node/local-exec-environment.js.map +1 -1
- package/esm/node/remote-exec-environment.d.ts +2 -1
- package/esm/node/remote-exec-environment.js +39 -0
- package/esm/node/remote-exec-environment.js.map +1 -1
- package/esm/node/ssh/node-dist.d.ts +20 -0
- package/esm/node/ssh/node-dist.js +77 -0
- package/esm/node/ssh/node-dist.js.map +1 -0
- package/esm/node/ssh/ssh-askpass.d.ts +24 -0
- package/esm/node/ssh/ssh-askpass.js +112 -0
- package/esm/node/ssh/ssh-askpass.js.map +1 -0
- package/esm/node/ssh/ssh-config.d.ts +20 -0
- package/esm/node/ssh/ssh-config.js +127 -0
- package/esm/node/ssh/ssh-config.js.map +1 -0
- package/esm/node/ssh/ssh-host.d.ts +73 -0
- package/esm/node/ssh/ssh-host.js +258 -0
- package/esm/node/ssh/ssh-host.js.map +1 -0
- package/esm/node/ssh/ssh-util.d.ts +45 -0
- package/esm/node/ssh/ssh-util.js +110 -0
- package/esm/node/ssh/ssh-util.js.map +1 -0
- package/lib/node/exec-client.d.ts +28 -11
- package/lib/node/exec-client.d.ts.map +1 -1
- package/lib/node/exec-client.js +89 -33
- package/lib/node/exec-client.js.map +1 -1
- package/lib/node/exec-peer.d.ts +41 -0
- package/lib/node/exec-peer.d.ts.map +1 -0
- package/lib/node/exec-peer.js +171 -0
- package/lib/node/exec-peer.js.map +1 -0
- package/lib/node/exec-protocol.d.ts +14 -0
- package/lib/node/exec-protocol.d.ts.map +1 -1
- package/lib/node/exec-remote-source.d.ts +6 -0
- package/lib/node/exec-remote-source.d.ts.map +1 -0
- package/lib/node/exec-remote-source.js +10 -0
- package/lib/node/exec-remote-source.js.map +1 -0
- package/lib/node/exec-rpc.d.ts +21 -3
- package/lib/node/exec-rpc.d.ts.map +1 -1
- package/lib/node/exec-rpc.js +14 -3
- package/lib/node/exec-rpc.js.map +1 -1
- package/lib/node/exec-server.d.ts +2 -26
- package/lib/node/exec-server.d.ts.map +1 -1
- package/lib/node/exec-server.js +4 -134
- package/lib/node/exec-server.js.map +1 -1
- package/lib/node/exec-server.spec.js +1 -1
- package/lib/node/exec-server.spec.js.map +1 -1
- package/lib/node/exec-stdio.d.ts +28 -0
- package/lib/node/exec-stdio.d.ts.map +1 -0
- package/lib/node/exec-stdio.js +64 -0
- package/lib/node/exec-stdio.js.map +1 -0
- package/lib/node/exec-stdio.spec.d.ts +2 -0
- package/lib/node/exec-stdio.spec.d.ts.map +1 -0
- package/lib/node/exec-stdio.spec.js +105 -0
- package/lib/node/exec-stdio.spec.js.map +1 -0
- package/lib/node/index.d.ts +8 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +8 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/local-exec-environment.d.ts.map +1 -1
- package/lib/node/local-exec-environment.js +8 -8
- package/lib/node/local-exec-environment.js.map +1 -1
- package/lib/node/remote-exec-environment.d.ts +2 -1
- package/lib/node/remote-exec-environment.d.ts.map +1 -1
- package/lib/node/remote-exec-environment.js +39 -0
- package/lib/node/remote-exec-environment.js.map +1 -1
- package/lib/node/ssh/node-dist.d.ts +21 -0
- package/lib/node/ssh/node-dist.d.ts.map +1 -0
- package/lib/node/ssh/node-dist.js +80 -0
- package/lib/node/ssh/node-dist.js.map +1 -0
- package/lib/node/ssh/ssh-askpass.d.ts +25 -0
- package/lib/node/ssh/ssh-askpass.d.ts.map +1 -0
- package/lib/node/ssh/ssh-askpass.js +114 -0
- package/lib/node/ssh/ssh-askpass.js.map +1 -0
- package/lib/node/ssh/ssh-config.d.ts +21 -0
- package/lib/node/ssh/ssh-config.d.ts.map +1 -0
- package/lib/node/ssh/ssh-config.js +130 -0
- package/lib/node/ssh/ssh-config.js.map +1 -0
- package/lib/node/ssh/ssh-host.d.ts +74 -0
- package/lib/node/ssh/ssh-host.d.ts.map +1 -0
- package/lib/node/ssh/ssh-host.js +262 -0
- package/lib/node/ssh/ssh-host.js.map +1 -0
- package/lib/node/ssh/ssh-host.spec.d.ts +2 -0
- package/lib/node/ssh/ssh-host.spec.d.ts.map +1 -0
- package/lib/node/ssh/ssh-host.spec.js +182 -0
- package/lib/node/ssh/ssh-host.spec.js.map +1 -0
- package/lib/node/ssh/ssh-util.d.ts +46 -0
- package/lib/node/ssh/ssh-util.d.ts.map +1 -0
- package/lib/node/ssh/ssh-util.js +113 -0
- package/lib/node/ssh/ssh-util.js.map +1 -0
- package/lib/node/ssh/ssh-util.spec.d.ts +2 -0
- package/lib/node/ssh/ssh-util.spec.d.ts.map +1 -0
- package/lib/node/ssh/ssh-util.spec.js +87 -0
- package/lib/node/ssh/ssh-util.spec.js.map +1 -0
- package/package.json +3 -3
- package/src/node/exec-client.ts +108 -39
- package/src/node/exec-peer.ts +186 -0
- package/src/node/exec-protocol.ts +15 -0
- package/src/node/exec-remote-source.ts +7 -0
- package/src/node/exec-rpc.ts +23 -3
- package/src/node/exec-server.spec.ts +1 -1
- package/src/node/exec-server.ts +4 -140
- package/src/node/exec-stdio.spec.ts +107 -0
- package/src/node/exec-stdio.ts +75 -0
- package/src/node/index.ts +8 -0
- package/src/node/local-exec-environment.ts +7 -6
- package/src/node/remote-exec-environment.ts +39 -1
- package/src/node/ssh/node-dist.ts +83 -0
- package/src/node/ssh/ssh-askpass.ts +117 -0
- package/src/node/ssh/ssh-config.ts +128 -0
- package/src/node/ssh/ssh-host.spec.ts +189 -0
- package/src/node/ssh/ssh-host.ts +300 -0
- package/src/node/ssh/ssh-util.spec.ts +97 -0
- package/src/node/ssh/ssh-util.ts +127 -0
|
@@ -98,14 +98,15 @@ export class LocalExecEnvironment implements ExecEnvironment {
|
|
|
98
98
|
if (child.pid === undefined) {
|
|
99
99
|
return;
|
|
100
100
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
child.kill();
|
|
104
|
-
} else {
|
|
101
|
+
if (process.platform !== 'win32') {
|
|
102
|
+
try {
|
|
105
103
|
process.kill(-child.pid, 'SIGKILL');
|
|
104
|
+
return;
|
|
105
|
+
} catch {
|
|
106
|
+
// No such group (it ended, or the runtime did not give the shell its own group): the shell
|
|
107
|
+
// itself, below, which a single command replaces.
|
|
106
108
|
}
|
|
107
|
-
} catch {
|
|
108
|
-
// It already ended.
|
|
109
109
|
}
|
|
110
|
+
child.kill('SIGKILL');
|
|
110
111
|
}
|
|
111
112
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ExecClient } from './exec-client';
|
|
2
|
-
import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, FileStat, SpawnOptions } from './exec-protocol';
|
|
2
|
+
import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, ExecSocket, FileStat, SpawnOptions } from './exec-protocol';
|
|
3
3
|
import { ExecRpc } from './exec-rpc';
|
|
4
4
|
|
|
5
5
|
type Listener<T extends unknown[]> = (...args: T) => void;
|
|
@@ -101,6 +101,44 @@ export class RemoteExecEnvironment implements ExecEnvironment {
|
|
|
101
101
|
return this.client.call(ExecRpc.Method.REMOVE, { ...this.path(path), recursive: options.recursive });
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
async connect(port: number, host?: string): Promise<ExecSocket> {
|
|
105
|
+
const id = this.client.processId();
|
|
106
|
+
const data = new Set<Listener<[Uint8Array]>>();
|
|
107
|
+
const closed = new Set<Listener<[]>>();
|
|
108
|
+
let ended = false;
|
|
109
|
+
const end = () => {
|
|
110
|
+
if (!ended) {
|
|
111
|
+
ended = true;
|
|
112
|
+
stop();
|
|
113
|
+
for (const listener of closed) {
|
|
114
|
+
listener();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const stop = this.client.listen(id, (method, params) => {
|
|
119
|
+
if (method === ExecRpc.Notification.NET_DATA && params.data) {
|
|
120
|
+
const bytes = ExecRpc.fromBase64(params.data);
|
|
121
|
+
for (const listener of data) {
|
|
122
|
+
listener(bytes);
|
|
123
|
+
}
|
|
124
|
+
} else if (method === ExecRpc.Notification.NET_CLOSED || method === ExecRpc.Notification.EXIT) {
|
|
125
|
+
end();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
try {
|
|
129
|
+
await this.client.call(ExecRpc.Method.NET_CONNECT, { id, port, host } satisfies ExecRpc.ConnectParams);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
stop();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
write: bytes => void this.client.call(ExecRpc.Method.NET_WRITE, { id, data: ExecRpc.toBase64(bytes) }).catch(end),
|
|
136
|
+
end: () => void this.client.call(ExecRpc.Method.NET_CLOSE, { id }).catch(end),
|
|
137
|
+
onData: listener => data.add(listener),
|
|
138
|
+
onClose: listener => (ended ? listener() : closed.add(listener)),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
104
142
|
protected path(path: string): ExecRpc.PathParams {
|
|
105
143
|
return { root: this.cwd, path };
|
|
106
144
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { createReadStream, createWriteStream, existsSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/** A build of Node.js, downloaded and checked. */
|
|
6
|
+
export interface NodeTarball {
|
|
7
|
+
version: string;
|
|
8
|
+
file: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Node.js for hosts that have none, from nodejs.org (or a mirror with the same layout): the latest 22,
|
|
13
|
+
* checked against the SHA-256 sums published beside it, kept on this machine for the next host.
|
|
14
|
+
*/
|
|
15
|
+
export namespace NodeDist {
|
|
16
|
+
export const DEFAULT_MIRROR = 'https://nodejs.org/dist';
|
|
17
|
+
export const LINE = 'latest-v22.x';
|
|
18
|
+
|
|
19
|
+
/** The file name and sum of `platform` (`linux-x64`...) in a SHASUMS256.txt. */
|
|
20
|
+
export function find(sums: string, platform: string): { name: string; sha256: string; version: string } | undefined {
|
|
21
|
+
for (const line of sums.split('\n')) {
|
|
22
|
+
const match = /^([0-9a-f]{64})\s+(node-(v[\d.]+)-([\w-]+)\.tar\.gz)$/.exec(line.trim());
|
|
23
|
+
if (match && match[4] === platform) {
|
|
24
|
+
return { sha256: match[1], name: match[2], version: match[3] };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function download(platform: string, dir: string, mirror = DEFAULT_MIRROR, onVersion?: (version: string) => void): Promise<NodeTarball> {
|
|
31
|
+
const base = `${mirror.replace(/\/+$/, '')}/${LINE}`;
|
|
32
|
+
const sums = await get(`${base}/SHASUMS256.txt`);
|
|
33
|
+
const found = find(await sums.text(), platform);
|
|
34
|
+
if (!found) {
|
|
35
|
+
throw new Error(`Node.js has no build for ${platform} at ${base}.`);
|
|
36
|
+
}
|
|
37
|
+
onVersion?.(found.version);
|
|
38
|
+
mkdirSync(dir, { recursive: true });
|
|
39
|
+
const file = join(dir, found.name);
|
|
40
|
+
if (existsSync(file) && (await sha256(file)) === found.sha256) {
|
|
41
|
+
return { version: found.version, file };
|
|
42
|
+
}
|
|
43
|
+
const response = await get(`${base}/${found.name}`);
|
|
44
|
+
const partial = `${file}.${process.pid}.part`;
|
|
45
|
+
const hash = createHash('sha256');
|
|
46
|
+
const out = createWriteStream(partial);
|
|
47
|
+
try {
|
|
48
|
+
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
|
|
49
|
+
hash.update(chunk);
|
|
50
|
+
if (!out.write(chunk)) {
|
|
51
|
+
await new Promise(resolve => out.once('drain', resolve));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
await new Promise<void>((resolve, reject) => out.end((error?: Error | null) => (error ? reject(error) : resolve())));
|
|
55
|
+
if (hash.digest('hex') !== found.sha256) {
|
|
56
|
+
throw new Error(`The download of ${found.name} does not match its SHA-256 sum.`);
|
|
57
|
+
}
|
|
58
|
+
renameSync(partial, file);
|
|
59
|
+
} finally {
|
|
60
|
+
out.destroy();
|
|
61
|
+
rmSync(partial, { force: true });
|
|
62
|
+
}
|
|
63
|
+
return { version: found.version, file };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function get(url: string): Promise<Response> {
|
|
67
|
+
const response = await fetch(url);
|
|
68
|
+
if (!response.ok || !response.body) {
|
|
69
|
+
throw new Error(`Cannot download ${url}: HTTP ${response.status}.`);
|
|
70
|
+
}
|
|
71
|
+
return response;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function sha256(file: string): Promise<string> {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const hash = createHash('sha256');
|
|
77
|
+
createReadStream(file)
|
|
78
|
+
.on('data', data => hash.update(data))
|
|
79
|
+
.on('end', () => resolve(hash.digest('hex')))
|
|
80
|
+
.on('error', reject);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { createServer, type Server } from 'node:net';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { type SshQuestion, SshUtil } from './ssh-util';
|
|
6
|
+
|
|
7
|
+
/** Run by ssh for each question: asks ta serve on its socket and prints the answer. */
|
|
8
|
+
const ASKPASS_JS = `const net = require('net');
|
|
9
|
+
const e = process.env;
|
|
10
|
+
const s = net.connect(e.TA_ASKPASS_SOCKET, () => s.write(JSON.stringify({ token: e.TA_ASKPASS_TOKEN, prompt: process.argv[2] || '' }) + '\\n'));
|
|
11
|
+
let out = '';
|
|
12
|
+
s.on('data', d => (out += d));
|
|
13
|
+
s.on('close', () => {
|
|
14
|
+
let r = {};
|
|
15
|
+
try { r = JSON.parse(out); } catch {}
|
|
16
|
+
if (typeof r.answer !== 'string') process.exit(1);
|
|
17
|
+
process.stdout.write(r.answer + '\\n');
|
|
18
|
+
});
|
|
19
|
+
s.on('error', () => process.exit(1));
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Lets ssh ask the user through Ta (SSH_ASKPASS): a password, a passphrase, whether to trust a new host
|
|
24
|
+
* key. ssh runs a small script, which asks on a socket of this process only those that know its token;
|
|
25
|
+
* the answer goes to ssh only.
|
|
26
|
+
*/
|
|
27
|
+
export class SshAskpass {
|
|
28
|
+
protected server?: Promise<Server>;
|
|
29
|
+
protected readonly token = randomBytes(24).toString('hex');
|
|
30
|
+
protected readonly socket: string;
|
|
31
|
+
|
|
32
|
+
constructor(
|
|
33
|
+
protected readonly dir: string,
|
|
34
|
+
protected readonly ask: (question: SshQuestion) => Promise<string | undefined>,
|
|
35
|
+
) {
|
|
36
|
+
const name = `askpass-${process.pid}-${randomBytes(4).toString('hex')}`;
|
|
37
|
+
this.socket = process.platform === 'win32' ? `\\\\.\\pipe\\ta-${name}` : join(dir, `${name}.sock`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The environment of an ssh that asks through Ta. */
|
|
41
|
+
async env(): Promise<NodeJS.ProcessEnv> {
|
|
42
|
+
await this.listen();
|
|
43
|
+
const script = this.writeScripts();
|
|
44
|
+
return {
|
|
45
|
+
...process.env,
|
|
46
|
+
SSH_ASKPASS: script,
|
|
47
|
+
SSH_ASKPASS_REQUIRE: 'force',
|
|
48
|
+
DISPLAY: process.env.DISPLAY || ':0',
|
|
49
|
+
TA_ASKPASS_NODE: process.execPath,
|
|
50
|
+
TA_ASKPASS_JS: join(this.dir, 'askpass.js'),
|
|
51
|
+
TA_ASKPASS_SOCKET: this.socket,
|
|
52
|
+
TA_ASKPASS_TOKEN: this.token,
|
|
53
|
+
// In Ta's desktop app, the Node.js of ta serve is Electron's.
|
|
54
|
+
...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async close(): Promise<void> {
|
|
59
|
+
const server = await this.server?.catch(() => undefined);
|
|
60
|
+
this.server = undefined;
|
|
61
|
+
await new Promise<void>(resolve => (server ? server.close(() => resolve()) : resolve()));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
protected listen(): Promise<Server> {
|
|
65
|
+
this.server ??= new Promise((resolve, reject) => {
|
|
66
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
67
|
+
if (process.platform !== 'win32') {
|
|
68
|
+
rmSync(this.socket, { force: true });
|
|
69
|
+
}
|
|
70
|
+
// One line asks, the answer ends the connection.
|
|
71
|
+
const server = createServer(connection => {
|
|
72
|
+
let text = '';
|
|
73
|
+
connection.on('data', data => {
|
|
74
|
+
text += data;
|
|
75
|
+
if (text.includes('\n')) {
|
|
76
|
+
connection.removeAllListeners('data');
|
|
77
|
+
void this.answer(text).then(reply => connection.end(JSON.stringify(reply)));
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
connection.on('error', () => undefined);
|
|
81
|
+
});
|
|
82
|
+
server.once('error', reject);
|
|
83
|
+
server.listen(this.socket, () => {
|
|
84
|
+
server.unref();
|
|
85
|
+
resolve(server);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
return this.server;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
protected async answer(text: string): Promise<{ answer?: string }> {
|
|
92
|
+
try {
|
|
93
|
+
const { token, prompt } = JSON.parse(text);
|
|
94
|
+
if (token !== this.token || typeof prompt !== 'string') {
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
const answer = await this.ask(SshUtil.question(prompt));
|
|
98
|
+
return answer === undefined ? {} : { answer };
|
|
99
|
+
} catch {
|
|
100
|
+
return {};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Written each time: the directory may have been cleaned. Only the user may read or run them. */
|
|
105
|
+
protected writeScripts(): string {
|
|
106
|
+
writeFileSync(join(this.dir, 'askpass.js'), ASKPASS_JS, { mode: 0o600 });
|
|
107
|
+
if (process.platform === 'win32') {
|
|
108
|
+
const script = join(this.dir, 'askpass.cmd');
|
|
109
|
+
writeFileSync(script, '@"%TA_ASKPASS_NODE%" "%TA_ASKPASS_JS%" %*\r\n');
|
|
110
|
+
return script;
|
|
111
|
+
}
|
|
112
|
+
const script = join(this.dir, 'askpass.sh');
|
|
113
|
+
writeFileSync(script, '#!/bin/sh\nexec "$TA_ASKPASS_NODE" "$TA_ASKPASS_JS" "$@"\n', { mode: 0o700 });
|
|
114
|
+
chmodSync(script, 0o700);
|
|
115
|
+
return script;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/** A line of a configuration that matters here: a `Host` with its names, an `Include`, or a `Match`. */
|
|
6
|
+
export type SshConfigEntry = { host: string[] } | { include: string } | { match: true };
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The hosts of an OpenSSH configuration that a person picks from: `Host` names without wildcards, as
|
|
10
|
+
* ssh reads them. An `Include` inside a `Host` block counts only for the hosts that block matches (ssh
|
|
11
|
+
* reads the file only for them), and one inside a `Match` block not at all.
|
|
12
|
+
*/
|
|
13
|
+
export namespace SshConfig {
|
|
14
|
+
const MAX_FILES = 16;
|
|
15
|
+
|
|
16
|
+
/** The hosts of ~/.ssh/config and the files it includes, in order, each once. */
|
|
17
|
+
export function hosts(file = join(homedir(), '.ssh', 'config')): string[] {
|
|
18
|
+
const found = new Set<string>();
|
|
19
|
+
read(file, ['*'], found, new Set());
|
|
20
|
+
return [...found];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function parse(text: string): SshConfigEntry[] {
|
|
24
|
+
const entries: SshConfigEntry[] = [];
|
|
25
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
26
|
+
const line = raw.replace(/#.*/, '').trim();
|
|
27
|
+
const found = /^(\w+)(?:\s*=\s*|\s+)(.+)$/.exec(line);
|
|
28
|
+
if (!found) {
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const values = words(found[2]);
|
|
32
|
+
const keyword = found[1].toLowerCase();
|
|
33
|
+
if (keyword === 'host') {
|
|
34
|
+
entries.push({ host: values });
|
|
35
|
+
} else if (keyword === 'match') {
|
|
36
|
+
entries.push({ match: true });
|
|
37
|
+
} else if (keyword === 'include') {
|
|
38
|
+
entries.push(...values.map(include => ({ include })));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return entries;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Whether ssh applies a `Host` line of these patterns to `host`: one matches, and no `!` one does. */
|
|
45
|
+
export function matches(patterns: string[], host: string): boolean {
|
|
46
|
+
let matched = false;
|
|
47
|
+
for (const pattern of patterns) {
|
|
48
|
+
const negated = pattern.startsWith('!');
|
|
49
|
+
if (glob(negated ? pattern.slice(1) : pattern).test(host)) {
|
|
50
|
+
if (negated) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
matched = true;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return matched;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* `scope`: the patterns of the `Host` block the file is included from (`['*']` at the top). A host of
|
|
61
|
+
* the file counts when that block applies to it.
|
|
62
|
+
*/
|
|
63
|
+
function read(file: string, scope: string[], found: Set<string>, seen: Set<string>): void {
|
|
64
|
+
if (seen.has(file) || seen.size >= MAX_FILES) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
seen.add(file);
|
|
68
|
+
let text: string;
|
|
69
|
+
try {
|
|
70
|
+
text = readFileSync(file, 'utf8');
|
|
71
|
+
} catch {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
// Before the first Host or Match, a file applies as its scope does.
|
|
75
|
+
let block: string[] | undefined = scope;
|
|
76
|
+
for (const entry of parse(text)) {
|
|
77
|
+
if ('host' in entry) {
|
|
78
|
+
block = entry.host;
|
|
79
|
+
for (const host of entry.host) {
|
|
80
|
+
if (!/[*?!]/.test(host) && matches(scope, host)) {
|
|
81
|
+
found.add(host);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
} else if ('match' in entry) {
|
|
85
|
+
block = undefined;
|
|
86
|
+
} else if (block) {
|
|
87
|
+
for (const path of expand(entry.include, dirname(file))) {
|
|
88
|
+
read(path, block === scope ? scope : narrow(scope, block), found, seen);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The patterns of a block inside another: those of the inner one, when the outer one is everything. */
|
|
95
|
+
function narrow(outer: string[], inner: string[]): string[] {
|
|
96
|
+
return outer.length === 1 && outer[0] === '*' ? inner : inner.filter(pattern => !/[*?!]/.test(pattern) && matches(outer, pattern));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function glob(pattern: string): RegExp {
|
|
100
|
+
const escaped = pattern
|
|
101
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
102
|
+
.replace(/\*/g, '.*')
|
|
103
|
+
.replace(/\?/g, '.');
|
|
104
|
+
return new RegExp(`^${escaped}$`, 'i');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A path of `Include`: `~` is home, relative ones are beside the file, `*` in its last part matches names. */
|
|
108
|
+
function expand(pattern: string, dir: string): string[] {
|
|
109
|
+
const path = pattern.startsWith('~/') ? join(homedir(), pattern.slice(2)) : isAbsolute(pattern) ? pattern : join(dir, pattern);
|
|
110
|
+
const name = basename(path);
|
|
111
|
+
if (!/[*?]/.test(name)) {
|
|
112
|
+
return [path];
|
|
113
|
+
}
|
|
114
|
+
const match = glob(name);
|
|
115
|
+
try {
|
|
116
|
+
return readdirSync(dirname(path))
|
|
117
|
+
.filter(entry => match.test(entry))
|
|
118
|
+
.sort()
|
|
119
|
+
.map(entry => join(dirname(path), entry));
|
|
120
|
+
} catch {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function words(value: string): string[] {
|
|
126
|
+
return [...value.matchAll(/"([^"]*)"|(\S+)/g)].map(match => match[1] ?? match[2]).filter(Boolean);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
|
|
2
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { createServer, type Server } from 'node:http';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { RemoteExecEnvironment } from '../remote-exec-environment';
|
|
9
|
+
import { SshHost, type SshHostOptions, type SshStep } from './ssh-host';
|
|
10
|
+
import { SshUtil } from './ssh-util';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* An ssh that runs the command on this machine, as ssh would on the host: in the home directory of the
|
|
14
|
+
* test, with a PATH of the test. Its master is a process that waits; it asks for a password through
|
|
15
|
+
* SSH_ASKPASS when FAKE_SSH_PASSWORD is set.
|
|
16
|
+
*/
|
|
17
|
+
const FAKE_SSH = `#!/bin/sh
|
|
18
|
+
echo "$*" >> "$FAKE_SSH_DIR/log"
|
|
19
|
+
master=0; control=
|
|
20
|
+
while [ $# -gt 0 ]; do
|
|
21
|
+
case "$1" in
|
|
22
|
+
--) shift; break;;
|
|
23
|
+
-N) master=1; shift;;
|
|
24
|
+
-T) shift;;
|
|
25
|
+
-O) control="$2"; shift 2;;
|
|
26
|
+
-o|-F|-p|-i|-l) shift 2;;
|
|
27
|
+
*) shift;;
|
|
28
|
+
esac
|
|
29
|
+
done
|
|
30
|
+
shift
|
|
31
|
+
if [ -n "$control" ]; then [ -f "$FAKE_SSH_DIR/master" ]; exit $?; fi
|
|
32
|
+
if [ "$master" = 1 ]; then
|
|
33
|
+
if [ -n "$FAKE_SSH_PASSWORD" ]; then
|
|
34
|
+
answer=$("$SSH_ASKPASS" "fake's password: ") || { echo "Permission denied (cancelled)." >&2; exit 255; }
|
|
35
|
+
[ "$answer" = "$FAKE_SSH_PASSWORD" ] || { echo "Permission denied (password)." >&2; exit 255; }
|
|
36
|
+
fi
|
|
37
|
+
touch "$FAKE_SSH_DIR/master"
|
|
38
|
+
trap 'rm -f "$FAKE_SSH_DIR/master"; exit 0' TERM INT
|
|
39
|
+
while :; do sleep 1 & wait $!; done
|
|
40
|
+
fi
|
|
41
|
+
[ -f "$FAKE_SSH_DIR/master" ] || { echo "no master" >&2; exit 255; }
|
|
42
|
+
cmd=$(printf '%s' "$*" | sed -e 's#/opt/homebrew/bin/node#/none#g' -e 's#/usr/local/bin/node#/none#g')
|
|
43
|
+
HOME="$FAKE_SSH_HOME" PATH="$FAKE_SSH_PATH" SHELL="$FAKE_SSH_DIR/login-sh" exec /bin/sh -c "$cmd"
|
|
44
|
+
`;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The login shell of the host, with the PATH of the test: a real one reads /etc/profile, whose PATH on
|
|
48
|
+
* macOS has /usr/local/bin, where the runners of CI have a Node.js.
|
|
49
|
+
*/
|
|
50
|
+
const LOGIN_SH = `#!/bin/sh
|
|
51
|
+
[ "$1" = -lc ] && shift && set -- -c "$@"
|
|
52
|
+
exec /bin/sh "$@"
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
const which = (name: string) =>
|
|
56
|
+
execFileSync('/bin/sh', ['-c', `command -v ${name} || true`])
|
|
57
|
+
.toString()
|
|
58
|
+
.trim();
|
|
59
|
+
const node = which('node');
|
|
60
|
+
|
|
61
|
+
describe.skipIf(process.platform === 'win32' || !node)('SshHost', () => {
|
|
62
|
+
const root = mkdtempSync(join(tmpdir(), 'ta-ssh-host-'));
|
|
63
|
+
const ssh = join(root, 'ssh');
|
|
64
|
+
/** A PATH with the tools the scripts use, and no Node.js. */
|
|
65
|
+
const bare = join(root, 'bin');
|
|
66
|
+
const hosts: SshHost[] = [];
|
|
67
|
+
let mirror: Server;
|
|
68
|
+
let mirrorUrl: string;
|
|
69
|
+
|
|
70
|
+
const steps: SshStep[] = [];
|
|
71
|
+
const host = (options: Partial<SshHostOptions> = {}) => {
|
|
72
|
+
const created = new SshHost({ host: 'fake', stateDir: join(root, 'state'), ssh, onStep: step => steps.push(step), nodeMirror: mirrorUrl, ...options });
|
|
73
|
+
hosts.push(created);
|
|
74
|
+
return created;
|
|
75
|
+
};
|
|
76
|
+
const remote = (name: string, path: string) => {
|
|
77
|
+
const home = join(root, name);
|
|
78
|
+
mkdirSync(home, { recursive: true });
|
|
79
|
+
process.env.FAKE_SSH_HOME = home;
|
|
80
|
+
process.env.FAKE_SSH_PATH = path;
|
|
81
|
+
return home;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
beforeAll(async () => {
|
|
85
|
+
writeFileSync(ssh, FAKE_SSH, { mode: 0o755 });
|
|
86
|
+
writeFileSync(join(root, 'login-sh'), LOGIN_SH, { mode: 0o755 });
|
|
87
|
+
process.env.FAKE_SSH_DIR = root;
|
|
88
|
+
mkdirSync(bare);
|
|
89
|
+
for (const tool of ['sh', 'uname', 'tar', 'gzip', 'cat', 'mkdir', 'mv', 'rm', 'dirname', 'tail', 'ls', 'sleep', 'sed']) {
|
|
90
|
+
symlinkSync(which(tool), join(bare, tool));
|
|
91
|
+
}
|
|
92
|
+
// A mirror of nodejs.org with one build, for this machine, whose node runs the real one.
|
|
93
|
+
const platform = SshUtil.nodePlatform(execFileSync('uname', ['-s']).toString().trim(), execFileSync('uname', ['-m']).toString().trim());
|
|
94
|
+
const name = `node-v22.99.0-${platform}`;
|
|
95
|
+
mkdirSync(join(root, 'dist', name, 'bin'), { recursive: true });
|
|
96
|
+
writeFileSync(join(root, 'dist', name, 'bin', 'node'), `#!/bin/sh\nexec "${node}" "$@"\n`, { mode: 0o755 });
|
|
97
|
+
execFileSync('tar', ['-czf', `${name}.tar.gz`, name], { cwd: join(root, 'dist') });
|
|
98
|
+
const tarball = readFileSync(join(root, 'dist', `${name}.tar.gz`));
|
|
99
|
+
const sums = `${createHash('sha256').update(tarball).digest('hex')} ${name}.tar.gz\n`;
|
|
100
|
+
mirror = createServer((request, response) => {
|
|
101
|
+
if (request.url === '/latest-v22.x/SHASUMS256.txt') {
|
|
102
|
+
response.end(sums);
|
|
103
|
+
} else if (request.url === `/latest-v22.x/${name}.tar.gz`) {
|
|
104
|
+
response.end(tarball);
|
|
105
|
+
} else {
|
|
106
|
+
response.writeHead(404).end();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
await new Promise<void>(resolve => mirror.listen(0, '127.0.0.1', resolve));
|
|
110
|
+
mirrorUrl = `http://127.0.0.1:${(mirror.address() as { port: number }).port}`;
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
afterAll(async () => {
|
|
114
|
+
await Promise.all(hosts.map(created => created.dispose()));
|
|
115
|
+
mirror.close();
|
|
116
|
+
delete process.env.FAKE_SSH_PASSWORD;
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('copies its server once, and runs commands there with the Node.js of the host', async () => {
|
|
120
|
+
const home = remote('with-node', `${join(node, '..')}:/usr/bin:/bin`);
|
|
121
|
+
steps.length = 0;
|
|
122
|
+
const first = host();
|
|
123
|
+
const env = new RemoteExecEnvironment(first.client, home);
|
|
124
|
+
const chunks: Uint8Array[] = [];
|
|
125
|
+
expect((await env.exec('pwd; echo "$HOME"', { onData: data => chunks.push(data) })).exitCode).toBe(0);
|
|
126
|
+
expect(Buffer.concat(chunks).toString()).toBe(`${home}\n${home}\n`);
|
|
127
|
+
expect(steps).toEqual(['connecting', 'checking', 'copying-server', 'starting']);
|
|
128
|
+
expect((await first.client.info()).cwd).toBe(realpathSync(home));
|
|
129
|
+
await first.dispose();
|
|
130
|
+
expect(existsSync(join(root, 'master'))).toBe(false);
|
|
131
|
+
|
|
132
|
+
steps.length = 0;
|
|
133
|
+
const second = host();
|
|
134
|
+
expect((await new RemoteExecEnvironment(second.client, home).stat('.'))?.isDirectory).toBe(true);
|
|
135
|
+
expect(steps).toEqual(['connecting', 'checking', 'starting']);
|
|
136
|
+
await second.dispose();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('installs Node.js on a host without one, from the mirror, checked', async () => {
|
|
140
|
+
const home = remote('without-node', bare);
|
|
141
|
+
steps.length = 0;
|
|
142
|
+
const created = host();
|
|
143
|
+
const env = new RemoteExecEnvironment(created.client, home);
|
|
144
|
+
expect((await env.exec('true')).exitCode).toBe(0);
|
|
145
|
+
expect(steps).toEqual(['connecting', 'checking', 'installing-node', 'installing-node', 'copying-server', 'starting']);
|
|
146
|
+
expect(existsSync(join(home, '.ta/server/node/bin/node'))).toBe(true);
|
|
147
|
+
await created.dispose();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('asks for the password through Ta, and fails with what ssh said when it is wrong', async () => {
|
|
151
|
+
remote('password', `${join(node, '..')}:/usr/bin:/bin`);
|
|
152
|
+
process.env.FAKE_SSH_PASSWORD = 's3cret';
|
|
153
|
+
try {
|
|
154
|
+
const questions: string[] = [];
|
|
155
|
+
const right = host({
|
|
156
|
+
ask: async question => {
|
|
157
|
+
questions.push(`${question.kind}:${question.message}`);
|
|
158
|
+
return 's3cret';
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
await right.client.info();
|
|
162
|
+
expect(questions).toEqual(["secret:fake's password:"]);
|
|
163
|
+
await right.dispose();
|
|
164
|
+
|
|
165
|
+
const wrong = host({ ask: async () => 'nope' });
|
|
166
|
+
await expect(wrong.client.info()).rejects.toThrow('Permission denied (password).');
|
|
167
|
+
const cancelled = host({ ask: async () => undefined });
|
|
168
|
+
await expect(cancelled.client.info()).rejects.toThrow('Permission denied (cancelled).');
|
|
169
|
+
} finally {
|
|
170
|
+
delete process.env.FAKE_SSH_PASSWORD;
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('says the connection was lost when ssh ends', async () => {
|
|
175
|
+
const home = remote('lost', `${join(node, '..')}:/usr/bin:/bin`);
|
|
176
|
+
const created = host();
|
|
177
|
+
const env = new RemoteExecEnvironment(created.client, home);
|
|
178
|
+
// Connected first: a first connection can take longer than the wait below, and then there would be
|
|
179
|
+
// no server to end yet.
|
|
180
|
+
await created.client.info();
|
|
181
|
+
const running = env.exec('sleep 30');
|
|
182
|
+
await new Promise(resolve => setTimeout(resolve, 300));
|
|
183
|
+
// Not through a shell, whose command line would match too.
|
|
184
|
+
spawnSync('pkill', ['-f', `${home}/.ta/server`]);
|
|
185
|
+
await expect(running).rejects.toThrow(/lost/);
|
|
186
|
+
expect(created.client.connected).toBe(false);
|
|
187
|
+
expect((await env.exec('true')).exitCode).toBe(0);
|
|
188
|
+
});
|
|
189
|
+
});
|