@celljs/ta-exec 4.6.1 → 4.8.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.
Files changed (140) hide show
  1. package/README.en.md +43 -0
  2. package/README.md +5 -1
  3. package/esm/node/exec-client.d.ts +28 -11
  4. package/esm/node/exec-client.js +89 -33
  5. package/esm/node/exec-client.js.map +1 -1
  6. package/esm/node/exec-peer.d.ts +40 -0
  7. package/esm/node/exec-peer.js +167 -0
  8. package/esm/node/exec-peer.js.map +1 -0
  9. package/esm/node/exec-protocol.d.ts +19 -1
  10. package/esm/node/exec-remote-source.d.ts +5 -0
  11. package/esm/node/exec-remote-source.js +9 -0
  12. package/esm/node/exec-remote-source.js.map +1 -0
  13. package/esm/node/exec-rpc.d.ts +21 -3
  14. package/esm/node/exec-rpc.js +14 -3
  15. package/esm/node/exec-rpc.js.map +1 -1
  16. package/esm/node/exec-server.d.ts +2 -26
  17. package/esm/node/exec-server.js +3 -132
  18. package/esm/node/exec-server.js.map +1 -1
  19. package/esm/node/exec-stdio.d.ts +27 -0
  20. package/esm/node/exec-stdio.js +60 -0
  21. package/esm/node/exec-stdio.js.map +1 -0
  22. package/esm/node/index.d.ts +8 -0
  23. package/esm/node/index.js +8 -0
  24. package/esm/node/index.js.map +1 -1
  25. package/esm/node/local-exec-environment.d.ts +2 -2
  26. package/esm/node/local-exec-environment.js +11 -11
  27. package/esm/node/local-exec-environment.js.map +1 -1
  28. package/esm/node/remote-exec-environment.d.ts +3 -2
  29. package/esm/node/remote-exec-environment.js +41 -2
  30. package/esm/node/remote-exec-environment.js.map +1 -1
  31. package/esm/node/ssh/node-dist.d.ts +20 -0
  32. package/esm/node/ssh/node-dist.js +77 -0
  33. package/esm/node/ssh/node-dist.js.map +1 -0
  34. package/esm/node/ssh/ssh-askpass.d.ts +24 -0
  35. package/esm/node/ssh/ssh-askpass.js +112 -0
  36. package/esm/node/ssh/ssh-askpass.js.map +1 -0
  37. package/esm/node/ssh/ssh-config.d.ts +20 -0
  38. package/esm/node/ssh/ssh-config.js +127 -0
  39. package/esm/node/ssh/ssh-config.js.map +1 -0
  40. package/esm/node/ssh/ssh-host.d.ts +73 -0
  41. package/esm/node/ssh/ssh-host.js +258 -0
  42. package/esm/node/ssh/ssh-host.js.map +1 -0
  43. package/esm/node/ssh/ssh-util.d.ts +45 -0
  44. package/esm/node/ssh/ssh-util.js +110 -0
  45. package/esm/node/ssh/ssh-util.js.map +1 -0
  46. package/lib/node/exec-client.d.ts +28 -11
  47. package/lib/node/exec-client.d.ts.map +1 -1
  48. package/lib/node/exec-client.js +89 -33
  49. package/lib/node/exec-client.js.map +1 -1
  50. package/lib/node/exec-peer.d.ts +41 -0
  51. package/lib/node/exec-peer.d.ts.map +1 -0
  52. package/lib/node/exec-peer.js +171 -0
  53. package/lib/node/exec-peer.js.map +1 -0
  54. package/lib/node/exec-protocol.d.ts +19 -1
  55. package/lib/node/exec-protocol.d.ts.map +1 -1
  56. package/lib/node/exec-remote-source.d.ts +6 -0
  57. package/lib/node/exec-remote-source.d.ts.map +1 -0
  58. package/lib/node/exec-remote-source.js +10 -0
  59. package/lib/node/exec-remote-source.js.map +1 -0
  60. package/lib/node/exec-rpc.d.ts +21 -3
  61. package/lib/node/exec-rpc.d.ts.map +1 -1
  62. package/lib/node/exec-rpc.js +14 -3
  63. package/lib/node/exec-rpc.js.map +1 -1
  64. package/lib/node/exec-server.d.ts +2 -26
  65. package/lib/node/exec-server.d.ts.map +1 -1
  66. package/lib/node/exec-server.js +4 -134
  67. package/lib/node/exec-server.js.map +1 -1
  68. package/lib/node/exec-server.spec.js +4 -1
  69. package/lib/node/exec-server.spec.js.map +1 -1
  70. package/lib/node/exec-stdio.d.ts +28 -0
  71. package/lib/node/exec-stdio.d.ts.map +1 -0
  72. package/lib/node/exec-stdio.js +64 -0
  73. package/lib/node/exec-stdio.js.map +1 -0
  74. package/lib/node/exec-stdio.spec.d.ts +2 -0
  75. package/lib/node/exec-stdio.spec.d.ts.map +1 -0
  76. package/lib/node/exec-stdio.spec.js +106 -0
  77. package/lib/node/exec-stdio.spec.js.map +1 -0
  78. package/lib/node/index.d.ts +8 -0
  79. package/lib/node/index.d.ts.map +1 -1
  80. package/lib/node/index.js +8 -0
  81. package/lib/node/index.js.map +1 -1
  82. package/lib/node/local-exec-environment.d.ts +2 -2
  83. package/lib/node/local-exec-environment.d.ts.map +1 -1
  84. package/lib/node/local-exec-environment.js +10 -10
  85. package/lib/node/local-exec-environment.js.map +1 -1
  86. package/lib/node/local-exec-environment.spec.js +2 -0
  87. package/lib/node/local-exec-environment.spec.js.map +1 -1
  88. package/lib/node/remote-exec-environment.d.ts +3 -2
  89. package/lib/node/remote-exec-environment.d.ts.map +1 -1
  90. package/lib/node/remote-exec-environment.js +41 -2
  91. package/lib/node/remote-exec-environment.js.map +1 -1
  92. package/lib/node/ssh/node-dist.d.ts +21 -0
  93. package/lib/node/ssh/node-dist.d.ts.map +1 -0
  94. package/lib/node/ssh/node-dist.js +80 -0
  95. package/lib/node/ssh/node-dist.js.map +1 -0
  96. package/lib/node/ssh/ssh-askpass.d.ts +25 -0
  97. package/lib/node/ssh/ssh-askpass.d.ts.map +1 -0
  98. package/lib/node/ssh/ssh-askpass.js +114 -0
  99. package/lib/node/ssh/ssh-askpass.js.map +1 -0
  100. package/lib/node/ssh/ssh-config.d.ts +21 -0
  101. package/lib/node/ssh/ssh-config.d.ts.map +1 -0
  102. package/lib/node/ssh/ssh-config.js +130 -0
  103. package/lib/node/ssh/ssh-config.js.map +1 -0
  104. package/lib/node/ssh/ssh-host.d.ts +74 -0
  105. package/lib/node/ssh/ssh-host.d.ts.map +1 -0
  106. package/lib/node/ssh/ssh-host.js +262 -0
  107. package/lib/node/ssh/ssh-host.js.map +1 -0
  108. package/lib/node/ssh/ssh-host.spec.d.ts +2 -0
  109. package/lib/node/ssh/ssh-host.spec.d.ts.map +1 -0
  110. package/lib/node/ssh/ssh-host.spec.js +182 -0
  111. package/lib/node/ssh/ssh-host.spec.js.map +1 -0
  112. package/lib/node/ssh/ssh-util.d.ts +46 -0
  113. package/lib/node/ssh/ssh-util.d.ts.map +1 -0
  114. package/lib/node/ssh/ssh-util.js +113 -0
  115. package/lib/node/ssh/ssh-util.js.map +1 -0
  116. package/lib/node/ssh/ssh-util.spec.d.ts +2 -0
  117. package/lib/node/ssh/ssh-util.spec.d.ts.map +1 -0
  118. package/lib/node/ssh/ssh-util.spec.js +87 -0
  119. package/lib/node/ssh/ssh-util.spec.js.map +1 -0
  120. package/package.json +3 -3
  121. package/src/node/exec-client.ts +108 -39
  122. package/src/node/exec-peer.ts +186 -0
  123. package/src/node/exec-protocol.ts +21 -1
  124. package/src/node/exec-remote-source.ts +7 -0
  125. package/src/node/exec-rpc.ts +23 -3
  126. package/src/node/exec-server.spec.ts +4 -1
  127. package/src/node/exec-server.ts +4 -140
  128. package/src/node/exec-stdio.spec.ts +108 -0
  129. package/src/node/exec-stdio.ts +75 -0
  130. package/src/node/index.ts +8 -0
  131. package/src/node/local-exec-environment.spec.ts +2 -0
  132. package/src/node/local-exec-environment.ts +11 -10
  133. package/src/node/remote-exec-environment.ts +41 -3
  134. package/src/node/ssh/node-dist.ts +83 -0
  135. package/src/node/ssh/ssh-askpass.ts +117 -0
  136. package/src/node/ssh/ssh-config.ts +128 -0
  137. package/src/node/ssh/ssh-host.spec.ts +189 -0
  138. package/src/node/ssh/ssh-host.ts +300 -0
  139. package/src/node/ssh/ssh-util.spec.ts +97 -0
  140. package/src/node/ssh/ssh-util.ts +127 -0
