@celljs/ta-exec 4.8.0 → 4.9.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.
Files changed (86) hide show
  1. package/package.json +4 -3
  2. package/esm/node/exec-client.js.map +0 -1
  3. package/esm/node/exec-peer.js.map +0 -1
  4. package/esm/node/exec-protocol.js.map +0 -1
  5. package/esm/node/exec-remote-source.js.map +0 -1
  6. package/esm/node/exec-rpc.js.map +0 -1
  7. package/esm/node/exec-server.js.map +0 -1
  8. package/esm/node/exec-stdio.js.map +0 -1
  9. package/esm/node/index.js.map +0 -1
  10. package/esm/node/local-exec-environment.js.map +0 -1
  11. package/esm/node/remote-exec-environment.js.map +0 -1
  12. package/esm/node/ssh/node-dist.js.map +0 -1
  13. package/esm/node/ssh/ssh-askpass.js.map +0 -1
  14. package/esm/node/ssh/ssh-config.js.map +0 -1
  15. package/esm/node/ssh/ssh-host.js.map +0 -1
  16. package/esm/node/ssh/ssh-util.js.map +0 -1
  17. package/lib/node/exec-client.d.ts.map +0 -1
  18. package/lib/node/exec-client.js.map +0 -1
  19. package/lib/node/exec-peer.d.ts.map +0 -1
  20. package/lib/node/exec-peer.js.map +0 -1
  21. package/lib/node/exec-protocol.d.ts.map +0 -1
  22. package/lib/node/exec-protocol.js.map +0 -1
  23. package/lib/node/exec-remote-source.d.ts.map +0 -1
  24. package/lib/node/exec-remote-source.js.map +0 -1
  25. package/lib/node/exec-rpc.d.ts.map +0 -1
  26. package/lib/node/exec-rpc.js.map +0 -1
  27. package/lib/node/exec-server.d.ts.map +0 -1
  28. package/lib/node/exec-server.js.map +0 -1
  29. package/lib/node/exec-server.spec.d.ts +0 -2
  30. package/lib/node/exec-server.spec.d.ts.map +0 -1
  31. package/lib/node/exec-server.spec.js +0 -104
  32. package/lib/node/exec-server.spec.js.map +0 -1
  33. package/lib/node/exec-stdio.d.ts.map +0 -1
  34. package/lib/node/exec-stdio.js.map +0 -1
  35. package/lib/node/exec-stdio.spec.d.ts +0 -2
  36. package/lib/node/exec-stdio.spec.d.ts.map +0 -1
  37. package/lib/node/exec-stdio.spec.js +0 -106
  38. package/lib/node/exec-stdio.spec.js.map +0 -1
  39. package/lib/node/index.d.ts.map +0 -1
  40. package/lib/node/index.js.map +0 -1
  41. package/lib/node/local-exec-environment.d.ts.map +0 -1
  42. package/lib/node/local-exec-environment.js.map +0 -1
  43. package/lib/node/local-exec-environment.spec.d.ts +0 -2
  44. package/lib/node/local-exec-environment.spec.d.ts.map +0 -1
  45. package/lib/node/local-exec-environment.spec.js +0 -57
  46. package/lib/node/local-exec-environment.spec.js.map +0 -1
  47. package/lib/node/remote-exec-environment.d.ts.map +0 -1
  48. package/lib/node/remote-exec-environment.js.map +0 -1
  49. package/lib/node/ssh/node-dist.d.ts.map +0 -1
  50. package/lib/node/ssh/node-dist.js.map +0 -1
  51. package/lib/node/ssh/ssh-askpass.d.ts.map +0 -1
  52. package/lib/node/ssh/ssh-askpass.js.map +0 -1
  53. package/lib/node/ssh/ssh-config.d.ts.map +0 -1
  54. package/lib/node/ssh/ssh-config.js.map +0 -1
  55. package/lib/node/ssh/ssh-host.d.ts.map +0 -1
  56. package/lib/node/ssh/ssh-host.js.map +0 -1
  57. package/lib/node/ssh/ssh-host.spec.d.ts +0 -2
  58. package/lib/node/ssh/ssh-host.spec.d.ts.map +0 -1
  59. package/lib/node/ssh/ssh-host.spec.js +0 -182
  60. package/lib/node/ssh/ssh-host.spec.js.map +0 -1
  61. package/lib/node/ssh/ssh-util.d.ts.map +0 -1
  62. package/lib/node/ssh/ssh-util.js.map +0 -1
  63. package/lib/node/ssh/ssh-util.spec.d.ts +0 -2
  64. package/lib/node/ssh/ssh-util.spec.d.ts.map +0 -1
  65. package/lib/node/ssh/ssh-util.spec.js +0 -87
  66. package/lib/node/ssh/ssh-util.spec.js.map +0 -1
  67. package/src/node/exec-client.ts +0 -221
  68. package/src/node/exec-peer.ts +0 -186
  69. package/src/node/exec-protocol.ts +0 -89
  70. package/src/node/exec-remote-source.ts +0 -7
  71. package/src/node/exec-rpc.ts +0 -124
  72. package/src/node/exec-server.spec.ts +0 -113
  73. package/src/node/exec-server.ts +0 -107
  74. package/src/node/exec-stdio.spec.ts +0 -108
  75. package/src/node/exec-stdio.ts +0 -75
  76. package/src/node/index.ts +0 -14
  77. package/src/node/local-exec-environment.spec.ts +0 -60
  78. package/src/node/local-exec-environment.ts +0 -112
  79. package/src/node/remote-exec-environment.ts +0 -162
  80. package/src/node/ssh/node-dist.ts +0 -83
  81. package/src/node/ssh/ssh-askpass.ts +0 -117
  82. package/src/node/ssh/ssh-config.ts +0 -128
  83. package/src/node/ssh/ssh-host.spec.ts +0 -189
  84. package/src/node/ssh/ssh-host.ts +0 -300
  85. package/src/node/ssh/ssh-util.spec.ts +0 -97
  86. package/src/node/ssh/ssh-util.ts +0 -127
