@celljs/ta-exec 4.7.0 → 4.9.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/esm/node/exec-peer.js +1 -1
- package/esm/node/exec-protocol.d.ts +5 -1
- package/esm/node/exec-remote-source.js +2 -2
- package/esm/node/local-exec-environment.d.ts +2 -2
- package/esm/node/local-exec-environment.js +3 -3
- package/esm/node/remote-exec-environment.d.ts +2 -2
- package/esm/node/remote-exec-environment.js +2 -2
- package/lib/node/exec-peer.js +1 -1
- package/lib/node/exec-protocol.d.ts +5 -1
- package/lib/node/exec-remote-source.js +2 -2
- package/lib/node/local-exec-environment.d.ts +2 -2
- package/lib/node/local-exec-environment.js +2 -2
- package/lib/node/remote-exec-environment.d.ts +2 -2
- package/lib/node/remote-exec-environment.js +2 -2
- package/package.json +4 -3
- package/esm/node/exec-client.js.map +0 -1
- package/esm/node/exec-peer.js.map +0 -1
- package/esm/node/exec-protocol.js.map +0 -1
- package/esm/node/exec-remote-source.js.map +0 -1
- package/esm/node/exec-rpc.js.map +0 -1
- package/esm/node/exec-server.js.map +0 -1
- package/esm/node/exec-stdio.js.map +0 -1
- package/esm/node/index.js.map +0 -1
- package/esm/node/local-exec-environment.js.map +0 -1
- package/esm/node/remote-exec-environment.js.map +0 -1
- package/esm/node/ssh/node-dist.js.map +0 -1
- package/esm/node/ssh/ssh-askpass.js.map +0 -1
- package/esm/node/ssh/ssh-config.js.map +0 -1
- package/esm/node/ssh/ssh-host.js.map +0 -1
- package/esm/node/ssh/ssh-util.js.map +0 -1
- package/lib/node/exec-client.d.ts.map +0 -1
- package/lib/node/exec-client.js.map +0 -1
- package/lib/node/exec-peer.d.ts.map +0 -1
- package/lib/node/exec-peer.js.map +0 -1
- package/lib/node/exec-protocol.d.ts.map +0 -1
- package/lib/node/exec-protocol.js.map +0 -1
- package/lib/node/exec-remote-source.d.ts.map +0 -1
- package/lib/node/exec-remote-source.js.map +0 -1
- package/lib/node/exec-rpc.d.ts.map +0 -1
- package/lib/node/exec-rpc.js.map +0 -1
- package/lib/node/exec-server.d.ts.map +0 -1
- package/lib/node/exec-server.js.map +0 -1
- package/lib/node/exec-server.spec.d.ts +0 -2
- package/lib/node/exec-server.spec.d.ts.map +0 -1
- package/lib/node/exec-server.spec.js +0 -101
- package/lib/node/exec-server.spec.js.map +0 -1
- package/lib/node/exec-stdio.d.ts.map +0 -1
- package/lib/node/exec-stdio.js.map +0 -1
- package/lib/node/exec-stdio.spec.d.ts +0 -2
- package/lib/node/exec-stdio.spec.d.ts.map +0 -1
- package/lib/node/exec-stdio.spec.js +0 -105
- package/lib/node/exec-stdio.spec.js.map +0 -1
- package/lib/node/index.d.ts.map +0 -1
- package/lib/node/index.js.map +0 -1
- package/lib/node/local-exec-environment.d.ts.map +0 -1
- package/lib/node/local-exec-environment.js.map +0 -1
- package/lib/node/local-exec-environment.spec.d.ts +0 -2
- package/lib/node/local-exec-environment.spec.d.ts.map +0 -1
- package/lib/node/local-exec-environment.spec.js +0 -55
- package/lib/node/local-exec-environment.spec.js.map +0 -1
- package/lib/node/remote-exec-environment.d.ts.map +0 -1
- package/lib/node/remote-exec-environment.js.map +0 -1
- package/lib/node/ssh/node-dist.d.ts.map +0 -1
- package/lib/node/ssh/node-dist.js.map +0 -1
- package/lib/node/ssh/ssh-askpass.d.ts.map +0 -1
- package/lib/node/ssh/ssh-askpass.js.map +0 -1
- package/lib/node/ssh/ssh-config.d.ts.map +0 -1
- package/lib/node/ssh/ssh-config.js.map +0 -1
- package/lib/node/ssh/ssh-host.d.ts.map +0 -1
- package/lib/node/ssh/ssh-host.js.map +0 -1
- package/lib/node/ssh/ssh-host.spec.d.ts +0 -2
- package/lib/node/ssh/ssh-host.spec.d.ts.map +0 -1
- package/lib/node/ssh/ssh-host.spec.js +0 -182
- package/lib/node/ssh/ssh-host.spec.js.map +0 -1
- package/lib/node/ssh/ssh-util.d.ts.map +0 -1
- package/lib/node/ssh/ssh-util.js.map +0 -1
- package/lib/node/ssh/ssh-util.spec.d.ts +0 -2
- package/lib/node/ssh/ssh-util.spec.d.ts.map +0 -1
- package/lib/node/ssh/ssh-util.spec.js +0 -87
- package/lib/node/ssh/ssh-util.spec.js.map +0 -1
- package/src/node/exec-client.ts +0 -221
- package/src/node/exec-peer.ts +0 -186
- package/src/node/exec-protocol.ts +0 -84
- package/src/node/exec-remote-source.ts +0 -7
- package/src/node/exec-rpc.ts +0 -124
- package/src/node/exec-server.spec.ts +0 -110
- package/src/node/exec-server.ts +0 -107
- package/src/node/exec-stdio.spec.ts +0 -107
- package/src/node/exec-stdio.ts +0 -75
- package/src/node/index.ts +0 -14
- package/src/node/local-exec-environment.spec.ts +0 -58
- package/src/node/local-exec-environment.ts +0 -112
- package/src/node/remote-exec-environment.ts +0 -162
- package/src/node/ssh/node-dist.ts +0 -83
- package/src/node/ssh/ssh-askpass.ts +0 -117
- package/src/node/ssh/ssh-config.ts +0 -128
- package/src/node/ssh/ssh-host.spec.ts +0 -189
- package/src/node/ssh/ssh-host.ts +0 -300
- package/src/node/ssh/ssh-util.spec.ts +0 -97
- package/src/node/ssh/ssh-util.ts +0 -127
package/src/node/exec-peer.ts
DELETED
|
@@ -1,186 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
export const ExecEnvironmentFactory = Symbol('ExecEnvironmentFactory');
|
|
2
|
-
|
|
3
|
-
export interface ExecOptions {
|
|
4
|
-
/** Default: the `cwd` of the environment. */
|
|
5
|
-
cwd?: string;
|
|
6
|
-
env?: NodeJS.ProcessEnv;
|
|
7
|
-
/** Milliseconds; the process is killed afterwards. */
|
|
8
|
-
timeout?: number;
|
|
9
|
-
signal?: AbortSignal;
|
|
10
|
-
onData?: (data: Uint8Array) => void;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface ExecResult {
|
|
14
|
-
/** null when the process was killed. */
|
|
15
|
-
exitCode: number | null;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export interface SpawnOptions {
|
|
19
|
-
cwd?: string;
|
|
20
|
-
env?: NodeJS.ProcessEnv;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** A running program, for long-lived ones that talk over stdin and stdout (MCP servers, language servers). */
|
|
24
|
-
export interface ExecProcess {
|
|
25
|
-
write(data: Uint8Array | string): void;
|
|
26
|
-
onStdout(listener: (data: Uint8Array) => void): void;
|
|
27
|
-
onStderr(listener: (data: Uint8Array) => void): void;
|
|
28
|
-
/** Also called when the program could not start, with a null code. */
|
|
29
|
-
onExit(listener: (exitCode: number | null) => void): void;
|
|
30
|
-
kill(): void;
|
|
31
|
-
}
|
|
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
|
-
|
|
43
|
-
export interface FileStat {
|
|
44
|
-
isDirectory: boolean;
|
|
45
|
-
size: number;
|
|
46
|
-
mtimeMs: number;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export interface DirEntry {
|
|
50
|
-
name: string;
|
|
51
|
-
isDirectory: boolean;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* Where an agent runs commands and touches files. Paths are paths inside this environment, which may
|
|
56
|
-
* be another machine: never hand one to `node:fs`, and hand the model only these.
|
|
57
|
-
*/
|
|
58
|
-
export interface ExecEnvironment {
|
|
59
|
-
/** Working directory, inside the environment. */
|
|
60
|
-
readonly cwd: string;
|
|
61
|
-
/** This machine: pi's own implementations of its tools do the same work, so they stay in use. */
|
|
62
|
-
readonly local: boolean;
|
|
63
|
-
exec(command: string, options?: ExecOptions): Promise<ExecResult>;
|
|
64
|
-
spawn(command: string, args: string[], options?: SpawnOptions): ExecProcess;
|
|
65
|
-
readFile(path: string): Promise<Uint8Array>;
|
|
66
|
-
writeFile(path: string, data: Uint8Array | string): Promise<void>;
|
|
67
|
-
/** undefined when nothing is there. */
|
|
68
|
-
stat(path: string): Promise<FileStat | undefined>;
|
|
69
|
-
readdir(path: string): Promise<DirEntry[]>;
|
|
70
|
-
mkdir(path: string): Promise<void>;
|
|
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>;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Bind another implementation with `rebind: true` to run sessions elsewhere. */
|
|
80
|
-
export interface ExecEnvironmentFactory {
|
|
81
|
-
create(cwd: string): ExecEnvironment;
|
|
82
|
-
/** Where sessions run when nobody names a directory: a path of the environment. */
|
|
83
|
-
defaultCwd(): Promise<string>;
|
|
84
|
-
}
|
|
@@ -1,7 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
/**
|
|
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.
|
|
6
|
-
*/
|
|
7
|
-
export namespace ExecRpc {
|
|
8
|
-
/** Path of the WebSocket endpoint. */
|
|
9
|
-
export const PATH = '/exec';
|
|
10
|
-
|
|
11
|
-
export const Method = {
|
|
12
|
-
INITIALIZE: 'initialize',
|
|
13
|
-
EXEC: 'process/exec',
|
|
14
|
-
SPAWN: 'process/spawn',
|
|
15
|
-
WRITE: 'process/write',
|
|
16
|
-
KILL: 'process/kill',
|
|
17
|
-
READ_FILE: 'fs/readFile',
|
|
18
|
-
WRITE_FILE: 'fs/writeFile',
|
|
19
|
-
STAT: 'fs/stat',
|
|
20
|
-
READDIR: 'fs/readdir',
|
|
21
|
-
MKDIR: 'fs/mkdir',
|
|
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',
|
|
27
|
-
} as const;
|
|
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
|
-
|
|
32
|
-
export const Notification = {
|
|
33
|
-
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
34
|
-
OUTPUT: 'process/output',
|
|
35
|
-
STDERR: 'process/stderr',
|
|
36
|
-
/** A spawned process ended. */
|
|
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',
|
|
42
|
-
} as const;
|
|
43
|
-
|
|
44
|
-
/** `error.data.code` of failed calls. */
|
|
45
|
-
export const ErrorCode = {
|
|
46
|
-
/** A host with a newer epoch connected: this one may no longer run anything. */
|
|
47
|
-
STALE_EPOCH: 'CELL_TA_EXEC_STALE_EPOCH',
|
|
48
|
-
NOT_INITIALIZED: 'CELL_TA_EXEC_NOT_INITIALIZED',
|
|
49
|
-
FAILED: 'CELL_TA_EXEC_FAILED',
|
|
50
|
-
CONNECTION_LOST: 'CELL_TA_EXEC_CONNECTION_LOST',
|
|
51
|
-
} as const;
|
|
52
|
-
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* The epoch fences hosts: when a session moves to another host instance (a restart, a failover), the
|
|
56
|
-
* new one connects with a larger epoch, and the server stops taking calls from smaller ones and kills
|
|
57
|
-
* their processes, so that two hosts never run the same session's tools.
|
|
58
|
-
*/
|
|
59
|
-
export interface InitializeParams {
|
|
60
|
-
epoch: number;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export interface InitializeResult {
|
|
64
|
-
platform: string;
|
|
65
|
-
/** The working directory of the server: where sessions run when nobody names another. */
|
|
66
|
-
cwd: string;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** Every call names the directory of its environment; a relative `cwd` or path resolves against it. */
|
|
70
|
-
export interface ProcessParams {
|
|
71
|
-
root: string;
|
|
72
|
-
/** Chosen by the host, unique per connection: the notifications carry it. */
|
|
73
|
-
id: number;
|
|
74
|
-
cwd?: string;
|
|
75
|
-
/** Only what the host sets on top of the server's own environment, never the host's environment. */
|
|
76
|
-
env?: Record<string, string>;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export interface ExecParams extends ProcessParams {
|
|
80
|
-
command: string;
|
|
81
|
-
timeout?: number;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export interface SpawnParams extends ProcessParams {
|
|
85
|
-
command: string;
|
|
86
|
-
args: string[];
|
|
87
|
-
}
|
|
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
|
-
|
|
97
|
-
export interface PathParams {
|
|
98
|
-
root: string;
|
|
99
|
-
path: string;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export interface Message {
|
|
103
|
-
jsonrpc: '2.0';
|
|
104
|
-
id?: number;
|
|
105
|
-
method?: string;
|
|
106
|
-
params?: any;
|
|
107
|
-
result?: unknown;
|
|
108
|
-
error?: { code: number; message: string; data?: { code: ErrorCode } };
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export const ERROR = -32060;
|
|
112
|
-
|
|
113
|
-
export function error(id: number | undefined, code: ErrorCode, message: string): Message {
|
|
114
|
-
return { jsonrpc: '2.0', id, error: { code: ERROR, message, data: { code } } };
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function toBase64(data: Uint8Array | string): string {
|
|
118
|
-
return Buffer.from(data).toString('base64');
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function fromBase64(data: string): Uint8Array {
|
|
122
|
-
return Buffer.from(data, 'base64');
|
|
123
|
-
}
|
|
124
|
-
}
|
|
@@ -1,110 +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
|
-
expect(Buffer.from(await env.readFile('dir/sub/a.txt')).toString()).toBe('hello');
|
|
74
|
-
expect(await env.stat('dir')).toMatchObject({ isDirectory: true });
|
|
75
|
-
expect(await env.stat('nothing')).toBeUndefined();
|
|
76
|
-
expect(await env.readdir('dir')).toEqual([{ name: 'sub', isDirectory: true }]);
|
|
77
|
-
await env.remove('dir', { recursive: true });
|
|
78
|
-
expect(await env.stat('dir')).toBeUndefined();
|
|
79
|
-
await expect(env.readFile('nothing')).rejects.toThrow('ENOENT');
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it('talks to a long-running program over stdin and stdout', async () => {
|
|
83
|
-
const child = environment().spawn('cat', []);
|
|
84
|
-
const chunks: Uint8Array[] = [];
|
|
85
|
-
child.onStdout(data => chunks.push(data));
|
|
86
|
-
const exited = new Promise<number | null>(resolve => child.onExit(resolve));
|
|
87
|
-
child.write('ping\n');
|
|
88
|
-
for (let i = 0; i < 100 && !text(chunks).includes('ping'); i++) {
|
|
89
|
-
await Bun.sleep(10);
|
|
90
|
-
}
|
|
91
|
-
expect(text(chunks)).toBe('ping\n');
|
|
92
|
-
child.kill();
|
|
93
|
-
expect(await exited).not.toBe(0);
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
it('refuses a host without the token', async () => {
|
|
97
|
-
await expect(environment(1, 'wrong').exec('true')).rejects.toBeInstanceOf(ExecError);
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
it('fences a host once one with a newer epoch connects', async () => {
|
|
101
|
-
const old = environment(10);
|
|
102
|
-
const running = old.exec('sleep 30').catch((error: ExecError) => error);
|
|
103
|
-
await Bun.sleep(100);
|
|
104
|
-
const current = environment(11);
|
|
105
|
-
expect((await current.exec('true')).exitCode).toBe(0);
|
|
106
|
-
expect(await running).toMatchObject({ code: ExecRpc.ErrorCode.CONNECTION_LOST });
|
|
107
|
-
await expect(old.exec('true')).rejects.toMatchObject({ code: ExecRpc.ErrorCode.STALE_EPOCH });
|
|
108
|
-
await expect(old.exec('true')).rejects.toMatchObject({ code: ExecRpc.ErrorCode.STALE_EPOCH });
|
|
109
|
-
});
|
|
110
|
-
});
|
package/src/node/exec-server.ts
DELETED
|
@@ -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
|
-
}
|