@@ -3,9 +3,8 @@ import { createServer, type IncomingMessage, type Server } from 'node:http';
3
3
  import type { AddressInfo } from 'node:net';
4
4
  import type { Duplex } from 'node:stream';
5
5
  import { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
6
- import type { ExecProcess } from './exec-protocol';
6
+ import { ExecPeer, type ExecPeerServer } from './exec-peer';
7
7
  import { ExecRpc } from './exec-rpc';
8
- import { LocalExecEnvironment } from './local-exec-environment';
9
8
 
10
9
  export interface ExecServerOptions {
11
10
  /** Default 127.0.0.1. */
@@ -20,14 +19,12 @@ export interface ExecServerOptions {
20
19
  maxPayload?: number;
21
20
  }
22
21
 
23
- type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
24
-
25
22
  /**
26
23
  * `ta exec-server`: runs the commands and file operations of a host's sessions on this machine, which
27
24
  * may be a container or a sandbox: the security boundary is the machine, as pi's is. Processes belong
28
25
  * to the connection that started them and end with it.
29
26
  */
30
- export class ExecServer {
27
+ export class ExecServer implements ExecPeerServer {
31
28
  protected server?: Server;
32
29
  /** The largest epoch a host connected with. */
33
30
  protected epoch = 0;
@@ -94,7 +91,8 @@ export class ExecServer {
94
91
  return;
95
92
  }
96
93
  const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: this.options.maxPayload ?? 67108864, heartbeat: 30000 });
97
- const peer = new ExecPeer(this, connection);
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));
98
96
  this.peers.add(peer);
