@celljs/ta-exec 4.6.1 → 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
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { connect, type Socket } from 'node:net';
|
|
2
|
+
import type { ExecProcess } from './exec-protocol';
|
|
3
|
+
import { ExecRpc } from './exec-rpc';
|
|
4
|
+
import { LocalExecEnvironment } from './local-exec-environment';
|
|
5
|
+
|
|
6
|
+
type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
|
|
7
|
+
|
|
8
|
+
/** What a peer needs of its server: the default directory, and which host may run things now. */
|
|
9
|
+
export interface ExecPeerServer {
|
|
10
|
+
readonly cwd: string;
|
|
11
|
+
/** False when a newer host has taken over. */
|
|
12
|
+
admit(peer: ExecPeer, epoch: number): boolean;
|
|
13
|
+
isCurrent(epoch: number | undefined): boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** How a peer answers its host: a WebSocket, or the standard output. */
|
|
17
|
+
export interface ExecPeerChannel {
|
|
18
|
+
send(text: string): void;
|
|
19
|
+
close(code: number, reason: string): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One host connection: its calls, and the processes and TCP connections it started. */
|
|
23
|
+
export class ExecPeer {
|
|
24
|
+
epoch?: number;
|
|
25
|
+
protected readonly running = new Map<number, AbortController>();
|
|
26
|
+
protected readonly spawned = new Map<number, ExecProcess>();
|
|
27
|
+
protected readonly sockets = new Map<number, Socket>();
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
protected readonly server: ExecPeerServer,
|
|
31
|
+
protected readonly channel: ExecPeerChannel,
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
close(code: number, reason: string): void {
|
|
35
|
+
this.dispose();
|
|
36
|
+
this.channel.close(code, reason);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Ends what this host started. */
|
|
40
|
+
dispose(): void {
|
|
41
|
+
for (const controller of this.running.values()) {
|
|
42
|
+
controller.abort();
|
|
43
|
+
}
|
|
44
|
+
for (const child of this.spawned.values()) {
|
|
45
|
+
child.kill();
|
|
46
|
+
}
|
|
47
|
+
for (const socket of this.sockets.values()) {
|
|
48
|
+
socket.destroy();
|
|
49
|
+
}
|
|
50
|
+
this.running.clear();
|
|
51
|
+
this.spawned.clear();
|
|
52
|
+
this.sockets.clear();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async receive(text: string): Promise<void> {
|
|
56
|
+
let message: ExecRpc.Message;
|
|
57
|
+
try {
|
|
58
|
+
message = JSON.parse(text);
|
|
59
|
+
} catch {
|
|
60
|
+
this.close(1007, 'Not JSON.');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const { id, method, params } = message;
|
|
64
|
+
if (method === ExecRpc.PING) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
let reply: ExecRpc.Message;
|
|
68
|
+
if (method === ExecRpc.Method.INITIALIZE) {
|
|
69
|
+
reply = this.initialize(id, params);
|
|
70
|
+
} else if (this.epoch === undefined) {
|
|
71
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.NOT_INITIALIZED, 'Call initialize first.');
|
|
72
|
+
} else if (!this.server.isCurrent(this.epoch)) {
|
|
73
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch took over.');
|
|
74
|
+
} else {
|
|
75
|
+
try {
|
|
76
|
+
reply = { jsonrpc: '2.0', id, result: (await this.call(method as Method, params)) ?? null };
|
|
77
|
+
} catch (error) {
|
|
78
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.FAILED, error instanceof Error ? error.message : String(error));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (id !== undefined) {
|
|
82
|
+
this.send(reply);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
protected initialize(id: number | undefined, params: ExecRpc.InitializeParams): ExecRpc.Message {
|
|
87
|
+
if (typeof params?.epoch !== 'number' || !this.server.admit(this, params.epoch)) {
|
|
88
|
+
return ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch is connected.');
|
|
89
|
+
}
|
|
90
|
+
this.epoch = params.epoch;
|
|
91
|
+
const result: ExecRpc.InitializeResult = { platform: process.platform, cwd: this.server.cwd };
|
|
92
|
+
return { jsonrpc: '2.0', id, result };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
protected async call(method: Method, params: any): Promise<unknown> {
|
|
96
|
+
const environment = new LocalExecEnvironment(params.root ?? this.server.cwd);
|
|
97
|
+
switch (method) {
|
|
98
|
+
case ExecRpc.Method.EXEC:
|
|
99
|
+
return this.exec(environment, params);
|
|
100
|
+
case ExecRpc.Method.SPAWN:
|
|
101
|
+
return this.spawn(environment, params);
|
|
102
|
+
case ExecRpc.Method.WRITE:
|
|
103
|
+
this.spawned.get(params.id)?.write(ExecRpc.fromBase64(params.data));
|
|
104
|
+
return;
|
|
105
|
+
case ExecRpc.Method.KILL:
|
|
106
|
+
this.running.get(params.id)?.abort();
|
|
107
|
+
this.spawned.get(params.id)?.kill();
|
|
108
|
+
return;
|
|
109
|
+
case ExecRpc.Method.READ_FILE:
|
|
110
|
+
return ExecRpc.toBase64(await environment.readFile(params.path));
|
|
111
|
+
case ExecRpc.Method.WRITE_FILE:
|
|
112
|
+
return environment.writeFile(params.path, ExecRpc.fromBase64(params.data));
|
|
113
|
+
case ExecRpc.Method.STAT:
|
|
114
|
+
return environment.stat(params.path);
|
|
115
|
+
case ExecRpc.Method.READDIR:
|
|
116
|
+
return environment.readdir(params.path);
|
|
117
|
+
case ExecRpc.Method.MKDIR:
|
|
118
|
+
return environment.mkdir(params.path);
|
|
119
|
+
case ExecRpc.Method.REMOVE:
|
|
120
|
+
return environment.remove(params.path, { recursive: params.recursive });
|
|
121
|
+
case ExecRpc.Method.NET_CONNECT:
|
|
122
|
+
return this.connect(params);
|
|
123
|
+
case ExecRpc.Method.NET_WRITE:
|
|
124
|
+
this.sockets.get(params.id)?.write(ExecRpc.fromBase64(params.data));
|
|
125
|
+
return;
|
|
126
|
+
case ExecRpc.Method.NET_CLOSE:
|
|
127
|
+
this.sockets.get(params.id)?.end();
|
|
128
|
+
return;
|
|
129
|
+
default:
|
|
130
|
+
throw new Error(`No method ${method}.`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
protected async exec(environment: LocalExecEnvironment, params: ExecRpc.ExecParams): Promise<unknown> {
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
this.running.set(params.id, controller);
|
|
137
|
+
try {
|
|
138
|
+
return await environment.exec(params.command, {
|
|
139
|
+
cwd: params.cwd,
|
|
140
|
+
env: { ...process.env, ...params.env },
|
|
141
|
+
timeout: params.timeout,
|
|
142
|
+
signal: controller.signal,
|
|
143
|
+
onData: data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }),
|
|
144
|
+
});
|
|
145
|
+
} finally {
|
|
146
|
+
this.running.delete(params.id);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
protected spawn(environment: LocalExecEnvironment, params: ExecRpc.SpawnParams): void {
|
|
151
|
+
const child = environment.spawn(params.command, params.args, { cwd: params.cwd, env: { ...process.env, ...params.env } });
|
|
152
|
+
this.spawned.set(params.id, child);
|
|
153
|
+
child.onStdout(data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
154
|
+
child.onStderr(data => this.notify(ExecRpc.Notification.STDERR, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
155
|
+
child.onExit(exitCode => {
|
|
156
|
+
this.spawned.delete(params.id);
|
|
157
|
+
this.notify(ExecRpc.Notification.EXIT, { id: params.id, exitCode });
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Resolves once connected; the data comes as notifications, the end as NET_CLOSED. */
|
|
162
|
+
protected connect(params: ExecRpc.ConnectParams): Promise<void> {
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
const socket = connect({ port: params.port, host: params.host ?? '127.0.0.1' });
|
|
165
|
+
socket.once('connect', () => {
|
|
166
|
+
this.sockets.set(params.id, socket);
|
|
167
|
+
resolve();
|
|
168
|
+
});
|
|
169
|
+
socket.on('data', data => this.notify(ExecRpc.Notification.NET_DATA, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
170
|
+
socket.once('error', reject);
|
|
171
|
+
socket.once('close', () => {
|
|
172
|
+
if (this.sockets.delete(params.id)) {
|
|
173
|
+
this.notify(ExecRpc.Notification.NET_CLOSED, { id: params.id });
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
protected notify(method: string, params: unknown): void {
|
|
180
|
+
this.send({ jsonrpc: '2.0', method, params });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
protected send(message: ExecRpc.Message): void {
|
|
184
|
+
this.channel.send(JSON.stringify(message));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -30,6 +30,16 @@ export interface ExecProcess {
|
|
|
30
30
|
kill(): void;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** A TCP connection made from inside an environment. */
|
|
34
|
+
export interface ExecSocket {
|
|
35
|
+
write(data: Uint8Array): void;
|
|
36
|
+
/** Ends the connection; `onClose` follows. */
|
|
37
|
+
end(): void;
|
|
38
|
+
onData(listener: (data: Uint8Array) => void): void;
|
|
39
|
+
/** Once, when either side ended it or the environment was lost. */
|
|
40
|
+
onClose(listener: () => void): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
33
43
|
export interface FileStat {
|
|
34
44
|
isDirectory: boolean;
|
|
35
45
|
size: number;
|
|
@@ -59,6 +69,11 @@ export interface ExecEnvironment {
|
|
|
59
69
|
readdir(path: string): Promise<DirEntry[]>;
|
|
60
70
|
mkdir(path: string): Promise<void>;
|
|
61
71
|
remove(path: string, options?: { recursive?: boolean }): Promise<void>;
|
|
72
|
+
/**
|
|
73
|
+
* A TCP connection to a port of the environment's machine (default host 127.0.0.1), for one only
|
|
74
|
+
* reachable there; only environments on another machine have it. Rejects when nothing listens.
|
|
75
|
+
*/
|
|
76
|
+
connect?(port: number, host?: string): Promise<ExecSocket>;
|
|
62
77
|
}
|
|
63
78
|
|
|
64
79
|
/** Bind another implementation with `rebind: true` to run sessions elsewhere. */
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Generated by scripts/remote-server.ts from scripts/remote-main.ts: do not edit.
|
|
2
|
+
|
|
3
|
+
/** `ta exec-server` on stdio in one script for Node.js 18, and the hash that names its version. */
|
|
4
|
+
export const EXEC_REMOTE_SOURCE = {
|
|
5
|
+
hash: "f84cb6eb0c85a661",
|
|
6
|
+
script: "var T=require(\"node:net\");var H;((X)=>{X.PATH=\"/exec\",X.Method={INITIALIZE:\"initialize\",EXEC:\"process/exec\",SPAWN:\"process/spawn\",WRITE:\"process/write\",KILL:\"process/kill\",READ_FILE:\"fs/readFile\",WRITE_FILE:\"fs/writeFile\",STAT:\"fs/stat\",READDIR:\"fs/readdir\",MKDIR:\"fs/mkdir\",REMOVE:\"fs/remove\",NET_CONNECT:\"net/connect\",NET_WRITE:\"net/write\",NET_CLOSE:\"net/close\"},X.PING=\"ping\",X.Notification={OUTPUT:\"process/output\",STDERR:\"process/stderr\",EXIT:\"process/exit\",NET_DATA:\"net/data\",NET_CLOSED:\"net/closed\"},X.ErrorCode={STALE_EPOCH:\"CELL_TA_EXEC_STALE_EPOCH\",NOT_INITIALIZED:\"CELL_TA_EXEC_NOT_INITIALIZED\",FAILED:\"CELL_TA_EXEC_FAILED\",CONNECTION_LOST:\"CELL_TA_EXEC_CONNECTION_LOST\"},X.ERROR=-32060;function Q(U,q,B){return{jsonrpc:\"2.0\",id:U,error:{code:-32060,message:B,data:{code:q}}}}X.error=Q;function $(U){return Buffer.from(U).toString(\"base64\")}X.toBase64=$;function Z(U){return Buffer.from(U,\"base64\")}X.fromBase64=Z})(H||={});var O=require(\"node:child_process\"),Y=require(\"node:fs/promises\"),I=require(\"node:path\");class P{cwd;local=!0;constructor(A){this.cwd=A}exec(A,z={}){let[G,...J]=process.platform===\"win32\"?[\"cmd.exe\",\"/d\",\"/s\",\"/c\"]:[\"/bin/sh\",\"-c\"],K=O.spawn(G,[...J,A],{cwd:I.resolve(this.cwd,z.cwd??\".\"),env:z.env??process.env,stdio:[\"ignore\",\"pipe\",\"pipe\"],detached:process.platform!==\"win32\"});return new Promise((V)=>{let Q=()=>this.killGroup(K),$=z.timeout?setTimeout(Q,z.timeout):void 0;if(z.signal?.addEventListener(\"abort\",Q,{once:!0}),z.signal?.aborted)Q();K.stdout?.on(\"data\",(U)=>z.onData?.(U)),K.stderr?.on(\"data\",(U)=>z.onData?.(U));let Z=(U)=>{clearTimeout($),z.signal?.removeEventListener(\"abort\",Q),V({exitCode:U})};K.once(\"error\",()=>Z(null)),K.once(\"close\",Z)})}spawn(A,z,G={}){let J=O.spawn(A,z,{cwd:I.resolve(this.cwd,G.cwd??\".\"),env:G.env??process.env,stdio:[\"pipe\",\"pipe\",\"pipe\"]});return J.stdin.on(\"error\",()=>{return}),{write:(K)=>J.stdin.write(K),onStdout:(K)=>J.stdout.on(\"data\",K),onStderr:(K)=>J.stderr.on(\"data\",K),onExit:(K)=>{J.once(\"error\",()=>K(null)),J.once(\"close\",K)},kill:()=>J.kill()}}readFile(A){return Y.readFile(this.resolve(A))}writeFile(A,z){return Y.writeFile(this.resolve(A),z)}async stat(A){try{let z=await Y.stat(this.resolve(A));return{isDirectory:z.isDirectory(),size:z.size,mtimeMs:z.mtimeMs}}catch(z){if(z.code===\"ENOENT\")return;throw z}}async readdir(A){return(await Y.readdir(this.resolve(A),{withFileTypes:!0})).map((G)=>({name:G.name,isDirectory:G.isDirectory()}))}async mkdir(A){await Y.mkdir(this.resolve(A),{recursive:!0})}remove(A,z={}){return Y.rm(this.resolve(A),{recursive:z.recursive,force:!0})}resolve(A){return I.resolve(this.cwd,A)}killGroup(A){if(A.pid===void 0)return;if(process.platform!==\"win32\")try{process.kill(-A.pid,\"SIGKILL\");return}catch{}A.kill(\"SIGKILL\")}}class W{server;channel;epoch;running=new Map;spawned=new Map;sockets=new Map;constructor(A,z){this.server=A;this.channel=z}close(A,z){this.dispose(),this.channel.close(A,z)}dispose(){for(let A of this.running.values())A.abort();for(let A of this.spawned.values())A.kill();for(let A of this.sockets.values())A.destroy();this.running.clear(),this.spawned.clear(),this.sockets.clear()}async receive(A){let z;try{z=JSON.parse(A)}catch{this.close(1007,\"Not JSON.\");return}let{id:G,method:J,params:K}=z;if(J===H.PING)return;let V;if(J===H.Method.INITIALIZE)V=this.initialize(G,K);else if(this.epoch===void 0)V=H.error(G,H.ErrorCode.NOT_INITIALIZED,\"Call initialize first.\");else if(!this.server.isCurrent(this.epoch))V=H.error(G,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch took over.\");else try{V={jsonrpc:\"2.0\",id:G,result:await this.call(J,K)??null}}catch(Q){V=H.error(G,H.ErrorCode.FAILED,Q instanceof Error?Q.message:String(Q))}if(G!==void 0)this.send(V)}initialize(A,z){if(typeof z?.epoch!==\"number\"||!this.server.admit(this,z.epoch))return H.error(A,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch is connected.\");this.epoch=z.epoch;let G={platform:process.platform,cwd:this.server.cwd};return{jsonrpc:\"2.0\",id:A,result:G}}async call(A,z){let G=new P(z.root??this.server.cwd);switch(A){case H.Method.EXEC:return this.exec(G,z);case H.Method.SPAWN:return this.spawn(G,z);case H.Method.WRITE:this.spawned.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.KILL:this.running.get(z.id)?.abort(),this.spawned.get(z.id)?.kill();return;case H.Method.READ_FILE:return H.toBase64(await G.readFile(z.path));case H.Method.WRITE_FILE:return G.writeFile(z.path,H.fromBase64(z.data));case H.Method.STAT:return G.stat(z.path);case H.Method.READDIR:return G.readdir(z.path);case H.Method.MKDIR:return G.mkdir(z.path);case H.Method.REMOVE:return G.remove(z.path,{recursive:z.recursive});case H.Method.NET_CONNECT:return this.connect(z);case H.Method.NET_WRITE:this.sockets.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.NET_CLOSE:this.sockets.get(z.id)?.end();return;default:throw Error(`No method ${A}.`)}}async exec(A,z){let G=new AbortController;this.running.set(z.id,G);try{return await A.exec(z.command,{cwd:z.cwd,env:{...process.env,...z.env},timeout:z.timeout,signal:G.signal,onData:(J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})})}finally{this.running.delete(z.id)}}spawn(A,z){let G=A.spawn(z.command,z.args,{cwd:z.cwd,env:{...process.env,...z.env}});this.spawned.set(z.id,G),G.onStdout((J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})),G.onStderr((J)=>this.notify(H.Notification.STDERR,{id:z.id,data:H.toBase64(J)})),G.onExit((J)=>{this.spawned.delete(z.id),this.notify(H.Notification.EXIT,{id:z.id,exitCode:J})})}connect(A){return new Promise((z,G)=>{let J=T.connect({port:A.port,host:A.host??\"127.0.0.1\"});J.once(\"connect\",()=>{this.sockets.set(A.id,J),z()}),J.on(\"data\",(K)=>this.notify(H.Notification.NET_DATA,{id:A.id,data:H.toBase64(K)})),J.once(\"error\",G),J.once(\"close\",()=>{if(this.sockets.delete(A.id))this.notify(H.Notification.NET_CLOSED,{id:A.id})})})}notify(A,z){this.send({jsonrpc:\"2.0\",method:A,params:z})}send(A){this.channel.send(JSON.stringify(A))}}class F{options;cwd;epoch;constructor(A){this.options=A;this.cwd=A.cwd??process.cwd()}serve(){let{input:A,output:z,idleMs:G}=this.options;return new Promise((J)=>{let K,V=\"\",Q=()=>{clearTimeout(K),A.removeListener(\"data\",U),$.dispose(),J()},$=new W(this,{send:(q)=>z.write(`${q}\n`),close:Q}),Z=()=>{if(G)clearTimeout(K),K=setTimeout(Q,G)},U=(q)=>{Z();let B=(V+q.toString()).split(`\n`);V=B.pop()??\"\";for(let N of B)if(N.trim())$.receive(N)};A.on(\"data\",U),A.once(\"end\",Q),A.once(\"error\",Q),Z()})}admit(A,z){if(this.epoch!==void 0&&z<this.epoch)return!1;return this.epoch=z,!0}isCurrent(A){return A===this.epoch}}var b=60000;new F({input:process.stdin,output:process.stdout,idleMs:b}).serve().then(()=>process.exit(0));\n",
|
|
7
|
+
};
|
package/src/node/exec-rpc.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The protocol of `ta exec-server`: JSON-RPC 2.0
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* The protocol of `ta exec-server`: JSON-RPC 2.0, as Codex's exec-server does it, over a WebSocket (one
|
|
3
|
+
* text message each) or over the standard input and output of the server (one line each), which is how
|
|
4
|
+
* it runs at the other end of ssh. The host calls methods; the server sends the output of processes
|
|
5
|
+
* and the data of connections as notifications. Bytes travel as base64.
|
|
5
6
|
*/
|
|
6
7
|
export namespace ExecRpc {
|
|
7
8
|
/** Path of the WebSocket endpoint. */
|
|
@@ -19,14 +20,25 @@ export namespace ExecRpc {
|
|
|
19
20
|
READDIR: 'fs/readdir',
|
|
20
21
|
MKDIR: 'fs/mkdir',
|
|
21
22
|
REMOVE: 'fs/remove',
|
|
23
|
+
/** A TCP connection from the server's machine, for a port only reachable there. */
|
|
24
|
+
NET_CONNECT: 'net/connect',
|
|
25
|
+
NET_WRITE: 'net/write',
|
|
26
|
+
NET_CLOSE: 'net/close',
|
|
22
27
|
} as const;
|
|
23
28
|
|
|
29
|
+
/** Sent by the host, without an id, to say it is still there; over stdio the server ends without it. */
|
|
30
|
+
export const PING = 'ping';
|
|
31
|
+
|
|
24
32
|
export const Notification = {
|
|
25
33
|
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
26
34
|
OUTPUT: 'process/output',
|
|
27
35
|
STDERR: 'process/stderr',
|
|
28
36
|
/** A spawned process ended. */
|
|
29
37
|
EXIT: 'process/exit',
|
|
38
|
+
/** Data a connection of `net/connect` received. */
|
|
39
|
+
NET_DATA: 'net/data',
|
|
40
|
+
/** A connection of `net/connect` ended. */
|
|
41
|
+
NET_CLOSED: 'net/closed',
|
|
30
42
|
} as const;
|
|
31
43
|
|
|
32
44
|
/** `error.data.code` of failed calls. */
|
|
@@ -74,6 +86,14 @@ export namespace ExecRpc {
|
|
|
74
86
|
args: string[];
|
|
75
87
|
}
|
|
76
88
|
|
|
89
|
+
export interface ConnectParams {
|
|
90
|
+
/** Chosen by the host, unique per connection, as the id of a process: the notifications carry it. */
|
|
91
|
+
id: number;
|
|
92
|
+
port: number;
|
|
93
|
+
/** Default 127.0.0.1. */
|
|
94
|
+
host?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
77
97
|
export interface PathParams {
|
|
78
98
|
root: string;
|
|
79
99
|
path: string;
|
|
@@ -24,7 +24,7 @@ describe('ta exec-server', () => {
|
|
|
24
24
|
let url: string;
|
|
25
25
|
|
|
26
26
|
const environment = (epoch = 1, token = TOKEN) => {
|
|
27
|
-
const client = new ExecClient({ url, token, epoch });
|
|
27
|
+
const client = new ExecClient({ connect: ExecClient.webSocket(url, token), epoch });
|
|
28
28
|
clients.push(client);
|
|
29
29
|
return new RemoteExecEnvironment(client, root);
|
|
30
30
|
};
|
package/src/node/exec-server.ts
CHANGED
|
@@ -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
|
|
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,107 @@
|
|
|
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', 'text');
|
|
65
|
+
expect(Buffer.from(await env.readFile('a.txt')).toString()).toBe('text');
|
|
66
|
+
expect((await env.stat('a.txt'))?.size).toBe(4);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('connects to a port of its machine, both ways', async () => {
|
|
70
|
+
const server = createServer(socket => socket.on('data', data => socket.end(`echo:${data}`)));
|
|
71
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
72
|
+
const { port } = server.address() as { port: number };
|
|
73
|
+
try {
|
|
74
|
+
const socket = await environment().connect(port);
|
|
75
|
+
const received: Uint8Array[] = [];
|
|
76
|
+
socket.onData(data => received.push(data));
|
|
77
|
+
const closed = new Promise<void>(resolve => socket.onClose(resolve));
|
|
78
|
+
socket.write(Buffer.from('ping'));
|
|
79
|
+
await closed;
|
|
80
|
+
expect(Buffer.concat(received).toString()).toBe('echo:ping');
|
|
81
|
+
} finally {
|
|
82
|
+
server.close();
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('refuses to connect where nothing listens', async () => {
|
|
87
|
+
const server = createServer();
|
|
88
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
89
|
+
const { port } = server.address() as { port: number };
|
|
90
|
+
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
91
|
+
await expect(environment().connect(port)).rejects.toThrow();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('ends what the host started when its input ends', async () => {
|
|
95
|
+
const env = environment();
|
|
96
|
+
const pidFile = join(root, 'sleep.pid');
|
|
97
|
+
const running = env.exec(`sh -c 'echo $$ > ${pidFile}; exec sleep 30'`);
|
|
98
|
+
for (let i = 0; i < 50 && !(await env.stat('sleep.pid'))?.size; i++) {
|
|
99
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
100
|
+
}
|
|
101
|
+
const pid = Number(Buffer.from(await env.readFile('sleep.pid')).toString());
|
|
102
|
+
clients.at(-1)?.close();
|
|
103
|
+
await expect(running).rejects.toThrow();
|
|
104
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
105
|
+
expect(() => process.kill(pid, 0)).toThrow();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -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';
|