@revoengine/cli 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +26 -12
  2. package/dist/src/cli.js +4 -0
  3. package/dist/src/client.d.ts +5 -11
  4. package/dist/src/client.js +41 -74
  5. package/dist/src/commands/component.js +26 -25
  6. package/dist/src/commands/env.js +1 -5
  7. package/dist/src/commands/migrate.js +10 -0
  8. package/dist/src/commands/terminal-browser.d.ts +41 -6
  9. package/dist/src/commands/terminal-browser.js +503 -20
  10. package/dist/src/commands/terminal-image.js +59 -1
  11. package/dist/src/commands/terminal-operational-log.d.ts +18 -0
  12. package/dist/src/commands/terminal-operational-log.js +119 -0
  13. package/dist/src/commands/terminal-policy.d.ts +29 -0
  14. package/dist/src/commands/terminal-policy.js +67 -0
  15. package/dist/src/commands/terminal-pty.d.ts +4 -0
  16. package/dist/src/commands/terminal-pty.js +41 -0
  17. package/dist/src/commands/terminal-reconnect-grace.d.ts +30 -0
  18. package/dist/src/commands/terminal-reconnect-grace.js +87 -0
  19. package/dist/src/commands/terminal-sandbox.d.ts +5 -1
  20. package/dist/src/commands/terminal-sandbox.js +19 -5
  21. package/dist/src/commands/terminal-secure-browser.d.ts +25 -0
  22. package/dist/src/commands/terminal-secure-browser.js +58 -0
  23. package/dist/src/commands/terminal-service.d.ts +4 -3
  24. package/dist/src/commands/terminal-service.js +19 -15
  25. package/dist/src/commands/terminal.d.ts +22 -3
  26. package/dist/src/commands/terminal.js +622 -95
  27. package/dist/src/config.d.ts +0 -3
  28. package/dist/src/config.js +0 -2
  29. package/dist/src/migration.js +10 -11
  30. package/dist/src/request-queue.d.ts +20 -0
  31. package/dist/src/request-queue.js +80 -0
  32. package/dist/src/resource-inventory.js +9 -10
  33. package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
  34. package/dist/src/resource-syncs/database-view-sync.js +1 -12
  35. package/dist/src/resource-syncs/endpoint-sync.js +12 -46
  36. package/dist/src/types.d.ts +2 -0
  37. package/package.json +5 -3
@@ -1,7 +1,61 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
3
4
  const MAX_IMAGE_BYTES = 30 * 1024 * 1024;
4
5
  const MAX_IMAGE_BATCH_BYTES = 240 * 1024 * 1024;