99
97
  connection.onClose(() => {
100
98
  this.peers.delete(peer);
@@ -107,137 +105,3 @@ export class ExecServer {
107
105
  return left.length === right.length && timingSafeEqual(left, right);
108
106
  }
109
107
  }
110
-
111
- /** One host connection: its calls, and the processes it started. */
112
- export class ExecPeer {
113
- epoch?: number;
114
- protected readonly running = new Map<number, AbortController>();
115
- protected readonly spawned = new Map<number, ExecProcess>();
116
-
117
- constructor(
118
- protected readonly server: ExecServer,
119
- protected readonly connection: WebSocketConnection,
120
- ) {
121
- connection.onMessage(text => void this.receive(text));
122
- }
123
-
124
- close(code: number, reason: string): void {
125
- this.dispose();
126
- this.connection.close(code, reason);
127
- }
128
-
129
- /** Ends what this host started. */
130
- dispose(): void {
131
- for (const controller of this.running.values()) {
132
- controller.abort();
133
- }
134
- for (const child of this.spawned.values()) {
135
- child.kill();
136
- }
137
- this.running.clear();
138
- this.spawned.clear();
139
- }
140
-
141
- protected async receive(text: string): Promise<void> {
142
- let message: ExecRpc.Message;
143
- try {
144
- message = JSON.parse(text);
145
- } catch {
146
- this.connection.close(1007, 'Not JSON.');
147
- return;
148
- }
149
- const { id, method, params } = message;
150
- let reply: ExecRpc.Message;
151
- if (method === ExecRpc.Method.INITIALIZE) {
152
- reply = this.initialize(id, params);
153
- } else if (this.epoch === undefined) {
154
- reply = ExecRpc.error(id, ExecRpc.ErrorCode.NOT_INITIALIZED, 'Call initialize first.');
155
- } else if (!this.server.isCurrent(this.epoch)) {
156
- reply = ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch took over.');
157
- } else {
158
- try {
159
- reply = { jsonrpc: '2.0', id, result: (await this.call(method as Method, params)) ?? null };
160
- } catch (error) {
161
- reply = ExecRpc.error(id, ExecRpc.ErrorCode.FAILED, error instanceof Error ? error.message : String(error));
162
- }
163
- }
164
- if (id !== undefined) {
165
- this.send(reply);
166
- }
167
- }
168
-
169
- protected initialize(id: number | undefined, params: ExecRpc.InitializeParams): ExecRpc.Message {
170
- if (typeof params?.epoch !== 'number' || !this.server.admit(this, params.epoch)) {
171
- return ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch is connected.');
172
- }
173
- this.epoch = params.epoch;
174
- const result: ExecRpc.InitializeResult = { platform: process.platform, cwd: this.server.cwd };
175
- return { jsonrpc: '2.0', id, result };
176
- }
177
-
178
- protected async call(method: Method, params: any): Promise<unknown> {
179
- const environment = new LocalExecEnvironment(params.root ?? this.server.cwd);
180
- switch (method) {
181
- case ExecRpc.Method.EXEC:
182
- return this.exec(environment, params);
183
- case ExecRpc.Method.SPAWN:
184
- return this.spawn(environment, params);
185
- case ExecRpc.Method.WRITE:
186
- this.spawned.get(params.id)?.write(ExecRpc.fromBase64(params.data));
187
- return;
188
- case ExecRpc.Method.KILL:
189
- this.running.get(params.id)?.abort();
190
- this.spawned.get(params.id)?.kill();
191
- return;
192
- case ExecRpc.Method.READ_FILE:
193
- return ExecRpc.toBase64(await environment.readFile(params.path));
194
- case ExecRpc.Method.WRITE_FILE:
195
- return environment.writeFile(params.path, ExecRpc.fromBase64(params.data));
196
- case ExecRpc.Method.STAT:
197
- return environment.stat(params.path);
198
- case ExecRpc.Method.READDIR:
199
- return environment.readdir(params.path);
200
- case ExecRpc.Method.MKDIR:
201
- return environment.mkdir(params.path);
202
- case ExecRpc.Method.REMOVE:
203
- return environment.remove(params.path, { recursive: params.recursive });
204
- default:
205
- throw new Error(`No method ${method}.`);
206
- }
207
- }
208
-
209
- protected async exec(environment: LocalExecEnvironment, params: ExecRpc.ExecParams): Promise<unknown> {
210
- const controller = new AbortController();
211
- this.running.set(params.id, controller);
212
- try {
213
- return await environment.exec(params.command, {
214
- cwd: params.cwd,
215
- env: { ...process.env, ...params.env },
216
- timeout: params.timeout,
217
- signal: controller.signal,
218
- onData: data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }),
219
- });
220
- } finally {
221
- this.running.delete(params.id);
222
- }
223
- }
224
-
225
- protected spawn(environment: LocalExecEnvironment, params: ExecRpc.SpawnParams): void {
226
- const child = environment.spawn(params.command, params.args, { cwd: params.cwd, env: { ...process.env, ...params.env } });
227
- this.spawned.set(params.id, child);
228
- child.onStdout(data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }));
229
- child.onStderr(data => this.notify(ExecRpc.Notification.STDERR, { id: params.id, data: ExecRpc.toBase64(data) }));
230
- child.onExit(exitCode => {
231
- this.spawned.delete(params.id);
232
- this.notify(ExecRpc.Notification.EXIT, { id: params.id, exitCode });
233
- });
234
- }
235
-
236
- protected notify(method: string, params: unknown): void {
237
- this.send({ jsonrpc: '2.0', method, params });
238
- }
239
-
240
- protected send(message: ExecRpc.Message): void {
241
- this.connection.send(JSON.stringify(message));
242
- }
243
- }
@@ -0,0 +1,108 @@
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
+ });
@@ -0,0 +1,75 @@
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 CHANGED
@@ -1,6 +1,14 @@
1
1
  export * from './exec-client';