@@ -1,113 +0,0 @@
1
- import { afterAll, beforeAll, describe, expect, it } from 'bun:test';
2
- import { type ChildProcess, spawn } from 'node:child_process';
3
- import { mkdtempSync, readFileSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { ExecClient, ExecError } from './exec-client';
7
- import { ExecRpc } from './exec-rpc';
8
- import { RemoteExecEnvironment } from './remote-exec-environment';
9
-
10
- const TOKEN = 'secret-token';
11
- const text = (chunks: Uint8Array[]) => Buffer.concat(chunks).toString();
12
-
13
- /** In Node.js: the HTTP server of Bun before 1.4 cannot answer WebSocket upgrades. */
14
- function startServer(cwd: string): Promise<{ child: ChildProcess; url: string }> {
15
- const script = `require(${JSON.stringify(join(__dirname, 'exec-server.js'))}).ExecServer.prototype.listen.call(new (require(${JSON.stringify(join(__dirname, 'exec-server.js'))}).ExecServer)({ token: ${JSON.stringify(TOKEN)}, cwd: ${JSON.stringify(cwd)} })).then(url => console.log(url))`;
16
- const child = spawn('node', ['-e', script], { stdio: ['ignore', 'pipe', 'inherit'] });
17
- return new Promise(resolve => child.stdout?.once('data', data => resolve({ child, url: String(data).trim() })));
18
- }
19
-
20
- describe('ta exec-server', () => {
21
- const root = mkdtempSync(join(tmpdir(), 'ta-exec-remote-'));
22
- let server: ChildProcess;
23
- const clients: ExecClient[] = [];
24
- let url: string;
25
-
26
- const environment = (epoch = 1, token = TOKEN) => {
27
- const client = new ExecClient({ connect: ExecClient.webSocket(url, token), epoch });
28
- clients.push(client);
29
- return new RemoteExecEnvironment(client, root);
30
- };
31
-
32
- beforeAll(async () => {
33
- ({ child: server, url } = await startServer(root));
34
- });
35
-
36
- afterAll(() => {
37
- for (const client of clients) {
38
- client.close();
39
- }
40
- server.kill();
41
- });
42
-
43
- it('runs a command there and streams its output', async () => {
44
- const chunks: Uint8Array[] = [];
45
- const result = await environment().exec('pwd; echo out; echo err >&2; exit 3', { onData: data => chunks.push(data) });
46
- expect(result.exitCode).toBe(3);
47
- expect(text(chunks)).toContain(root.split('/').pop() ?? root);
48
- expect(text(chunks)).toContain('err');
49
- });
50
-
51
- it("sends only what a tool adds to the environment, not the host's", async () => {
52
- process.env.TA_HOST_ONLY_SECRET = 'host';
53
- const chunks: Uint8Array[] = [];
54
- await environment().exec('echo "[$TA_HOST_ONLY_SECRET][$EXTRA]"', { env: { ...process.env, EXTRA: 'tool' }, onData: data => chunks.push(data) });
55
- // The server runs in its own process: the host's variable is not there unless sent.
56
- expect(text(chunks).trim()).toBe('[][tool]');
57
- expect(RemoteExecEnvironment.delta({ ...process.env, EXTRA: 'tool' })).toEqual({ EXTRA: 'tool' });
58
- delete process.env.TA_HOST_ONLY_SECRET;
59
- });
60
-
61
- it('kills a command when aborted', async () => {
62
- const controller = new AbortController();
63
- const running = environment().exec('sleep 30', { signal: controller.signal });
64
- setTimeout(() => controller.abort(), 100);
65
- expect((await running).exitCode).not.toBe(0);
66
- });
67
-
68
- it('reads and writes files there, with paths of that machine', async () => {
69
- const env = environment();
70
- await env.mkdir('dir/sub');
71
- await env.writeFile('dir/sub/a.txt', 'hello');
72
- expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello');
73
- await env.writeFile('dir/sub/a.txt', ' world', { append: true });
74
- expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello world');
75
- await env.writeFile('dir/sub/a.txt', 'hello');
76
- expect(Buffer.from(await env.readFile('dir/sub/a.txt')).toString()).toBe('hello');
77
- expect(await env.stat('dir')).toMatchObject({ isDirectory: true });
78
- expect(await env.stat('nothing')).toBeUndefined();
79
- expect(await env.readdir('dir')).toEqual([{ name: 'sub', isDirectory: true }]);
80
- await env.remove('dir', { recursive: true });
81
- expect(await env.stat('dir')).toBeUndefined();
82
- await expect(env.readFile('nothing')).rejects.toThrow('ENOENT');
83
- });
84
-
85
- it('talks to a long-running program over stdin and stdout', async () => {
86
- const child = environment().spawn('cat', []);
87
- const chunks: Uint8Array[] = [];
88
- child.onStdout(data => chunks.push(data));
89
- const exited = new Promise<number | null>(resolve => child.onExit(resolve));
90
- child.write('ping\n');
91
- for (let i = 0; i < 100 && !text(chunks).includes('ping'); i++) {
92
- await Bun.sleep(10);
93
- }
94
- expect(text(chunks)).toBe('ping\n');
95
- child.kill();
96
- expect(await exited).not.toBe(0);
97
- });
98
-
99
- it('refuses a host without the token', async () => {
100
- await expect(environment(1, 'wrong').exec('true')).rejects.toBeInstanceOf(ExecError);
101
- });
102
-
103
- it('fences a host once one with a newer epoch connects', async () => {
104
- const old = environment(10);
105
- const running = old.exec('sleep 30').catch((error: ExecError) => error);
106
- await Bun.sleep(100);
107
- const current = environment(11);
108
- expect((await current.exec('true')).exitCode).toBe(0);
109
- expect(await running).toMatchObject({ code: ExecRpc.ErrorCode.CONNECTION_LOST });
110
- await expect(old.exec('true')).rejects.toMatchObject({ code: ExecRpc.ErrorCode.STALE_EPOCH });
111
- await expect(old.exec('true')).rejects.toMatchObject({ code: ExecRpc.ErrorCode.STALE_EPOCH });
112
- });
113
- });
@@ -1,107 +0,0 @@
1
- import { timingSafeEqual } from 'node:crypto';
2
- import { createServer, type IncomingMessage, type Server } from 'node:http';
3
- import type { AddressInfo } from 'node:net';
4
- import type { Duplex } from 'node:stream';
5
- import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
- import { ExecPeer, type ExecPeerServer } from './exec-peer';
7
- import { ExecRpc } from './exec-rpc';
8
-
9
- export interface ExecServerOptions {
10
- /** Default 127.0.0.1. */
11
- host?: string;
12
- /** Default: a free port. */
13
- port?: number;
14
- /** What hosts must present. */
15
- token: string;
16
- /** Default: the working directory of the process. */
17
- cwd?: string;
18
- /** Largest message in bytes, for files in one piece. Default 64 MiB. */
19
- maxPayload?: number;
20
- }
21
-
22
- /**
23
- * `ta exec-server`: runs the commands and file operations of a host's sessions on this machine, which
24
- * may be a container or a sandbox: the security boundary is the machine, as pi's is. Processes belong
25
- * to the connection that started them and end with it.
26
- */
27
- export class ExecServer implements ExecPeerServer {
28
- protected server?: Server;
29
- /** The largest epoch a host connected with. */
30
- protected epoch = 0;
31
- protected readonly peers = new Set<ExecPeer>();
32
-
33
- constructor(protected readonly options: ExecServerOptions) {}
34
-
35
- get cwd(): string {
36
- return this.options.cwd ?? process.cwd();
37
- }
38
-
39
- /** Resolves to the WebSocket URL. */
40
- async listen(): Promise<string> {
41
- const server = createServer((_request, response) => response.writeHead(404).end());
42
- server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
43
- this.server = server;
44
- await new Promise<void>(resolve => server.listen(this.options.port ?? 0, this.options.host ?? '127.0.0.1', resolve));
45
- const { port } = server.address() as AddressInfo;
46
- return `ws://${this.options.host ?? '127.0.0.1'}:${port}${ExecRpc.PATH}`;
47
- }
48
-
49
- async close(): Promise<void> {
50
- for (const peer of this.peers) {
51
- peer.close(1001, 'The server stops.');
52
- }
53
- await new Promise<void>(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
54
- }
55
-
56
- /** False when a newer host has taken over; a newer one fences the older ones. */
57
- admit(peer: ExecPeer, epoch: number): boolean {
58
- if (epoch < this.epoch) {
59
- return false;
60
- }
61
- if (epoch > this.epoch) {
62
- this.epoch = epoch;
63
- for (const other of this.peers) {
64
- if (other !== peer && other.epoch !== undefined && other.epoch < epoch) {
65
- other.close(4001, 'A host with a newer epoch connected.');
66
- }
67
- }
68
- }
69
- return true;
70
- }
71
-
72
- isCurrent(epoch: number | undefined): boolean {
73
- return epoch === this.epoch;
74
- }
75
-
76
- protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {
77
- const url = new URL(request.url ?? '/', 'http://localhost');
78
- if (url.pathname !== ExecRpc.PATH) {
79
- WebSocketConnection.refuse(socket, 404, 'Not found.');
80
- return;
81
- }
82
- const checked = WebSocketConnection.check(request);
83
- if ('status' in checked) {
84
- WebSocketConnection.refuse(socket, checked.status, checked.message);
85
- return;
86
- }
87
- const header = request.headers.authorization;
88
- const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : url.searchParams.get('token');
89
- if (!token || !this.matches(token)) {
90
- WebSocketConnection.refuse(socket, 401, 'Not authorized.');
91
- return;
92
- }
93
- const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: this.options.maxPayload ?? 67108864, heartbeat: 30000 });
94
- const peer = new ExecPeer(this, { send: text => connection.send(text), close: (code, reason) => connection.close(code, reason) });
95
- connection.onMessage(text => void peer.receive(text));
96
- this.peers.add(peer);
97
- connection.onClose(() => {
98
- this.peers.delete(peer);
99
- peer.dispose();
100
- });
101
- }
102
-
103
- protected matches(token: string): boolean {
104
- const [left, right] = [Buffer.from(token), Buffer.from(this.options.token)];
105
- return left.length === right.length && timingSafeEqual(left, right);
106
- }
107
- }
@@ -1,108 +0,0 @@
1
- import { afterAll, describe, expect, it } from 'bun:test';
2
- import { spawn } from 'node:child_process';
3
- import { mkdtempSync, writeFileSync } from 'node:fs';
4
- import { createServer } from 'node:net';
5
- import { tmpdir } from 'node:os';
6
- import { join } from 'node:path';
7
- import { ExecClient, type ExecConnection } from './exec-client';
8
- import { EXEC_REMOTE_SOURCE } from './exec-remote-source';
9
- import { RemoteExecEnvironment } from './remote-exec-environment';
10
-
11
- const root = mkdtempSync(join(tmpdir(), 'ta-exec-stdio-'));
12
- const script = join(root, 'exec-server.js');
13
- writeFileSync(script, EXEC_REMOTE_SOURCE.script);
14
-
15
- /** The script ta copies to other machines, on the standard input and output of a child, as over ssh. */
16
- function connect(banner = ''): () => Promise<ExecConnection> {
17
- return async () => {
18
- const child = spawn('/bin/sh', ['-c', `printf %s "$0"; exec node "$1"`, banner, script], { cwd: root, stdio: ['pipe', 'pipe', 'inherit'] });
19
- let rest = '';
20
- const listeners = new Set<(text: string) => void>();
21
- child.stdout.on('data', data => {
22
- const lines = (rest + data.toString()).split('\n');
23
- rest = lines.pop() ?? '';
24
- for (const line of lines) {
25
- for (const listener of listeners) {
26
- listener(line);
27
- }
28
- }
29
- });
30
- return {
31
- send: text => child.stdin.write(`${text}\n`),
32
- close: () => child.stdin.end(),
33
- onMessage: listener => listeners.add(listener),
34
- onClose: listener => child.once('close', () => listener()),
35
- };
36
- };
37
- }
38
-
39
- describe('ta exec-server on stdio', () => {
40
- const clients: ExecClient[] = [];
41
- const environment = (banner?: string) => {
42
- const client = new ExecClient({ connect: connect(banner), epoch: 1 });
43
- clients.push(client);
44
- return new RemoteExecEnvironment(client, root);
45
- };
46
-
47
- afterAll(() => {
48
- for (const client of clients) {
49
- client.close();
50
- }
51
- });
52
-
53
- it('is one script that needs no package', () => {
54
- expect(EXEC_REMOTE_SOURCE.hash).toMatch(/^[0-9a-f]{16}$/);
55
- expect(EXEC_REMOTE_SOURCE.script).not.toMatch(/require\("@celljs/);
56
- });
57
-
58
- it('runs commands and touches files, past what a login shell printed first', async () => {
59
- const env = environment('Welcome to the host\n');
60
- const chunks: Uint8Array[] = [];
61
- const { exitCode } = await env.exec('echo hello', { onData: data => chunks.push(data) });
62
- expect(exitCode).toBe(0);
63
- expect(Buffer.concat(chunks).toString()).toBe('hello\n');
64
- await env.writeFile('a.txt', 'te');
65
- await env.writeFile('a.txt', 'xt', { append: true });
66
- expect(Buffer.from(await env.readFile('a.txt')).toString()).toBe('text');
67
- expect((await env.stat('a.txt'))?.size).toBe(4);
68
- });
69
-
70
- it('connects to a port of its machine, both ways', async () => {
71
- const server = createServer(socket => socket.on('data', data => socket.end(`echo:${data}`)));
72
- await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
73
- const { port } = server.address() as { port: number };
74
- try {
75
- const socket = await environment().connect(port);
76
- const received: Uint8Array[] = [];
77
- socket.onData(data => received.push(data));
78
- const closed = new Promise<void>(resolve => socket.onClose(resolve));
79
- socket.write(Buffer.from('ping'));
80
- await closed;
81
- expect(Buffer.concat(received).toString()).toBe('echo:ping');
82
- } finally {
83
- server.close();
84
- }
85
- });
86
-
87
- it('refuses to connect where nothing listens', async () => {
88
- const server = createServer();
89
- await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
90
- const { port } = server.address() as { port: number };
91
- await new Promise<void>(resolve => server.close(() => resolve()));
92
- await expect(environment().connect(port)).rejects.toThrow();
93
- });
94
-
95
- it('ends what the host started when its input ends', async () => {
96
- const env = environment();
97
- const pidFile = join(root, 'sleep.pid');
98
- const running = env.exec(`sh -c 'echo $$ > ${pidFile}; exec sleep 30'`);
99
- for (let i = 0; i < 50 && !(await env.stat('sleep.pid'))?.size; i++) {
100
- await new Promise(resolve => setTimeout(resolve, 20));
101
- }
102
- const pid = Number(Buffer.from(await env.readFile('sleep.pid')).toString());
103
- clients.at(-1)?.close();
104
- await expect(running).rejects.toThrow();
105
- await new Promise(resolve => setTimeout(resolve, 200));
106
- expect(() => process.kill(pid, 0)).toThrow();
107
- });
108
- });
@@ -1,75 +0,0 @@
1
- import { ExecPeer, type ExecPeerServer } from './exec-peer';
2
-
3
- export interface ExecStdioOptions {
4
- input: NodeJS.ReadableStream;
5
- output: NodeJS.WritableStream;
6
- /** Default: the working directory of the process. */
7
- cwd?: string;
8
- /**
9
- * Ends when nothing came for this long (milliseconds; the host pings): over ssh, a connection that
10
- * died silently leaves the input open, and the processes of the host must not run on. Default: never.
11
- */
12
- idleMs?: number;
13
- }
14
-
15
- /**
16
- * `ta exec-server` for one host on the standard input and output, one JSON-RPC message per line: how it
17
- * runs at the other end of ssh, which takes care of access. Everything the host started ends with the
18
- * input. The process prints nothing else on its standard output.
19
- */
20
- export class ExecStdio implements ExecPeerServer {
21
- readonly cwd: string;
22
- protected epoch?: number;
23
-
24
- constructor(protected readonly options: ExecStdioOptions) {
25
- this.cwd = options.cwd ?? process.cwd();
26
- }
27
-
28
- /** Resolves when the input ends, the host closed the connection, or it was idle too long. */
29
- serve(): Promise<void> {
30
- const { input, output, idleMs } = this.options;
31
- return new Promise(resolve => {
32
- let timer: ReturnType<typeof setTimeout> | undefined;
33
- let rest = '';
34
- const end = () => {
35
- clearTimeout(timer);
36
- input.removeListener('data', receive);
37
- peer.dispose();
38
- resolve();
39
- };
40
- const peer = new ExecPeer(this, { send: text => output.write(`${text}\n`), close: end });
41
- const watch = () => {
42
- if (idleMs) {
43
- clearTimeout(timer);
44
- timer = setTimeout(end, idleMs);
45
- }
46
- };
47
- const receive = (data: Buffer | string) => {
48
- watch();
49
- const lines = (rest + data.toString()).split('\n');
50
- rest = lines.pop() ?? '';
51
- for (const line of lines) {
52
- if (line.trim()) {
53
- void peer.receive(line);
54
- }
55
- }
56
- };
57
- input.on('data', receive);
58
- input.once('end', end);
59
- input.once('error', end);
60
- watch();
61
- });
62
- }
63
-
64
- admit(_peer: ExecPeer, epoch: number): boolean {
65
- if (this.epoch !== undefined && epoch < this.epoch) {
66
- return false;
67
- }
68
- this.epoch = epoch;
69
- return true;
70
- }
71
-
72
- isCurrent(epoch: number | undefined): boolean {
73
- return epoch === this.epoch;
74
- }
75
- }
package/src/node/index.ts DELETED
@@ -1,14 +0,0 @@
1
- export * from './exec-client';
2
- export * from './exec-peer';
3
- export * from './exec-protocol';
4
- export * from './exec-remote-source';
5
- export * from './exec-rpc';
6
- export * from './exec-server';
7
- export * from './exec-stdio';
8
- export * from './local-exec-environment';
9
- export * from './remote-exec-environment';
10
- export * from './ssh/node-dist';
11
- export * from './ssh/ssh-askpass';
12
- export * from './ssh/ssh-config';
13
- export * from './ssh/ssh-host';
14
- export * from './ssh/ssh-util';
@@ -1,60 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { mkdtempSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
- import { join } from 'node:path';
5
- import { LocalExecEnvironment } from './local-exec-environment';
6
-
7
- const environment = () => new LocalExecEnvironment(mkdtempSync(join(tmpdir(), 'ta-exec-')));
8
- const text = (chunks: Uint8Array[]) => Buffer.concat(chunks).toString();
9
-
10
- describe('LocalExecEnvironment', () => {
11
- it('runs a command in its directory and streams the output', async () => {
12
- const env = environment();
13
- const chunks: Uint8Array[] = [];
14
- const result = await env.exec('pwd; echo out; echo err >&2; exit 3', { onData: data => chunks.push(data) });
15
- expect(result.exitCode).toBe(3);
16
- expect(text(chunks)).toContain('out');
17
- expect(text(chunks)).toContain('err');
18
- });
19
-
20
- it('kills what the command started when aborted', async () => {
21
- const controller = new AbortController();
22
- const running = environment().exec('sleep 30 & wait', { signal: controller.signal });
23
- controller.abort();
24
- expect((await running).exitCode).not.toBe(0);
25
- });
26
-
27
- it('kills the command at the timeout', async () => {
28
- const start = Date.now();
29
- await environment().exec('sleep 30', { timeout: 50 });
30
- expect(Date.now() - start).toBeLessThan(5000);
31
- });
32
-
33
- it('reports a program that cannot start', async () => {
34
- const exit = await new Promise(done => environment().spawn('/no/such/program', []).onExit(done));
35
- expect(exit).toBeNull();
36
- });
37
-
38
- it('talks to a long-lived program over stdin and stdout', async () => {
39
- const child = environment().spawn('cat', []);
40
- const output = new Promise<string>(done => child.onStdout(data => done(Buffer.from(data).toString())));
41
- child.write('hello');
42
- expect(await output).toBe('hello');
43
- const exit = new Promise(done => child.onExit(done));
44
- child.kill();
45
- await exit;
46
- });
47
-
48
- it('reads, writes, lists and removes files relative to its directory', async () => {
49
- const env = environment();
50
- await env.mkdir('a/b');
51
- await env.writeFile('a/b/c.txt', 'data');
52
- expect(Buffer.from(await env.readFile(join(env.cwd, 'a/b/c.txt'))).toString()).toBe('data');
53
- await env.writeFile('a/b/c.txt', new Uint8Array([45, 46]), { append: true });
54
- expect(Buffer.from(await env.readFile('a/b/c.txt')).toString()).toBe('data-.');
55
- expect(await env.readdir('a')).toEqual([{ name: 'b', isDirectory: true }]);
56
- expect((await env.stat('a/b'))?.isDirectory).toBe(true);
57
- await env.remove('a', { recursive: true });
58
- expect(await env.stat('a')).toBeUndefined();
59
- });
60
- });
@@ -1,112 +0,0 @@
1
- import { type ChildProcess, spawn } from 'node:child_process';
2
- import { appendFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
- import { resolve } from 'node:path';
4
- import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, FileStat, SpawnOptions, WriteFileOptions } from './exec-protocol';
5
-
6
- /** This machine. */
7
- export class LocalExecEnvironment implements ExecEnvironment {
8
- readonly local: boolean = true;
9
-
10
- constructor(readonly cwd: string) {}
11
-
12
- exec(command: string, options: ExecOptions = {}): Promise<ExecResult> {
13
- const [shell, ...args] = process.platform === 'win32' ? ['cmd.exe', '/d', '/s', '/c'] : ['/bin/sh', '-c'];
14
- const child = spawn(shell, [...args, command], {
15
- cwd: resolve(this.cwd, options.cwd ?? '.'),
16
- env: options.env ?? process.env,
17
- stdio: ['ignore', 'pipe', 'pipe'],
18
- // Its own process group: killing the shell must also end what the command started.
19
- detached: process.platform !== 'win32',
20
- });
21
- return new Promise(done => {
22
- const kill = () => this.killGroup(child);
23
- const timer = options.timeout ? setTimeout(kill, options.timeout) : undefined;
24
- options.signal?.addEventListener('abort', kill, { once: true });
25
- if (options.signal?.aborted) {
26
- kill();
27
- }
28
- child.stdout?.on('data', data => options.onData?.(data));
29
- child.stderr?.on('data', data => options.onData?.(data));
30
- const finish = (exitCode: number | null) => {
31
- clearTimeout(timer);
32
- options.signal?.removeEventListener('abort', kill);
33
- done({ exitCode });
34
- };
35
- child.once('error', () => finish(null));
36
- child.once('close', finish);
37
- });
38
- }
39
-
40
- spawn(command: string, args: string[], options: SpawnOptions = {}): ExecProcess {
41
- const child = spawn(command, args, {
42
- cwd: resolve(this.cwd, options.cwd ?? '.'),
43
- env: options.env ?? process.env,
44
- stdio: ['pipe', 'pipe', 'pipe'],
45
- });
46
- // Writes after the program ended surface as EPIPE here; onExit tells the owner.
47
- child.stdin.on('error', () => undefined);
48
- return {
49
- write: data => child.stdin.write(data),
50
- onStdout: listener => child.stdout.on('data', listener),
51
- onStderr: listener => child.stderr.on('data', listener),
52
- onExit: listener => {
53
- child.once('error', () => listener(null));
54
- child.once('close', listener);
55
- },
56
- kill: () => child.kill(),
57
- };
58
- }
59
-
60
- readFile(path: string): Promise<Uint8Array> {
61
- return readFile(this.resolve(path));
62
- }
63
-
64
- writeFile(path: string, data: Uint8Array | string, options: WriteFileOptions = {}): Promise<void> {
65
- return options.append ? appendFile(this.resolve(path), data) : writeFile(this.resolve(path), data);
66
- }
67
-
68
- async stat(path: string): Promise<FileStat | undefined> {
69
- try {
70
- const info = await stat(this.resolve(path));
71
- return { isDirectory: info.isDirectory(), size: info.size, mtimeMs: info.mtimeMs };
72
- } catch (error) {
73
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
74
- return undefined;
75
- }
76
- throw error;
77
- }
78
- }
79
-
80
- async readdir(path: string): Promise<DirEntry[]> {
81
- const entries = await readdir(this.resolve(path), { withFileTypes: true });
82
- return entries.map(entry => ({ name: entry.name, isDirectory: entry.isDirectory() }));
83
- }
84
-
85
- async mkdir(path: string): Promise<void> {
86
- await mkdir(this.resolve(path), { recursive: true });
87
- }
88
-
89
- remove(path: string, options: { recursive?: boolean } = {}): Promise<void> {
90
- return rm(this.resolve(path), { recursive: options.recursive, force: true });
91
- }
92
-
93
- protected resolve(path: string): string {
94
- return resolve(this.cwd, path);
95
- }
96
-
97
- protected killGroup(child: ChildProcess): void {
98
- if (child.pid === undefined) {
99
- return;
100
- }
101
- if (process.platform !== 'win32') {
102
- try {
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.
108
- }
109
- }
110
- child.kill('SIGKILL');
111
- }
112
- }