@celljs/ta-exec 4.5.0 → 4.6.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.md +24 -2
- package/esm/node/exec-client.d.ts +52 -0
- package/esm/node/exec-client.js +128 -0
- package/esm/node/exec-client.js.map +1 -0
- package/esm/node/exec-protocol.d.ts +2 -0
- package/esm/node/exec-rpc.d.ts +90 -0
- package/esm/node/exec-rpc.js +52 -0
- package/esm/node/exec-rpc.js.map +1 -0
- package/esm/node/exec-server.d.ts +61 -0
- package/esm/node/exec-server.js +217 -0
- package/esm/node/exec-server.js.map +1 -0
- package/esm/node/index.d.ts +4 -0
- package/esm/node/index.js +4 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/remote-exec-environment.d.ts +26 -0
- package/esm/node/remote-exec-environment.js +115 -0
- package/esm/node/remote-exec-environment.js.map +1 -0
- package/lib/node/exec-client.d.ts +53 -0
- package/lib/node/exec-client.d.ts.map +1 -0
- package/lib/node/exec-client.js +133 -0
- package/lib/node/exec-client.js.map +1 -0
- package/lib/node/exec-protocol.d.ts +2 -0
- package/lib/node/exec-protocol.d.ts.map +1 -1
- package/lib/node/exec-rpc.d.ts +91 -0
- package/lib/node/exec-rpc.d.ts.map +1 -0
- package/lib/node/exec-rpc.js +55 -0
- package/lib/node/exec-rpc.js.map +1 -0
- package/lib/node/exec-server.d.ts +62 -0
- package/lib/node/exec-server.d.ts.map +1 -0
- package/lib/node/exec-server.js +222 -0
- package/lib/node/exec-server.js.map +1 -0
- package/lib/node/exec-server.spec.d.ts +2 -0
- package/lib/node/exec-server.spec.d.ts.map +1 -0
- package/lib/node/exec-server.spec.js +101 -0
- package/lib/node/exec-server.spec.js.map +1 -0
- package/lib/node/index.d.ts +4 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +4 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/remote-exec-environment.d.ts +27 -0
- package/lib/node/remote-exec-environment.d.ts.map +1 -0
- package/lib/node/remote-exec-environment.js +119 -0
- package/lib/node/remote-exec-environment.js.map +1 -0
- package/package.json +5 -3
- package/src/node/exec-client.ts +152 -0
- package/src/node/exec-protocol.ts +2 -0
- package/src/node/exec-rpc.ts +104 -0
- package/src/node/exec-server.spec.ts +110 -0
- package/src/node/exec-server.ts +243 -0
- package/src/node/index.ts +4 -0
- package/src/node/remote-exec-environment.ts +124 -0
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { ExecRpc } from './exec-rpc';
|
|
2
|
+
|
|
3
|
+
export interface ExecClientOptions {
|
|
4
|
+
/** The WebSocket URL of `ta exec-server`. */
|
|
5
|
+
url: string;
|
|
6
|
+
token: string;
|
|
7
|
+
/** Larger than the epoch of any host that ran these sessions before; see {@link ExecRpc.InitializeParams}. */
|
|
8
|
+
epoch: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** A failed call to `ta exec-server`. */
|
|
12
|
+
export class ExecError extends Error {
|
|
13
|
+
constructor(
|
|
14
|
+
message: string,
|
|
15
|
+
readonly code: ExecRpc.ErrorCode,
|
|
16
|
+
) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'ExecError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type NotificationListener = (method: string, params: { data?: string; exitCode?: number | null }) => void;
|
|
23
|
+
|
|
24
|
+
interface PendingCall {
|
|
25
|
+
resolve(result: unknown): void;
|
|
26
|
+
reject(error: Error): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One connection of a host to `ta exec-server`, shared by its environments. It connects on the first
|
|
31
|
+
* call and again on the first call after a loss; processes do not survive a loss. Once fenced by a
|
|
32
|
+
* host with a newer epoch it refuses every call: this host must stop running sessions there.
|
|
33
|
+
*/
|
|
34
|
+
export class ExecClient {
|
|
35
|
+
protected socket?: Promise<WebSocket>;
|
|
36
|
+
protected current?: WebSocket;
|
|
37
|
+
protected nextCall = 0;
|
|
38
|
+
protected nextProcess = 0;
|
|
39
|
+
protected fenced = false;
|
|
40
|
+
protected initialized?: ExecRpc.InitializeResult;
|
|
41
|
+
protected readonly pending = new Map<number, PendingCall>();
|
|
42
|
+
protected readonly listeners = new Map<number, NotificationListener>();
|
|
43
|
+
|
|
44
|
+
constructor(protected readonly options: ExecClientOptions) {}
|
|
45
|
+
|
|
46
|
+
async call<T>(method: string, params: object): Promise<T> {
|
|
47
|
+
const socket = await this.connect();
|
|
48
|
+
return this.send<T>(socket, method, params);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What the server said when this client connected. */
|
|
52
|
+
async info(): Promise<ExecRpc.InitializeResult> {
|
|
53
|
+
await this.connect();
|
|
54
|
+
return this.initialized as ExecRpc.InitializeResult;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** An id for a process, which its notifications carry. */
|
|
58
|
+
processId(): number {
|
|
59
|
+
return ++this.nextProcess;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
listen(id: number, listener: NotificationListener): () => void {
|
|
63
|
+
this.listeners.set(id, listener);
|
|
64
|
+
return () => this.listeners.delete(id);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
close(): void {
|
|
68
|
+
this.current?.close();
|
|
69
|
+
this.current = undefined;
|
|
70
|
+
this.socket = undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
protected connect(): Promise<WebSocket> {
|
|
74
|
+
if (this.fenced) {
|
|
75
|
+
return Promise.reject(new ExecError('A host with a newer epoch took over the execution environment.', ExecRpc.ErrorCode.STALE_EPOCH));
|
|
76
|
+
}
|
|
77
|
+
this.socket ??= this.open().catch(error => {
|
|
78
|
+
this.socket = undefined;
|
|
79
|
+
throw error;
|
|
80
|
+
});
|
|
81
|
+
return this.socket;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
protected async open(): Promise<WebSocket> {
|
|
85
|
+
const url = new URL(this.options.url);
|
|
86
|
+
url.searchParams.set('token', this.options.token);
|
|
87
|
+
const socket = new WebSocket(url);
|
|
88
|
+
await new Promise<void>((resolve, reject) => {
|
|
89
|
+
socket.onopen = () => resolve();
|
|
90
|
+
socket.onerror = () => reject(new ExecError(`Cannot connect to ${this.options.url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
91
|
+
});
|
|
92
|
+
socket.onmessage = message => this.receive(String(message.data));
|
|
93
|
+
this.current = socket;
|
|
94
|
+
socket.onclose = () => this.lost(socket);
|
|
95
|
+
try {
|
|
96
|
+
this.initialized = await this.send(socket, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch } satisfies ExecRpc.InitializeParams);
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if ((error as ExecError).code === ExecRpc.ErrorCode.STALE_EPOCH) {
|
|
99
|
+
this.fenced = true;
|
|
100
|
+
}
|
|
101
|
+
socket.close();
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
return socket;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
protected send<T>(socket: WebSocket, method: string, params: object): Promise<T> {
|
|
108
|
+
if (socket.readyState !== WebSocket.OPEN) {
|
|
109
|
+
return Promise.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
110
|
+
}
|
|
111
|
+
const id = ++this.nextCall;
|
|
112
|
+
return new Promise<T>((resolve, reject) => {
|
|
113
|
+
this.pending.set(id, { resolve: resolve as (result: unknown) => void, reject });
|
|
114
|
+
socket.send(JSON.stringify({ jsonrpc: '2.0', id, method, params } satisfies ExecRpc.Message));
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
protected receive(text: string): void {
|
|
119
|
+
const message = JSON.parse(text) as ExecRpc.Message;
|
|
120
|
+
if (message.method) {
|
|
121
|
+
this.listeners.get(message.params?.id)?.(message.method, message.params);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const call = this.pending.get(message.id as number);
|
|
125
|
+
this.pending.delete(message.id as number);
|
|
126
|
+
if (message.error) {
|
|
127
|
+
const code = message.error.data?.code ?? ExecRpc.ErrorCode.FAILED;
|
|
128
|
+
if (code === ExecRpc.ErrorCode.STALE_EPOCH) {
|
|
129
|
+
this.fenced = true;
|
|
130
|
+
}
|
|
131
|
+
call?.reject(new ExecError(message.error.message, code));
|
|
132
|
+
} else {
|
|
133
|
+
call?.resolve(message.result);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Calls fail, and processes are gone: the server ended them with the connection. */
|
|
138
|
+
protected lost(socket: WebSocket): void {
|
|
139
|
+
if (this.current === socket) {
|
|
140
|
+
this.current = undefined;
|
|
141
|
+
this.socket = undefined;
|
|
142
|
+
}
|
|
143
|
+
for (const call of this.pending.values()) {
|
|
144
|
+
call.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
145
|
+
}
|
|
146
|
+
this.pending.clear();
|
|
147
|
+
for (const listener of [...this.listeners.values()]) {
|
|
148
|
+
listener(ExecRpc.Notification.EXIT, { exitCode: null });
|
|
149
|
+
}
|
|
150
|
+
this.listeners.clear();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -64,4 +64,6 @@ export interface ExecEnvironment {
|
|
|
64
64
|
/** Bind another implementation with `rebind: true` to run sessions elsewhere. */
|
|
65
65
|
export interface ExecEnvironmentFactory {
|
|
66
66
|
create(cwd: string): ExecEnvironment;
|
|
67
|
+
/** Where sessions run when nobody names a directory: a path of the environment. */
|
|
68
|
+
defaultCwd(): Promise<string>;
|
|
67
69
|
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The protocol of `ta exec-server`: JSON-RPC 2.0 over a WebSocket, one text message each, as Codex's
|
|
3
|
+
* exec-server does it. The host calls methods; the server sends the output of processes as
|
|
4
|
+
* notifications. Bytes travel as base64.
|
|
5
|
+
*/
|
|
6
|
+
export namespace ExecRpc {
|
|
7
|
+
/** Path of the WebSocket endpoint. */
|
|
8
|
+
export const PATH = '/exec';
|
|
9
|
+
|
|
10
|
+
export const Method = {
|
|
11
|
+
INITIALIZE: 'initialize',
|
|
12
|
+
EXEC: 'process/exec',
|
|
13
|
+
SPAWN: 'process/spawn',
|
|
14
|
+
WRITE: 'process/write',
|
|
15
|
+
KILL: 'process/kill',
|
|
16
|
+
READ_FILE: 'fs/readFile',
|
|
17
|
+
WRITE_FILE: 'fs/writeFile',
|
|
18
|
+
STAT: 'fs/stat',
|
|
19
|
+
READDIR: 'fs/readdir',
|
|
20
|
+
MKDIR: 'fs/mkdir',
|
|
21
|
+
REMOVE: 'fs/remove',
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
24
|
+
export const Notification = {
|
|
25
|
+
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
26
|
+
OUTPUT: 'process/output',
|
|
27
|
+
STDERR: 'process/stderr',
|
|
28
|
+
/** A spawned process ended. */
|
|
29
|
+
EXIT: 'process/exit',
|
|
30
|
+
} as const;
|
|
31
|
+
|
|
32
|
+
/** `error.data.code` of failed calls. */
|
|
33
|
+
export const ErrorCode = {
|
|
34
|
+
/** A host with a newer epoch connected: this one may no longer run anything. */
|
|
35
|
+
STALE_EPOCH: 'CELL_TA_EXEC_STALE_EPOCH',
|
|
36
|
+
NOT_INITIALIZED: 'CELL_TA_EXEC_NOT_INITIALIZED',
|
|
37
|
+
FAILED: 'CELL_TA_EXEC_FAILED',
|
|
38
|
+
CONNECTION_LOST: 'CELL_TA_EXEC_CONNECTION_LOST',
|
|
39
|
+
} as const;
|
|
40
|
+
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The epoch fences hosts: when a session moves to another host instance (a restart, a failover), the
|
|
44
|
+
* new one connects with a larger epoch, and the server stops taking calls from smaller ones and kills
|
|
45
|
+
* their processes, so that two hosts never run the same session's tools.
|
|
46
|
+
*/
|
|
47
|
+
export interface InitializeParams {
|
|
48
|
+
epoch: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface InitializeResult {
|
|
52
|
+
platform: string;
|
|
53
|
+
/** The working directory of the server: where sessions run when nobody names another. */
|
|
54
|
+
cwd: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Every call names the directory of its environment; a relative `cwd` or path resolves against it. */
|
|
58
|
+
export interface ProcessParams {
|
|
59
|
+
root: string;
|
|
60
|
+
/** Chosen by the host, unique per connection: the notifications carry it. */
|
|
61
|
+
id: number;
|
|
62
|
+
cwd?: string;
|
|
63
|
+
/** Only what the host sets on top of the server's own environment, never the host's environment. */
|
|
64
|
+
env?: Record<string, string>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ExecParams extends ProcessParams {
|
|
68
|
+
command: string;
|
|
69
|
+
timeout?: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface SpawnParams extends ProcessParams {
|
|
73
|
+
command: string;
|
|
74
|
+
args: string[];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface PathParams {
|
|
78
|
+
root: string;
|
|
79
|
+
path: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface Message {
|
|
83
|
+
jsonrpc: '2.0';
|
|
84
|
+
id?: number;
|
|
85
|
+
method?: string;
|
|
86
|
+
params?: any;
|
|
87
|
+
result?: unknown;
|
|
88
|
+
error?: { code: number; message: string; data?: { code: ErrorCode } };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export const ERROR = -32060;
|
|
92
|
+
|
|
93
|
+
export function error(id: number | undefined, code: ErrorCode, message: string): Message {
|
|
94
|
+
return { jsonrpc: '2.0', id, error: { code: ERROR, message, data: { code } } };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function toBase64(data: Uint8Array | string): string {
|
|
98
|
+
return Buffer.from(data).toString('base64');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function fromBase64(data: string): Uint8Array {
|
|
102
|
+
return Buffer.from(data, 'base64');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
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({ 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
|
+
});
|
|
@@ -0,0 +1,243 @@
|
|
|
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 type { ExecProcess } from './exec-protocol';
|
|
7
|
+
import { ExecRpc } from './exec-rpc';
|
|
8
|
+
import { LocalExecEnvironment } from './local-exec-environment';
|
|
9
|
+
|
|
10
|
+
export interface ExecServerOptions {
|
|
11
|
+
/** Default 127.0.0.1. */
|
|
12
|
+
host?: string;
|
|
13
|
+
/** Default: a free port. */
|
|
14
|
+
port?: number;
|
|
15
|
+
/** What hosts must present. */
|
|
16
|
+
token: string;
|
|
17
|
+
/** Default: the working directory of the process. */
|
|
18
|
+
cwd?: string;
|
|
19
|
+
/** Largest message in bytes, for files in one piece. Default 64 MiB. */
|
|
20
|
+
maxPayload?: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* `ta exec-server`: runs the commands and file operations of a host's sessions on this machine, which
|
|
27
|
+
* may be a container or a sandbox: the security boundary is the machine, as pi's is. Processes belong
|
|
28
|
+
* to the connection that started them and end with it.
|
|
29
|
+
*/
|
|
30
|
+
export class ExecServer {
|
|
31
|
+
protected server?: Server;
|
|
32
|
+
/** The largest epoch a host connected with. */
|
|
33
|
+
protected epoch = 0;
|
|
34
|
+
protected readonly peers = new Set<ExecPeer>();
|
|
35
|
+
|
|
36
|
+
constructor(protected readonly options: ExecServerOptions) {}
|
|
37
|
+
|
|
38
|
+
get cwd(): string {
|
|
39
|
+
return this.options.cwd ?? process.cwd();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Resolves to the WebSocket URL. */
|
|
43
|
+
async listen(): Promise<string> {
|
|
44
|
+
const server = createServer((_request, response) => response.writeHead(404).end());
|
|
45
|
+
server.on('upgrade', (request, socket, head) => this.upgrade(request, socket, head));
|
|
46
|
+
this.server = server;
|
|
47
|
+
await new Promise<void>(resolve => server.listen(this.options.port ?? 0, this.options.host ?? '127.0.0.1', resolve));
|
|
48
|
+
const { port } = server.address() as AddressInfo;
|
|
49
|
+
return `ws://${this.options.host ?? '127.0.0.1'}:${port}${ExecRpc.PATH}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async close(): Promise<void> {
|
|
53
|
+
for (const peer of this.peers) {
|
|
54
|
+
peer.close(1001, 'The server stops.');
|
|
55
|
+
}
|
|
56
|
+
await new Promise<void>(resolve => (this.server ? this.server.close(() => resolve()) : resolve()));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** False when a newer host has taken over; a newer one fences the older ones. */
|
|
60
|
+
admit(peer: ExecPeer, epoch: number): boolean {
|
|
61
|
+
if (epoch < this.epoch) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (epoch > this.epoch) {
|
|
65
|
+
this.epoch = epoch;
|
|
66
|
+
for (const other of this.peers) {
|
|
67
|
+
if (other !== peer && other.epoch !== undefined && other.epoch < epoch) {
|
|
68
|
+
other.close(4001, 'A host with a newer epoch connected.');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
isCurrent(epoch: number | undefined): boolean {
|
|
76
|
+
return epoch === this.epoch;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
protected upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void {
|
|
80
|
+
const url = new URL(request.url ?? '/', 'http://localhost');
|
|
81
|
+
if (url.pathname !== ExecRpc.PATH) {
|
|
82
|
+
WebSocketConnection.refuse(socket, 404, 'Not found.');
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const checked = WebSocketConnection.check(request);
|
|
86
|
+
if ('status' in checked) {
|
|
87
|
+
WebSocketConnection.refuse(socket, checked.status, checked.message);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const header = request.headers.authorization;
|
|
91
|
+
const token = header?.startsWith('Bearer ') ? header.slice('Bearer '.length) : url.searchParams.get('token');
|
|
92
|
+
if (!token || !this.matches(token)) {
|
|
93
|
+
WebSocketConnection.refuse(socket, 401, 'Not authorized.');
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: this.options.maxPayload ?? 67108864, heartbeat: 30000 });
|
|
97
|
+
const peer = new ExecPeer(this, connection);
|
|
98
|
+
this.peers.add(peer);
|
|
99
|
+
connection.onClose(() => {
|
|
100
|
+
this.peers.delete(peer);
|
|
101
|
+
peer.dispose();
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
protected matches(token: string): boolean {
|
|
106
|
+
const [left, right] = [Buffer.from(token), Buffer.from(this.options.token)];
|
|
107
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
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
|
+
}
|