@revoengine/cli 1.0.14 → 1.0.16
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 +57 -21
- package/dist/src/cli.js +5 -1
- package/dist/src/client.d.ts +25 -14
- package/dist/src/client.js +67 -34
- package/dist/src/commands/component.js +1 -0
- package/dist/src/commands/env.js +1 -5
- package/dist/src/commands/index.d.ts +1 -0
- package/dist/src/commands/index.js +1 -0
- package/dist/src/commands/migrate.js +12 -2
- package/dist/src/commands/service-accounts.d.ts +2 -0
- package/dist/src/commands/service-accounts.js +149 -0
- package/dist/src/commands/terminal-browser.d.ts +29 -1
- package/dist/src/commands/terminal-browser.js +165 -34
- package/dist/src/commands/terminal-file.d.ts +21 -0
- package/dist/src/commands/terminal-file.js +160 -0
- package/dist/src/commands/terminal-operational-log.js +2 -2
- package/dist/src/commands/terminal-policy.d.ts +11 -2
- package/dist/src/commands/terminal-policy.js +27 -2
- package/dist/src/commands/terminal-pty.js +2 -0
- package/dist/src/commands/terminal-reconnect-grace.d.ts +19 -0
- package/dist/src/commands/terminal-reconnect-grace.js +59 -1
- package/dist/src/commands/terminal-sandbox.js +7 -0
- package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
- package/dist/src/commands/terminal-secure-browser.js +2 -1
- package/dist/src/commands/terminal-service.d.ts +4 -3
- package/dist/src/commands/terminal-service.js +23 -19
- package/dist/src/commands/terminal.d.ts +29 -1
- package/dist/src/commands/terminal.js +508 -107
- package/dist/src/component-lock.d.ts +4 -0
- package/dist/src/component-lock.js +21 -2
- package/dist/src/config.d.ts +0 -3
- package/dist/src/config.js +0 -2
- package/dist/src/metadata-backfill.js +50 -1
- package/dist/src/migration.d.ts +10 -2
- package/dist/src/migration.js +159 -69
- package/dist/src/resource-inventory.d.ts +3 -2
- package/dist/src/resource-inventory.js +6 -1
- package/dist/src/resource-syncs/account-principal.d.ts +22 -0
- package/dist/src/resource-syncs/account-principal.js +86 -0
- package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
- package/dist/src/resource-syncs/database-view-sync.js +1 -12
- package/dist/src/resource-syncs/group-sync.d.ts +10 -0
- package/dist/src/resource-syncs/group-sync.js +92 -20
- package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
- package/dist/src/resource-syncs/identity-migration.js +108 -0
- package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
- package/dist/src/resource-syncs/job-template-sync.js +55 -12
- package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
- package/dist/src/resource-syncs/service-account-sync.js +620 -0
- package/dist/src/sync-output.js +3 -0
- package/dist/src/tracked-resources.d.ts +1 -1
- package/dist/src/tracked-resources.js +5 -1
- package/dist/src/types.d.ts +12 -0
- package/dist/src/ui.js +4 -1
- package/dist/src/workspace-diff.d.ts +1 -0
- package/dist/src/workspace-diff.js +4 -1
- package/package.json +6 -5
- package/scripts/ensure-pty-helper.mjs +0 -9
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import https from 'node:https';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
const HEADERS = new Set(['content-type', 'content-length', 'content-range', 'range', 'if-match', 'if-none-match',
|
|
7
|
+
'x-goog-if-generation-match', 'x-goog-if-metageneration-match']);
|
|
8
|
+
/** URLs and headers are credentials. Never include them in errors or operational logs. */
|
|
9
|
+
export function validateFileTransfer(value) {
|
|
10
|
+
const item = value;
|
|
11
|
+
if (!item || typeof item.path !== 'string' || !path.isAbsolute(item.path) || item.path.includes('\0')
|
|
12
|
+
|| item.path.length > 2048 || typeof item.url !== 'string' || item.url.length > 16_384
|
|
13
|
+
|| typeof item.overwrite !== 'boolean' || !Array.isArray(item.headers) || item.headers.length > 16
|
|
14
|
+
|| [item.offset, item.length].some(number => number !== null && (!Number.isSafeInteger(number) || number < 0)))
|
|
15
|
+
return false;
|
|
16
|
+
try {
|
|
17
|
+
const url = new URL(item.url);
|
|
18
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.port && url.port !== '443'
|
|
19
|
+
|| !(url.hostname === 'storage.googleapis.com' || url.hostname.endsWith('.storage.googleapis.com')))
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return item.headers.every(header => header && typeof header.name === 'string' && HEADERS.has(header.name.toLowerCase())
|
|
26
|
+
&& typeof header.value === 'string' && header.value.length <= 2048 && !/[\r\n]/u.test(header.value))
|
|
27
|
+
&& new Set(item.headers.map(header => header.name.toLowerCase())).size === item.headers.length;
|
|
28
|
+
}
|
|
29
|
+
function inside(root, file) {
|
|
30
|
+
const relative = path.relative(root, file);
|
|
31
|
+
return !!relative && !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative);
|
|
32
|
+
}
|
|
33
|
+
function transferError(status) {
|
|
34
|
+
return new Error(status ? `file_transfer_http_${status}` : 'file_transfer_transport_failed');
|
|
35
|
+
}
|
|
36
|
+
async function request(url, method, headers, signal, source) {
|
|
37
|
+
let written = Promise.resolve();
|
|
38
|
+
const response = new Promise((resolve, reject) => {
|
|
39
|
+
const req = https.request(url, { method, headers, signal }, resolve);
|
|
40
|
+
req.setTimeout(90_000, () => req.destroy(new Error('file_transfer_idle_timeout')));
|
|
41
|
+
req.on('error', () => reject(transferError()));
|
|
42
|
+
if (source)
|
|
43
|
+
written = pipeline(source, req, { signal }).catch(() => { throw transferError(); });
|
|
44
|
+
else
|
|
45
|
+
req.end();
|
|
46
|
+
});
|
|
47
|
+
// Observe both promises immediately, even when a server rejects a request before reading its body.
|
|
48
|
+
const [received] = await Promise.all([response, written]);
|
|
49
|
+
return received;
|
|
50
|
+
}
|
|
51
|
+
function drain(response) { response.on('error', () => undefined); response.resume(); }
|
|
52
|
+
function nextOffset(response) {
|
|
53
|
+
const range = /^bytes=0-(\d+)$/u.exec(String(response.headers.range || ''));
|
|
54
|
+
return range ? Number(range[1]) + 1 : 0;
|
|
55
|
+
}
|
|
56
|
+
export async function transferWorkspaceFile(workspace, operation, transfer, signal) {
|
|
57
|
+
if (!validateFileTransfer(transfer))
|
|
58
|
+
throw new Error('invalid_file_transfer');
|
|
59
|
+
if (operation === 'download_file' && (transfer.offset !== null || transfer.length !== null))
|
|
60
|
+
throw new Error('invalid_file_transfer_range');
|
|
61
|
+
if (signal.aborted)
|
|
62
|
+
throw new Error('file_transfer_cancelled');
|
|
63
|
+
const root = await fs.promises.realpath(workspace);
|
|
64
|
+
const parent = await fs.promises.realpath(path.dirname(transfer.path));
|
|
65
|
+
const target = path.join(parent, path.basename(transfer.path));
|
|
66
|
+
if (!inside(root, target) || path.resolve(transfer.path) !== target)
|
|
67
|
+
throw new Error('file_transfer_outside_workspace');
|
|
68
|
+
const headers = Object.fromEntries(transfer.headers.map(header => [header.name.toLowerCase(), header.value]));
|
|
69
|
+
if (operation === 'upload_file') {
|
|
70
|
+
const file = await fs.promises.open(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
71
|
+
try {
|
|
72
|
+
const stat = await file.stat();
|
|
73
|
+
if (!stat.isFile() || !Number.isSafeInteger(stat.size))
|
|
74
|
+
throw new Error('file_transfer_not_regular');
|
|
75
|
+
const resumable = new URL(transfer.url).searchParams.has('upload_id');
|
|
76
|
+
let offset = transfer.offset ?? 0;
|
|
77
|
+
if (resumable && transfer.offset === null) {
|
|
78
|
+
const status = await request(transfer.url, 'PUT', { ...headers, 'content-length': '0',
|
|
79
|
+
'content-range': `bytes */${stat.size}` }, signal);
|
|
80
|
+
if ([200, 201].includes(status.statusCode || 0)) {
|
|
81
|
+
drain(status);
|
|
82
|
+
return { bytes: 0, complete: true, status: status.statusCode, nextOffset: stat.size };
|
|
83
|
+
}
|
|
84
|
+
if (status.statusCode !== 308) {
|
|
85
|
+
drain(status);
|
|
86
|
+
throw transferError(status.statusCode);
|
|
87
|
+
}
|
|
88
|
+
offset = nextOffset(status);
|
|
89
|
+
drain(status);
|
|
90
|
+
}
|
|
91
|
+
const length = transfer.length ?? stat.size - offset;
|
|
92
|
+
if (offset > stat.size || length > stat.size - offset || !resumable && (offset !== 0 || length !== stat.size))
|
|
93
|
+
throw new Error('invalid_file_transfer_range');
|
|
94
|
+
if (resumable && offset + length < stat.size && (!length || length % (256 * 1024)))
|
|
95
|
+
throw new Error('invalid_file_transfer_chunk_size');
|
|
96
|
+
if (headers['content-length'] !== undefined && Number(headers['content-length']) !== length)
|
|
97
|
+
throw new Error('invalid_file_transfer_range');
|
|
98
|
+
headers['content-length'] = String(length);
|
|
99
|
+
if (resumable)
|
|
100
|
+
headers['content-range'] = stat.size ? `bytes ${offset}-${offset + length - 1}/${stat.size}` : 'bytes */0';
|
|
101
|
+
else if (headers['content-range'])
|
|
102
|
+
throw new Error('invalid_file_transfer_range');
|
|
103
|
+
const source = length ? file.createReadStream({ start: offset, end: offset + length - 1, autoClose: false }) : undefined;
|
|
104
|
+
const response = await request(transfer.url, 'PUT', headers, signal, source);
|
|
105
|
+
const status = response.statusCode || 0;
|
|
106
|
+
if (![200, 201, 204, 308].includes(status) || status === 308 && !resumable) {
|
|
107
|
+
source?.destroy();
|
|
108
|
+
drain(response);
|
|
109
|
+
throw transferError(status);
|
|
110
|
+
}
|
|
111
|
+
const changed = await file.stat();
|
|
112
|
+
if (changed.size !== stat.size || changed.mtimeMs !== stat.mtimeMs) {
|
|
113
|
+
drain(response);
|
|
114
|
+
throw new Error('file_transfer_source_changed');
|
|
115
|
+
}
|
|
116
|
+
const result = { bytes: length, complete: status !== 308, status,
|
|
117
|
+
...(status === 308 ? { nextOffset: nextOffset(response) } : { nextOffset: offset + length }),
|
|
118
|
+
...(typeof response.headers.etag === 'string' ? { etag: response.headers.etag } : {}) };
|
|
119
|
+
drain(response);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
await file.close();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (transfer.offset !== null || transfer.length !== null || headers.range)
|
|
127
|
+
throw new Error('file_download_range_not_supported');
|
|
128
|
+
const temporary = path.join(parent, `.revo-transfer-${randomUUID()}.part`);
|
|
129
|
+
try {
|
|
130
|
+
const existing = await fs.promises.lstat(target).catch(error => {
|
|
131
|
+
if (error.code === 'ENOENT')
|
|
132
|
+
return null;
|
|
133
|
+
throw error;
|
|
134
|
+
});
|
|
135
|
+
if (existing && (!transfer.overwrite || !existing.isFile() || existing.isSymbolicLink()))
|
|
136
|
+
throw new Error('file_transfer_target_exists');
|
|
137
|
+
const response = await request(transfer.url, 'GET', headers, signal);
|
|
138
|
+
if (response.statusCode !== 200) {
|
|
139
|
+
drain(response);
|
|
140
|
+
throw transferError(response.statusCode);
|
|
141
|
+
}
|
|
142
|
+
await pipeline(response, fs.createWriteStream(temporary, { flags: 'wx', mode: 0o600 }), { signal });
|
|
143
|
+
const stat = await fs.promises.stat(temporary);
|
|
144
|
+
if (response.headers['content-length'] !== undefined && Number(response.headers['content-length']) !== stat.size)
|
|
145
|
+
throw new Error('file_transfer_incomplete');
|
|
146
|
+
if (await fs.promises.realpath(path.dirname(transfer.path)) !== parent)
|
|
147
|
+
throw new Error('file_transfer_outside_workspace');
|
|
148
|
+
if (transfer.overwrite)
|
|
149
|
+
await fs.promises.rename(temporary, target);
|
|
150
|
+
else {
|
|
151
|
+
await fs.promises.link(temporary, target);
|
|
152
|
+
await fs.promises.unlink(temporary);
|
|
153
|
+
}
|
|
154
|
+
return { bytes: stat.size, complete: true, status: 200,
|
|
155
|
+
...(typeof response.headers.etag === 'string' ? { etag: response.headers.etag } : {}) };
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
await fs.promises.rm(temporary, { force: true });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -5,8 +5,8 @@ import { gunzipSync, gzipSync } from 'node:zlib';
|
|
|
5
5
|
const ARCHIVE_RETENTION_MS = 30 * 24 * 60 * 60 * 1_000;
|
|
6
6
|
const SAFE_ATOM = /^[A-Za-z0-9_.:-]{1,120}$/u;
|
|
7
7
|
const DETAIL_KEYS = new Set(['operation', 'sandbox', 'reason', 'errorCode', 'browserAction',
|
|
8
|
-
'exitCode', 'images', 'screenshot', 'executed', 'timedOut', 'truncated', 'activeExecutions',
|
|
9
|
-
'resumedExecutions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds']);
|
|
8
|
+
'exitCode', 'signal', 'images', 'screenshot', 'executed', 'timedOut', 'truncated', 'activeExecutions',
|
|
9
|
+
'resumedExecutions', 'stoppedExecutions', 'closedBrowserSessions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds']);
|
|
10
10
|
function atom(value) {
|
|
11
11
|
return typeof value === 'string' && SAFE_ATOM.test(value) ? value : '-';
|
|
12
12
|
}
|
|
@@ -7,17 +7,26 @@ export type TerminalExecutePolicy = {
|
|
|
7
7
|
commandAccessExpiresAt: number | null;
|
|
8
8
|
networkAccessExpiresAt: number | null;
|
|
9
9
|
networkAccessOnce?: boolean;
|
|
10
|
+
commandAccessForThread?: boolean;
|
|
11
|
+
networkAccessForThread?: boolean;
|
|
10
12
|
policyGrantRevision: number;
|
|
11
13
|
};
|
|
14
|
+
export type TerminalGrantPolicy = {
|
|
15
|
+
mode: 'review' | 'full';
|
|
16
|
+
networkMode: 'restricted' | 'sandbox' | 'external';
|
|
17
|
+
};
|
|
18
|
+
export declare function executionAllowedByGrant(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy, now?: number): boolean;
|
|
19
|
+
export declare function remainingPolicyDeadline(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy): number | null;
|
|
12
20
|
type PolicyFrame = Partial<TerminalExecutePolicy> & {
|
|
13
|
-
operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
|
|
21
|
+
operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image' | 'upload_file' | 'download_file';
|
|
14
22
|
sandbox?: TerminalSandbox;
|
|
23
|
+
browserAction?: string;
|
|
15
24
|
browserLocalOnly?: boolean;
|
|
16
25
|
};
|
|
17
26
|
/** The connected Realtime process must send a complete, current policy for every execution. */
|
|
18
27
|
export declare function validateExecutePolicy(frame: PolicyFrame, now?: number): string | null;
|
|
19
28
|
export declare function executionPolicyDeadline(frame: TerminalExecutePolicy & {
|
|
20
|
-
operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
|
|
29
|
+
operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image' | 'upload_file' | 'download_file';
|
|
21
30
|
sandbox?: TerminalSandbox;
|
|
22
31
|
}): number | null;
|
|
23
32
|
export {};
|
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
export function executionAllowedByGrant(policy, grant, now = Date.now()) {
|
|
2
|
+
const networkRank = { none: 0, local: 1, full: 2 };
|
|
3
|
+
const permanentNetwork = grant.networkMode === 'external' ? 2 : grant.networkMode === 'sandbox' ? 1 : 0;
|
|
4
|
+
const commandAllowed = policy.commandAccess !== 'host' || grant.mode === 'full'
|
|
5
|
+
|| policy.commandAccessForThread === true || policy.commandAccessExpiresAt !== null && policy.commandAccessExpiresAt > now;
|
|
6
|
+
const networkAllowed = networkRank[policy.networkAccess] <= permanentNetwork
|
|
7
|
+
|| policy.networkAccessForThread === true || policy.networkAccessExpiresAt !== null && policy.networkAccessExpiresAt > now;
|
|
8
|
+
return commandAllowed && networkAllowed;
|
|
9
|
+
}
|
|
10
|
+
export function remainingPolicyDeadline(policy, grant) {
|
|
11
|
+
const deadlines = [
|
|
12
|
+
...(policy.commandAccess === 'host' && grant.mode !== 'full' && policy.commandAccessExpiresAt !== null
|
|
13
|
+
? [policy.commandAccessExpiresAt] : []),
|
|
14
|
+
...(policy.networkAccess !== 'none' && grant.networkMode !== 'external'
|
|
15
|
+
&& !(policy.networkAccess === 'local' && grant.networkMode === 'sandbox')
|
|
16
|
+
&& policy.networkAccessExpiresAt !== null ? [policy.networkAccessExpiresAt] : []),
|
|
17
|
+
];
|
|
18
|
+
return deadlines.length ? Math.min(...deadlines) : null;
|
|
19
|
+
}
|
|
1
20
|
function validDeadline(value) {
|
|
2
21
|
return value === null || Number.isSafeInteger(value) && Number(value) > 0;
|
|
3
22
|
}
|
|
@@ -9,6 +28,12 @@ export function validateExecutePolicy(frame, now = Date.now()) {
|
|
|
9
28
|
|| !validDeadline(frame.networkAccessExpiresAt)
|
|
10
29
|
|| !Number.isSafeInteger(frame.policyGrantRevision) || frame.policyGrantRevision < 0)
|
|
11
30
|
return 'terminal_policy_v2_required';
|
|
31
|
+
if (frame.commandAccessForThread !== undefined && typeof frame.commandAccessForThread !== 'boolean'
|
|
32
|
+
|| frame.networkAccessForThread !== undefined && typeof frame.networkAccessForThread !== 'boolean'
|
|
33
|
+
|| frame.commandAccessForThread === true && (frame.commandAccess !== 'host' || frame.commandAccessExpiresAt !== null)
|
|
34
|
+
|| frame.networkAccessForThread === true && (frame.networkAccess === 'none' || frame.networkAccessExpiresAt !== null
|
|
35
|
+
|| frame.networkAccessOnce === true))
|
|
36
|
+
return 'terminal_policy_invalid';
|
|
12
37
|
if (frame.commandAccessExpiresAt !== null && frame.commandAccessExpiresAt <= now
|
|
13
38
|
|| frame.networkAccessExpiresAt !== null && frame.networkAccessExpiresAt <= now)
|
|
14
39
|
return 'terminal_policy_expired';
|
|
@@ -23,7 +48,7 @@ export function validateExecutePolicy(frame, now = Date.now()) {
|
|
|
23
48
|
if (frame.operation === 'apply_patch' && frame.networkAccess !== 'none')
|
|
24
49
|
return 'terminal_policy_invalid';
|
|
25
50
|
if (frame.operation === 'browser') {
|
|
26
|
-
if (frame.networkAccess === 'none')
|
|
51
|
+
if (frame.networkAccess === 'none' && !['tabs', 'close', 'close_tab'].includes(frame.browserAction || ''))
|
|
27
52
|
return 'terminal_network_disabled';
|
|
28
53
|
if (frame.browserLocalOnly !== (frame.networkAccess === 'local'))
|
|
29
54
|
return 'terminal_policy_invalid';
|
|
@@ -32,7 +57,7 @@ export function validateExecutePolicy(frame, now = Date.now()) {
|
|
|
32
57
|
|| frame.networkAccessOnce === true && (frame.operation !== 'browser'
|
|
33
58
|
|| frame.networkAccessExpiresAt === null))
|
|
34
59
|
return 'terminal_policy_invalid';
|
|
35
|
-
if (frame.operation
|
|
60
|
+
if (['save_image', 'upload_file', 'download_file'].includes(frame.operation || '') && frame.networkAccess !== 'full')
|
|
36
61
|
return 'terminal_network_disabled';
|
|
37
62
|
return null;
|
|
38
63
|
}
|
|
@@ -35,5 +35,7 @@ export function ensurePtyHelperExecutable(packageRoot = path.dirname(require.res
|
|
|
35
35
|
export function normalizePtyStartError(error) {
|
|
36
36
|
const message = error instanceof Error ? error.message : String(error);
|
|
37
37
|
return message === 'posix_spawnp failed.' || /^pty_helper_(?:invalid|missing|not_executable)$/u.test(message)
|
|
38
|
+
|| (['MODULE_NOT_FOUND', 'ERR_MODULE_NOT_FOUND'].includes(error?.code || '')
|
|
39
|
+
&& /node-pty|pty\.node/u.test(message))
|
|
38
40
|
? new Error('pty_unavailable') : error instanceof Error ? error : new Error(message);
|
|
39
41
|
}
|
|
@@ -9,3 +9,22 @@ export declare class TerminalReconnectGrace {
|
|
|
9
9
|
start(hasRunningWork: boolean): void;
|
|
10
10
|
clear(): void;
|
|
11
11
|
}
|
|
12
|
+
/** A transport is recovered only after ready and every pending execution resume. */
|
|
13
|
+
export declare class TerminalTransportRecovery {
|
|
14
|
+
private timer?;
|
|
15
|
+
private readonly pending;
|
|
16
|
+
private readyReceived;
|
|
17
|
+
private recovered;
|
|
18
|
+
private readonly onTimeout;
|
|
19
|
+
private readonly onRecovered;
|
|
20
|
+
private readonly delayMs;
|
|
21
|
+
private readonly scheduleTimer;
|
|
22
|
+
private readonly clearTimer;
|
|
23
|
+
constructor(onTimeout: () => void, onRecovered: () => void, delayMs?: number, scheduleTimer?: typeof setTimeout, clearTimer?: typeof clearTimeout);
|
|
24
|
+
ready(executionIds: Iterable<string>): void;
|
|
25
|
+
accepted(executionId: string): void;
|
|
26
|
+
close(): void;
|
|
27
|
+
private complete;
|
|
28
|
+
private arm;
|
|
29
|
+
}
|
|
30
|
+
export declare function isRunnerTransportHeartbeat(frame: unknown, connectionId: string): boolean;
|
|
@@ -5,7 +5,7 @@ export class TerminalReconnectGrace {
|
|
|
5
5
|
delayMs;
|
|
6
6
|
scheduleTimer;
|
|
7
7
|
clearTimer;
|
|
8
|
-
constructor(onExpire, delayMs =
|
|
8
|
+
constructor(onExpire, delayMs = 180_000, scheduleTimer = setTimeout, clearTimer = clearTimeout) {
|
|
9
9
|
this.onExpire = onExpire;
|
|
10
10
|
this.delayMs = delayMs;
|
|
11
11
|
this.scheduleTimer = scheduleTimer;
|
|
@@ -27,3 +27,61 @@ export class TerminalReconnectGrace {
|
|
|
27
27
|
this.timer = undefined;
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
|
+
/** A transport is recovered only after ready and every pending execution resume. */
|
|
31
|
+
export class TerminalTransportRecovery {
|
|
32
|
+
timer;
|
|
33
|
+
pending = new Set();
|
|
34
|
+
readyReceived = false;
|
|
35
|
+
recovered = false;
|
|
36
|
+
onTimeout;
|
|
37
|
+
onRecovered;
|
|
38
|
+
delayMs;
|
|
39
|
+
scheduleTimer;
|
|
40
|
+
clearTimer;
|
|
41
|
+
constructor(onTimeout, onRecovered, delayMs = 10_000, scheduleTimer = setTimeout, clearTimer = clearTimeout) {
|
|
42
|
+
this.onTimeout = onTimeout;
|
|
43
|
+
this.onRecovered = onRecovered;
|
|
44
|
+
this.delayMs = delayMs;
|
|
45
|
+
this.scheduleTimer = scheduleTimer;
|
|
46
|
+
this.clearTimer = clearTimer;
|
|
47
|
+
this.arm();
|
|
48
|
+
}
|
|
49
|
+
ready(executionIds) {
|
|
50
|
+
this.close();
|
|
51
|
+
this.readyReceived = true;
|
|
52
|
+
for (const id of executionIds)
|
|
53
|
+
this.pending.add(id);
|
|
54
|
+
if (this.pending.size)
|
|
55
|
+
this.arm();
|
|
56
|
+
else
|
|
57
|
+
this.complete();
|
|
58
|
+
}
|
|
59
|
+
accepted(executionId) {
|
|
60
|
+
if (!this.pending.delete(executionId))
|
|
61
|
+
return;
|
|
62
|
+
if (!this.pending.size)
|
|
63
|
+
this.complete();
|
|
64
|
+
}
|
|
65
|
+
close() {
|
|
66
|
+
if (this.timer)
|
|
67
|
+
this.clearTimer(this.timer);
|
|
68
|
+
this.timer = undefined;
|
|
69
|
+
}
|
|
70
|
+
complete() {
|
|
71
|
+
if (!this.readyReceived || this.recovered)
|
|
72
|
+
return;
|
|
73
|
+
this.recovered = true;
|
|
74
|
+
this.close();
|
|
75
|
+
this.onRecovered();
|
|
76
|
+
}
|
|
77
|
+
arm() {
|
|
78
|
+
this.timer = this.scheduleTimer(this.onTimeout, this.delayMs);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function isRunnerTransportHeartbeat(frame, connectionId) {
|
|
82
|
+
if (!connectionId || !frame || typeof frame !== 'object')
|
|
83
|
+
return false;
|
|
84
|
+
const heartbeat = frame;
|
|
85
|
+
return heartbeat.type === 'heartbeat'
|
|
86
|
+
&& (heartbeat.connectionId === undefined || heartbeat.connectionId === connectionId);
|
|
87
|
+
}
|
|
@@ -67,6 +67,13 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
|
|
|
67
67
|
const profile = [
|
|
68
68
|
'(version 1)', '(allow default)',
|
|
69
69
|
...(sandbox === 'workspace' ? ['(deny network*)',
|
|
70
|
+
// Build workers need local IPC. Keep it inside this command's private scratch;
|
|
71
|
+
// sockets in the workspace, other commands and host services remain denied.
|
|
72
|
+
...(scratchDir ? [
|
|
73
|
+
`(allow network-bind (local unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
|
|
74
|
+
`(allow network-inbound (local unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
|
|
75
|
+
`(allow network-outbound (remote unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
|
|
76
|
+
] : []),
|
|
70
77
|
...(networkAccess !== 'none' ? ['(allow network-outbound (remote ip "localhost:*"))',
|
|
71
78
|
'(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
|
|
72
79
|
'(deny file-write*)',
|
|
@@ -18,13 +18,14 @@ export function createSecureBrowserIdentity() {
|
|
|
18
18
|
export function secureBrowserInputAad(frame) {
|
|
19
19
|
return Buffer.from(JSON.stringify([frame.requestId, frame.threadId, frame.agentTerminalId,
|
|
20
20
|
frame.browserSessionId, frame.origin, frame.selector, frame.connectionId,
|
|
21
|
-
frame.keyId, frame.expiresAt]), 'utf8');
|
|
21
|
+
frame.keyId, frame.expiresAt, ...(frame.browserTabId ? [frame.browserTabId] : [])]), 'utf8');
|
|
22
22
|
}
|
|
23
23
|
export function decryptSecureBrowserInput(frame, identity) {
|
|
24
24
|
if (frame.keyId !== identity.keyId || !Number.isSafeInteger(frame.expiresAt)
|
|
25
25
|
|| frame.expiresAt < Date.now() || frame.expiresAt > Date.now() + 120_000
|
|
26
26
|
|| !/^[a-f0-9-]{36}$/iu.test(frame.requestId)
|
|
27
27
|
|| !/^[a-f0-9]{64}$/u.test(frame.browserSessionId)
|
|
28
|
+
|| frame.browserTabId !== undefined && !/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(frame.browserTabId)
|
|
28
29
|
|| typeof frame.selector !== 'string' || !frame.selector.trim() || frame.selector.length > 500
|
|
29
30
|
|| typeof frame.origin !== 'string' || frame.origin.length > 2_048
|
|
30
31
|
|| typeof frame.threadId !== 'string' || frame.threadId.length > 128
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
type Launchctl = (args: string[]) => void;
|
|
2
2
|
type ServiceOptions = {
|
|
3
3
|
workspace: string;
|
|
4
|
+
terminalId?: string;
|
|
4
5
|
envName?: string;
|
|
5
6
|
home?: string;
|
|
6
7
|
entrypoint?: string;
|
|
@@ -12,20 +13,20 @@ type ServiceOptions = {
|
|
|
12
13
|
launchctl?: Launchctl;
|
|
13
14
|
systemctl?: (args: string[]) => void;
|
|
14
15
|
};
|
|
15
|
-
export declare function terminalServicePaths(workspace: string, envName?: string, home?: string): {
|
|
16
|
+
export declare function terminalServicePaths(workspace: string, envName?: string, home?: string, terminalId?: string): {
|
|
16
17
|
label: string;
|
|
17
18
|
plist: string;
|
|
18
19
|
logDirectory: string;
|
|
19
20
|
stdout: string;
|
|
20
21
|
stderr: string;
|
|
21
22
|
};
|
|
22
|
-
export declare function terminalSystemdPaths(workspace: string, envName?: string, home?: string, configHome?: string): {
|
|
23
|
+
export declare function terminalSystemdPaths(workspace: string, envName?: string, home?: string, configHome?: string, terminalId?: string): {
|
|
23
24
|
label: string;
|
|
24
25
|
unit: string;
|
|
25
26
|
};
|
|
26
27
|
export declare function renderTerminalSystemdUnit(options: ServiceOptions): string;
|
|
27
28
|
export declare function renderTerminalServicePlist(options: ServiceOptions): string;
|
|
28
|
-
export declare function terminalServiceInstalled(workspace: string, envName?: string): boolean;
|
|
29
|
+
export declare function terminalServiceInstalled(workspace: string, envName?: string, terminalId?: string): boolean;
|
|
29
30
|
export declare function installTerminalService(options: ServiceOptions): {
|
|
30
31
|
label: string;
|
|
31
32
|
serviceFile: string;
|
|
@@ -12,8 +12,8 @@ function xml(value) {
|
|
|
12
12
|
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
13
13
|
.replace(/"/g, '"').replace(/'/g, ''');
|
|
14
14
|
}
|
|
15
|
-
export function terminalServicePaths(workspace, envName = 'default', home = os.homedir()) {
|
|
16
|
-
const hash = createHash('sha256').update(`${workspace}\0${envName}`).digest('hex').slice(0, 16);
|
|
15
|
+
export function terminalServicePaths(workspace, envName = 'default', home = os.homedir(), terminalId) {
|
|
16
|
+
const hash = createHash('sha256').update(`${workspace}\0${envName}${terminalId ? `\0${terminalId}` : ''}`).digest('hex').slice(0, 16);
|
|
17
17
|
const label = `com.revoengine.terminal.${hash}`;
|
|
18
18
|
return {
|
|
19
19
|
label,
|
|
@@ -23,10 +23,10 @@ export function terminalServicePaths(workspace, envName = 'default', home = os.h
|
|
|
23
23
|
stderr: path.join(home, 'Library', 'Logs', 'RevoEngine', `${label}.err.log`),
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
-
export function terminalSystemdPaths(workspace, envName = 'default', home = os.homedir(), configHome = path.join(home, '.config')) {
|
|
26
|
+
export function terminalSystemdPaths(workspace, envName = 'default', home = os.homedir(), configHome = path.join(home, '.config'), terminalId) {
|
|
27
27
|
if (!path.isAbsolute(configHome))
|
|
28
28
|
throw new Error('XDG_CONFIG_HOME must be an absolute path.');
|
|
29
|
-
const hash = createHash('sha256').update(`${workspace}\0${envName}`).digest('hex').slice(0, 16);
|
|
29
|
+
const hash = createHash('sha256').update(`${workspace}\0${envName}${terminalId ? `\0${terminalId}` : ''}`).digest('hex').slice(0, 16);
|
|
30
30
|
const label = `revo-terminal-${hash}.service`;
|
|
31
31
|
return { label, unit: path.join(configHome, 'systemd', 'user', label) };
|
|
32
32
|
}
|
|
@@ -43,22 +43,24 @@ export function renderTerminalSystemdUnit(options) {
|
|
|
43
43
|
const entrypoint = options.entrypoint || (process.argv[1] && fs.realpathSync(process.argv[1]));
|
|
44
44
|
if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
|
|
45
45
|
throw new Error('Cannot resolve absolute Node.js and revo executable paths for systemd.');
|
|
46
|
-
const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
|
|
47
|
-
|
|
46
|
+
const args = [node, entrypoint, 'terminal', 'connect', '--service-runner', '--workspace', options.workspace,
|
|
47
|
+
'--project', options.envName || 'default',
|
|
48
|
+
...(options.terminalId ? ['--terminal-id', options.terminalId] : [])];
|
|
48
49
|
const env = [
|
|
49
50
|
...(options.pathValue ? [`Environment=${systemdQuote(`PATH=${options.pathValue}`)}`] : []),
|
|
50
51
|
...(options.configHome ? [`Environment=${systemdQuote(`XDG_CONFIG_HOME=${options.configHome}`)}`] : []),
|
|
51
52
|
];
|
|
52
|
-
return `[Unit]\nDescription=RevoEngine Agent Terminal\n\n[Service]\nType=simple\nExecStart=${args.map(arg => systemdQuote(arg, true)).join(' ')}\nRestart=
|
|
53
|
+
return `[Unit]\nDescription=RevoEngine Agent Terminal\n\n[Service]\nType=simple\nExecStart=${args.map(arg => systemdQuote(arg, true)).join(' ')}\nRestart=on-failure\nRestartSec=30s\n${env.join('\n')}${env.length ? '\n' : ''}UnsetEnvironment=${AUTH_ENV_KEYS.join(' ')}\n\n[Install]\nWantedBy=default.target\n`;
|
|
53
54
|
}
|
|
54
55
|
export function renderTerminalServicePlist(options) {
|
|
55
|
-
const paths = terminalServicePaths(options.workspace, options.envName, options.home);
|
|
56
|
+
const paths = terminalServicePaths(options.workspace, options.envName, options.home, options.terminalId);
|
|
56
57
|
const node = options.nodePath || process.execPath;
|
|
57
58
|
const entrypoint = options.entrypoint || (process.argv[1] && fs.realpathSync(process.argv[1]));
|
|
58
59
|
if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
|
|
59
60
|
throw new Error('Cannot resolve absolute Node.js and revo executable paths for LaunchAgent.');
|
|
60
|
-
const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
|
|
61
|
-
|
|
61
|
+
const args = [node, entrypoint, 'terminal', 'connect', '--service-runner', '--workspace', options.workspace,
|
|
62
|
+
'--project', options.envName || 'default',
|
|
63
|
+
...(options.terminalId ? ['--terminal-id', options.terminalId] : [])];
|
|
62
64
|
const lines = args.map(arg => ` <string>${xml(arg)}</string>`).join('\n');
|
|
63
65
|
const env = [];
|
|
64
66
|
if (options.pathValue)
|
|
@@ -67,7 +69,7 @@ export function renderTerminalServicePlist(options) {
|
|
|
67
69
|
env.push(` <key>XDG_CONFIG_HOME</key><string>${xml(options.configHome)}</string>`);
|
|
68
70
|
for (const key of AUTH_ENV_KEYS)
|
|
69
71
|
env.push(` <key>${key}</key><string></string>`);
|
|
70
|
-
return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key><string>${xml(paths.label)}</string>\n <key>ProgramArguments</key>\n <array>\n${lines}\n </array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><
|
|
72
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key><string>${xml(paths.label)}</string>\n <key>ProgramArguments</key>\n <array>\n${lines}\n </array>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n <key>ThrottleInterval</key><integer>30</integer>\n <key>StandardOutPath</key><string>${xml(paths.stdout)}</string>\n <key>StandardErrorPath</key><string>${xml(paths.stderr)}</string>\n <key>EnvironmentVariables</key>\n <dict>\n${env.join('\n')}\n </dict>\n</dict>\n</plist>\n`;
|
|
71
73
|
}
|
|
72
74
|
function ensureMac(options) {
|
|
73
75
|
if ((options.platform || process.platform) !== 'darwin')
|
|
@@ -104,13 +106,15 @@ function isLoaded(options, uid, label) {
|
|
|
104
106
|
return false;
|
|
105
107
|
}
|
|
106
108
|
}
|
|
107
|
-
export function terminalServiceInstalled(workspace, envName = 'default') {
|
|
108
|
-
if (process.platform === 'linux')
|
|
109
|
-
|
|
110
|
-
|
|
109
|
+
export function terminalServiceInstalled(workspace, envName = 'default', terminalId) {
|
|
110
|
+
if (process.platform === 'linux') {
|
|
111
|
+
const configHome = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
112
|
+
return fs.existsSync(terminalSystemdPaths(workspace, envName, os.homedir(), configHome, terminalId).unit);
|
|
113
|
+
}
|
|
114
|
+
return fs.existsSync(terminalServicePaths(workspace, envName, os.homedir(), terminalId).plist);
|
|
111
115
|
}
|
|
112
116
|
function installLinuxTerminalService(options) {
|
|
113
|
-
const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'));
|
|
117
|
+
const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'), options.terminalId);
|
|
114
118
|
const content = renderTerminalSystemdUnit(options);
|
|
115
119
|
fs.mkdirSync(path.dirname(paths.unit), { recursive: true, mode: 0o700 });
|
|
116
120
|
if (fs.existsSync(paths.unit)) {
|
|
@@ -155,7 +159,7 @@ export function installTerminalService(options) {
|
|
|
155
159
|
if (ensureSupported(options) === 'linux')
|
|
156
160
|
return installLinuxTerminalService(options);
|
|
157
161
|
const uid = ensureMac(options);
|
|
158
|
-
const paths = terminalServicePaths(options.workspace, options.envName, options.home);
|
|
162
|
+
const paths = terminalServicePaths(options.workspace, options.envName, options.home, options.terminalId);
|
|
159
163
|
const content = renderTerminalServicePlist(options);
|
|
160
164
|
fs.mkdirSync(path.dirname(paths.plist), { recursive: true, mode: 0o700 });
|
|
161
165
|
fs.mkdirSync(paths.logDirectory, { recursive: true, mode: 0o700 });
|
|
@@ -191,7 +195,7 @@ export function installTerminalService(options) {
|
|
|
191
195
|
}
|
|
192
196
|
export function uninstallTerminalService(options) {
|
|
193
197
|
if (ensureSupported(options) === 'linux') {
|
|
194
|
-
const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'));
|
|
198
|
+
const paths = terminalSystemdPaths(options.workspace, options.envName, options.home, options.configHome || path.join(options.home || os.homedir(), '.config'), options.terminalId);
|
|
195
199
|
if (!fs.existsSync(paths.unit))
|
|
196
200
|
return { label: paths.label, removed: false };
|
|
197
201
|
systemctl(options, ['disable', '--now', paths.label]);
|
|
@@ -200,7 +204,7 @@ export function uninstallTerminalService(options) {
|
|
|
200
204
|
return { label: paths.label, removed: true };
|
|
201
205
|
}
|
|
202
206
|
const uid = ensureMac(options);
|
|
203
|
-
const paths = terminalServicePaths(options.workspace, options.envName, options.home);
|
|
207
|
+
const paths = terminalServicePaths(options.workspace, options.envName, options.home, options.terminalId);
|
|
204
208
|
const exists = fs.existsSync(paths.plist);
|
|
205
209
|
if (isLoaded(options, uid, paths.label))
|
|
206
210
|
launchctl(options, ['bootout', `gui/${uid}/${paths.label}`]);
|
|
@@ -1,11 +1,33 @@
|
|
|
1
1
|
import { type ChildProcess } from 'node:child_process';
|
|
2
2
|
import { type TerminalNetworkAccess, type TerminalSandbox } from './terminal-sandbox.ts';
|
|
3
|
+
type TerminalGrant = {
|
|
4
|
+
agentTerminalId: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
workspace?: string;
|
|
7
|
+
workspaces?: Array<{
|
|
8
|
+
agentTerminalWorkspaceId: string;
|
|
9
|
+
path: string;
|
|
10
|
+
status: 'pending' | 'approved';
|
|
11
|
+
}>;
|
|
12
|
+
revision?: number;
|
|
13
|
+
connectionRevision?: number;
|
|
14
|
+
online?: boolean;
|
|
15
|
+
lastOnlineAt?: string | null;
|
|
16
|
+
status: 'pending' | 'approved' | 'revoked';
|
|
17
|
+
mode: 'review' | 'full';
|
|
18
|
+
networkMode?: 'restricted' | 'sandbox' | 'external';
|
|
19
|
+
};
|
|
20
|
+
export declare function selectRegisteredTerminal<T extends {
|
|
21
|
+
agentTerminalId: string;
|
|
22
|
+
name: string;
|
|
23
|
+
}>(devices: T[], grants: TerminalGrant[], name: string, terminalId?: string): T | undefined;
|
|
3
24
|
export declare const MAX_TERMINAL_PROCESS_MS: number;
|
|
4
25
|
type CommandResult = {
|
|
5
26
|
executed: boolean;
|
|
6
27
|
exitCode: number | null;
|
|
7
28
|
stdout: string;
|
|
8
29
|
stderr: string;
|
|
30
|
+
signal?: NodeJS.Signals;
|
|
9
31
|
timedOut: boolean;
|
|
10
32
|
truncated: boolean;
|
|
11
33
|
logTruncated: boolean;
|
|
@@ -18,8 +40,10 @@ export type RunningProcess = {
|
|
|
18
40
|
closeStdin: (chars: string) => void;
|
|
19
41
|
resize: (cols: number, rows: number) => void;
|
|
20
42
|
terminate: () => void;
|
|
43
|
+
updatePolicyDeadline?: (deadline: number | null) => void;
|
|
21
44
|
};
|
|
22
45
|
export declare function childEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
46
|
+
export declare function acquireRunnerLock(agentTerminalId: string): () => void;
|
|
23
47
|
export declare function resolveWorkspaceDirectory(root: string, requested: string): string;
|
|
24
48
|
export declare function boundResultFrame(frame: Record<string, unknown>): Record<string, unknown>;
|
|
25
49
|
export declare function runCommand(input: {
|
|
@@ -27,6 +51,7 @@ export declare function runCommand(input: {
|
|
|
27
51
|
workdir: string;
|
|
28
52
|
workspace: string;
|
|
29
53
|
timeoutMs: number;
|
|
54
|
+
background?: boolean;
|
|
30
55
|
sandbox?: TerminalSandbox;
|
|
31
56
|
networkAccess?: TerminalNetworkAccess;
|
|
32
57
|
policyDeadlineMs?: number | null;
|
|
@@ -47,6 +72,9 @@ export declare function runWorkspacePatch(input: {
|
|
|
47
72
|
stdout: string;
|
|
48
73
|
stderr: string;
|
|
49
74
|
timedOut: boolean;
|
|
50
|
-
}) => void): ChildProcess
|
|
75
|
+
}) => void): ChildProcess & {
|
|
76
|
+
updatePolicyDeadline: (deadline: number | null) => void;
|
|
77
|
+
};
|
|
78
|
+
/** Supervisors retry crashes, but a revoked grant or 401/403 needs a human credential/grant change. */
|
|
51
79
|
export declare function handleTerminalCommand(argv: string[]): Promise<void>;
|
|
52
80
|
export {};
|