6
+ /** Resolve the file actually held by an open descriptor, never the mutable input path. */
7
+ function openedFilePath(fd) {
8
+ if (process.platform === 'linux') {
9
+ try {
10
+ return fs.readlinkSync(`/proc/self/fd/${fd}`);
11
+ }
12
+ catch {
13
+ throw new Error('image_path_unverifiable');
14
+ }
15
+ }
16
+ if (process.platform === 'darwin') {
17
+ const result = spawnSync('/usr/sbin/lsof', ['-a', '-p', String(process.pid), '-d', String(fd), '-F0n'], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64_000 });
18
+ if (result.error || result.status !== 0 || typeof result.stdout !== 'string')
19
+ throw new Error('image_path_unverifiable');
20
+ const fields = result.stdout.split('\0').map(field => field.replace(/^\n/u, ''));
21
+ if (!fields.includes(`p${process.pid}`) || !fields.includes(`f${fd}`))
22
+ throw new Error('image_path_unverifiable');
23
+ const names = fields.filter(field => field.startsWith('n')).map(field => field.slice(1));
24
+ if (names.length !== 1)
25
+ throw new Error('image_path_unverifiable');
26
+ return names[0];
27
+ }
28
+ throw new Error('image_path_unverifiable');
29
+ }
30
+ function readWorkspaceImage(workspace, file) {
31
+ const root = fs.realpathSync(workspace);
32
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
33
+ try {
34
+ const stat = fs.fstatSync(fd);
35
+ const openedPath = openedFilePath(fd);
36
+ const relative = path.relative(root, openedPath);
37
+ if (!path.isAbsolute(openedPath) || !relative || relative.startsWith('..')
38
+ || path.isAbsolute(relative) || !stat.isFile())
39
+ throw new Error('image_outside_workspace');
40
+ if (stat.size < 1 || stat.size > MAX_IMAGE_BYTES)
41
+ throw new Error('image_size_invalid');
42
+ const data = Buffer.allocUnsafe(stat.size);
43
+ let offset = 0;
44
+ while (offset < data.length) {
45
+ const bytes = fs.readSync(fd, data, offset, data.length - offset, offset);
46
+ if (!bytes)
47
+ throw new Error('image_size_invalid');
48
+ offset += bytes;
49
+ }
50
+ if (fs.readSync(fd, Buffer.alloc(1), 0, 1, data.length) !== 0
51
+ || fs.fstatSync(fd).size !== data.length)
52
+ throw new Error('image_size_invalid');
53
+ return data;
54
+ }
55
+ finally {
56
+ fs.closeSync(fd);
57
+ }
58
+ }
5
59
  export function resolveWorkspaceImage(workspace, file) {
6
60
  const root = fs.realpathSync(workspace);
7
61
  const resolved = fs.realpathSync(file);
@@ -19,12 +73,16 @@ export async function uploadWorkspaceImages(workspace, files, signal) {
19
73
  const checked = files.map(file => ({ file, resolved: resolveWorkspaceImage(workspace, file.path) }));
20
74
  if (checked.reduce((total, item) => total + fs.statSync(item.resolved).size, 0) > MAX_IMAGE_BATCH_BYTES)
21
75
  throw new Error('image_batch_too_large');
76
+ let uploadedBytes = 0;
22
77
  for (const { file, resolved } of checked) {
23
78
  const url = new URL(file.uploadUrl);
24
79
  if (url.protocol !== 'https:' || url.username || url.password || url.port
25
80
  || !/(^|\.)storage\.googleapis\.com$/iu.test(url.hostname))
26
81
  throw new Error('image_upload_destination_invalid');
27
- const data = fs.readFileSync(resolved);
82
+ const data = readWorkspaceImage(workspace, resolved);
83
+ uploadedBytes += data.length;
84
+ if (uploadedBytes > MAX_IMAGE_BATCH_BYTES)
85
+ throw new Error('image_batch_too_large');
28
86
  const png = data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
29
87
  const jpeg = data.subarray(0, 3).equals(Buffer.from([255, 216, 255]));
30
88
  const webp = data.toString('ascii', 0, 4) === 'RIFF' && data.toString('ascii', 8, 12) === 'WEBP';
@@ -0,0 +1,18 @@
1
+ export type TerminalLogSeverity = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR';
2
+ export type TerminalLogTrace = {
3
+ assistantThreadId?: unknown;
4
+ assistantMessageId?: unknown;
5
+ executionId?: unknown;
6
+ };
7
+ export declare class TerminalOperationalLog {
8
+ private prepared;
9
+ private failed;
10
+ private currentDate;
11
+ private readonly directory;
12
+ private readonly now;
13
+ constructor(directory: string, now?: () => Date);
14
+ write(severity: TerminalLogSeverity, trace: TerminalLogTrace, event: string, details?: Record<string, unknown>): void;
15
+ private prepare;
16
+ private rotate;
17
+ private prune;
18
+ }
@@ -0,0 +1,119 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { gunzipSync, gzipSync } from 'node:zlib';
5
+ const ARCHIVE_RETENTION_MS = 30 * 24 * 60 * 60 * 1_000;
6
+ const SAFE_ATOM = /^[A-Za-z0-9_.:-]{1,120}$/u;
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']);
10
+ function atom(value) {
11
+ return typeof value === 'string' && SAFE_ATOM.test(value) ? value : '-';
12
+ }
13
+ function dateOf(value) {
14
+ return value.toISOString().slice(0, 10);
15
+ }
16
+ export class TerminalOperationalLog {
17
+ prepared = false;
18
+ failed = false;
19
+ currentDate = '';
20
+ directory;
21
+ now;
22
+ constructor(directory, now = () => new Date()) {
23
+ this.directory = directory;
24
+ this.now = now;
25
+ }
26
+ write(severity, trace, event, details = {}) {
27
+ if (this.failed)
28
+ return;
29
+ try {
30
+ const time = this.now();
31
+ this.prepare(time);
32
+ const fields = Object.entries(details)
33
+ .filter(([key]) => DETAIL_KEYS.has(key))
34
+ .map(([key, value]) => `${key}=${typeof value === 'number' && Number.isFinite(value) ? value
35
+ : typeof value === 'boolean' ? value : atom(value)}`);
36
+ if (trace.executionId)
37
+ fields.unshift(`executionId=${atom(trace.executionId)}`);
38
+ const line = `[${time.toISOString()}][${severity}][${atom(trace.assistantThreadId)}]`
39
+ + `[${atom(trace.assistantMessageId)}] ${atom(event)}${fields.length ? ` ${fields.join(' ')}` : ''}\n`;
40
+ const file = path.join(this.directory, 'debug.log');
41
+ const descriptor = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND
42
+ | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW || 0), 0o600);
43
+ try {
44
+ fs.fchmodSync(descriptor, 0o600);
45
+ fs.writeSync(descriptor, line);
46
+ }
47
+ finally {
48
+ fs.closeSync(descriptor);
49
+ }
50
+ }
51
+ catch {
52
+ // Operational diagnostics must never terminate a command or print sensitive data.
53
+ this.failed = true;
54
+ process.stderr.write('Revo terminal operational log unavailable.\n');
55
+ }
56
+ }
57
+ prepare(time) {
58
+ const currentDate = dateOf(time);
59
+ if (this.prepared && this.currentDate === currentDate)
60
+ return;
61
+ if (!this.prepared) {
62
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
63
+ fs.chmodSync(this.directory, 0o700);
64
+ this.prepared = true;
65
+ }
66
+ this.rotate(time);
67
+ this.prune(time);
68
+ this.currentDate = currentDate;
69
+ }
70
+ rotate(time) {
71
+ const active = path.join(this.directory, 'debug.log');
72
+ let stats;
73
+ try {
74
+ stats = fs.lstatSync(active);
75
+ }
76
+ catch (error) {
77
+ if (error.code === 'ENOENT')
78
+ return;
79
+ throw error;
80
+ }
81
+ if (!stats.isFile() || stats.isSymbolicLink())
82
+ throw new Error('invalid_operational_log');
83
+ const sourceDate = dateOf(stats.mtime);
84
+ if (sourceDate === dateOf(time))
85
+ return;
86
+ const archive = path.join(this.directory, `${sourceDate}-debug.log.gz`);
87
+ const archived = fs.existsSync(archive) ? fs.lstatSync(archive) : null;
88
+ if (archived && (!archived.isFile() || archived.isSymbolicLink()))
89
+ throw new Error('invalid_operational_archive');
90
+ const prior = archived ? gunzipSync(fs.readFileSync(archive)) : Buffer.alloc(0);
91
+ const compressed = gzipSync(Buffer.concat([prior, fs.readFileSync(active)]));
92
+ const temporary = `${archive}.${randomUUID()}.tmp`;
93
+ try {
94
+ fs.writeFileSync(temporary, compressed, { flag: 'wx', mode: 0o600 });
95
+ fs.renameSync(temporary, archive);
96
+ fs.chmodSync(archive, 0o600);
97
+ fs.unlinkSync(active);
98
+ }
99
+ finally {
100
+ try {
101
+ fs.unlinkSync(temporary);
102
+ }
103
+ catch (error) {
104
+ if (error.code !== 'ENOENT')
105
+ throw error;
106
+ }
107
+ }
108
+ }
109
+ prune(time) {
110
+ for (const name of fs.readdirSync(this.directory)) {
111
+ const match = /^(\d{4}-\d{2}-\d{2})-debug\.log\.gz$/u.exec(name);
112
+ if (!match)
113
+ continue;
114
+ const date = new Date(`${match[1]}T00:00:00.000Z`);
115
+ if (Number.isFinite(date.getTime()) && time.getTime() - date.getTime() > ARCHIVE_RETENTION_MS)
116
+ fs.unlinkSync(path.join(this.directory, name));
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,29 @@
1
+ import type { TerminalNetworkAccess, TerminalSandbox } from './terminal-sandbox.ts';
2
+ export type TerminalCommandAccess = 'workspace' | 'host';
3
+ export type TerminalExecutePolicy = {
4
+ policyVersion: 2;
5
+ commandAccess: TerminalCommandAccess;
6
+ networkAccess: TerminalNetworkAccess;
7
+ commandAccessExpiresAt: number | null;
8
+ networkAccessExpiresAt: number | null;
9
+ networkAccessOnce?: boolean;
10
+ policyGrantRevision: number;
11
+ };
12
+ export type TerminalGrantPolicy = {
13
+ mode: 'review' | 'full';
14
+ networkMode: 'restricted' | 'sandbox' | 'external';
15
+ };
16
+ export declare function executionAllowedByGrant(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy, now?: number): boolean;
17
+ export declare function remainingPolicyDeadline(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy): number | null;
18
+ type PolicyFrame = Partial<TerminalExecutePolicy> & {
19
+ operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
20
+ sandbox?: TerminalSandbox;
21
+ browserLocalOnly?: boolean;
22
+ };
23
+ /** The connected Realtime process must send a complete, current policy for every execution. */
24
+ export declare function validateExecutePolicy(frame: PolicyFrame, now?: number): string | null;
25
+ export declare function executionPolicyDeadline(frame: TerminalExecutePolicy & {
26
+ operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
27
+ sandbox?: TerminalSandbox;
28
+ }): number | null;
29
+ export {};
@@ -0,0 +1,67 @@
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.commandAccessExpiresAt !== null && policy.commandAccessExpiresAt > now;
6
+ const networkAllowed = networkRank[policy.networkAccess] <= permanentNetwork
7
+ || 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
+ }
20
+ function validDeadline(value) {
21
+ return value === null || Number.isSafeInteger(value) && Number(value) > 0;
22
+ }
23
+ /** The connected Realtime process must send a complete, current policy for every execution. */
24
+ export function validateExecutePolicy(frame, now = Date.now()) {
25
+ if (frame.policyVersion !== 2 || !['workspace', 'host'].includes(frame.commandAccess || '')
26
+ || !['none', 'local', 'full'].includes(frame.networkAccess || '')
27
+ || !validDeadline(frame.commandAccessExpiresAt)
28
+ || !validDeadline(frame.networkAccessExpiresAt)
29
+ || !Number.isSafeInteger(frame.policyGrantRevision) || frame.policyGrantRevision < 0)
30
+ return 'terminal_policy_v2_required';
31
+ if (frame.commandAccessExpiresAt !== null && frame.commandAccessExpiresAt <= now
32
+ || frame.networkAccessExpiresAt !== null && frame.networkAccessExpiresAt <= now)
33
+ return 'terminal_policy_expired';
34
+ if (frame.sandbox === 'unrestricted' && frame.commandAccess !== 'host')
35
+ return 'terminal_command_access_denied';
36
+ if (frame.sandbox === 'workspace-network' && frame.operation === 'shell'
37
+ && frame.networkAccess !== 'full')
38
+ return 'terminal_network_disabled';
39
+ if (frame.sandbox === 'workspace' && frame.operation === 'shell'
40
+ && frame.networkAccess === 'full')
41
+ return 'terminal_policy_invalid';
42
+ if (frame.operation === 'apply_patch' && frame.networkAccess !== 'none')
43
+ return 'terminal_policy_invalid';
44
+ if (frame.operation === 'browser') {
45
+ if (frame.networkAccess === 'none')
46
+ return 'terminal_network_disabled';
47
+ if (frame.browserLocalOnly !== (frame.networkAccess === 'local'))
48
+ return 'terminal_policy_invalid';
49
+ }
50
+ if (frame.networkAccessOnce !== undefined && typeof frame.networkAccessOnce !== 'boolean'
51
+ || frame.networkAccessOnce === true && (frame.operation !== 'browser'
52
+ || frame.networkAccessExpiresAt === null))
53
+ return 'terminal_policy_invalid';
54
+ if (frame.operation === 'save_image' && frame.networkAccess !== 'full')
55
+ return 'terminal_network_disabled';
56
+ return null;
57
+ }
58
+ export function executionPolicyDeadline(frame) {
59
+ const deadlines = [
60
+ ...(frame.sandbox === 'unrestricted' && frame.commandAccessExpiresAt !== null
61
+ ? [frame.commandAccessExpiresAt] : []),
62
+ ...(frame.networkAccess !== 'none' && frame.networkAccessExpiresAt !== null
63
+ && (frame.sandbox === 'unrestricted' || frame.sandbox === 'workspace-network'
64
+ || frame.operation === 'browser') ? [frame.networkAccessExpiresAt] : []),
65
+ ];
66
+ return deadlines.length ? Math.min(...deadlines) : null;
67
+ }
@@ -0,0 +1,4 @@
1
+ /** node-pty's macOS prebuild launches this helper with posix_spawn. */
2
+ export declare function ensurePtyHelperExecutable(packageRoot?: string, platform?: NodeJS.Platform, arch?: NodeJS.Architecture): void;
3
+ /** These failures happen before node-pty starts the requested process. */
4
+ export declare function normalizePtyStartError(error: unknown): Error;
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ const require = createRequire(import.meta.url);
5
+ /** node-pty's macOS prebuild launches this helper with posix_spawn. */
6
+ export function ensurePtyHelperExecutable(packageRoot = path.dirname(require.resolve('node-pty/package.json')), platform = process.platform, arch = process.arch) {
7
+ if (platform !== 'darwin')
8
+ return;
9
+ const candidates = [path.join(packageRoot, 'prebuilds', `darwin-${arch}`, 'spawn-helper'),
10
+ path.join(packageRoot, 'build', 'Release', 'spawn-helper')];
11
+ let found = false;
12
+ for (const helper of candidates) {
13
+ if (!fs.existsSync(helper))
14
+ continue;
15
+ found = true;
16
+ const stat = fs.lstatSync(helper);
17
+ if (!stat.isFile())
18
+ throw new Error('pty_helper_invalid');
19
+ try {
20
+ // Keep the package file executable without inheriting world/group write
21
+ // or special permission bits from a damaged installation.
22
+ const safeMode = ((stat.mode & 0o777) & ~0o022) | 0o111;
23
+ if ((stat.mode & 0o7777) !== safeMode)
24
+ fs.chmodSync(helper, safeMode);
25
+ fs.accessSync(helper, fs.constants.X_OK);
26
+ }
27
+ catch {
28
+ throw new Error('pty_helper_not_executable');
29
+ }
30
+ }
31
+ if (!found)
32
+ throw new Error('pty_helper_missing');
33
+ }
34
+ /** These failures happen before node-pty starts the requested process. */
35
+ export function normalizePtyStartError(error) {
36
+ const message = error instanceof Error ? error.message : String(error);
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))
40
+ ? new Error('pty_unavailable') : error instanceof Error ? error : new Error(message);
41
+ }
@@ -0,0 +1,30 @@
1
+ /** One grace period from the first lost runner socket; failed reconnects do not renew it. */
2
+ export declare class TerminalReconnectGrace {
3
+ private timer?;
4
+ private readonly onExpire;
5
+ private readonly delayMs;
6
+ private readonly scheduleTimer;
7
+ private readonly clearTimer;
8
+ constructor(onExpire: () => void, delayMs?: number, scheduleTimer?: typeof setTimeout, clearTimer?: typeof clearTimeout);
9
+ start(hasRunningWork: boolean): void;
10
+ clear(): void;
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;
@@ -0,0 +1,87 @@
1
+ /** One grace period from the first lost runner socket; failed reconnects do not renew it. */
2
+ export class TerminalReconnectGrace {
3
+ timer;
4
+ onExpire;
5
+ delayMs;
6
+ scheduleTimer;
7
+ clearTimer;
8
+ constructor(onExpire, delayMs = 120_000, scheduleTimer = setTimeout, clearTimer = clearTimeout) {
9
+ this.onExpire = onExpire;
10
+ this.delayMs = delayMs;
11
+ this.scheduleTimer = scheduleTimer;
12
+ this.clearTimer = clearTimer;
13
+ }
14
+ start(hasRunningWork) {
15
+ if (!hasRunningWork || this.timer)
16
+ return;
17
+ this.timer = this.scheduleTimer(() => {
18
+ this.timer = undefined;
19
+ this.onExpire();
20
+ }, this.delayMs);
21
+ this.timer.unref?.();
22
+ }
23
+ clear() {
24
+ if (!this.timer)
25
+ return;
26
+ this.clearTimer(this.timer);
27
+ this.timer = undefined;
28
+ }
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
+ }
@@ -1,6 +1,10 @@
1
1
  export type TerminalSandbox = 'workspace' | 'workspace-network' | 'unrestricted';
2
+ export type TerminalNetworkAccess = 'none' | 'local' | 'full';
3
+ export declare function isTerminalSandbox(value: unknown): value is TerminalSandbox;
4
+ /** Keep macOS private TMPDIR short enough for Nx and other Unix-domain sockets. */
5
+ export declare function createSandboxScratchDirectory(platform?: NodeJS.Platform): string;
2
6
  export declare function shellQuote(value: string): string;
3
- export declare function sandboxCommand(workspace: string, workdir: string, command: string, sandbox: TerminalSandbox, platform?: NodeJS.Platform, scratchDir?: string, readPaths?: string[], networkAllowed?: boolean): {
7
+ export declare function sandboxCommand(workspace: string, workdir: string, command: string, sandbox: TerminalSandbox, platform?: NodeJS.Platform, scratchDir?: string, readPaths?: string[], networkAccess?: TerminalNetworkAccess): {
4
8
  file: string;
5
9
  args: string[];
6
10
  };
@@ -1,22 +1,34 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ export function isTerminalSandbox(value) {
5
+ return value === 'workspace' || value === 'workspace-network' || value === 'unrestricted';
6
+ }
7
+ /** Keep macOS private TMPDIR short enough for Nx and other Unix-domain sockets. */
8
+ export function createSandboxScratchDirectory(platform = process.platform) {
9
+ const base = platform === 'darwin' ? fs.realpathSync('/tmp') : os.tmpdir();
10
+ return fs.mkdtempSync(path.join(base, 'revo-terminal-'));
11
+ }
4
12
  export function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
5
13
  function seatbeltLiteral(value) {
6
14
  return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
7
15
  }
8
- export function sandboxCommand(workspace, workdir, command, sandbox, platform = process.platform, scratchDir, readPaths = [], networkAllowed = true) {
16
+ export function sandboxCommand(workspace, workdir, command, sandbox, platform = process.platform, scratchDir, readPaths = [], networkAccess = 'none') {
9
17
  const shell = platform === 'darwin' ? '/bin/zsh' : '/bin/sh';
10
- if (sandbox === 'unrestricted' && networkAllowed)
18
+ if (sandbox === 'unrestricted' && networkAccess === 'full')
11
19
  return { file: shell, args: ['-lc', command] };
12
20
  if (sandbox === 'unrestricted') {
13
21
  if (platform === 'darwin') {
14
22
  if (!fs.existsSync('/usr/bin/sandbox-exec'))
15
23
  throw new Error('network_sandbox_unavailable');
16
24
  return { file: '/usr/bin/sandbox-exec',
17
- args: ['-p', '(version 1)\n(allow default)\n(deny network*)', shell, '-c', command] };
25
+ args: ['-p', ['(version 1)', '(allow default)', '(deny network*)',
26
+ ...(networkAccess === 'local' ? ['(allow network-outbound (remote ip "localhost:*"))',
27
+ '(allow network-inbound (local ip "localhost:*"))'] : [])].join('\n'), shell, '-c', command] };
18
28
  }
19
29
  if (platform === 'linux') {
30
+ if (networkAccess === 'local')
31
+ throw new Error('local_network_sandbox_unavailable');
20
32
  return { file: 'bwrap', args: ['--die-with-parent', '--unshare-net', '--bind', '/', '/',
21
33
  '--dev-bind', '/dev', '/dev', '--proc', '/proc', '--chdir', fs.realpathSync(workdir), shell, '-c', command] };
22
34
  }
@@ -24,7 +36,7 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
24
36
  }
25
37
  if (sandbox !== 'workspace' && sandbox !== 'workspace-network')
26
38
  throw new Error('Invalid terminal sandbox.');
27
- if (sandbox === 'workspace-network' && !networkAllowed)
39
+ if (sandbox === 'workspace-network' && networkAccess !== 'full')
28
40
  throw new Error('terminal_network_disabled');
29
41
  const root = fs.realpathSync(workspace);
30
42
  const cwd = fs.realpathSync(workdir);
@@ -55,7 +67,7 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
55
67
  const profile = [
56
68
  '(version 1)', '(allow default)',
57
69
  ...(sandbox === 'workspace' ? ['(deny network*)',
58
- ...(networkAllowed ? ['(allow network-outbound (remote ip "localhost:*"))',
70
+ ...(networkAccess !== 'none' ? ['(allow network-outbound (remote ip "localhost:*"))',
59
71
  '(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
60
72
  '(deny file-write*)',
61
73
  `(allow file-write* (subpath ${seatbeltLiteral(root)}))`,
@@ -74,6 +86,8 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
74
86
  if (platform === 'linux') {
75
87
  if (root === '/')
76
88
  throw new Error('Workspace root cannot be the filesystem root.');
89
+ if (sandbox === 'workspace' && networkAccess === 'local')
90
+ throw new Error('local_network_sandbox_unavailable');
77
91
  return { file: 'bwrap', args: ['--die-with-parent',
78
92
  ...(sandbox === 'workspace' ? ['--unshare-net'] : []), '--ro-bind', '/', '/',
79
93
  '--dev-bind', '/dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
@@ -0,0 +1,25 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ export type SecureBrowserInputEnvelope = {
3
+ type: 'secure_browser_input';
4
+ requestId: string;
5
+ threadId: string;
6
+ agentTerminalId: string;
7
+ browserSessionId: string;
8
+ origin: string;
9
+ selector: string;
10
+ connectionId: string;
11
+ keyId: string;
12
+ expiresAt: number;
13
+ ephemeralPublicKey: string;
14
+ iv: string;
15
+ ciphertext: string;
16
+ tag: string;
17
+ };
18
+ export type SecureBrowserIdentity = {
19
+ publicKey: string;
20
+ keyId: string;
21
+ privateKey: KeyObject;
22
+ };
23
+ export declare function createSecureBrowserIdentity(): SecureBrowserIdentity;
24
+ export declare function secureBrowserInputAad(frame: SecureBrowserInputEnvelope): Buffer;
25
+ export declare function decryptSecureBrowserInput(frame: SecureBrowserInputEnvelope, identity: SecureBrowserIdentity): string;
@@ -0,0 +1,58 @@
1
+ import { createDecipheriv, createHash, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync } from 'node:crypto';
2
+ const INFO = Buffer.from('revo-browser-credential-v1', 'utf8');
3
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
4
+ function bytes(value, min, max) {
5
+ if (typeof value !== 'string' || !BASE64.test(value))
6
+ throw new Error('secure_input_invalid');
7
+ const decoded = Buffer.from(value, 'base64');
8
+ if (decoded.length < min || decoded.length > max || decoded.toString('base64') !== value)
9
+ throw new Error('secure_input_invalid');
10
+ return decoded;
11
+ }
12
+ export function createSecureBrowserIdentity() {
13
+ const pair = generateKeyPairSync('x25519');
14
+ const publicKey = pair.publicKey.export({ type: 'spki', format: 'der' });
15
+ return { publicKey: publicKey.toString('base64'),
16
+ keyId: createHash('sha256').update(publicKey).digest('hex'), privateKey: pair.privateKey };
17
+ }
18
+ export function secureBrowserInputAad(frame) {
19
+ return Buffer.from(JSON.stringify([frame.requestId, frame.threadId, frame.agentTerminalId,
20
+ frame.browserSessionId, frame.origin, frame.selector, frame.connectionId,
21
+ frame.keyId, frame.expiresAt]), 'utf8');
22
+ }
23
+ export function decryptSecureBrowserInput(frame, identity) {
24
+ if (frame.keyId !== identity.keyId || !Number.isSafeInteger(frame.expiresAt)
25
+ || frame.expiresAt < Date.now() || frame.expiresAt > Date.now() + 120_000
26
+ || !/^[a-f0-9-]{36}$/iu.test(frame.requestId)
27
+ || !/^[a-f0-9]{64}$/u.test(frame.browserSessionId)
28
+ || typeof frame.selector !== 'string' || !frame.selector.trim() || frame.selector.length > 500
29
+ || typeof frame.origin !== 'string' || frame.origin.length > 2_048
30
+ || typeof frame.threadId !== 'string' || frame.threadId.length > 128
31
+ || typeof frame.agentTerminalId !== 'string' || frame.agentTerminalId.length > 128
32
+ || typeof frame.connectionId !== 'string' || frame.connectionId.length > 128)
33
+ throw new Error('secure_input_invalid');
34
+ const publicBytes = bytes(frame.ephemeralPublicKey, 44, 128);
35
+ const publicKey = createPublicKey({ key: publicBytes, format: 'der', type: 'spki' });
36
+ if (publicKey.asymmetricKeyType !== 'x25519')
37
+ throw new Error('secure_input_invalid');
38
+ const shared = diffieHellman({ privateKey: identity.privateKey, publicKey });
39
+ const key = Buffer.from(hkdfSync('sha256', shared, Buffer.from(frame.requestId, 'utf8'), INFO, 32));
40
+ shared.fill(0);
41
+ const decipher = createDecipheriv('aes-256-gcm', key, bytes(frame.iv, 12, 12));
42
+ decipher.setAAD(secureBrowserInputAad(frame));
43
+ decipher.setAuthTag(bytes(frame.tag, 16, 16));
44
+ try {
45
+ const plaintext = Buffer.concat([decipher.update(bytes(frame.ciphertext, 1, 8_192)), decipher.final()]);
46
+ if (plaintext.length > 4_096)
47
+ throw new Error('secure_input_invalid');
48
+ const value = plaintext.toString('utf8');
49
+ plaintext.fill(0);
50
+ return value;
51
+ }
52
+ catch {
53
+ throw new Error('secure_input_invalid');
54
+ }
55
+ finally {
56
+ key.fill(0);
57
+ }
58
+ }