@revoengine/cli 1.0.11 → 1.0.13
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 +275 -479
- package/dist/src/cli.js +71 -5
- package/dist/src/client.d.ts +28 -12
- package/dist/src/client.js +234 -66
- package/dist/src/commands/component.d.ts +67 -0
- package/dist/src/commands/component.js +299 -27
- package/dist/src/commands/database-tables.d.ts +2 -0
- package/dist/src/commands/{database-schemas.js → database-tables.js} +21 -40
- package/dist/src/commands/database-views.js +21 -18
- package/dist/src/commands/endpoints.js +26 -16
- package/dist/src/commands/events.js +18 -20
- package/dist/src/commands/groups.js +13 -22
- package/dist/src/commands/index.d.ts +2 -1
- package/dist/src/commands/index.js +2 -1
- package/dist/src/commands/job-templates.js +21 -15
- package/dist/src/commands/metadata.js +58 -15
- package/dist/src/commands/migrate.d.ts +6 -0
- package/dist/src/commands/migrate.js +658 -0
- package/dist/src/commands/project.js +4 -4
- package/dist/src/commands/role-groups.js +14 -25
- package/dist/src/commands/schedules.js +19 -20
- package/dist/src/commands/terminal-browser.d.ts +16 -0
- package/dist/src/commands/terminal-browser.js +92 -0
- package/dist/src/commands/terminal-image.d.ts +7 -0
- package/dist/src/commands/terminal-image.js +40 -0
- package/dist/src/commands/terminal-patch-worker.d.ts +1 -0
- package/dist/src/commands/terminal-patch-worker.js +24 -0
- package/dist/src/commands/terminal-patch.d.ts +2 -0
- package/dist/src/commands/terminal-patch.js +156 -0
- package/dist/src/commands/terminal-sandbox.d.ts +8 -0
- package/dist/src/commands/terminal-sandbox.js +87 -0
- package/dist/src/commands/terminal-service.js +2 -2
- package/dist/src/commands/terminal.d.ts +31 -4
- package/dist/src/commands/terminal.js +360 -45
- package/dist/src/component-lock.d.ts +12 -2
- package/dist/src/component-lock.js +60 -1
- package/dist/src/diff-details.d.ts +8 -0
- package/dist/src/diff-details.js +152 -0
- package/dist/src/env-sync.js +8 -6
- package/dist/src/http-trace.d.ts +94 -0
- package/dist/src/http-trace.js +226 -0
- package/dist/src/metadata-backfill.d.ts +5 -4
- package/dist/src/metadata-backfill.js +82 -158
- package/dist/src/migration.d.ts +141 -0
- package/dist/src/migration.js +1632 -0
- package/dist/src/resource-inventory.d.ts +28 -0
- package/dist/src/resource-inventory.js +85 -0
- package/dist/src/resource-syncs/{database-schema-sync.d.ts → database-table-sync.d.ts} +13 -3
- package/dist/src/resource-syncs/{database-schema-sync.js → database-table-sync.js} +147 -62
- package/dist/src/resource-syncs/database-view-sync.d.ts +24 -2
- package/dist/src/resource-syncs/database-view-sync.js +156 -68
- package/dist/src/resource-syncs/endpoint-sync.d.ts +27 -0
- package/dist/src/resource-syncs/endpoint-sync.js +362 -82
- package/dist/src/resource-syncs/event-sync.d.ts +27 -0
- package/dist/src/resource-syncs/event-sync.js +123 -26
- package/dist/src/resource-syncs/group-sync.d.ts +7 -0
- package/dist/src/resource-syncs/group-sync.js +60 -14
- package/dist/src/resource-syncs/job-template-sync.d.ts +21 -0
- package/dist/src/resource-syncs/job-template-sync.js +91 -30
- package/dist/src/resource-syncs/role-group-sync.d.ts +7 -0
- package/dist/src/resource-syncs/role-group-sync.js +47 -9
- package/dist/src/resource-syncs/schedule-sync.d.ts +30 -1
- package/dist/src/resource-syncs/schedule-sync.js +114 -20
- package/dist/src/resource-syncs/util.d.ts +3 -0
- package/dist/src/resource-syncs/util.js +8 -6
- package/dist/src/resource-target.d.ts +11 -0
- package/dist/src/resource-target.js +48 -0
- package/dist/src/sync-output.d.ts +29 -1
- package/dist/src/sync-output.js +139 -2
- package/dist/src/tracked-resources.d.ts +1 -1
- package/dist/src/tracked-resources.js +8 -6
- package/dist/src/types.d.ts +3 -0
- package/dist/src/ui.js +18 -9
- package/dist/src/utils.d.ts +2 -0
- package/dist/src/utils.js +17 -0
- package/dist/src/workspace-diff.d.ts +25 -0
- package/dist/src/workspace-diff.js +75 -0
- package/package.json +9 -6
- package/dist/src/commands/database-schemas.d.ts +0 -2
- /package/dist/src/{database-schema-artifacts.d.ts → database-table-artifacts.d.ts} +0 -0
- /package/dist/src/{database-schema-artifacts.js → database-table-artifacts.js} +0 -0
|
@@ -1,20 +1,11 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { RevoClient } from "../client.js";
|
|
4
3
|
import { resolveProjectRoot, readProjectStableKeyName } from "../project.js";
|
|
4
|
+
import { resolveResourceTarget } from "../resource-target.js";
|
|
5
5
|
import { buildRoleGroupsPlan, pullRoleGroupsToWorkspace, pushRoleGroups } from "../resource-syncs/role-group-sync.js";
|
|
6
6
|
import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
|
|
7
|
-
import { printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
|
|
8
|
-
import { readBoolFlag
|
|
9
|
-
function requireEnvName(context) {
|
|
10
|
-
const envName = readFlag(context.args, ['env']);
|
|
11
|
-
if (!envName)
|
|
12
|
-
throw new Error('Missing --project <name>.');
|
|
13
|
-
return envName;
|
|
14
|
-
}
|
|
15
|
-
function environmentClient(envName) {
|
|
16
|
-
return new RevoClient({ envName });
|
|
17
|
-
}
|
|
7
|
+
import { planListChanges, printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
|
|
8
|
+
import { readBoolFlag } from "../utils.js";
|
|
18
9
|
function warnAboutExperimentalState(context) {
|
|
19
10
|
const projectRoot = resolveProjectRoot(context.cwd) || path.resolve(context.cwd);
|
|
20
11
|
const legacyPaths = [
|
|
@@ -34,10 +25,10 @@ async function handlePull(context) {
|
|
|
34
25
|
if (!readBoolFlag(context.args, ['all', 'a'])) {
|
|
35
26
|
throw new Error('Role-group pull currently requires --all.');
|
|
36
27
|
}
|
|
37
|
-
const envName =
|
|
28
|
+
const { client, envName } = await resolveResourceTarget(context, { resource: 'Role-group', allowDefaultProfile: true });
|
|
38
29
|
const startedAt = Date.now();
|
|
39
30
|
const result = await pullRoleGroupsToWorkspace({
|
|
40
|
-
client
|
|
31
|
+
client,
|
|
41
32
|
cwd: context.cwd,
|
|
42
33
|
envName,
|
|
43
34
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
@@ -64,9 +55,9 @@ async function handlePlan(context) {
|
|
|
64
55
|
if (readBoolFlag(context.args, ['prune'])) {
|
|
65
56
|
throw new Error('Role-group prune is disabled until the backend soft-delete contract is confirmed.');
|
|
66
57
|
}
|
|
67
|
-
const envName =
|
|
58
|
+
const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Role-group', allowDefaultProfile: true });
|
|
68
59
|
const plan = await buildRoleGroupsPlan({
|
|
69
|
-
client
|
|
60
|
+
client,
|
|
70
61
|
cwd: context.cwd,
|
|
71
62
|
envName,
|
|
72
63
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
@@ -76,14 +67,12 @@ async function handlePlan(context) {
|
|
|
76
67
|
else
|
|
77
68
|
printSyncPlan(context.println, {
|
|
78
69
|
title: 'Role-group',
|
|
79
|
-
environment:
|
|
70
|
+
environment: displayName,
|
|
80
71
|
counts: plan.counts,
|
|
72
|
+
showHints: readBoolFlag(context.args, ['hints']),
|
|
81
73
|
items: plan.items.map((item) => ({
|
|
82
74
|
...item,
|
|
83
|
-
details:
|
|
84
|
-
...(item.rolesToAdd?.length ? [{ label: 'roles add', values: item.rolesToAdd }] : []),
|
|
85
|
-
...(item.rolesToRemove?.length ? [{ label: 'roles remove', values: item.rolesToRemove }] : []),
|
|
86
|
-
],
|
|
75
|
+
details: planListChanges('roles', item.rolesToRemove, item.rolesToAdd),
|
|
87
76
|
})),
|
|
88
77
|
blockers: plan.blockers,
|
|
89
78
|
});
|
|
@@ -100,15 +89,15 @@ async function handlePush(context) {
|
|
|
100
89
|
if (readBoolFlag(context.args, ['prune'])) {
|
|
101
90
|
throw new Error('Role-group prune is disabled until the backend soft-delete contract is confirmed.');
|
|
102
91
|
}
|
|
103
|
-
const envName =
|
|
92
|
+
const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Role-group', allowDefaultProfile: true });
|
|
104
93
|
if (!readBoolFlag(context.args, ['yes', 'y'])) {
|
|
105
|
-
if (!isInteractiveTerminal() || !await promptConfirm(`Push role-groups to "${
|
|
94
|
+
if (!isInteractiveTerminal() || !await promptConfirm(`Push role-groups to "${displayName}"?`, false)) {
|
|
106
95
|
throw new Error('Role-group push requires confirmation. Re-run with --yes or use an interactive terminal.');
|
|
107
96
|
}
|
|
108
97
|
}
|
|
109
98
|
const startedAt = Date.now();
|
|
110
99
|
const result = await pushRoleGroups({
|
|
111
|
-
client
|
|
100
|
+
client,
|
|
112
101
|
cwd: context.cwd,
|
|
113
102
|
envName,
|
|
114
103
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
@@ -148,5 +137,5 @@ export async function handleRoleGroupsCommand(context) {
|
|
|
148
137
|
await handlePush(context);
|
|
149
138
|
return;
|
|
150
139
|
}
|
|
151
|
-
throw new Error('Unknown role-groups command. Usage: revo role-groups <pull|plan|push> --all --
|
|
140
|
+
throw new Error('Unknown role-groups command. Usage: revo role-groups <pull|plan|push> --all [--env <name>]');
|
|
152
141
|
}
|
|
@@ -1,25 +1,18 @@
|
|
|
1
|
-
import { RevoClient } from "../client.js";
|
|
2
|
-
import { DEFAULT_ENV_NAME } from "../config.js";
|
|
3
1
|
import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
|
|
4
2
|
import { readProjectStableKeyName } from "../project.js";
|
|
3
|
+
import { resolveResourceTarget } from "../resource-target.js";
|
|
5
4
|
import { activateVerifiedSchedules, buildSchedulesPlan, pullSchedulesToWorkspace, pushSchedules } from "../resource-syncs/schedule-sync.js";
|
|
6
|
-
import { printSyncNotice, printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
|
|
7
|
-
import { readBoolFlag
|
|
5
|
+
import { planDependencyHints, printSyncNotice, printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
|
|
6
|
+
import { readBoolFlag } from "../utils.js";
|
|
8
7
|
export async function handleSchedulesCommand(context) {
|
|
9
8
|
const subcommand = context.args._[1] || '';
|
|
10
9
|
if (!['pull', 'plan', 'push'].includes(subcommand)) {
|
|
11
|
-
throw new Error('Unknown schedules command. Usage: revo schedules <pull|plan|push> --all --
|
|
10
|
+
throw new Error('Unknown schedules command. Usage: revo schedules <pull|plan|push> --all [--env <name>]');
|
|
12
11
|
}
|
|
13
12
|
if (!readBoolFlag(context.args, ['all', 'a'])) {
|
|
14
13
|
throw new Error('Schedule sync currently requires --all.');
|
|
15
14
|
}
|
|
16
|
-
const envName =
|
|
17
|
-
if (!envName) {
|
|
18
|
-
throw new Error('Missing --project <name>.');
|
|
19
|
-
}
|
|
20
|
-
if (envName === DEFAULT_ENV_NAME) {
|
|
21
|
-
throw new Error('Schedule sync requires a named environment profile; "default" is not supported.');
|
|
22
|
-
}
|
|
15
|
+
const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Schedule' });
|
|
23
16
|
const activate = readBoolFlag(context.args, ['activate']);
|
|
24
17
|
if (activate && subcommand !== 'push') {
|
|
25
18
|
throw new Error('--activate is available only with schedules push.');
|
|
@@ -30,25 +23,23 @@ export async function handleSchedulesCommand(context) {
|
|
|
30
23
|
throw new Error('Schedule activation in non-interactive mode requires --yes --activate.');
|
|
31
24
|
}
|
|
32
25
|
if (!yes) {
|
|
33
|
-
if (!isInteractiveTerminal() || !await promptConfirm(`Push Schedules to "${
|
|
26
|
+
if (!isInteractiveTerminal() || !await promptConfirm(`Push Schedules to "${displayName}"?`, false)) {
|
|
34
27
|
throw new Error('Schedule push requires confirmation. Re-run with --yes or use an interactive terminal.');
|
|
35
28
|
}
|
|
36
29
|
}
|
|
37
30
|
const startedAt = Date.now();
|
|
38
|
-
const client = new RevoClient({ envName });
|
|
39
31
|
const pushed = await pushSchedules({
|
|
40
32
|
client,
|
|
41
33
|
cwd: context.cwd,
|
|
42
34
|
envName,
|
|
43
35
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
44
36
|
force: readBoolFlag(context.args, ['force', 'f']),
|
|
45
|
-
allowMaterialized: readBoolFlag(context.args, ['allow-materialized']),
|
|
46
37
|
});
|
|
47
38
|
const results = [...pushed.results];
|
|
48
39
|
let activation;
|
|
49
40
|
if (activate) {
|
|
50
41
|
const candidateCount = pushed.verifiedActivationCandidates.length;
|
|
51
|
-
const confirmed = !isInteractiveTerminal() || await promptConfirm(`Activate ${candidateCount} verified Schedule(s) on "${
|
|
42
|
+
const confirmed = !isInteractiveTerminal() || await promptConfirm(`Activate ${candidateCount} verified Schedule(s) on "${displayName}"?`, false);
|
|
52
43
|
if (confirmed) {
|
|
53
44
|
const activationResults = await activateVerifiedSchedules({
|
|
54
45
|
client,
|
|
@@ -91,7 +82,7 @@ export async function handleSchedulesCommand(context) {
|
|
|
91
82
|
}
|
|
92
83
|
if (subcommand === 'plan') {
|
|
93
84
|
const plan = await buildSchedulesPlan({
|
|
94
|
-
client
|
|
85
|
+
client,
|
|
95
86
|
cwd: context.cwd,
|
|
96
87
|
envName,
|
|
97
88
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
@@ -102,9 +93,13 @@ export async function handleSchedulesCommand(context) {
|
|
|
102
93
|
else {
|
|
103
94
|
printSyncPlan(context.println, {
|
|
104
95
|
title: 'Schedule',
|
|
105
|
-
environment:
|
|
96
|
+
environment: displayName,
|
|
106
97
|
counts: plan.counts,
|
|
107
|
-
|
|
98
|
+
showHints: readBoolFlag(context.args, ['hints']),
|
|
99
|
+
items: plan.items.map((item) => ({
|
|
100
|
+
...item,
|
|
101
|
+
hints: item.dependency ? planDependencyHints(item.dependency) : undefined,
|
|
102
|
+
})),
|
|
108
103
|
warnings: [...plan.warnings, ...plan.exclusions],
|
|
109
104
|
blockers: plan.blockers,
|
|
110
105
|
});
|
|
@@ -119,7 +114,7 @@ export async function handleSchedulesCommand(context) {
|
|
|
119
114
|
}
|
|
120
115
|
const startedAt = Date.now();
|
|
121
116
|
const result = await pullSchedulesToWorkspace({
|
|
122
|
-
client
|
|
117
|
+
client,
|
|
123
118
|
cwd: context.cwd,
|
|
124
119
|
envName,
|
|
125
120
|
stableKeyName: readProjectStableKeyName(context.cwd),
|
|
@@ -134,6 +129,10 @@ export async function handleSchedulesCommand(context) {
|
|
|
134
129
|
printSyncStatus(context.println, { status: 'Pulled', direction: 'pull', targetPath: pulled.targetPath });
|
|
135
130
|
output.push({ status: 'pulled', targetPath: pulled.targetPath });
|
|
136
131
|
}
|
|
132
|
+
for (const pruned of result.pruned) {
|
|
133
|
+
printSyncStatus(context.println, { status: 'Pruned', direction: 'pull', targetPath: pruned.targetPath });
|
|
134
|
+
output.push({ status: 'pruned', targetPath: pruned.targetPath });
|
|
135
|
+
}
|
|
137
136
|
for (const warning of result.warnings) {
|
|
138
137
|
printSyncNotice(context.println, `${warning.stableKey}: ${warning.reason}`);
|
|
139
138
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type BrowserAction = 'navigate' | 'dom' | 'screenshot';
|
|
2
|
+
export declare function browserUrl(value: string): string;
|
|
3
|
+
export declare function localBrowserUrl(value: string): string;
|
|
4
|
+
export declare function runBrowserAction(input: {
|
|
5
|
+
url: string;
|
|
6
|
+
action: BrowserAction;
|
|
7
|
+
workspace: string;
|
|
8
|
+
selector?: string | null;
|
|
9
|
+
width?: number;
|
|
10
|
+
height?: number;
|
|
11
|
+
localOnly?: boolean;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
dom: string;
|
|
15
|
+
screenshotPath?: string;
|
|
16
|
+
}>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { chromium } from 'playwright-core';
|
|
5
|
+
export function browserUrl(value) {
|
|
6
|
+
const parsed = new URL(value);
|
|
7
|
+
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
|
|
8
|
+
throw new Error('browser_url_not_allowed');
|
|
9
|
+
return parsed.toString();
|
|
10
|
+
}
|
|
11
|
+
export function localBrowserUrl(value) {
|
|
12
|
+
const parsed = new URL(browserUrl(value));
|
|
13
|
+
if (!['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname.toLowerCase()))
|
|
14
|
+
throw new Error('browser_localhost_only');
|
|
15
|
+
return parsed.toString();
|
|
16
|
+
}
|
|
17
|
+
export async function runBrowserAction(input) {
|
|
18
|
+
const url = input.localOnly ? localBrowserUrl(input.url) : browserUrl(input.url);
|
|
19
|
+
if (!['navigate', 'dom', 'screenshot'].includes(input.action))
|
|
20
|
+
throw new Error('invalid_browser_action');
|
|
21
|
+
const width = input.width ?? 1440;
|
|
22
|
+
const height = input.height ?? 900;
|
|
23
|
+
if (!Number.isInteger(width) || width < 320 || width > 1920
|
|
24
|
+
|| !Number.isInteger(height) || height < 240 || height > 1080)
|
|
25
|
+
throw new Error('invalid_browser_viewport');
|
|
26
|
+
if (input.selector && (input.selector.length > 500 || input.action === 'navigate'))
|
|
27
|
+
throw new Error('invalid_browser_selector');
|
|
28
|
+
const browser = await chromium.launch({ headless: true,
|
|
29
|
+
args: input.localOnly ? ['--disable-background-networking',
|
|
30
|
+
'--host-resolver-rules=MAP localhost 127.0.0.1'] : [] }).catch(error => {
|
|
31
|
+
if (error instanceof Error && error.message.includes("Executable doesn't exist at"))
|
|
32
|
+
throw new Error('browser_binary_unavailable');
|
|
33
|
+
throw error;
|
|
34
|
+
});
|
|
35
|
+
const onAbort = () => { void browser.close(); };
|
|
36
|
+
input.signal?.addEventListener('abort', onAbort, { once: true });
|
|
37
|
+
try {
|
|
38
|
+
if (input.signal?.aborted)
|
|
39
|
+
throw new Error('browser_cancelled');
|
|
40
|
+
const context = await browser.newContext({ viewport: { width, height }, acceptDownloads: false,
|
|
41
|
+
serviceWorkers: 'block' });
|
|
42
|
+
await context.route('**/*', route => {
|
|
43
|
+
try {
|
|
44
|
+
(input.localOnly ? localBrowserUrl : browserUrl)(route.request().url());
|
|
45
|
+
return route.continue();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return route.abort();
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
if (input.localOnly)
|
|
52
|
+
await context.routeWebSocket('**/*', socket => {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = new URL(socket.url());
|
|
55
|
+
const httpUrl = parsed.protocol === 'wss:' ? `https://${parsed.host}${parsed.pathname}`
|
|
56
|
+
: parsed.protocol === 'ws:' ? `http://${parsed.host}${parsed.pathname}` : '';
|
|
57
|
+
localBrowserUrl(httpUrl);
|
|
58
|
+
socket.connectToServer();
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
socket.close();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
const page = await context.newPage();
|
|
65
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
|
|
66
|
+
(input.localOnly ? localBrowserUrl : browserUrl)(page.url());
|
|
67
|
+
const target = input.selector ? page.locator(input.selector).first() : page.locator('body');
|
|
68
|
+
const dom = (await target.innerText({ timeout: 10_000 })).slice(0, 30_000);
|
|
69
|
+
if (input.action !== 'screenshot')
|
|
70
|
+
return { dom };
|
|
71
|
+
const root = fs.realpathSync(input.workspace);
|
|
72
|
+
const privateDirectory = path.join(root, '.revo');
|
|
73
|
+
fs.mkdirSync(privateDirectory, { recursive: true, mode: 0o700 });
|
|
74
|
+
if (fs.realpathSync(privateDirectory) !== privateDirectory)
|
|
75
|
+
throw new Error('browser_output_outside_workspace');
|
|
76
|
+
const directory = path.join(privateDirectory, 'browser-screenshots');
|
|
77
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
78
|
+
if (fs.realpathSync(directory) !== directory)
|
|
79
|
+
throw new Error('browser_output_outside_workspace');
|
|
80
|
+
const screenshotPath = path.join(directory, `${randomUUID()}.png`);
|
|
81
|
+
await (input.selector ? target : page).screenshot({ path: screenshotPath, timeout: 20_000 });
|
|
82
|
+
if (fs.statSync(screenshotPath).size > 30 * 1024 * 1024) {
|
|
83
|
+
fs.rmSync(screenshotPath, { force: true });
|
|
84
|
+
throw new Error('browser_screenshot_too_large');
|
|
85
|
+
}
|
|
86
|
+
return { dom, screenshotPath };
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
input.signal?.removeEventListener('abort', onAbort);
|
|
90
|
+
await browser.close();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type ImageUpload = {
|
|
2
|
+
path: string;
|
|
3
|
+
uploadUrl: string;
|
|
4
|
+
contentType: 'image/png' | 'image/jpeg' | 'image/webp';
|
|
5
|
+
};
|
|
6
|
+
export declare function resolveWorkspaceImage(workspace: string, file: string): string;
|
|
7
|
+
export declare function uploadWorkspaceImages(workspace: string, files: ImageUpload[], signal?: AbortSignal): Promise<number>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
const MAX_IMAGE_BYTES = 30 * 1024 * 1024;
|
|
4
|
+
const MAX_IMAGE_BATCH_BYTES = 240 * 1024 * 1024;
|
|
5
|
+
export function resolveWorkspaceImage(workspace, file) {
|
|
6
|
+
const root = fs.realpathSync(workspace);
|
|
7
|
+
const resolved = fs.realpathSync(file);
|
|
8
|
+
const relative = path.relative(root, resolved);
|
|
9
|
+
if (!relative || relative.startsWith('..') || path.isAbsolute(relative) || !fs.statSync(resolved).isFile())
|
|
10
|
+
throw new Error('image_outside_workspace');
|
|
11
|
+
const size = fs.statSync(resolved).size;
|
|
12
|
+
if (size < 1 || size > MAX_IMAGE_BYTES)
|
|
13
|
+
throw new Error('image_size_invalid');
|
|
14
|
+
return resolved;
|
|
15
|
+
}
|
|
16
|
+
export async function uploadWorkspaceImages(workspace, files, signal) {
|
|
17
|
+
if (!Array.isArray(files) || !files.length || files.length > 32)
|
|
18
|
+
throw new Error('invalid_image_batch');
|
|
19
|
+
const checked = files.map(file => ({ file, resolved: resolveWorkspaceImage(workspace, file.path) }));
|
|
20
|
+
if (checked.reduce((total, item) => total + fs.statSync(item.resolved).size, 0) > MAX_IMAGE_BATCH_BYTES)
|
|
21
|
+
throw new Error('image_batch_too_large');
|
|
22
|
+
for (const { file, resolved } of checked) {
|
|
23
|
+
const url = new URL(file.uploadUrl);
|
|
24
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.port
|
|
25
|
+
|| !/(^|\.)storage\.googleapis\.com$/iu.test(url.hostname))
|
|
26
|
+
throw new Error('image_upload_destination_invalid');
|
|
27
|
+
const data = fs.readFileSync(resolved);
|
|
28
|
+
const png = data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
|
|
29
|
+
const jpeg = data.subarray(0, 3).equals(Buffer.from([255, 216, 255]));
|
|
30
|
+
const webp = data.toString('ascii', 0, 4) === 'RIFF' && data.toString('ascii', 8, 12) === 'WEBP';
|
|
31
|
+
if (!((file.contentType === 'image/png' && png) || (file.contentType === 'image/jpeg' && jpeg)
|
|
32
|
+
|| (file.contentType === 'image/webp' && webp)))
|
|
33
|
+
throw new Error('image_content_mismatch');
|
|
34
|
+
const response = await fetch(url, { method: 'PUT', headers: { 'Content-Type': file.contentType },
|
|
35
|
+
body: data, signal: signal || AbortSignal.timeout(120_000), redirect: 'error' });
|
|
36
|
+
if (!response.ok)
|
|
37
|
+
throw new Error(`image_upload_failed_${response.status}`);
|
|
38
|
+
}
|
|
39
|
+
return files.length;
|
|
40
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
import { applyWorkspacePatch } from "./terminal-patch.js";
|
|
3
|
+
async function main() {
|
|
4
|
+
const workspace = process.argv[2];
|
|
5
|
+
const allowDelete = process.argv[3] === 'true';
|
|
6
|
+
if (!workspace)
|
|
7
|
+
throw new Error('Workspace is required.');
|
|
8
|
+
const chunks = [];
|
|
9
|
+
let bytes = 0;
|
|
10
|
+
for await (const chunk of process.stdin) {
|
|
11
|
+
const data = Buffer.from(chunk);
|
|
12
|
+
bytes += data.length;
|
|
13
|
+
if (bytes > 64_000)
|
|
14
|
+
throw new Error('Patch exceeds 64 KB.');
|
|
15
|
+
chunks.push(data);
|
|
16
|
+
}
|
|
17
|
+
process.stdout.write(applyWorkspacePatch(Buffer.concat(chunks).toString('utf8'), workspace, allowDelete));
|
|
18
|
+
}
|
|
19
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
20
|
+
void main().catch(error => {
|
|
21
|
+
process.stderr.write(error instanceof Error ? error.message : String(error));
|
|
22
|
+
process.exitCode = 1;
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
function targetPath(root, name) {
|
|
5
|
+
if (!name || path.isAbsolute(name) || name.includes('\0') || name.split('/').includes('..'))
|
|
6
|
+
throw new Error('Patch path is outside the workspace.');
|
|
7
|
+
const target = path.resolve(root, name);
|
|
8
|
+
if (target === root || !target.startsWith(`${root}${path.sep}`))
|
|
9
|
+
throw new Error('Patch path is outside the workspace.');
|
|
10
|
+
let current = root;
|
|
11
|
+
for (const part of path.relative(root, target).split(path.sep)) {
|
|
12
|
+
current = path.join(current, part);
|
|
13
|
+
if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink())
|
|
14
|
+
throw new Error('Patch cannot follow a symbolic link.');
|
|
15
|
+
}
|
|
16
|
+
return target;
|
|
17
|
+
}
|
|
18
|
+
function parsePatch(patch) {
|
|
19
|
+
if (!patch.startsWith('*** Begin Patch\n') || !patch.trimEnd().endsWith('*** End Patch'))
|
|
20
|
+
throw new Error('Invalid apply_patch envelope.');
|
|
21
|
+
const lines = patch.replace(/\r\n/gu, '\n').trimEnd().split('\n');
|
|
22
|
+
const changes = [];
|
|
23
|
+
let index = 1;
|
|
24
|
+
while (index < lines.length - 1) {
|
|
25
|
+
const header = /\*\*\* (Add|Update|Delete) File: (.+)/u.exec(lines[index] || '');
|
|
26
|
+
if (!header)
|
|
27
|
+
throw new Error('Invalid apply_patch file header.');
|
|
28
|
+
const kind = header[1].toLowerCase();
|
|
29
|
+
const name = header[2];
|
|
30
|
+
if (changes.some(change => change.name === name))
|
|
31
|
+
throw new Error('Duplicate patch target.');
|
|
32
|
+
index++;
|
|
33
|
+
const body = [];
|
|
34
|
+
while (index < lines.length - 1 && !lines[index].startsWith('*** '))
|
|
35
|
+
body.push(lines[index++]);
|
|
36
|
+
changes.push({ kind, name, lines: body });
|
|
37
|
+
}
|
|
38
|
+
if (!changes.length || changes.length > 20)
|
|
39
|
+
throw new Error('Patch must change 1 to 20 files.');
|
|
40
|
+
return changes;
|
|
41
|
+
}
|
|
42
|
+
export function patchDeletesFile(patch) {
|
|
43
|
+
return /^\*\*\* Delete File:/mu.test(patch);
|
|
44
|
+
}
|
|
45
|
+
function updateContent(original, body) {
|
|
46
|
+
const trailingNewline = original.endsWith('\n');
|
|
47
|
+
let lines = original.replace(/\r\n/gu, '\n').split('\n');
|
|
48
|
+
if (trailingNewline)
|
|
49
|
+
lines.pop();
|
|
50
|
+
let cursor = 0;
|
|
51
|
+
let changed = false;
|
|
52
|
+
for (let index = 0; index < body.length;) {
|
|
53
|
+
const marker = body[index];
|
|
54
|
+
if (!marker.startsWith('@@'))
|
|
55
|
+
throw new Error('Patch update requires @@ hunks.');
|
|
56
|
+
index++;
|
|
57
|
+
const oldLines = [];
|
|
58
|
+
const newLines = [];
|
|
59
|
+
while (index < body.length && !body[index].startsWith('@@')) {
|
|
60
|
+
const line = body[index++];
|
|
61
|
+
if (line === '\')
|
|
62
|
+
continue;
|
|
63
|
+
const prefix = line[0];
|
|
64
|
+
if (![' ', '-', '+'].includes(prefix))
|
|
65
|
+
throw new Error('Invalid patch hunk line.');
|
|
66
|
+
if (prefix !== '+')
|
|
67
|
+
oldLines.push(line.slice(1));
|
|
68
|
+
if (prefix !== '-')
|
|
69
|
+
newLines.push(line.slice(1));
|
|
70
|
+
}
|
|
71
|
+
if (!oldLines.length)
|
|
72
|
+
throw new Error('Patch hunk needs context or removed lines.');
|
|
73
|
+
const candidates = [];
|
|
74
|
+
for (let at = cursor; at <= lines.length - oldLines.length; at++) {
|
|
75
|
+
if (oldLines.every((line, offset) => lines[at + offset] === line))
|
|
76
|
+
candidates.push(at);
|
|
77
|
+
}
|
|
78
|
+
if (candidates.length !== 1)
|
|
79
|
+
throw new Error('Patch context is missing or ambiguous.');
|
|
80
|
+
lines.splice(candidates[0], oldLines.length, ...newLines);
|
|
81
|
+
cursor = candidates[0] + newLines.length;
|
|
82
|
+
changed = true;
|
|
83
|
+
}
|
|
84
|
+
if (!changed)
|
|
85
|
+
throw new Error('Patch has no update hunks.');
|
|
86
|
+
return lines.join('\n') + (trailingNewline ? '\n' : '');
|
|
87
|
+
}
|
|
88
|
+
export function applyWorkspacePatch(patch, workspace, allowDelete = false) {
|
|
89
|
+
if (Buffer.byteLength(patch) > 64_000)
|
|
90
|
+
throw new Error('Patch exceeds 64 KB.');
|
|
91
|
+
const root = fs.realpathSync(workspace);
|
|
92
|
+
const changes = parsePatch(patch);
|
|
93
|
+
if (changes.some(change => change.kind === 'delete') && !allowDelete)
|
|
94
|
+
throw new Error('Deleting files requires elevated approval.');
|
|
95
|
+
const prepared = changes.map(change => {
|
|
96
|
+
const target = targetPath(root, change.name);
|
|
97
|
+
const exists = fs.existsSync(target);
|
|
98
|
+
if (exists && !fs.statSync(target).isFile())
|
|
99
|
+
throw new Error('Patch target must be a regular file.');
|
|
100
|
+
if (change.kind === 'add' && exists)
|
|
101
|
+
throw new Error('Patch add target already exists.');
|
|
102
|
+
if (change.kind !== 'add' && !exists)
|
|
103
|
+
throw new Error('Patch target does not exist.');
|
|
104
|
+
const original = exists ? fs.readFileSync(target, 'utf8') : '';
|
|
105
|
+
if (Buffer.byteLength(original) > 2_000_000)
|
|
106
|
+
throw new Error('Patch target exceeds 2 MB.');
|
|
107
|
+
if (change.kind === 'delete' && change.lines.length)
|
|
108
|
+
throw new Error('Delete patch cannot contain hunks.');
|
|
109
|
+
const content = change.kind === 'add'
|
|
110
|
+
? change.lines.map(line => {
|
|
111
|
+
if (!line.startsWith('+'))
|
|
112
|
+
throw new Error('Add patch requires + lines.');
|
|
113
|
+
return line.slice(1);
|
|
114
|
+
}).join('\n') + (change.lines.length ? '\n' : '')
|
|
115
|
+
: change.kind === 'update' ? updateContent(original, change.lines) : null;
|
|
116
|
+
return { change, target, content, original: exists ? original : null,
|
|
117
|
+
mode: exists ? fs.statSync(target).mode : 0o644 };
|
|
118
|
+
});
|
|
119
|
+
const completed = [];
|
|
120
|
+
try {
|
|
121
|
+
for (const item of prepared) {
|
|
122
|
+
if (item.content === null)
|
|
123
|
+
fs.unlinkSync(item.target);
|
|
124
|
+
else {
|
|
125
|
+
fs.mkdirSync(path.dirname(item.target), { recursive: true });
|
|
126
|
+
targetPath(root, item.change.name);
|
|
127
|
+
const temporary = `${item.target}.${randomUUID()}.revo-patch-tmp`;
|
|
128
|
+
fs.writeFileSync(temporary, item.content, { mode: item.mode, flag: 'wx' });
|
|
129
|
+
try {
|
|
130
|
+
fs.renameSync(temporary, item.target);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
fs.unlinkSync(temporary);
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
completed.push(item);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
let rollbackFailed = false;
|
|
142
|
+
for (const item of completed.reverse()) {
|
|
143
|
+
try {
|
|
144
|
+
if (item.original === null)
|
|
145
|
+
fs.unlinkSync(item.target);
|
|
146
|
+
else
|
|
147
|
+
fs.writeFileSync(item.target, item.original, { mode: item.mode });
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
rollbackFailed = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
throw new Error(`Patch failed${rollbackFailed ? ' and rollback was incomplete' : ''}: ${error instanceof Error ? error.message : String(error)}`);
|
|
154
|
+
}
|
|
155
|
+
return `Applied patch to ${prepared.length} file${prepared.length === 1 ? '' : 's'}.`;
|
|
156
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type TerminalSandbox = 'workspace' | 'workspace-network' | 'unrestricted';
|
|
2
|
+
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): {
|
|
4
|
+
file: string;
|
|
5
|
+
args: string[];
|
|
6
|
+
};
|
|
7
|
+
/** Obvious destructive shell forms need an explicit elevated request even inside the workspace. */
|
|
8
|
+
export declare function requiresElevatedCommand(command: string): boolean;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
|
|
5
|
+
function seatbeltLiteral(value) {
|
|
6
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
7
|
+
}
|
|
8
|
+
export function sandboxCommand(workspace, workdir, command, sandbox, platform = process.platform, scratchDir, readPaths = [], networkAllowed = true) {
|
|
9
|
+
const shell = platform === 'darwin' ? '/bin/zsh' : '/bin/sh';
|
|
10
|
+
if (sandbox === 'unrestricted' && networkAllowed)
|
|
11
|
+
return { file: shell, args: ['-lc', command] };
|
|
12
|
+
if (sandbox === 'unrestricted') {
|
|
13
|
+
if (platform === 'darwin') {
|
|
14
|
+
if (!fs.existsSync('/usr/bin/sandbox-exec'))
|
|
15
|
+
throw new Error('network_sandbox_unavailable');
|
|
16
|
+
return { file: '/usr/bin/sandbox-exec',
|
|
17
|
+
args: ['-p', '(version 1)\n(allow default)\n(deny network*)', shell, '-c', command] };
|
|
18
|
+
}
|
|
19
|
+
if (platform === 'linux') {
|
|
20
|
+
return { file: 'bwrap', args: ['--die-with-parent', '--unshare-net', '--bind', '/', '/',
|
|
21
|
+
'--dev-bind', '/dev', '/dev', '--proc', '/proc', '--chdir', fs.realpathSync(workdir), shell, '-c', command] };
|
|
22
|
+
}
|
|
23
|
+
throw new Error('network_sandbox_unavailable');
|
|
24
|
+
}
|
|
25
|
+
if (sandbox !== 'workspace' && sandbox !== 'workspace-network')
|
|
26
|
+
throw new Error('Invalid terminal sandbox.');
|
|
27
|
+
if (sandbox === 'workspace-network' && !networkAllowed)
|
|
28
|
+
throw new Error('terminal_network_disabled');
|
|
29
|
+
const root = fs.realpathSync(workspace);
|
|
30
|
+
const cwd = fs.realpathSync(workdir);
|
|
31
|
+
const relative = path.relative(root, cwd);
|
|
32
|
+
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
33
|
+
throw new Error('Working directory is outside the workspace.');
|
|
34
|
+
if (platform === 'darwin') {
|
|
35
|
+
if (!fs.existsSync('/usr/bin/sandbox-exec'))
|
|
36
|
+
throw new Error('workspace_sandbox_unavailable');
|
|
37
|
+
const home = fs.realpathSync(os.homedir());
|
|
38
|
+
const tmp = fs.realpathSync(os.tmpdir());
|
|
39
|
+
const toolchainPaths = (process.env.PATH || '').split(path.delimiter)
|
|
40
|
+
.filter(candidate => path.isAbsolute(candidate) && fs.existsSync(candidate))
|
|
41
|
+
.map(candidate => fs.realpathSync(candidate))
|
|
42
|
+
.map(candidate => path.basename(candidate) === 'bin' ? path.dirname(candidate) : candidate)
|
|
43
|
+
.filter(candidate => candidate.startsWith(`${home}/`) && candidate !== root && !candidate.startsWith(`${root}/`));
|
|
44
|
+
const readablePaths = [root, ...(scratchDir ? [fs.realpathSync(scratchDir)] : []),
|
|
45
|
+
...toolchainPaths, ...readPaths.map(candidate => fs.realpathSync(candidate))];
|
|
46
|
+
const protectedPrefixes = new Set();
|
|
47
|
+
for (const candidate of readablePaths) {
|
|
48
|
+
for (const boundary of [home, tmp]) {
|
|
49
|
+
for (let ancestor = candidate; ancestor.startsWith(`${boundary}/`); ancestor = path.dirname(ancestor))
|
|
50
|
+
protectedPrefixes.add(ancestor);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
protectedPrefixes.add(home);
|
|
54
|
+
protectedPrefixes.add(tmp);
|
|
55
|
+
const profile = [
|
|
56
|
+
'(version 1)', '(allow default)',
|
|
57
|
+
...(sandbox === 'workspace' ? ['(deny network*)',
|
|
58
|
+
...(networkAllowed ? ['(allow network-outbound (remote ip "localhost:*"))',
|
|
59
|
+
'(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
|
|
60
|
+
'(deny file-write*)',
|
|
61
|
+
`(allow file-write* (subpath ${seatbeltLiteral(root)}))`,
|
|
62
|
+
...(scratchDir ? [`(allow file-write* (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))}))`] : []),
|
|
63
|
+
'(allow file-write* (literal "/dev/null"))',
|
|
64
|
+
`(deny file-read* (subpath ${seatbeltLiteral(home)}))`,
|
|
65
|
+
`(deny file-read* (subpath ${seatbeltLiteral(tmp)}))`,
|
|
66
|
+
...[...protectedPrefixes].map(candidate => `(allow file-read* (literal ${seatbeltLiteral(candidate)}))`),
|
|
67
|
+
`(allow file-read* (subpath ${seatbeltLiteral(root)}))`,
|
|
68
|
+
...(scratchDir ? [`(allow file-read* (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))}))`] : []),
|
|
69
|
+
...toolchainPaths.map(candidate => `(allow file-read* (subpath ${seatbeltLiteral(candidate)}))`),
|
|
70
|
+
...readPaths.map(candidate => `(allow file-read* (subpath ${seatbeltLiteral(fs.realpathSync(candidate))}))`),
|
|
71
|
+
].join('\n');
|
|
72
|
+
return { file: '/usr/bin/sandbox-exec', args: ['-p', profile, shell, '-c', command] };
|
|
73
|
+
}
|
|
74
|
+
if (platform === 'linux') {
|
|
75
|
+
if (root === '/')
|
|
76
|
+
throw new Error('Workspace root cannot be the filesystem root.');
|
|
77
|
+
return { file: 'bwrap', args: ['--die-with-parent',
|
|
78
|
+
...(sandbox === 'workspace' ? ['--unshare-net'] : []), '--ro-bind', '/', '/',
|
|
79
|
+
'--dev-bind', '/dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
|
|
80
|
+
'--bind', root, root, '--chdir', cwd, shell, '-c', command] };
|
|
81
|
+
}
|
|
82
|
+
throw new Error('workspace_sandbox_unavailable');
|
|
83
|
+
}
|
|
84
|
+
/** Obvious destructive shell forms need an explicit elevated request even inside the workspace. */
|
|
85
|
+
export function requiresElevatedCommand(command) {
|
|
86
|
+
return /(?:^|[;&|()\n]\s*|\b(?:sudo|env|command)\s+)(?:rm|rmdir|shred)\b|\bgit\s+(?:clean\b|reset\s+--hard\b|checkout\s+--\b|restore\b)|\b(?:mkfs|dd|shutdown|reboot)\b/u.test(command);
|
|
87
|
+
}
|