2
+ export * from './exec-peer';
2
3
  export * from './exec-protocol';
4
+ export * from './exec-remote-source';
3
5
  export * from './exec-rpc';
4
6
  export * from './exec-server';
7
+ export * from './exec-stdio';
5
8
  export * from './local-exec-environment';
6
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';
@@ -50,6 +50,8 @@ describe('LocalExecEnvironment', () => {
50
50
  await env.mkdir('a/b');
51
51
  await env.writeFile('a/b/c.txt', 'data');
52
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-.');
53
55
  expect(await env.readdir('a')).toEqual([{ name: 'b', isDirectory: true }]);
54
56
  expect((await env.stat('a/b'))?.isDirectory).toBe(true);
55
57
  await env.remove('a', { recursive: true });
@@ -1,7 +1,7 @@
1
1
  import { type ChildProcess, spawn } from 'node:child_process';
2
- import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { appendFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
3
3
  import { resolve } from 'node:path';
4
- import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, FileStat, SpawnOptions } from './exec-protocol';
4
+ import type { DirEntry, ExecEnvironment, ExecOptions, ExecProcess, ExecResult, FileStat, SpawnOptions, WriteFileOptions } from './exec-protocol';
5
5
 
6
6
  /** This machine. */
7
7
  export class LocalExecEnvironment implements ExecEnvironment {
@@ -61,8 +61,8 @@ export class LocalExecEnvironment implements ExecEnvironment {
61
61
  return readFile(this.resolve(path));
62
62
  }
63
63
 
64
- writeFile(path: string, data: Uint8Array | string): Promise<void> {
65
- return writeFile(this.resolve(path), data);
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
66
  }
67
67
 
68
68
  async stat(path: string): Promise<FileStat | undefined> {
@@ -98,14 +98,15 @@ export class LocalExecEnvironment implements ExecEnvironment {
98
98
  if (child.pid === undefined) {
99
99
  return;
100
100
  }
101
- try {
102
- if (process.platform === 'win32') {
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, WriteFileOptions } from './exec-protocol';
3
3
  import { ExecRpc } from './exec-rpc';
4
4
 
5
5
  type Listener<T extends unknown[]> = (...args: T) => void;
@@ -81,8 +81,8 @@ export class RemoteExecEnvironment implements ExecEnvironment {
81
81
  return ExecRpc.fromBase64(await this.client.call<string>(ExecRpc.Method.READ_FILE, this.path(path)));
82
82
  }
83
83
 
84
- writeFile(path: string, data: Uint8Array | string): Promise<void> {
85
- return this.client.call(ExecRpc.Method.WRITE_FILE, { ...this.path(path), data: ExecRpc.toBase64(data) });
84
+ writeFile(path: string, data: Uint8Array | string, options: WriteFileOptions = {}): Promise<void> {
85
+ return this.client.call(ExecRpc.Method.WRITE_FILE, { ...this.path(path), data: ExecRpc.toBase64(data), ...(options.append ? { append: true } : {}) });
86
86
  }
87
87
 
88
88
  async stat(path: string): Promise<FileStat | undefined> {
@@ -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
+ }