@revoengine/cli 1.0.38 → 2.0.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/CHANGELOG.md +33 -0
- package/README.md +22 -10
- package/dist/src/argument-contract.js +5 -5
- package/dist/src/automation-contract.generated.d.ts +6 -30
- package/dist/src/automation-contract.generated.js +6 -30
- package/dist/src/client.d.ts +2 -2
- package/dist/src/client.js +4 -14
- package/dist/src/commands/component.js +16 -0
- package/dist/src/commands/database-tables.js +1 -1
- package/dist/src/commands/emulate.js +67 -74
- package/dist/src/commands/terminal-browser-human-input.d.ts +28 -0
- package/dist/src/commands/terminal-browser-human-input.js +56 -7
- package/dist/src/commands/terminal-browser-live-protocol.d.ts +13 -1
- package/dist/src/commands/terminal-browser-live-protocol.js +20 -4
- package/dist/src/commands/terminal-browser-live-transport.d.ts +2 -0
- package/dist/src/commands/terminal-browser-live-transport.js +21 -4
- package/dist/src/commands/terminal-browser-live.d.ts +36 -1
- package/dist/src/commands/terminal-browser-live.js +435 -106
- package/dist/src/commands/terminal-browser-observation.d.ts +1 -1
- package/dist/src/commands/terminal-browser-observation.js +10 -1
- package/dist/src/commands/terminal-browser-page-input.d.ts +1 -0
- package/dist/src/commands/terminal-browser-page-input.js +20 -0
- package/dist/src/commands/terminal-browser-profile-sync.d.ts +5 -1
- package/dist/src/commands/terminal-browser-profile-sync.js +13 -2
- package/dist/src/commands/terminal-browser-profile-sync.protocol.d.ts +2 -0
- package/dist/src/commands/terminal-browser-recording.d.ts +6 -3
- package/dist/src/commands/terminal-browser-recording.js +45 -15
- package/dist/src/commands/terminal-browser.d.ts +17 -0
- package/dist/src/commands/terminal-browser.js +318 -111
- package/dist/src/commands/terminal-operational-log.js +2 -1
- package/dist/src/commands/terminal-output-buffer.d.ts +2 -0
- package/dist/src/commands/terminal-output-buffer.js +6 -0
- package/dist/src/commands/terminal-reconnect-grace.d.ts +1 -0
- package/dist/src/commands/terminal-reconnect-grace.js +1 -0
- package/dist/src/commands/terminal-sandbox.js +22 -6
- package/dist/src/commands/terminal.js +136 -40
- package/dist/src/endpoint-emulator.d.ts +16 -13
- package/dist/src/endpoint-emulator.js +26 -35
- package/dist/src/project.js +1 -0
- package/dist/src/request-contract.d.ts +2 -0
- package/dist/src/request-contract.js +11 -1
- package/dist/src/resource-syncs/database-table-sync.d.ts +2 -1
- package/dist/src/resource-syncs/database-table-sync.js +60 -23
- package/dist/src/sync-omit.js +1 -1
- package/dist/src/types.d.ts +0 -3
- package/dist/src/ui.js +2 -2
- package/package.json +1 -1
|
@@ -6,7 +6,8 @@ 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
8
|
'exitCode', 'signal', 'images', 'screenshot', 'executed', 'timedOut', 'truncated', 'activeExecutions',
|
|
9
|
-
'resumedExecutions', 'stoppedExecutions', 'closedBrowserSessions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds'
|
|
9
|
+
'resumedExecutions', 'stoppedExecutions', 'closedBrowserSessions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds',
|
|
10
|
+
'status', 'recordingId', 'stage']);
|
|
10
11
|
function atom(value) {
|
|
11
12
|
return typeof value === 'string' && SAFE_ATOM.test(value) ? value : '-';
|
|
12
13
|
}
|
|
@@ -5,6 +5,8 @@ export type TerminalOutputChunk = {
|
|
|
5
5
|
};
|
|
6
6
|
export declare const TERMINAL_CAPTURE_MAX_BYTES = 1000000000;
|
|
7
7
|
export declare const TERMINAL_CAPTURE_MAX_CHUNKS = 1000000;
|
|
8
|
+
/** A UTF-16 limit must leave a complete Unicode code point at the boundary. */
|
|
9
|
+
export declare function clipTerminalText(text: string, limit: number): string;
|
|
8
10
|
/** Private, process-local replay spool. Only a committed server ACK prunes its index. */
|
|
9
11
|
export declare class TerminalOutputBuffer {
|
|
10
12
|
private readonly chunks;
|
|
@@ -4,6 +4,12 @@ import path from 'node:path';
|
|
|
4
4
|
export const TERMINAL_CAPTURE_MAX_BYTES = 1_000_000_000;
|
|
5
5
|
export const TERMINAL_CAPTURE_MAX_CHUNKS = 1_000_000;
|
|
6
6
|
const WINDOW_BYTES = 256_000;
|
|
7
|
+
/** A UTF-16 limit must leave a complete Unicode code point at the boundary. */
|
|
8
|
+
export function clipTerminalText(text, limit) {
|
|
9
|
+
if (text.length <= limit)
|
|
10
|
+
return text;
|
|
11
|
+
return text.slice(0, limit).replace(/[\uD800-\uDBFF]$/u, '');
|
|
12
|
+
}
|
|
7
13
|
/** Private, process-local replay spool. Only a committed server ACK prunes its index. */
|
|
8
14
|
export class TerminalOutputBuffer {
|
|
9
15
|
chunks = new Map();
|
|
@@ -13,6 +13,26 @@ export function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
|
13
13
|
function seatbeltLiteral(value) {
|
|
14
14
|
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
15
15
|
}
|
|
16
|
+
function privateUnixSocketRules(scratchDir, unrestricted = false) {
|
|
17
|
+
if (!scratchDir)
|
|
18
|
+
return [];
|
|
19
|
+
const scratchPath = fs.realpathSync(scratchDir);
|
|
20
|
+
const scratch = seatbeltLiteral(scratchPath);
|
|
21
|
+
// A host command can move an existing directory. Limit its socket allowance to
|
|
22
|
+
// direct children and prevent moving existing sockets or replacing scratch.
|
|
23
|
+
const socketPath = unrestricted
|
|
24
|
+
? `(regex #${seatbeltLiteral('^' + scratchPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '/[^/]+$')})`
|
|
25
|
+
: `(subpath ${scratch})`;
|
|
26
|
+
return [
|
|
27
|
+
`(allow network-bind (local unix-socket ${socketPath}))`,
|
|
28
|
+
`(allow network-inbound (local unix-socket ${socketPath}))`,
|
|
29
|
+
`(allow network-outbound (remote unix-socket ${socketPath}))`,
|
|
30
|
+
...(unrestricted ? [
|
|
31
|
+
`(deny file-write-unlink (require-all (vnode-type SOCKET) (require-not ${socketPath})))`,
|
|
32
|
+
`(deny file-write-unlink (literal ${scratch}))`,
|
|
33
|
+
] : []),
|
|
34
|
+
];
|
|
35
|
+
}
|
|
16
36
|
export function sandboxCommand(workspace, workdir, command, sandbox, platform = process.platform, scratchDir, readPaths = [], networkAccess = 'none') {
|
|
17
37
|
const shell = platform === 'darwin' ? '/bin/zsh' : '/bin/sh';
|
|
18
38
|
if (sandbox === 'unrestricted' && networkAccess === 'full')
|
|
@@ -24,7 +44,7 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
|
|
|
24
44
|
return { file: '/usr/bin/sandbox-exec',
|
|
25
45
|
args: ['-p', ['(version 1)', '(allow default)', '(deny network*)',
|
|
26
46
|
...(networkAccess === 'local' ? ['(allow network-outbound (remote ip "localhost:*"))',
|
|
27
|
-
'(allow network-inbound (local ip "localhost:*"))'] : [])].join('\n'), shell, '-c', command] };
|
|
47
|
+
'(allow network-inbound (local ip "localhost:*"))', ...privateUnixSocketRules(scratchDir, true)] : [])].join('\n'), shell, '-c', command] };
|
|
28
48
|
}
|
|
29
49
|
if (platform === 'linux') {
|
|
30
50
|
if (networkAccess === 'local')
|
|
@@ -69,11 +89,7 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
|
|
|
69
89
|
...(sandbox === 'workspace' ? ['(deny network*)',
|
|
70
90
|
// Build workers need local IPC. Keep it inside this command's private scratch;
|
|
71
91
|
// 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
|
-
] : []),
|
|
92
|
+
...privateUnixSocketRules(scratchDir),
|
|
77
93
|
...(networkAccess !== 'none' ? ['(allow network-outbound (remote ip "localhost:*"))',
|
|
78
94
|
'(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
|
|
79
95
|
'(deny file-write*)',
|
|
@@ -14,7 +14,7 @@ import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStor
|
|
|
14
14
|
import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
|
|
15
15
|
import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
|
|
16
16
|
import { executionAllowedByGrant, executionPolicyDeadline, remainingPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
|
|
17
|
-
import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, revokeBrowserProfileSession, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
|
|
17
|
+
import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, browserRuntimeInventory, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, revokeBrowserProfileSession, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
|
|
18
18
|
import { transferWorkspaceFile, validateFileTransfer } from "./terminal-file.js";
|
|
19
19
|
import { uploadWorkspaceImages } from "./terminal-image.js";
|
|
20
20
|
import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
|
|
@@ -24,7 +24,7 @@ import { CentralBrowserProfileLease } from "./terminal-browser-central-profile.j
|
|
|
24
24
|
import { BrowserProfileRunnerRpc } from "./terminal-browser-profile-sync.js";
|
|
25
25
|
import { LegacyBrowserProfileImporter } from "./terminal-browser-profile-import.js";
|
|
26
26
|
import { BrowserProfileImportRunner } from "./terminal-browser-profile-import-runner.js";
|
|
27
|
-
import { TerminalOutputBuffer, TERMINAL_CAPTURE_MAX_BYTES as MAX_CAPTURE_OUTPUT_BYTES } from "./terminal-output-buffer.js";
|
|
27
|
+
import { clipTerminalText, TerminalOutputBuffer, TERMINAL_CAPTURE_MAX_BYTES as MAX_CAPTURE_OUTPUT_BYTES } from "./terminal-output-buffer.js";
|
|
28
28
|
import { TerminalOperationalLog } from "./terminal-operational-log.js";
|
|
29
29
|
import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
|
|
30
30
|
import { BrowserAuthProfileStore, macOSBrowserProfileKeyStore, validateBrowserProfileName } from "./terminal-browser-profile.js";
|
|
@@ -393,9 +393,9 @@ export function boundResultFrame(frame) {
|
|
|
393
393
|
while (Buffer.byteLength(bounded.stdout) + Buffer.byteLength(bounded.stderr) > 80_000
|
|
394
394
|
|| Buffer.byteLength(JSON.stringify(bounded)) > 90_000) {
|
|
395
395
|
if (bounded.stdout.length >= bounded.stderr.length)
|
|
396
|
-
bounded.stdout = bounded.stdout
|
|
396
|
+
bounded.stdout = clipTerminalText(bounded.stdout, Math.floor(bounded.stdout.length * 0.75));
|
|
397
397
|
else
|
|
398
|
-
bounded.stderr = bounded.stderr
|
|
398
|
+
bounded.stderr = clipTerminalText(bounded.stderr, Math.floor(bounded.stderr.length * 0.75));
|
|
399
399
|
bounded.truncated = true;
|
|
400
400
|
}
|
|
401
401
|
return bounded;
|
|
@@ -412,7 +412,9 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
412
412
|
if (sandbox !== 'unrestricted' && requiresElevatedCommand(input.cmd))
|
|
413
413
|
throw new Error('destructive_command_requires_approval');
|
|
414
414
|
assertTerminalProcessProbeAvailable();
|
|
415
|
-
const
|
|
415
|
+
const isolatedWorkspace = sandbox !== 'unrestricted';
|
|
416
|
+
const needsScratch = isolatedWorkspace || (process.platform === 'darwin' && input.networkAccess === 'local');
|
|
417
|
+
const scratch = needsScratch ? createSandboxScratchDirectory() : undefined;
|
|
416
418
|
const scratchRoot = scratch ? fs.realpathSync(scratch) : undefined;
|
|
417
419
|
let launch;
|
|
418
420
|
try {
|
|
@@ -433,8 +435,9 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
433
435
|
catch (error) {
|
|
434
436
|
console.error(`Runner log unavailable: ${error.message}`);
|
|
435
437
|
}
|
|
436
|
-
const env = { ...childEnvironment(process.env),
|
|
437
|
-
|
|
438
|
+
const env = { ...childEnvironment(process.env),
|
|
439
|
+
...(scratchRoot ? { TMPDIR: scratchRoot, TMP: scratchRoot, TEMP: scratchRoot } : {}),
|
|
440
|
+
...(scratchRoot && isolatedWorkspace ? { HOME: scratchRoot, GIT_CONFIG_GLOBAL: '/dev/null',
|
|
438
441
|
XDG_CONFIG_HOME: path.join(scratchRoot, 'xdg-config'),
|
|
439
442
|
npm_config_cache: path.join(scratchRoot, 'npm-cache'), XDG_CACHE_HOME: path.join(scratchRoot, 'xdg-cache'),
|
|
440
443
|
PIP_CACHE_DIR: path.join(scratchRoot, 'pip-cache') } : {}) };
|
|
@@ -802,7 +805,18 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
802
805
|
? device.agentTerminalId : createHash('sha256').update(device.agentTerminalId).digest('hex');
|
|
803
806
|
const operationalLog = new TerminalOperationalLog(path.join(configDir(), 'logs', 'terminal', logDeviceId));
|
|
804
807
|
operationalLog.write('INFO', {}, 'runner.started');
|
|
808
|
+
let lastBrowserInventory = '';
|
|
809
|
+
const reportBrowserInventory = () => {
|
|
810
|
+
const inventory = browserRuntimeInventory();
|
|
811
|
+
const snapshot = JSON.stringify(inventory);
|
|
812
|
+
if (snapshot === lastBrowserInventory)
|
|
813
|
+
return;
|
|
814
|
+
lastBrowserInventory = snapshot;
|
|
815
|
+
console.log([`Browser: ${inventory.browsers} contexts · ${inventory.sessions.length} sessions · ${inventory.tabs} tabs`,
|
|
816
|
+
...inventory.sessions.map(session => ` ${session.id} ${session.profile || 'Temporary profile'} · ${session.tabs} tabs · ${session.mode}${session.restored ? ' · saved state loaded' : ''}`)].join('\n'));
|
|
817
|
+
};
|
|
805
818
|
let backoffMs = 1_000;
|
|
819
|
+
let announcedConnection = false;
|
|
806
820
|
let stopping = false;
|
|
807
821
|
let activeSocket;
|
|
808
822
|
let activeConnectionId = '';
|
|
@@ -907,6 +921,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
907
921
|
const live = new TerminalBrowserLiveTransport({ runnerUrl: device.realtimeUrl,
|
|
908
922
|
headers: { Authorization: `Bearer ${profile.token}`, ...(profile.instance ? { instance: profile.instance } : {}) },
|
|
909
923
|
authorized: liveAuthorized,
|
|
924
|
+
onInventoryChanged: reportBrowserInventory,
|
|
910
925
|
options: frame => {
|
|
911
926
|
const scope = browserScopes.get(frame.browserSessionId);
|
|
912
927
|
if (!scope || !liveAuthorized(frame))
|
|
@@ -915,7 +930,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
915
930
|
actorUserId: frame.actorUserId, threadId: frame.threadId,
|
|
916
931
|
agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId, connectionId: frame.connectionId,
|
|
917
932
|
identity: secureIdentity, profileOwner: scope.owner,
|
|
918
|
-
initialControl: { controlEpoch: frame.controlEpoch, mode: frame.mode, private: frame.private },
|
|
933
|
+
initialControl: { controlEpoch: frame.controlEpoch, mode: frame.mode, private: frame.private, tabId: frame.controlledTabId },
|
|
919
934
|
recordingDirectory: path.join(fs.realpathSync(configDir()), 'browser-recordings', device.agentTerminalId),
|
|
920
935
|
isAuthorized: () => liveAuthorized(frame) };
|
|
921
936
|
} });
|
|
@@ -928,13 +943,23 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
928
943
|
activeSocket = socket;
|
|
929
944
|
let connectionId = '';
|
|
930
945
|
let profileRpc;
|
|
946
|
+
const sharedProfileOpens = new Map();
|
|
947
|
+
const revokeProfileMember = async (id, profileId) => {
|
|
948
|
+
revokedProfileSessions.set(id, Date.now() + 60_000);
|
|
949
|
+
const central = centralProfiles.get(id);
|
|
950
|
+
centralProfiles.delete(id);
|
|
951
|
+
await revokeBrowserProfileSession(id, profileId);
|
|
952
|
+
if (central?.shared)
|
|
953
|
+
await central.shared.releaseMember();
|
|
954
|
+
else
|
|
955
|
+
await central?.lease.release();
|
|
956
|
+
};
|
|
931
957
|
let profileImports;
|
|
932
958
|
let defaultWorkspace = device.workspace;
|
|
933
959
|
let heartbeat;
|
|
934
960
|
let lastHeartbeat = Date.now();
|
|
935
961
|
let incoming = Promise.resolve();
|
|
936
962
|
const recovery = new TerminalTransportRecovery(() => socket.terminate(), () => {
|
|
937
|
-
backoffMs = 1_000;
|
|
938
963
|
reconnectGrace.clear();
|
|
939
964
|
});
|
|
940
965
|
socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
|
|
@@ -942,8 +967,8 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
942
967
|
'terminal_policy_v2', 'terminal_policy_selective_v1', 'background_shell_v1', 'terminal_thread_scope_v1',
|
|
943
968
|
'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
|
|
944
969
|
'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'browser_tabs_v1', 'save_image_v1',
|
|
945
|
-
'browser_timeout_v1', 'browser_public_read_v1', 'terminal_workspaces_v1', 'file_transfer_v1', 'browser_control_v1', 'browser_live_v1', 'browser_interaction_v1', 'browser_controls_v2', 'browser_recording_v1', 'browser_recording_session_v1',
|
|
946
|
-
'browser_profiles_v2', ...(legacyImportAvailable ? ['browser_profile_import_v1'] : []),
|
|
970
|
+
'browser_timeout_v1', 'browser_public_read_v1', 'terminal_workspaces_v1', 'file_transfer_v1', 'browser_control_v1', 'browser_live_v1', 'browser_interaction_v1', 'browser_controls_v2', 'browser_recording_v1', 'browser_recording_session_v1', 'browser_recording_save_v1',
|
|
971
|
+
'browser_profiles_v2', 'browser_shared_profiles_v1', 'browser_live_tab_management_v1', 'browser_live_pointer_v1', 'browser_live_tab_control_v1', ...(legacyImportAvailable ? ['browser_profile_import_v1'] : []),
|
|
947
972
|
...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
|
|
948
973
|
secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
|
|
949
974
|
socket.on('message', raw => {
|
|
@@ -958,6 +983,11 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
958
983
|
// A queued browser action or output processing must not hide a live transport.
|
|
959
984
|
if (isRunnerTransportHeartbeat(frame, connectionId)) {
|
|
960
985
|
lastHeartbeat = Date.now();
|
|
986
|
+
// Ready/resume can succeed before a replayed result fails again.
|
|
987
|
+
if (recovery.isRecovered && backoffMs > 1_000) {
|
|
988
|
+
backoffMs = 1_000;
|
|
989
|
+
console.log('Realtime connection recovered.');
|
|
990
|
+
}
|
|
961
991
|
return;
|
|
962
992
|
}
|
|
963
993
|
if (frame.type === 'browser_profile_sync_result') {
|
|
@@ -1011,8 +1041,12 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1011
1041
|
const ready = frame;
|
|
1012
1042
|
if (ready.grantMode && ready.networkMode && Number.isSafeInteger(ready.policyGrantRevision))
|
|
1013
1043
|
await updateGrantPolicy(ready.policyGrantRevision, { mode: ready.grantMode, networkMode: ready.networkMode });
|
|
1014
|
-
|
|
1044
|
+
if (!announcedConnection) {
|
|
1045
|
+
announcedConnection = true;
|
|
1046
|
+
console.log(`Connected ${device.name} (${device.agentTerminalId}).`);
|
|
1047
|
+
}
|
|
1015
1048
|
operationalLog.write('INFO', {}, 'socket.ready', { resumedExecutions: children.size + completed.size });
|
|
1049
|
+
reportBrowserInventory();
|
|
1016
1050
|
const pendingResumes = new Set([...children.keys(), ...completed.keys()]);
|
|
1017
1051
|
recovery.ready(pendingResumes);
|
|
1018
1052
|
for (const executionId of pendingResumes) {
|
|
@@ -1023,6 +1057,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1023
1057
|
socket.terminate();
|
|
1024
1058
|
return;
|
|
1025
1059
|
}
|
|
1060
|
+
reportBrowserInventory();
|
|
1026
1061
|
send(socket, { type: 'heartbeat', connectionId, threadBrowserScopes: threadBrowserScopes(), browserSessionIds: browserSessionIds() });
|
|
1027
1062
|
}, 15_000);
|
|
1028
1063
|
return;
|
|
@@ -1034,11 +1069,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1034
1069
|
for (const [id, expiresAt] of revokedProfileSessions)
|
|
1035
1070
|
if (expiresAt <= Date.now())
|
|
1036
1071
|
revokedProfileSessions.delete(id);
|
|
1037
|
-
|
|
1038
|
-
const central = centralProfiles.get(frame.browserSessionId);
|
|
1039
|
-
centralProfiles.delete(frame.browserSessionId);
|
|
1040
|
-
await revokeBrowserProfileSession(frame.browserSessionId, frame.browserProfileId);
|
|
1041
|
-
await central?.lease.release();
|
|
1072
|
+
await revokeProfileMember(frame.browserSessionId, frame.browserProfileId);
|
|
1042
1073
|
}
|
|
1043
1074
|
return;
|
|
1044
1075
|
}
|
|
@@ -1346,6 +1377,9 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1346
1377
|
activeChildren.add(child);
|
|
1347
1378
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
1348
1379
|
void (async () => {
|
|
1380
|
+
for (const [id, expiresAt] of revokedProfileSessions)
|
|
1381
|
+
if (expiresAt <= Date.now())
|
|
1382
|
+
revokedProfileSessions.delete(id);
|
|
1349
1383
|
if (frame.browserSessionId && revokedProfileSessions.has(frame.browserSessionId))
|
|
1350
1384
|
throw new Error('browser_profile_lease_expired');
|
|
1351
1385
|
let central = frame.browserSessionId ? centralProfiles.get(frame.browserSessionId) : undefined;
|
|
@@ -1359,15 +1393,73 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1359
1393
|
|| grant.scope.browserSessionId !== frame.browserSessionId || !Number.isSafeInteger(grant.scope.generation)
|
|
1360
1394
|
|| grant.scope.generation < 1 || !Number.isSafeInteger(grant.revision) || grant.revision < 0)
|
|
1361
1395
|
throw new Error('browser_profile_scope_changed');
|
|
1362
|
-
const
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1396
|
+
const id = grant.scope.browserSessionId;
|
|
1397
|
+
const contextId = grant.sharedContextId;
|
|
1398
|
+
const rpc = profileRpc;
|
|
1399
|
+
if (contextId !== undefined) {
|
|
1400
|
+
if (!/^[a-f0-9]{64}$/u.test(contextId) || contextId === id || revokedProfileSessions.has(contextId)
|
|
1401
|
+
|| frame.networkAccessOnce || frame.networkAccessExpiresAt != null)
|
|
1402
|
+
throw new Error('browser_profile_scope_changed');
|
|
1403
|
+
let opening = sharedProfileOpens.get(contextId);
|
|
1404
|
+
const contextScope = ['instanceId', 'browserProfileId', 'actorUserId', 'agentTerminalId',
|
|
1405
|
+
'agentTerminalWorkspaceId', 'connectionId', 'keyId', 'keyVersion', 'generation'];
|
|
1406
|
+
const openScope = opening?.scope;
|
|
1407
|
+
if (openScope && contextScope.some(key => openScope[key] !== grant.scope[key]))
|
|
1408
|
+
throw new Error('browser_profile_scope_changed');
|
|
1409
|
+
if (!opening) {
|
|
1410
|
+
const members = new Set();
|
|
1411
|
+
const forget = () => {
|
|
1412
|
+
sharedProfileOpens.delete(contextId);
|
|
1413
|
+
revokedProfileSessions.set(contextId, Date.now() + 60_000);
|
|
1414
|
+
};
|
|
1415
|
+
const lease = CentralBrowserProfileLease.open({ ...grant, digest: grant.download?.digest }, secureIdentity.privateKey, rpc.transport(grant, {
|
|
1416
|
+
current: () => [...members],
|
|
1417
|
+
revoke: ids => { for (const id of ids)
|
|
1418
|
+
void revokeProfileMember(id, grant.profile.id).catch(() => undefined); },
|
|
1419
|
+
}), async () => {
|
|
1420
|
+
forget();
|
|
1421
|
+
await Promise.all([...members].map(id => revokeProfileMember(id, grant.profile.id)));
|
|
1422
|
+
}).then(lease => ({
|
|
1423
|
+
get state() { return lease.state; },
|
|
1424
|
+
save: state => lease.save(state),
|
|
1425
|
+
release: () => { forget(); return lease.release(); },
|
|
1426
|
+
}), error => { forget(); throw error; });
|
|
1427
|
+
opening = { lease, members, scope: grant.scope };
|
|
1428
|
+
sharedProfileOpens.set(contextId, opening);
|
|
1429
|
+
}
|
|
1430
|
+
const { members, lease: openingLease } = opening;
|
|
1431
|
+
members.add(id);
|
|
1432
|
+
const lease = await openingLease;
|
|
1433
|
+
const authorized = () => activeConnectionId === frame.connectionId && !policyRevisionUnavailable
|
|
1434
|
+
&& minimumPolicyGrantRevision === frame.policyGrantRevision
|
|
1435
|
+
&& !revokedProfileSessions.has(contextId) && !revokedProfileSessions.has(id);
|
|
1436
|
+
const releaseMember = async () => {
|
|
1437
|
+
if (!members.delete(id))
|
|
1438
|
+
return;
|
|
1439
|
+
centralProfiles.delete(id);
|
|
1440
|
+
if (members.size === 0)
|
|
1441
|
+
await lease.release();
|
|
1442
|
+
else
|
|
1443
|
+
await rpc.releaseMember(id).catch(() => undefined);
|
|
1444
|
+
};
|
|
1445
|
+
if (!authorized()) {
|
|
1446
|
+
await releaseMember();
|
|
1447
|
+
throw new Error('browser_profile_lease_expired');
|
|
1448
|
+
}
|
|
1449
|
+
central = { ...grant.profile, lease, shared: { contextId, authorized, releaseMember } };
|
|
1450
|
+
}
|
|
1451
|
+
else {
|
|
1452
|
+
const lease = await CentralBrowserProfileLease.open({ ...grant, digest: grant.download?.digest }, secureIdentity.privateKey, rpc.transport(grant), async () => { await revokeProfileMember(id, grant.profile.id); });
|
|
1453
|
+
if (revokedProfileSessions.has(id)) {
|
|
1454
|
+
await lease.release();
|
|
1455
|
+
throw new Error('browser_profile_lease_expired');
|
|
1456
|
+
}
|
|
1457
|
+
central = { ...grant.profile, lease: {
|
|
1458
|
+
get state() { return lease.state; },
|
|
1459
|
+
save: state => lease.save(state),
|
|
1460
|
+
release: () => { centralProfiles.delete(id); return lease.release(); },
|
|
1461
|
+
} };
|
|
1369
1462
|
}
|
|
1370
|
-
central = { ...grant.profile, lease };
|
|
1371
1463
|
centralProfiles.set(grant.scope.browserSessionId, central);
|
|
1372
1464
|
}
|
|
1373
1465
|
if (frame.browserProfileId && (!central || central.id !== frame.browserProfileId))
|
|
@@ -1391,7 +1483,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1391
1483
|
sink = new BrowserSessionRecordingSink({ grant: recordingGrant,
|
|
1392
1484
|
terminalId: device.agentTerminalId, directory: recordingDirectory, isAuthorized: recordingAuthorized,
|
|
1393
1485
|
request: (route, token, body) => api(profile, 'POST', route, body, { 'x-revo-browser-recording-token': token }),
|
|
1394
|
-
onStatus: (status, recordingId) => operationalLog.write(status === 'saved' ? 'INFO' : 'ERROR', trace, 'browser.recording', { status, recordingId }),
|
|
1486
|
+
onStatus: (status, recordingId, stage) => operationalLog.write(status === 'saved' ? 'INFO' : 'ERROR', trace, 'browser.recording', { status, recordingId, ...(stage ? { stage } : {}) }),
|
|
1395
1487
|
});
|
|
1396
1488
|
recordingSinks.set(frame.browserSessionId, sink);
|
|
1397
1489
|
}
|
|
@@ -1417,7 +1509,8 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1417
1509
|
identity: secureIdentity, profileOwner: { baseUrl: device.baseUrl, instanceId: device.instance,
|
|
1418
1510
|
actorUserId: frame.actorUserId, terminalId: device.agentTerminalId, workspace },
|
|
1419
1511
|
browserSettings: recordingGrant.settings, recordingDirectory,
|
|
1420
|
-
isAuthorized:
|
|
1512
|
+
isAuthorized: recordingAuthorized, onFrame: () => undefined, onRecording: item => sink.accept(item),
|
|
1513
|
+
recordingCheckpoint: () => sink.checkpoint },
|
|
1421
1514
|
} } : {}),
|
|
1422
1515
|
signal: controller.signal });
|
|
1423
1516
|
})()
|
|
@@ -1456,14 +1549,14 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1456
1549
|
cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
1457
1550
|
operationalLog.write('INFO', trace, 'execution.completed', { operation,
|
|
1458
1551
|
browserAction: frame.browserAction, exitCode: 0, screenshot: frame.browserAction === 'screenshot' });
|
|
1552
|
+
reportBrowserInventory();
|
|
1459
1553
|
if (resumed.has(frame.executionId))
|
|
1460
1554
|
flushExecution(frame.executionId);
|
|
1461
1555
|
}).catch(async (error) => {
|
|
1462
1556
|
if (frame.browserProfileGrant && frame.browserSessionId) {
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
await central?.lease.release();
|
|
1557
|
+
await revokeProfileMember(frame.browserSessionId, frame.browserProfileGrant.profile.id).catch(() => undefined);
|
|
1558
|
+
if (frame.browserProfileGrant.sharedContextId)
|
|
1559
|
+
await profileRpc?.releaseMember(frame.browserSessionId).catch(() => undefined);
|
|
1467
1560
|
}
|
|
1468
1561
|
if (policyTimer)
|
|
1469
1562
|
clearTimeout(policyTimer);
|
|
@@ -1479,6 +1572,7 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1479
1572
|
browserAction: frame.browserAction,
|
|
1480
1573
|
errorCode: actionAttempted ? 'browser_action_outcome_unknown' : operationalErrorCode(error),
|
|
1481
1574
|
executed: actionAttempted });
|
|
1575
|
+
reportBrowserInventory();
|
|
1482
1576
|
if (resumed.has(frame.executionId))
|
|
1483
1577
|
flushExecution(frame.executionId);
|
|
1484
1578
|
});
|
|
@@ -1563,21 +1657,23 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1563
1657
|
socket.on('close', (code, reason) => {
|
|
1564
1658
|
profileImports?.dispose();
|
|
1565
1659
|
profileRpc?.dispose();
|
|
1566
|
-
for (const [sessionId, central] of centralProfiles)
|
|
1567
|
-
|
|
1568
|
-
void revokeBrowserProfileSession(sessionId, central.id).catch(() => undefined);
|
|
1569
|
-
}
|
|
1660
|
+
for (const [sessionId, central] of centralProfiles)
|
|
1661
|
+
void revokeProfileMember(sessionId, central.id).catch(() => undefined);
|
|
1570
1662
|
live.disconnectAll();
|
|
1571
1663
|
securePolicyEpoch++;
|
|
1572
|
-
|
|
1664
|
+
const closeReason = reason.toString();
|
|
1665
|
+
const loggedReason = ['dependency_unavailable', 'hello_timeout', 'terminal_connection_busy', 'heartbeat_timeout',
|
|
1666
|
+
'server_restart', 'grant_changed', 'recovery_requested', 'invalid_runner_frame', 'access_revoked',
|
|
1667
|
+
'account_access_revoked', 'API_KEY_EXPIRED'].find(value => value === closeReason);
|
|
1668
|
+
operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, ...(loggedReason ? { reason: loggedReason } : {}), activeExecutions: children.size, policyViolation: code === 1008 });
|
|
1573
1669
|
if (heartbeat)
|
|
1574
1670
|
clearInterval(heartbeat);
|
|
1575
1671
|
recovery.close();
|
|
1576
1672
|
if (activeSocket === socket)
|
|
1577
1673
|
activeConnectionId = '';
|
|
1578
1674
|
resumed.clear();
|
|
1579
|
-
const grantChanged = code === 1012 &&
|
|
1580
|
-
if (grantChanged || code === 1008 &&
|
|
1675
|
+
const grantChanged = code === 1012 && closeReason === 'grant_changed';
|
|
1676
|
+
if (grantChanged || code === 1008 && closeReason !== 'heartbeat_timeout') {
|
|
1581
1677
|
reconnectGrace.clear();
|
|
1582
1678
|
for (const [executionId, child] of children) {
|
|
1583
1679
|
cancelledExecutions.add(executionId);
|
|
@@ -1589,8 +1685,8 @@ async function connect(profile, device, legacyImportAvailable) {
|
|
|
1589
1685
|
reconnectGrace.start(children.size > 0 || hasBrowserSessions());
|
|
1590
1686
|
if (activeSocket === socket)
|
|
1591
1687
|
activeSocket = undefined;
|
|
1592
|
-
if (code === 1008 &&
|
|
1593
|
-
reject(new TerminalRunnerFatalError(`Runner rejected by Realtime: ${
|
|
1688
|
+
if (code === 1008 && closeReason !== 'heartbeat_timeout')
|
|
1689
|
+
reject(new TerminalRunnerFatalError(`Runner rejected by Realtime: ${closeReason || 'policy violation'}.`));
|
|
1594
1690
|
else
|
|
1595
1691
|
resolve();
|
|
1596
1692
|
});
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from 'node:http';
|
|
2
|
-
import { type EndpointManifest } from './resource-syncs/endpoint-sync.ts';
|
|
3
2
|
export declare const DEFAULT_EMULATOR_HOST = "127.0.0.1";
|
|
4
3
|
type HttpResult = {
|
|
5
4
|
status: number;
|
|
@@ -8,37 +7,41 @@ type HttpResult = {
|
|
|
8
7
|
};
|
|
9
8
|
type Debug = (payload: Record<string, unknown>, signal: AbortSignal, timeoutMs: number) => Promise<unknown>;
|
|
10
9
|
type PublishedEndpoint = (input: {
|
|
11
|
-
|
|
10
|
+
method: string;
|
|
12
11
|
url: URL;
|
|
13
12
|
headers: Headers;
|
|
14
13
|
body: Buffer;
|
|
15
14
|
signal: AbortSignal;
|
|
16
15
|
}) => Promise<HttpResult>;
|
|
16
|
+
type ExecutionPath = 'published' | 'sandbox';
|
|
17
17
|
export type EndpointRequestEvent = {
|
|
18
18
|
id: number;
|
|
19
19
|
method: string;
|
|
20
20
|
} & ({
|
|
21
21
|
event: 'request_started';
|
|
22
|
-
} | {
|
|
23
|
-
event: 'request_finished';
|
|
22
|
+
} | ({
|
|
24
23
|
route?: string;
|
|
25
|
-
|
|
24
|
+
execution?: ExecutionPath;
|
|
26
25
|
durationMs: number;
|
|
26
|
+
} & ({
|
|
27
|
+
event: 'request_finished';
|
|
28
|
+
status: number;
|
|
27
29
|
} | {
|
|
28
30
|
event: 'request_aborted';
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
});
|
|
32
|
-
type EmulatorOptions = {
|
|
31
|
+
})));
|
|
32
|
+
type LocalExecution = {
|
|
33
33
|
workspaceRoot: string;
|
|
34
34
|
stableKeyName: string;
|
|
35
|
-
host?: string;
|
|
36
35
|
readOnly: boolean;
|
|
37
|
-
|
|
38
|
-
runPublishedEndpoint?: PublishedEndpoint;
|
|
36
|
+
skipValidate?: boolean;
|
|
39
37
|
debug: Debug;
|
|
40
|
-
onRequest?: (event: EndpointRequestEvent) => void;
|
|
41
38
|
};
|
|
39
|
+
type EmulatorOptions = {
|
|
40
|
+
host?: string;
|
|
41
|
+
onRequest?: (event: EndpointRequestEvent) => void;
|
|
42
|
+
} & (LocalExecution | {
|
|
43
|
+
runPublishedEndpoint: PublishedEndpoint;
|
|
44
|
+
});
|
|
42
45
|
export declare function normalizeEmulatorHost(value: string): string;
|
|
43
46
|
export declare function formatEmulatorHost(host: string): string;
|
|
44
47
|
export declare function isLoopbackEmulatorHost(host: string): boolean;
|