@revoengine/cli 1.0.33 → 1.0.34
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 +25 -0
- package/README.md +83 -6
- package/dist/src/argument-contract.d.ts +17 -0
- package/dist/src/argument-contract.js +359 -0
- package/dist/src/automation-contract.generated.d.ts +2 -2
- package/dist/src/automation-contract.generated.js +2 -2
- package/dist/src/cli.js +15 -13
- package/dist/src/client.d.ts +2 -0
- package/dist/src/client.js +22 -0
- package/dist/src/commands/agents.js +5 -1
- package/dist/src/commands/auth.js +2 -0
- package/dist/src/commands/component.js +34 -17
- package/dist/src/commands/database-tables.js +5 -1
- package/dist/src/commands/database-views.js +5 -1
- package/dist/src/commands/endpoints.js +5 -1
- package/dist/src/commands/env.js +5 -1
- package/dist/src/commands/events.js +5 -1
- package/dist/src/commands/groups.js +5 -1
- package/dist/src/commands/info.js +2 -0
- package/dist/src/commands/job-templates.js +5 -1
- package/dist/src/commands/metadata.js +2 -0
- package/dist/src/commands/migrate.d.ts +2 -2
- package/dist/src/commands/migrate.js +31 -7
- package/dist/src/commands/project.js +19 -14
- package/dist/src/commands/request.js +2 -0
- package/dist/src/commands/role-groups.js +5 -1
- package/dist/src/commands/schedules.js +5 -1
- package/dist/src/commands/search.js +2 -0
- package/dist/src/commands/service-accounts.js +5 -1
- package/dist/src/commands/studio.js +2 -0
- package/dist/src/commands/terminal-file-descriptor.d.ts +9 -0
- package/dist/src/commands/terminal-file-descriptor.js +39 -0
- package/dist/src/commands/terminal-file.js +41 -6
- package/dist/src/commands/terminal-image.js +3 -31
- package/dist/src/commands/terminal-process-group.d.ts +25 -0
- package/dist/src/commands/terminal-process-group.js +144 -0
- package/dist/src/commands/terminal.js +123 -40
- package/dist/src/commands/tests.js +2 -0
- package/dist/src/component-lock.d.ts +15 -1
- package/dist/src/component-lock.js +96 -10
- package/dist/src/env-sync.js +12 -6
- package/dist/src/migration.d.ts +7 -0
- package/dist/src/migration.js +39 -21
- package/dist/src/planning-snapshot.d.ts +3 -0
- package/dist/src/planning-snapshot.js +60 -2
- package/dist/src/project.d.ts +1 -0
- package/dist/src/project.js +7 -8
- package/dist/src/resource-syncs/agent-sync.js +76 -24
- package/dist/src/resource-syncs/database-table-sync.js +33 -22
- package/dist/src/resource-syncs/database-view-sync.js +41 -28
- package/dist/src/resource-syncs/endpoint-sync.js +90 -18
- package/dist/src/resource-syncs/event-sync.js +33 -14
- package/dist/src/resource-syncs/group-sync.js +21 -11
- package/dist/src/resource-syncs/job-template-sync.js +98 -37
- package/dist/src/resource-syncs/role-group-sync.js +22 -11
- package/dist/src/resource-syncs/schedule-sync.js +26 -11
- package/dist/src/resource-syncs/service-account-sync.js +22 -11
- package/dist/src/reviewed-plan.js +3 -0
- package/dist/src/runtime-view.js +2 -18
- package/dist/src/sync-omit-command.d.ts +6 -0
- package/dist/src/sync-omit-command.js +49 -0
- package/dist/src/sync-omit-write-fence.d.ts +10 -0
- package/dist/src/sync-omit-write-fence.js +134 -0
- package/dist/src/sync-omit.d.ts +59 -0
- package/dist/src/sync-omit.js +469 -0
- package/dist/src/ui.js +10 -5
- package/dist/src/update-notifier.d.ts +1 -1
- package/dist/src/update-notifier.js +2 -1
- package/dist/src/utils.js +46 -17
- package/dist/src/workspace-prune.js +11 -3
- package/dist/src/workspace-write-lock.d.ts +7 -0
- package/dist/src/workspace-write-lock.js +144 -0
- package/package.json +3 -2
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import { validateCommandArguments } from "../argument-contract.js";
|
|
3
|
+
import { withWorkspaceWriteLockAtRoot } from "../workspace-write-lock.js";
|
|
2
4
|
import { readComponentLock } from "../component-lock.js";
|
|
3
5
|
import { applyMetadataBackfillPlan, buildMetadataBackfillPlan, } from "../metadata-backfill.js";
|
|
4
6
|
import { buildProjectSyncState, buildEditorTypesUrl, extractSandboxEndpoint, extractEditorTypesBundle, readProjectComponentIdentity, readProjectMetadata, readProjectStableKeyName, readProjectTrackedResources, resolveProjectInvocation, resolveProjectTarget, syncProjectFiles, } from "../project.js";
|
|
@@ -102,24 +104,27 @@ async function backfillStableKeyMetadata(context, stableKeyName, trackedResource
|
|
|
102
104
|
context.println(`Backfilled stable-key metadata on ${updated} component(s).`);
|
|
103
105
|
}
|
|
104
106
|
export async function handleProjectCommand(context) {
|
|
107
|
+
validateCommandArguments(context.args);
|
|
105
108
|
const { args, client, cwd, println } = context;
|
|
106
109
|
const invocation = resolveProjectInvocation(args);
|
|
107
110
|
if (invocation.extraArgs.length > 0) {
|
|
108
111
|
throw new Error(`Project ${invocation.action} accepts at most one path argument.`);
|
|
109
112
|
}
|
|
110
113
|
const layout = resolveProjectTarget(cwd, invocation.targetArg);
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
114
|
+
return withWorkspaceWriteLockAtRoot(layout.projectRoot, async () => {
|
|
115
|
+
const syncInput = await resolveProjectSyncInput(context);
|
|
116
|
+
syncInput.authProfile = context.componentEnvironment || 'default';
|
|
117
|
+
syncInput.componentIdentity = await resolveComponentIdentity(invocation, layout.projectRoot);
|
|
118
|
+
syncInput.trackedResources = await resolveTrackedResources(invocation, layout.projectRoot);
|
|
119
|
+
const result = syncProjectFiles(layout, syncInput);
|
|
120
|
+
printSyncSummary(println, layout.projectRoot, layout.workspaceRoot, result, invocation.action === 'update' ? 'Updated Revo project in' : 'Initialized Revo project in');
|
|
121
|
+
if (invocation.action === 'init'
|
|
122
|
+
&& syncInput.componentIdentity.mode === 'stableKey'
|
|
123
|
+
&& context.args['metadata-backfill'] !== false) {
|
|
124
|
+
await backfillStableKeyMetadata(context, syncInput.componentIdentity.metadataProperty || DEFAULT_STABLE_KEY_NAME, syncInput.trackedResources);
|
|
125
|
+
}
|
|
126
|
+
if (invocation.action === 'init' && shouldTrackResource(syncInput.trackedResources, 'database-table')) {
|
|
127
|
+
context.println('Database Table Stable Keys require an explicit review: revo metadata plan --resources database-table --project <source>');
|
|
128
|
+
}
|
|
129
|
+
});
|
|
125
130
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { validateCommandArguments } from "../argument-contract.js";
|
|
1
2
|
import { readFlag, readValues } from "../utils.js";
|
|
2
3
|
function parseJsonMaybe(value) {
|
|
3
4
|
if (!value) {
|
|
@@ -31,6 +32,7 @@ function parseQueryValue(value) {
|
|
|
31
32
|
return query;
|
|
32
33
|
}
|
|
33
34
|
export async function handleRequestCommand(context) {
|
|
35
|
+
validateCommandArguments(context.args);
|
|
34
36
|
const { args, client } = context;
|
|
35
37
|
const method = (args._[1] || readFlag(args, ['method', 'm']) || 'GET').toUpperCase();
|
|
36
38
|
const requestPath = args._[2] || readFlag(args, ['path', 'p']) || '';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withCommandSyncOmit } from "../sync-omit-command.js";
|
|
1
2
|
import fs from 'node:fs';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { resolveProjectRoot, readProjectStableKeyName } from "../project.js";
|
|
@@ -122,7 +123,7 @@ async function handlePush(context) {
|
|
|
122
123
|
if (failed.length > 0)
|
|
123
124
|
throw new Error(`Role-group push finished with ${failed.length} failure(s).`);
|
|
124
125
|
}
|
|
125
|
-
|
|
126
|
+
async function executeRoleGroupsCommand(context) {
|
|
126
127
|
warnAboutExperimentalState(context);
|
|
127
128
|
const subcommand = context.args._[1] || '';
|
|
128
129
|
if (subcommand === 'pull') {
|
|
@@ -139,3 +140,6 @@ export async function handleRoleGroupsCommand(context) {
|
|
|
139
140
|
}
|
|
140
141
|
throw new Error('Unknown role-groups command. Usage: revo role-groups <pull|plan|push> --all [--env <name>]');
|
|
141
142
|
}
|
|
143
|
+
export async function handleRoleGroupsCommand(context) {
|
|
144
|
+
return withCommandSyncOmit(context, ['role-group'], scoped => executeRoleGroupsCommand(scoped));
|
|
145
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { withCommandSyncOmit } from "../sync-omit-command.js";
|
|
1
2
|
import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
|
|
2
3
|
import { readProjectStableKeyName } from "../project.js";
|
|
3
4
|
import { resolveResourceTarget } from "../resource-target.js";
|
|
4
5
|
import { activateVerifiedSchedules, buildSchedulesPlan, pullSchedulesToWorkspace, pushSchedules } from "../resource-syncs/schedule-sync.js";
|
|
5
6
|
import { planDependencyHints, printSyncNotice, printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
|
|
6
7
|
import { readBoolFlag } from "../utils.js";
|
|
7
|
-
|
|
8
|
+
async function executeSchedulesCommand(context) {
|
|
8
9
|
const subcommand = context.args._[1] || '';
|
|
9
10
|
if (!['pull', 'plan', 'push'].includes(subcommand)) {
|
|
10
11
|
throw new Error('Unknown schedules command. Usage: revo schedules <pull|plan|push> --all [--env <name>]');
|
|
@@ -140,3 +141,6 @@ export async function handleSchedulesCommand(context) {
|
|
|
140
141
|
}
|
|
141
142
|
printSyncSummary(context.println, 'Pulled', output, Date.now() - startedAt);
|
|
142
143
|
}
|
|
144
|
+
export async function handleSchedulesCommand(context) {
|
|
145
|
+
return withCommandSyncOmit(context, ['schedule'], scoped => executeSchedulesCommand(scoped));
|
|
146
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { validateCommandArguments } from "../argument-contract.js";
|
|
1
2
|
import { readFlag } from "../utils.js";
|
|
2
3
|
const SEARCH_TYPES = new Set(['CODE', 'SIMPLE']);
|
|
3
4
|
export async function handleSearchCommand(context) {
|
|
5
|
+
validateCommandArguments(context.args);
|
|
4
6
|
const { args, client } = context;
|
|
5
7
|
const type = (readFlag(args, ['type', 't']) || args._[1] || '').toUpperCase();
|
|
6
8
|
const term = readFlag(args, ['term']) || args._[2] || '';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { withCommandSyncOmit } from "../sync-omit-command.js";
|
|
1
2
|
import fs from 'node:fs';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { resolveProjectRoot, readProjectStableKeyName } from "../project.js";
|
|
@@ -130,7 +131,7 @@ async function handlePush(context) {
|
|
|
130
131
|
throw new Error(`Service-account push finished with ${failed.length} failure(s).`);
|
|
131
132
|
}
|
|
132
133
|
}
|
|
133
|
-
|
|
134
|
+
async function executeServiceAccountsCommand(context) {
|
|
134
135
|
warnAboutExperimentalState(context);
|
|
135
136
|
const subcommand = context.args._[1] || '';
|
|
136
137
|
if (subcommand === 'pull') {
|
|
@@ -147,3 +148,6 @@ export async function handleServiceAccountsCommand(context) {
|
|
|
147
148
|
}
|
|
148
149
|
throw new Error('Unknown service-accounts command. Usage: revo service-accounts <pull|plan|push> --all [--env <name>]');
|
|
149
150
|
}
|
|
151
|
+
export async function handleServiceAccountsCommand(context) {
|
|
152
|
+
return withCommandSyncOmit(context, ['service-account'], scoped => executeServiceAccountsCommand(scoped));
|
|
153
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { validateCommandArguments } from "../argument-contract.js";
|
|
4
5
|
import { readFlag } from "../utils.js";
|
|
5
6
|
const mutations = { patch: 'patch', attach: 'resources', fork: 'fork', test: 'test-runs', freeze: 'proposals', commit: 'commit', prepare: 'prepare', activate: 'activate', rebase: 'rebase', share: 'share', participant: 'participants', presence: 'presence', claim: 'claims', message: 'chat/message', baseline: 'runtime/baseline', rollback: 'runtime/rollback' };
|
|
6
7
|
const reads = new Set(['diff', 'files', 'events', 'chat', 'search', 'preview-rebase', 'claims']);
|
|
@@ -28,6 +29,7 @@ function readBody(context) {
|
|
|
28
29
|
}
|
|
29
30
|
/** Never turns a rejected legacy write into an unreviewed source commit. */
|
|
30
31
|
export async function handleStudioCommand(context) {
|
|
32
|
+
validateCommandArguments(context.args);
|
|
31
33
|
const { args, client } = context;
|
|
32
34
|
const action = args._[1] || 'list';
|
|
33
35
|
const sessionId = args._[2];
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
type DescriptorErrors = {
|
|
3
|
+
unverifiable: string;
|
|
4
|
+
outside: string;
|
|
5
|
+
notRegular: string;
|
|
6
|
+
};
|
|
7
|
+
/** canonicalWorkspaceRoot is captured before open; do not re-resolve a mutable workspace path here. */
|
|
8
|
+
export declare function verifyWorkspaceFileDescriptor(canonicalWorkspaceRoot: string, fd: number, errors: DescriptorErrors): fs.Stats;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
/** Resolve the opened inode, never a path that can be substituted after validation. */
|
|
5
|
+
function openedFilePath(fd, unverifiable) {
|
|
6
|
+
if (process.platform === 'linux') {
|
|
7
|
+
try {
|
|
8
|
+
return fs.readlinkSync(`/proc/self/fd/${fd}`);
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
throw new Error(unverifiable);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (process.platform === 'darwin') {
|
|
15
|
+
const result = spawnSync('/usr/sbin/lsof', ['-a', '-p', String(process.pid), '-d', String(fd), '-F0n'], { encoding: 'utf8', timeout: 5_000, maxBuffer: 64_000 });
|
|
16
|
+
if (result.error || result.status !== 0 || typeof result.stdout !== 'string')
|
|
17
|
+
throw new Error(unverifiable);
|
|
18
|
+
const fields = result.stdout.split('\0').map(field => field.replace(/^\n/u, ''));
|
|
19
|
+
if (!fields.includes(`p${process.pid}`) || !fields.includes(`f${fd}`))
|
|
20
|
+
throw new Error(unverifiable);
|
|
21
|
+
const names = fields.filter(field => field.startsWith('n')).map(field => field.slice(1));
|
|
22
|
+
if (names.length !== 1)
|
|
23
|
+
throw new Error(unverifiable);
|
|
24
|
+
return names[0];
|
|
25
|
+
}
|
|
26
|
+
throw new Error(unverifiable);
|
|
27
|
+
}
|
|
28
|
+
/** canonicalWorkspaceRoot is captured before open; do not re-resolve a mutable workspace path here. */
|
|
29
|
+
export function verifyWorkspaceFileDescriptor(canonicalWorkspaceRoot, fd, errors) {
|
|
30
|
+
const stat = fs.fstatSync(fd);
|
|
31
|
+
const openedPath = openedFilePath(fd, errors.unverifiable);
|
|
32
|
+
const relative = path.relative(canonicalWorkspaceRoot, openedPath);
|
|
33
|
+
if (!path.isAbsolute(openedPath) || !relative || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
34
|
+
throw new Error(errors.outside);
|
|
35
|
+
}
|
|
36
|
+
if (!stat.isFile())
|
|
37
|
+
throw new Error(errors.notRegular);
|
|
38
|
+
return stat;
|
|
39
|
+
}
|
|
@@ -3,6 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import https from 'node:https';
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
5
|
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import { verifyWorkspaceFileDescriptor } from "./terminal-file-descriptor.js";
|
|
6
7
|
const HEADERS = new Set(['content-type', 'content-length', 'content-range', 'range', 'if-match', 'if-none-match',
|
|
7
8
|
'x-goog-if-generation-match', 'x-goog-if-metageneration-match']);
|
|
8
9
|
/** URLs and headers are credentials. Never include them in errors or operational logs. */
|
|
@@ -69,8 +70,9 @@ export async function transferWorkspaceFile(workspace, operation, transfer, sign
|
|
|
69
70
|
if (operation === 'upload_file') {
|
|
70
71
|
const file = await fs.promises.open(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
71
72
|
try {
|
|
72
|
-
const stat =
|
|
73
|
-
|
|
73
|
+
const stat = verifyWorkspaceFileDescriptor(root, file.fd, { unverifiable: 'file_transfer_path_unverifiable',
|
|
74
|
+
outside: 'file_transfer_outside_workspace', notRegular: 'file_transfer_not_regular' });
|
|
75
|
+
if (!Number.isSafeInteger(stat.size))
|
|
74
76
|
throw new Error('file_transfer_not_regular');
|
|
75
77
|
const resumable = new URL(transfer.url).searchParams.has('upload_id');
|
|
76
78
|
let offset = transfer.offset ?? 0;
|
|
@@ -126,6 +128,18 @@ export async function transferWorkspaceFile(workspace, operation, transfer, sign
|
|
|
126
128
|
if (transfer.offset !== null || transfer.length !== null || headers.range)
|
|
127
129
|
throw new Error('file_download_range_not_supported');
|
|
128
130
|
const temporary = path.join(parent, `.revo-transfer-${randomUUID()}.part`);
|
|
131
|
+
const parentIdentity = await fs.promises.stat(parent);
|
|
132
|
+
let file;
|
|
133
|
+
let temporaryIdentity;
|
|
134
|
+
const unchangedParent = () => {
|
|
135
|
+
try {
|
|
136
|
+
const current = fs.lstatSync(parent);
|
|
137
|
+
return current.isDirectory() && current.dev === parentIdentity.dev && current.ino === parentIdentity.ino;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
129
143
|
try {
|
|
130
144
|
const existing = await fs.promises.lstat(target).catch(error => {
|
|
131
145
|
if (error.code === 'ENOENT')
|
|
@@ -134,16 +148,27 @@ export async function transferWorkspaceFile(workspace, operation, transfer, sign
|
|
|
134
148
|
});
|
|
135
149
|
if (existing && (!transfer.overwrite || !existing.isFile() || existing.isSymbolicLink()))
|
|
136
150
|
throw new Error('file_transfer_target_exists');
|
|
151
|
+
file = await fs.promises.open(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600);
|
|
152
|
+
temporaryIdentity = verifyWorkspaceFileDescriptor(root, file.fd, { unverifiable: 'file_transfer_path_unverifiable',
|
|
153
|
+
outside: 'file_transfer_outside_workspace', notRegular: 'file_transfer_not_regular' });
|
|
154
|
+
if (!unchangedParent())
|
|
155
|
+
throw new Error('file_transfer_outside_workspace');
|
|
137
156
|
const response = await request(transfer.url, 'GET', headers, signal);
|
|
138
157
|
if (response.statusCode !== 200) {
|
|
139
158
|
drain(response);
|
|
140
159
|
throw transferError(response.statusCode);
|
|
141
160
|
}
|
|
142
|
-
await pipeline(response, fs.createWriteStream(temporary, {
|
|
143
|
-
const stat = await
|
|
161
|
+
await pipeline(response, fs.createWriteStream(temporary, { fd: file.fd, autoClose: false, emitClose: false }), { signal });
|
|
162
|
+
const stat = await file.stat();
|
|
144
163
|
if (response.headers['content-length'] !== undefined && Number(response.headers['content-length']) !== stat.size)
|
|
145
164
|
throw new Error('file_transfer_incomplete');
|
|
146
|
-
|
|
165
|
+
verifyWorkspaceFileDescriptor(root, file.fd, { unverifiable: 'file_transfer_path_unverifiable',
|
|
166
|
+
outside: 'file_transfer_outside_workspace', notRegular: 'file_transfer_not_regular' });
|
|
167
|
+
if (!unchangedParent())
|
|
168
|
+
throw new Error('file_transfer_outside_workspace');
|
|
169
|
+
const temporaryPathIdentity = await fs.promises.lstat(temporary).catch(() => { throw new Error('file_transfer_outside_workspace'); });
|
|
170
|
+
if (!unchangedParent() || !temporaryPathIdentity.isFile()
|
|
171
|
+
|| temporaryPathIdentity.dev !== stat.dev || temporaryPathIdentity.ino !== stat.ino)
|
|
147
172
|
throw new Error('file_transfer_outside_workspace');
|
|
148
173
|
if (transfer.overwrite)
|
|
149
174
|
await fs.promises.rename(temporary, target);
|
|
@@ -155,6 +180,16 @@ export async function transferWorkspaceFile(workspace, operation, transfer, sign
|
|
|
155
180
|
...(typeof response.headers.etag === 'string' ? { etag: response.headers.etag } : {}) };
|
|
156
181
|
}
|
|
157
182
|
finally {
|
|
158
|
-
|
|
183
|
+
// A substituted directory must never turn cleanup into deletion of a
|
|
184
|
+
// different file. A displaced temporary is retained rather than guessed.
|
|
185
|
+
if (temporaryIdentity && unchangedParent()) {
|
|
186
|
+
try {
|
|
187
|
+
const current = fs.lstatSync(temporary);
|
|
188
|
+
if (current.isFile() && current.dev === temporaryIdentity.dev && current.ino === temporaryIdentity.ino)
|
|
189
|
+
fs.unlinkSync(temporary);
|
|
190
|
+
}
|
|
191
|
+
catch { /* already committed or namespace changed */ }
|
|
192
|
+
}
|
|
193
|
+
await file?.close();
|
|
159
194
|
}
|
|
160
195
|
}
|
|
@@ -1,42 +1,14 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import {
|
|
3
|
+
import { verifyWorkspaceFileDescriptor } from "./terminal-file-descriptor.js";
|
|
4
4
|
const MAX_IMAGE_BYTES = 30 * 1024 * 1024;
|
|
5
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
6
|
function readWorkspaceImage(workspace, file) {
|
|
31
7
|
const root = fs.realpathSync(workspace);
|
|
32
8
|
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
33
9
|
try {
|
|
34
|
-
const stat =
|
|
35
|
-
|
|
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');
|
|
10
|
+
const stat = verifyWorkspaceFileDescriptor(root, fd, { unverifiable: 'image_path_unverifiable',
|
|
11
|
+
outside: 'image_outside_workspace', notRegular: 'image_outside_workspace' });
|
|
40
12
|
if (stat.size < 1 || stat.size > MAX_IMAGE_BYTES)
|
|
41
13
|
throw new Error('image_size_invalid');
|
|
42
14
|
const data = Buffer.allocUnsafe(stat.size);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export type TerminalProcessIdentity = {
|
|
2
|
+
pid: number;
|
|
3
|
+
group: number;
|
|
4
|
+
birth: string;
|
|
5
|
+
running: boolean;
|
|
6
|
+
};
|
|
7
|
+
export type TerminalProcessProbe = {
|
|
8
|
+
identity(pid: number): TerminalProcessIdentity | undefined;
|
|
9
|
+
group(group: number): TerminalProcessIdentity[];
|
|
10
|
+
};
|
|
11
|
+
export type TerminalGroupState = 'owned' | 'stopped' | 'unverified';
|
|
12
|
+
export declare function parseDarwinTerminalProcessIdentities(output: string): TerminalProcessIdentity[];
|
|
13
|
+
export declare function parseLinuxTerminalProcessStat(pid: number, value: string): TerminalProcessIdentity;
|
|
14
|
+
export declare const nativeTerminalProcessProbe: TerminalProcessProbe;
|
|
15
|
+
export declare function assertTerminalProcessProbeAvailable(): void;
|
|
16
|
+
/** Signal only a group with continuity to an observed PID/birth identity. Never fall back to a positive PID. */
|
|
17
|
+
export declare class ControlledTerminalProcessGroup {
|
|
18
|
+
private readonly owned;
|
|
19
|
+
private readonly pid;
|
|
20
|
+
private readonly probe;
|
|
21
|
+
private readonly kill;
|
|
22
|
+
constructor(pid: number, probe?: TerminalProcessProbe, kill?: (pid: number, signal: NodeJS.Signals) => unknown);
|
|
23
|
+
state(): TerminalGroupState;
|
|
24
|
+
signal(signal: NodeJS.Signals): TerminalGroupState;
|
|
25
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
export function parseDarwinTerminalProcessIdentities(output) {
|
|
4
|
+
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
|
|
5
|
+
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
6
|
+
return output.split('\n').flatMap(line => {
|
|
7
|
+
if (!line.trim())
|
|
8
|
+
return [];
|
|
9
|
+
// Native Darwin ps reports ? / ?E during process churn. Such rows still
|
|
10
|
+
// carry a birth identity and must never be mistaken for a stopped process.
|
|
11
|
+
const match = /^\s*(\d+)\s+(\d+)\s+([?A-Z][A-Za-z0-9+<=>?*\-]*)\s+(.+?)\s*$/u.exec(line);
|
|
12
|
+
if (!match)
|
|
13
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
14
|
+
const pid = Number(match[1]);
|
|
15
|
+
const group = Number(match[2]);
|
|
16
|
+
if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(group))
|
|
17
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
18
|
+
if (pid === 0 && match[4] === '-')
|
|
19
|
+
return [];
|
|
20
|
+
const birth = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})$/u.exec(match[4]);
|
|
21
|
+
if (!birth)
|
|
22
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
23
|
+
const day = Number(birth[3]);
|
|
24
|
+
const hour = Number(birth[4]);
|
|
25
|
+
const minute = Number(birth[5]);
|
|
26
|
+
const second = Number(birth[6]);
|
|
27
|
+
const year = Number(birth[7]);
|
|
28
|
+
const month = months.indexOf(birth[2]);
|
|
29
|
+
const date = new Date(Date.UTC(year, month, day, hour, minute, second));
|
|
30
|
+
if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day
|
|
31
|
+
|| hour > 23 || minute > 59 || second > 59 || weekdays[date.getUTCDay()] !== birth[1])
|
|
32
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
33
|
+
return [{ pid, group, birth: match[4].replace(/\s+/gu, ' '), running: !/^[ZX]/u.test(match[3]) }];
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
function processIdentities(id, selection) {
|
|
37
|
+
let output;
|
|
38
|
+
try {
|
|
39
|
+
output = execFileSync('/bin/ps', [selection === 'pid' ? '-p' : '-g', String(id), '-o', 'pid=,pgid=,stat=,lstart='], { encoding: 'utf8', timeout: 1_000, maxBuffer: 4 * 1024 * 1024, env: { LC_ALL: 'C', PATH: '/usr/bin:/bin' }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (error.status === 1 && !error.stdout?.trim())
|
|
43
|
+
return [];
|
|
44
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
45
|
+
}
|
|
46
|
+
return parseDarwinTerminalProcessIdentities(output);
|
|
47
|
+
}
|
|
48
|
+
export function parseLinuxTerminalProcessStat(pid, value) {
|
|
49
|
+
const end = value.lastIndexOf(')');
|
|
50
|
+
const fields = value.slice(end + 1).trim().split(/\s+/u);
|
|
51
|
+
const actualPid = Number(value.slice(0, value.indexOf('(')).trim());
|
|
52
|
+
const group = Number(fields[2]);
|
|
53
|
+
const birth = fields[19];
|
|
54
|
+
if (end < 0 || actualPid !== pid || !Number.isSafeInteger(group) || group < 0 || !birth || !/^\d+$/u.test(birth)) {
|
|
55
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
56
|
+
}
|
|
57
|
+
return { pid, group, birth: `linux:${birth}`, running: !/^[ZX]/u.test(fields[0] || '') };
|
|
58
|
+
}
|
|
59
|
+
function linuxProcessIdentity(pid) {
|
|
60
|
+
try {
|
|
61
|
+
return parseLinuxTerminalProcessStat(pid, fs.readFileSync(`/proc/${pid}/stat`, 'utf8'));
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (['ENOENT', 'ESRCH'].includes(error.code || ''))
|
|
65
|
+
return undefined;
|
|
66
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export const nativeTerminalProcessProbe = {
|
|
70
|
+
identity: pid => process.platform === 'linux' ? linuxProcessIdentity(pid) : processIdentities(pid, 'pid').find(item => item.pid === pid),
|
|
71
|
+
group: group => {
|
|
72
|
+
const started = Date.now();
|
|
73
|
+
const names = process.platform === 'linux' ? fs.readdirSync('/proc').filter(name => /^\d+$/u.test(name)) : [];
|
|
74
|
+
if (names.length > 16_384)
|
|
75
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
76
|
+
const identities = process.platform === 'linux'
|
|
77
|
+
? names.flatMap(name => {
|
|
78
|
+
if (Date.now() - started > 1_000)
|
|
79
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
80
|
+
const identity = linuxProcessIdentity(Number(name));
|
|
81
|
+
return identity ? [identity] : [];
|
|
82
|
+
}) : processIdentities(group, 'group');
|
|
83
|
+
if (Date.now() - started > 1_000)
|
|
84
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
85
|
+
return identities.filter(item => item.group === group);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
export function assertTerminalProcessProbeAvailable() {
|
|
89
|
+
const current = nativeTerminalProcessProbe.identity(process.pid);
|
|
90
|
+
if (!current?.birth)
|
|
91
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
92
|
+
nativeTerminalProcessProbe.group(current.group);
|
|
93
|
+
}
|
|
94
|
+
/** Signal only a group with continuity to an observed PID/birth identity. Never fall back to a positive PID. */
|
|
95
|
+
export class ControlledTerminalProcessGroup {
|
|
96
|
+
owned = new Map();
|
|
97
|
+
pid;
|
|
98
|
+
probe;
|
|
99
|
+
kill;
|
|
100
|
+
constructor(pid, probe = nativeTerminalProcessProbe, kill = process.kill.bind(process)) {
|
|
101
|
+
if (!Number.isSafeInteger(pid) || pid < 1)
|
|
102
|
+
throw new Error('terminal_process_identity_unavailable');
|
|
103
|
+
this.pid = pid;
|
|
104
|
+
this.probe = probe;
|
|
105
|
+
this.kill = kill;
|
|
106
|
+
try {
|
|
107
|
+
const leader = probe.identity(pid);
|
|
108
|
+
if (leader?.pid === pid && leader.birth)
|
|
109
|
+
this.owned.set(pid, leader.birth);
|
|
110
|
+
this.state();
|
|
111
|
+
}
|
|
112
|
+
catch { /* A missing proof never authorizes a signal. */ }
|
|
113
|
+
}
|
|
114
|
+
state() {
|
|
115
|
+
let members;
|
|
116
|
+
try {
|
|
117
|
+
members = this.probe.group(this.pid).filter(item => item.group === this.pid);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return 'unverified';
|
|
121
|
+
}
|
|
122
|
+
if (!members.some(item => item.running))
|
|
123
|
+
return 'stopped';
|
|
124
|
+
if (!members.some(item => this.owned.get(item.pid) === item.birth))
|
|
125
|
+
return 'unverified';
|
|
126
|
+
// Membership can evolve only while at least one original identity still
|
|
127
|
+
// proves continuity. A reused leader/group cannot acquire ownership here.
|
|
128
|
+
for (const member of members)
|
|
129
|
+
this.owned.set(member.pid, member.birth);
|
|
130
|
+
return 'owned';
|
|
131
|
+
}
|
|
132
|
+
signal(signal) {
|
|
133
|
+
const state = this.state();
|
|
134
|
+
if (state !== 'owned')
|
|
135
|
+
return state;
|
|
136
|
+
try {
|
|
137
|
+
this.kill(-this.pid, signal);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
return error.code === 'ESRCH' ? 'stopped' : 'unverified';
|
|
141
|
+
}
|
|
142
|
+
return 'owned';
|
|
143
|
+
}
|
|
144
|
+
}
|