Verify script revision binding and recovery after interrupted submission

This commit is contained in:
2026-11-17 22:43:46 +01:00
parent 439c729160
commit a3b7a237be
5 changed files with 1336 additions and 278 deletions
+262
View File
@@ -0,0 +1,262 @@
import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
import { createHash, randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
let server: ViteDevServer;
let origin: string;
const principal = 'operator-fixture';
const tenantId = randomUUID();
const auth = {
principal: { id: principal, display_name: 'Operator', simulated: true },
csrf_token: 'fixture',
tenants: [{ tenant_id: tenantId, name: 'Nord' }],
permissions: ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit', 'scripts:execute']
};
const linux = {
asset_id: randomUUID(),
agent_id: randomUUID(),
hostname: 'test-linux',
os: 'Debian',
source_id: 'linux.base',
status: 'online',
lifecycle: 'current'
};
const windows = {
...linux,
asset_id: randomUUID(),
agent_id: randomUUID(),
hostname: 'test-windows',
os: 'Windows',
source_id: 'windows.base'
};
const script = {
name: 'Betriebssystem anzeigen',
revision_id: randomUUID(),
interpreter: 'posix_sh',
execution_identity: 'agent_service',
script_utf8: 'uname -s\n',
version: 1
};
const hash = (text: string) => createHash('sha256').update(text).digest('hex');
const listing = (items: unknown[]) => ({
items,
as_of: new Date().toISOString(),
next_cursor: null,
truncated: false,
completeness: 'complete'
});
test.beforeAll(async () => {
server = await createServer({
root: resolve(__dirname, '../../web'),
configFile: false,
server: { host: '127.0.0.1', port: 0 },
logLevel: 'silent'
});
await server.listen();
const a = server.httpServer?.address();
if (!a || typeof a === 'string') throw Error('Missing fixture port');
origin = 'http://127.0.0.1:' + a.port;
});
test.afterAll(async () => {
await server?.close();
});
for (const library of [true, false]) {
test(
library
? 'pins a revision, blocks an incompatible target and finds the submitted order after a lost response'
: 'submits a one-time script without publishing a library revision',
async ({ page }) => {
let operationId: string | null = null;
let plan: Record<string, unknown> | null = null;
const posted: string[] = [];
let issuedVersion = 1;
await page.route(origin + '/fixture', (r) =>
r.fulfill({
contentType: 'text/html',
body: `<!doctype html><meta charset="utf-8"/><div id="root"></div><script type="module">
import React from '/node_modules/.vite/deps/react.js';
import ReactDOM from '/node_modules/.vite/deps/react-dom_client.js';
import {OrderComposer} from '/src/order-composer.tsx';
ReactDOM.createRoot(document.querySelector('#root')).render(React.createElement(OrderComposer,{tenantId:'${tenantId}',auth:${JSON.stringify(auth)},initialAssetIds:['${linux.asset_id}'],onSubmitted:id=>document.body.setAttribute('data-operation',id)}));
</script>`
})
);
const api = '/api/v1/tenants/' + tenantId;
await page.route(origin + api + '/**', async (r) => {
const req = r.request();
const suffix = new URL(req.url()).pathname.slice(api.length);
if (req.method() === 'GET') {
if (suffix === '/devices') return r.fulfill({ json: listing([linux, windows]) });
if (suffix.startsWith('/devices/'))
return r.fulfill({ json: suffix.endsWith(linux.asset_id) ? linux : windows });
if (suffix === '/script-revisions')
return r.fulfill({
json: listing([{ ...script, script_sha256: hash(script.script_utf8), version: issuedVersion }])
});
if (suffix === '/operation-plans/' + plan?.plan_id)
return r.fulfill({ json: { ...plan, operation_id: operationId } });
} else if (req.method() === 'POST') {
posted.push(suffix);
const body = req.postDataJSON();
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
if (suffix === (library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans')) {
expect(body.targets.asset_ids).toEqual([linux.asset_id]);
expect(body.reason).toBe('Abnahme');
const content = library ? script.script_utf8 : body.parameters.variants[0].script_utf8;
const action = {
action: 'run_script',
interpreter: 'posix_sh',
script_utf8: content,
arguments: [],
expected_stdout: null
};
const payload = {
schema_version: 1,
tenant_id: tenantId,
asset_id: linux.asset_id,
agent_id: linux.agent_id,
enrollment_generation: 1,
assignment_version: 1,
job_id: randomUUID(),
attempt_id: randomUUID(),
action,
execution_identity: 'agent_service',
not_before: body.schedule.not_before,
start_before: body.schedule.start_before,
max_runtime_seconds: library ? body.max_runtime_seconds : body.parameters.timeout_seconds,
max_output_bytes: library ? body.max_output_bytes : body.parameters.max_output_bytes
};
const job = { payload, job_payload_hash: hash(JSON.stringify(payload)), script_sha256: hash(content) };
const fixed = {
schema_version: 1,
plan_id: randomUUID(),
tenant_id: tenantId,
principal,
reason: body.reason,
jobs: [job],
max_parallel: 1,
halt_after_failures: 1,
...(library
? {
script_revision: {
revision_id: script.revision_id,
name: script.name,
version: 1,
script_sha256: job.script_sha256
}
}
: {})
};
const bytes = JSON.stringify(fixed);
plan = {
plan_id: fixed.plan_id,
plan_hash: hash(bytes),
plan_payload_bytes: [...Buffer.from(bytes)],
plan_payload: fixed,
payload: fixed,
jobs: [job],
resolved_targets: [{ asset_id: linux.asset_id, agent_id: linux.agent_id }],
excluded_targets: [],
expires_at: payload.start_before
};
return r.fulfill({ json: plan });
}
if (suffix === '/operation-plans/' + plan?.plan_id + '/submit') {
expect(body).toEqual({ idempotency_key: plan!.plan_id });
operationId = randomUUID();
if (library) return r.abort('connectionreset');
return r.fulfill({
json: { plan_id: plan!.plan_id, plan_hash: plan!.plan_hash, operation_id: operationId }
});
}
}
return r.fulfill({ status: 404, json: { code: 'unexpected', message: suffix } });
});
await page.goto(origin + '/fixture');
await expect(page.getByRole('checkbox', { name: /test-linux/ })).toBeChecked();
if (library) await page.getByRole('checkbox', { name: /test-windows/ }).check();
await page.getByRole('button', { name: 'Weiter zum Skript' }).click();
if (library) {
await page.getByLabel('Bibliotheksskript').selectOption(script.name);
await expect(page.getByRole('alert')).toContainText('test-windows');
await expect(page.getByRole('button', { name: 'Zusammenfassung ansehen' })).toBeDisabled();
await page.getByRole('button', { name: 'Zurück zu Geräten' }).click();
await page.getByRole('checkbox', { name: /test-windows/ }).uncheck();
await page.getByRole('button', { name: 'Weiter zum Skript' }).click();
} else {
await page.getByRole('radio', { name: 'Einmaliges Skript' }).check();
await page.getByLabel('Skriptinhalt').fill('uname\n');
}
await page.getByLabel('Begründung').fill('Abnahme');
await page.getByRole('button', { name: 'Zusammenfassung ansehen' }).click();
await expect(page.getByRole('heading', { name: 'Zusammenfassung' })).toBeVisible();
if (library) {
issuedVersion = 2;
await expect(page.getByRole('heading', { name: /Version 1/ })).toBeVisible();
}
await page.getByRole('button', { name: 'Zur Genehmigung einreichen' }).click();
if (library) {
await expect(page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' })).toBeVisible();
await page.reload();
await page.getByRole('button', { name: 'Eingereichten Auftrag öffnen' }).click();
}
await expect(page.locator('body')).toHaveAttribute('data-operation', /^[a-f0-9-]{36}$/);
expect(await page.locator('body').getAttribute('data-operation')).toBe(operationId);
expect(posted).toEqual([
library ? '/script-revisions/' + script.revision_id + '/plan' : '/operation-plans',
'/operation-plans/' + plan!.plan_id + '/submit'
]);
expect(await page.evaluate(() => sessionStorage.length)).toBe(0);
}
);
}
test('publishes versions in the library and keeps the earlier script readable', async ({ page }) => {
const revisions = [{ ...script, script_sha256: hash(script.script_utf8) }];
const writes: string[] = [];
await page.route(origin + '/fixture', (r) =>
r.fulfill({
contentType: 'text/html',
body: `<!doctype html><meta charset="utf-8"/><div id="root"></div><script type="module">
import React from '/node_modules/.vite/deps/react.js';
import ReactDOM from '/node_modules/.vite/deps/react-dom_client.js';
import {ScriptLibrary} from '/src/script-library.tsx';
ReactDOM.createRoot(document.querySelector('#root')).render(React.createElement(ScriptLibrary,{tenantId:'${tenantId}',auth:${JSON.stringify(auth)}}));
</script>`
})
);
await page.route(origin + '/api/v1/**', (r) => {
const req = r.request();
const path = '/api/v1/tenants/' + tenantId + '/script-revisions';
expect(new URL(req.url()).pathname).toBe(path);
if (req.method() === 'GET') return r.fulfill({ json: listing(revisions) });
writes.push(path);
expect(req.headers()['x-csrf-token']).toBe(auth.csrf_token);
const body = req.postDataJSON();
expect(body.expected_version).toBe(revisions.length);
const next = {
...script,
revision_id: randomUUID(),
script_utf8: body.script_utf8,
script_sha256: hash(body.script_utf8),
version: body.expected_version + 1
};
revisions.push(next);
return r.fulfill({ json: next });
});
await page.goto(origin + '/fixture');
await page.getByRole('button', { name: script.name, exact: true }).click();
await page.getByRole('button', { name: 'Neue Version', exact: true }).click();
await page.getByLabel('Skriptinhalt').fill('uname -r\n');
await page.getByRole('button', { name: 'Version veröffentlichen' }).click();
await expect(page.getByRole('status')).toContainText('Version 2 veröffentlicht.');
await page.getByText('Frühere Versionen (1)').click();
await page.getByText('Version 1 · Linux · Shell · Agent-Dienstkonto').click();
await expect(page.locator('pre').filter({ hasText: 'uname -s' })).toBeVisible();
await page.getByRole('button', { name: 'Zur Skriptbibliothek' }).click();
await expect(page.getByRole('row').filter({ hasText: script.name })).toHaveCount(1);
await expect(page.getByRole('row').filter({ hasText: script.name })).toContainText('2');
expect(writes).toHaveLength(1);
});
+705 -190
View File
@@ -1,18 +1,59 @@
import { useEffect, useRef, useState, type FormEvent } from 'react';
import { allowed, powerShellApprovalBlockers, validateSensitiveInput, verifyPlanIntegrity } from './safety';
import { ApiError, approvalBlockers, expectedStdout, fullMaintenanceScriptProfile, objectId, page, record, request, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, type PlanInput, type RecordValue, type Session } from './api';
import {
ApiError,
approvalBlockers,
expectedStdout,
fullMaintenanceScriptProfile,
objectId,
page,
record,
request,
tenantPath,
validateInput,
windowsPowerShellRemoteSignedProfile,
type PlanInput,
type RecordValue,
type Session
} from './api';
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan, windowsUpdateScriptHash } from './script-console';
import { ErrorBox, errorText, useResource } from './resource';
import { devicePlatform, identityNames, interpreterNames, latestRevisions, loadRevisions, scriptPlatform, type Identity, type Interpreter, type Script } from './script-catalog';
import {
devicePlatform,
identityNames,
interpreterNames,
latestRevisions,
loadRevisions,
scriptPlatform,
type Identity,
type Interpreter,
type Script
} from './script-catalog';
import { ScriptFields } from './script-library';
type Props = { tenantId: string; customerName?: string; auth: Session; initialAssetIds: string[]; onSubmitted: (operationId: string) => void };
type Target = { id: string; name: string; os: string; platform: 'linux' | 'windows' | null; state: string; current: boolean };
type Props = {
tenantId: string;
customerName?: string;
auth: Session;
initialAssetIds: string[];
onSubmitted: (operationId: string) => void;
};
type Target = {
id: string;
name: string;
os: string;
platform: 'linux' | 'windows' | null;
state: string;
current: boolean;
};
function target(row: RecordValue): Target {
return {
id: objectId(row, 'asset'), name: typeof row.hostname === 'string' && row.hostname ? row.hostname : objectId(row, 'asset'),
os: typeof row.os === 'string' ? row.os : 'OS unbekannt', platform: devicePlatform(row),
state: row.status === 'online' ? 'Online' : 'Offline', current: row.lifecycle === 'current'
id: objectId(row, 'asset'),
name: typeof row.hostname === 'string' && row.hostname ? row.hostname : objectId(row, 'asset'),
os: typeof row.os === 'string' ? row.os : 'OS unbekannt',
platform: devicePlatform(row),
state: row.status === 'online' ? 'Online' : 'Offline',
current: row.lifecycle === 'current'
};
}
function emptyScript(interpreter: Interpreter): Script {
@@ -30,9 +71,12 @@ function resumeTicket(key: string): Ticket | null {
const raw = sessionStorage.getItem(key);
if (!raw) return null;
data = JSON.parse(raw);
} catch { return null; }
} catch {
return null;
}
if (!data || !uuid.test(data.id) || !/^[a-f0-9]{64}$/.test(data.hash) || typeof data.attempted !== 'boolean') {
sessionStorage.removeItem(key); return null;
sessionStorage.removeItem(key);
return null;
}
return data;
}
@@ -42,18 +86,35 @@ async function verifiedScriptOrder(value: unknown, tenantId: string, principal:
await verifyScriptPlan(plan);
const payload = record(plan.plan_payload);
const jobs = scriptPlanJobs(plan);
if (payload.tenant_id !== tenantId || payload.principal !== principal || !Array.isArray(payload.jobs) ||
!jobs.length || jobs.length !== payload.jobs.length) throw Error('Dieser Skriptplan gehört nicht zu diesem Kunden und Antragsteller.');
return {plan, jobs, reason: String(payload.reason), maxParallel: Number(payload.max_parallel), halt: Number(payload.halt_after_failures)};
if (
payload.tenant_id !== tenantId ||
payload.principal !== principal ||
!Array.isArray(payload.jobs) ||
!jobs.length ||
jobs.length !== payload.jobs.length
)
throw Error('Dieser Skriptplan gehört nicht zu diesem Kunden und Antragsteller.');
return {
plan,
jobs,
reason: String(payload.reason),
maxParallel: Number(payload.max_parallel),
halt: Number(payload.halt_after_failures)
};
}
type Review = Awaited<ReturnType<typeof verifiedScriptOrder>>;
function blockers(review: Review) {
return [...approvalBlockers(review.plan), ...powerShellApprovalBlockers(review.plan), ...scriptApprovalBlockers(review.plan)];
return [
...approvalBlockers(review.plan),
...powerShellApprovalBlockers(review.plan),
...scriptApprovalBlockers(review.plan)
];
}
function issueMessage(err: unknown) {
if (err instanceof ApiError) {
if (err.status === 403) return 'Für diese Aktion oder die angeforderten Ausführungsrechte fehlt die Berechtigung.';
if (err.code === 'SCRIPT_VARIANT_UNAVAILABLE' || err.code.includes('CAPABILITY')) return 'Mindestens ein Zielgerät unterstützt die ausgewählte Ausführung noch nicht. ' + err.code;
if (err.code === 'SCRIPT_VARIANT_UNAVAILABLE' || err.code.includes('CAPABILITY'))
return 'Mindestens ein Zielgerät unterstützt die ausgewählte Ausführung noch nicht. ' + err.code;
}
return errorText(err);
}
@@ -86,221 +147,675 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, cu
const [error, setError] = useState<string | null>(null);
const lock = useRef(false);
const mounted = useRef(true);
useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const canPlan = ['inventory:read','operations:read','operations:plan','scripts:execute','operations:submit'].every(p => allowed(auth, p));
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const canPlan = [
'inventory:read',
'operations:read',
'operations:plan',
'scripts:execute',
'operations:submit'
].every((p) => allowed(auth, p));
const devices = useResource(async signal => {
if (!canPlan || ticket || step !== 1) return null;
const params = new URLSearchParams({limit:'40',view:'current'});
if (query.trim()) params.set('q',query.trim());
if (cursor) params.set('cursor',cursor);
const batch = page(await request(path('/devices?' + params), {signal}));
return {items: batch.items.map(target), next: batch.next_cursor};
}, [tenantId, canPlan, query, cursor, step, !!ticket]);
const review = useResource(async signal => {
if (!ticket) return null;
const checked = await verifiedScriptOrder(await request(path('/operation-plans/' + ticket.id), {signal}), tenantId, auth.principal.id);
if (checked.plan.plan_hash !== ticket.hash || objectId(checked.plan,'plan') !== ticket.id) throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
return checked;
}, [tenantId, ticket?.id, ticket?.hash, auth.principal.id]);
const missingIds = (review.data?.jobs.map(job => job.assetId) ?? initialAssetIds).filter(id => !known[id]);
const restored = useResource(async signal => {
if (!canPlan) return [];
const ids = missingIds;
const results: Target[] = [];
for (let i = 0; i < ids.length; i += 8) {
const chunk = await Promise.all(ids.slice(i, i + 8).map(async id => {
try { return target(record(await request(path('/devices/' + encodeURIComponent(id)), {signal}))); }
catch (err) { if (err instanceof ApiError && err.status === 404) return null; throw err; }
}));
for (const item of chunk) if (item) results.push(item);
}
return results;
}, [tenantId, canPlan, missingIds.join('/')]);
const directory = new Map([...restored.data ?? [], ...Object.values(known), ...devices.data?.items ?? []].map(d => [d.id, d]));
const targets = selected.map(id => directory.get(id));
const hasLinux = targets.some(d => d?.platform === 'linux');
const hasWindows = targets.some(d => d?.platform === 'windows');
const scripts = useResource(signal => canPlan && step === 2 && !ticket ? loadRevisions(tenantId, signal) : Promise.resolve([]), [tenantId, canPlan, step, !!ticket]);
const revision = scripts.data?.find(r => r.revision_id === revisionId);
const devices = useResource(
async (signal) => {
if (!canPlan || ticket || step !== 1) return null;
const params = new URLSearchParams({ limit: '40', view: 'current' });
if (query.trim()) params.set('q', query.trim());
if (cursor) params.set('cursor', cursor);
const batch = page(await request(path('/devices?' + params), { signal }));
return { items: batch.items.map(target), next: batch.next_cursor };
},
[tenantId, canPlan, query, cursor, step, !!ticket]
);
const review = useResource(
async (signal) => {
if (!ticket) return null;
const checked = await verifiedScriptOrder(
await request(path('/operation-plans/' + ticket.id), { signal }),
tenantId,
auth.principal.id
);
if (checked.plan.plan_hash !== ticket.hash || objectId(checked.plan, 'plan') !== ticket.id)
throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
return checked;
},
[tenantId, ticket?.id, ticket?.hash, auth.principal.id]
);
const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]);
const restored = useResource(
async (signal) => {
if (!canPlan) return [];
const ids = missingIds;
const results: Target[] = [];
for (let i = 0; i < ids.length; i += 8) {
const chunk = await Promise.all(
ids.slice(i, i + 8).map(async (id) => {
try {
return target(record(await request(path('/devices/' + encodeURIComponent(id)), { signal })));
} catch (err) {
if (err instanceof ApiError && err.status === 404) return null;
throw err;
}
})
);
for (const item of chunk) if (item) results.push(item);
}
return results;
},
[tenantId, canPlan, missingIds.join('/')]
);
const directory = new Map(
[...(restored.data ?? []), ...Object.values(known), ...(devices.data?.items ?? [])].map((d) => [d.id, d])
);
const targets = selected.map((id) => directory.get(id));
const hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows');
const scripts = useResource(
(signal) => (canPlan && step === 2 && !ticket ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket]
);
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
const issues: string[] = [];
if (targets.some(d => !d?.current)) issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter(d => d && !d.platform);
if (unidentified.length) issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map(d => d?.name).join(', '));
if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter((d) => d && !d.platform);
if (unidentified.length)
issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map((d) => d?.name).join(', '));
if (mode === 'library' && revision) {
const incompatible = targets.filter(d => d?.platform && d.platform !== scriptPlatform(revision.interpreter));
if (incompatible.length) issues.push(`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map(d => d?.name).join(', ')}.`);
const incompatible = targets.filter((d) => d?.platform && d.platform !== scriptPlatform(revision.interpreter));
if (incompatible.length)
issues.push(
`Dieses Skript unterstützt ${interpreterNames[revision.interpreter]}. Inkompatible Geräte: ${incompatible.map((d) => d?.name).join(', ')}.`
);
const identity = revision.execution_identity;
if (identity !== 'agent_service' && !allowed(auth, identity + ':execute')) issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
if (identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
}
if (mode === 'once' && hasLinux && hasWindows && (linux.execution_identity !== 'agent_service' || windows.execution_identity !== 'agent_service')) issues.push('Die ausgewählten Plattformen benötigen unterschiedliche Rechte. Verwenden Sie das gemeinsame Agent-Dienstkonto oder planen Sie getrennte Aufträge.');
if (
mode === 'once' &&
hasLinux &&
hasWindows &&
(linux.execution_identity !== 'agent_service' || windows.execution_identity !== 'agent_service')
)
issues.push(
'Die ausgewählten Plattformen benötigen unterschiedliche Rechte. Verwenden Sie das gemeinsame Agent-Dienstkonto oder planen Sie getrennte Aufträge.'
);
const existing = review.data?.plan.operation_id;
function saveTicket(next: Ticket | null) {
if (next) sessionStorage.setItem(key, JSON.stringify(next));
else sessionStorage.removeItem(key);
if (mounted.current) setTicket(next);
}
function submitted(id: string) { saveTicket(null); if (mounted.current) onSubmitted(id); }
function toggleTarget(d: Target) {
setKnown(old => ({...old,[d.id]:d}));
setSelected(old => old.includes(d.id) ? old.filter(id => id !== d.id) : [...old, d.id]);
function submitted(id: string) {
saveTicket(null);
if (mounted.current) onSubmitted(id);
}
const windowUpdate = mode === 'library' && revision?.script_sha256 === windowsUpdateScriptHash && revision.execution_identity === 'system';
const identity = mode === 'library' ? revision?.execution_identity : (hasWindows ? windows : linux).execution_identity;
const maxRuntime = windowUpdate ? 3600 : identity === 'system' ? 120 : identity === 'root' && (mode === 'library' || fullRoot) ? 300 : 3600;
function toggleTarget(d: Target) {
setKnown((old) => ({ ...old, [d.id]: d }));
setSelected((old) => (old.includes(d.id) ? old.filter((id) => id !== d.id) : [...old, d.id]));
}
const windowUpdate =
mode === 'library' &&
revision?.script_sha256 === windowsUpdateScriptHash &&
revision.execution_identity === 'system';
const identity =
mode === 'library' ? revision?.execution_identity : (hasWindows ? windows : linux).execution_identity;
const maxRuntime = windowUpdate
? 3600
: identity === 'system'
? 120
: identity === 'root' && (mode === 'library' || fullRoot)
? 300
: 3600;
async function prepare(e: FormEvent) {
e.preventDefault();
if (lock.current || !canPlan || issues.length || !selected.length) return;
lock.current = true; setBusy(true); setError(null);
lock.current = true;
setBusy(true);
setError(null);
try {
const schedule = {not_before:new Date(start).toISOString(),start_before:new Date(end).toISOString()};
if (Date.parse(schedule.start_before) <= Math.max(Date.now(),Date.parse(schedule.not_before))) throw Error('Die Startfrist muss nach dem frühesten Start und in der Zukunft liegen.');
const rollout = {max_parallel:parallel,halt_after_failures:halt};
const bound = {targets:{asset_ids:selected},rollout,reason:reason.trim()};
const schedule = { not_before: new Date(start).toISOString(), start_before: new Date(end).toISOString() };
if (Date.parse(schedule.start_before) <= Math.max(Date.now(), Date.parse(schedule.not_before)))
throw Error('Die Startfrist muss nach dem frühesten Start und in der Zukunft liegen.');
const rollout = { max_parallel: parallel, halt_after_failures: halt };
const bound = { targets: { asset_ids: selected }, rollout, reason: reason.trim() };
let raw: unknown;
if (mode === 'library') {
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
raw = await request(path('/script-revisions/' + revision.revision_id + '/plan'), {
csrf: auth.csrf_token, body:{...bound,schedule,max_runtime_seconds:runtime,max_output_bytes:limit}
csrf: auth.csrf_token,
body: { ...bound, schedule, max_runtime_seconds: runtime, max_output_bytes: limit }
});
} else {
const variants = [hasLinux ? linux : null, hasWindows ? windows : null].filter((s): s is Script => !!s).map(s => ({
os_family:scriptPlatform(s.interpreter),interpreter:s.interpreter,encoding:'utf-8',script_utf8:s.script_utf8,
...(s.interpreter === 'powershell' ? {windows_execution_profile:windowsPowerShellRemoteSignedProfile} : {})
}));
const parameters = {variants,execution_identity:identity,arguments:[],expected_stdout:expectedStdout(expected,expectedFormat),
timeout_seconds:runtime,max_output_bytes:limit,
...(identity === 'system' || (identity === 'root' && fullRoot) ? {privileged_script_profile:fullMaintenanceScriptProfile} : {})};
const input: PlanInput = {...bound,schedule:{...schedule,offline_policy:'wait_until_deadline'},tenant_id:tenantId,action:'run_script',parameters};
validateInput(input); await validateSensitiveInput(input, auth);
raw = await request(path('/operation-plans'), {csrf:auth.csrf_token,body:input});
const variants = [hasLinux ? linux : null, hasWindows ? windows : null]
.filter((s): s is Script => !!s)
.map((s) => ({
os_family: scriptPlatform(s.interpreter),
interpreter: s.interpreter,
encoding: 'utf-8',
script_utf8: s.script_utf8,
...(s.interpreter === 'powershell'
? { windows_execution_profile: windowsPowerShellRemoteSignedProfile }
: {})
}));
const parameters = {
variants,
execution_identity: identity,
arguments: [],
expected_stdout: expectedStdout(expected, expectedFormat),
timeout_seconds: runtime,
max_output_bytes: limit,
...(identity === 'system' || (identity === 'root' && fullRoot)
? { privileged_script_profile: fullMaintenanceScriptProfile }
: {})
};
const input: PlanInput = {
...bound,
schedule: { ...schedule, offline_policy: 'wait_until_deadline' },
tenant_id: tenantId,
action: 'run_script',
parameters
};
validateInput(input);
await validateSensitiveInput(input, auth);
raw = await request(path('/operation-plans'), { csrf: auth.csrf_token, body: input });
}
if (!mounted.current) return;
const checked = await verifiedScriptOrder(raw,tenantId,auth.principal.id);
const mismatchedJob = checked.jobs.some(j => {
const script = mode === 'library' ? revision : (directory.get(j.assetId)?.platform === 'windows' ? windows : linux);
return !selected.includes(j.assetId) || j.revision?.id !== (mode === 'library' ? revisionId : undefined)
|| j.script !== script?.script_utf8 || j.identity !== script.execution_identity || j.interpreter !== script.interpreter
|| j.runtimeSeconds !== runtime || j.outputBytes !== limit || !!j.arguments.length
|| j.expectedStdout !== (mode === 'library' ? null : expectedStdout(expected, expectedFormat))
|| Date.parse(j.notBefore) !== Date.parse(schedule.not_before) || Date.parse(j.startBefore) !== Date.parse(schedule.start_before);
const checked = await verifiedScriptOrder(raw, tenantId, auth.principal.id);
const mismatchedJob = checked.jobs.some((j) => {
const script =
mode === 'library' ? revision : directory.get(j.assetId)?.platform === 'windows' ? windows : linux;
return (
!selected.includes(j.assetId) ||
j.revision?.id !== (mode === 'library' ? revisionId : undefined) ||
j.script !== script?.script_utf8 ||
j.identity !== script.execution_identity ||
j.interpreter !== script.interpreter ||
j.runtimeSeconds !== runtime ||
j.outputBytes !== limit ||
!!j.arguments.length ||
j.expectedStdout !== (mode === 'library' ? null : expectedStdout(expected, expectedFormat)) ||
Date.parse(j.notBefore) !== Date.parse(schedule.not_before) ||
Date.parse(j.startBefore) !== Date.parse(schedule.start_before)
);
});
if (mismatchedJob || checked.jobs.length !== selected.length || checked.reason !== bound.reason ||
checked.maxParallel !== parallel || checked.halt !== halt) throw Error('Der erstellte Plan weicht von diesem Entwurf ab.');
const problems = blockers(checked); if (problems.length) throw Error(problems.join(' · '));
if (mounted.current) saveTicket({id:objectId(checked.plan,'plan'),hash:String(checked.plan.plan_hash),attempted:false});
} catch (e) { if (mounted.current) setError(issueMessage(e)); }
finally { lock.current = false; if (mounted.current) setBusy(false); }
if (
mismatchedJob ||
checked.jobs.length !== selected.length ||
checked.reason !== bound.reason ||
checked.maxParallel !== parallel ||
checked.halt !== halt
)
throw Error('Der erstellte Plan weicht von diesem Entwurf ab.');
const problems = blockers(checked);
if (problems.length) throw Error(problems.join(' · '));
if (mounted.current)
saveTicket({ id: objectId(checked.plan, 'plan'), hash: String(checked.plan.plan_hash), attempted: false });
} catch (e) {
if (mounted.current) setError(issueMessage(e));
} finally {
lock.current = false;
if (mounted.current) setBusy(false);
}
}
async function submit() {
if (!ticket || !review.data || !canPlan || lock.current) return;
lock.current = true; setBusy(true); setError(null);
lock.current = true;
setBusy(true);
setError(null);
try {
const fresh = await verifiedScriptOrder(await request(path('/operation-plans/' + ticket.id)),tenantId,auth.principal.id);
if (fresh.plan.plan_hash !== ticket.hash || fresh.plan.plan_id !== ticket.id) throw Error('Der geprüfte Auftrag hat sich geändert.');
if (typeof fresh.plan.operation_id === 'string') { submitted(fresh.plan.operation_id); return; }
const problems = blockers(fresh); if (problems.length) throw Error(problems.join(' · '));
const fresh = await verifiedScriptOrder(
await request(path('/operation-plans/' + ticket.id)),
tenantId,
auth.principal.id
);
if (fresh.plan.plan_hash !== ticket.hash || fresh.plan.plan_id !== ticket.id)
throw Error('Der geprüfte Auftrag hat sich geändert.');
if (typeof fresh.plan.operation_id === 'string') {
submitted(fresh.plan.operation_id);
return;
}
const problems = blockers(fresh);
if (problems.length) throw Error(problems.join(' · '));
if (!mounted.current) return;
saveTicket({...ticket,attempted:true});
const operation = record(await request(path('/operation-plans/' + ticket.id + '/submit'), {
csrf:auth.csrf_token,body:{idempotency_key:ticket.id}
}));
if (operation.plan_id !== ticket.id || operation.plan_hash !== ticket.hash) throw Error('Die Antwort gehört nicht zum eingereichten Plan.');
if (mounted.current) submitted(objectId(operation,'operation'));
saveTicket({ ...ticket, attempted: true });
const operation = record(
await request(path('/operation-plans/' + ticket.id + '/submit'), {
csrf: auth.csrf_token,
body: { idempotency_key: ticket.id }
})
);
if (operation.plan_id !== ticket.id || operation.plan_hash !== ticket.hash)
throw Error('Die Antwort gehört nicht zum eingereichten Plan.');
if (mounted.current) submitted(objectId(operation, 'operation'));
} catch (err) {
if (mounted.current) {
if (!ticket.attempted && err instanceof ApiError && err.status >= 400 && err.status < 500) saveTicket({...ticket, attempted:false});
setError(issueMessage(err)); review.reload();
if (!ticket.attempted && err instanceof ApiError && err.status >= 400 && err.status < 500)
saveTicket({ ...ticket, attempted: false });
setError(issueMessage(err));
review.reload();
}
} finally {
lock.current = false;
if (mounted.current) setBusy(false);
}
finally {lock.current = false; if (mounted.current) setBusy(false);}
}
const stepNumber = ticket ? 3 : step;
return <>
<div className="page-title"><h1>Neuer Auftrag</h1></div>
<ol className="order-progress" aria-label="Auftragsschritte">{['Geräte','Skript','Zusammenfassung'].map((name,i) => <li key={name} aria-current={stepNumber === i+1 ? 'step' : undefined}>{i+1}. {name}</li>)}</ol>
<ErrorBox error={error ?? review.error ?? restored.error ?? devices.error ?? scripts.error}/>
{!canPlan ? <section><p>Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von Skriptaufträgen.</p></section> :
ticket ? <section aria-label="Auftrag prüfen"><h2>Zusammenfassung</h2>
{review.data ? <>
<h3>{review.data.jobs[0]?.revision ? `${review.data.jobs[0].revision.name} · Version ${review.data.jobs[0].revision.version}` : 'Einmaliges Skript'}</h3>
<p>{review.data.reason}</p>
<dl className="facts"><div><dt>Kunde</dt><dd>{customerName ?? auth.tenants.find(t => t.tenant_id === tenantId)?.name ?? tenantId}</dd></div>
<div><dt>Ausführen als</dt><dd>{identityNames[review.data.jobs[0]!.identity as Identity]}</dd></div>
<div><dt>Frühester Start</dt><dd>{new Date(review.data.jobs[0]!.notBefore).toLocaleString('de-DE')}</dd></div>
<div><dt>Startfrist</dt><dd>{new Date(review.data.jobs[0]!.startBefore).toLocaleString('de-DE')}</dd></div>
<div><dt>Maximale Laufzeit pro Gerät</dt><dd>{review.data.jobs[0]!.runtimeSeconds} Sekunden</dd></div>
<div><dt>Parallelität</dt><dd>{review.data.maxParallel} gleichzeitig · Stopp nach {review.data.halt} Fehlern</dd></div>
</dl>
<h3>Zielgeräte ({review.data.jobs.length})</h3>
<ul>{review.data.jobs.map(j => <li key={j.assetId}>{directory.get(j.assetId)?.name ?? j.assetId}</li>)}</ul>
{review.data.jobs[0]?.identity !== 'agent_service' && <p className="warning">Dieser Auftrag erfordert erhöhte Rechte auf den Zielgeräten.</p>}
<details><summary>Gebundenen Skriptinhalt ansehen</summary>
{[...new Map(review.data.jobs.map(job => [job.scriptHash,job])).values()].map(job => <div key={job.scriptHash}><h4>{interpreterNames[job.interpreter as Interpreter]}</h4><pre className="script-body">{job.script}</pre></div>)}
</details>
{typeof existing === 'string' ? <div className="work-actions"><button className="primary" onClick={() => submitted(existing)}>Eingereichten Auftrag öffnen</button></div> :
<><ErrorBox error={blockers(review.data).join(' · ') || null}/><div className="work-actions">
{(!ticket.attempted || Date.parse(String(review.data.plan.expires_at)) <= Date.now()) && <button disabled={busy} onClick={() => {saveTicket(null);setError(null);}}>Zurück zum Entwurf</button>}
<button className="primary" disabled={busy || !!blockers(review.data).length} onClick={() => void submit()}>{busy ? 'Wird eingereicht …' : 'Zur Genehmigung einreichen'}</button>
</div></>}
</> : review.error ? <div className="work-actions"><button onClick={review.reload}>Erneut prüfen</button>
{!ticket.attempted && <button onClick={() => saveTicket(null)}>Entwurf verwerfen</button>}</div> : <p role="status">Gespeicherter Plan wird geprüft …</p>}
</section> :
step === 1 ? <section aria-label="Zielgeräte"><h2>Geräte auswählen</h2>
<label>Hostname suchen<input type="search" value={query} onChange={e => {setQuery(e.target.value);setCursor(null);setPrior([]);}}/></label>
{!devices.data && !devices.error && <p role="status">Geräte werden geladen …</p>}
{devices.data && <><ul className="order-targets">{devices.data.items.map(d => <li key={d.id}><label>
<input type="checkbox" checked={selected.includes(d.id)} onChange={() => toggleTarget(d)}/>
<strong>{d.name}</strong><small>{d.os} · {d.state}</small>
</label></li>)}</ul>{!devices.data.items.length && <p>{query ? 'Kein Gerät passt zur Suche.' : 'Keine Geräte im Bestand dieses Kunden.'}</p>}
{(prior.length > 0 || devices.data.next) && <div><button disabled={!prior.length} onClick={() => {setCursor(prior.at(-1) ?? null);setPrior(prior.slice(0,-1));}}>Vorherige Geräte</button>
<button disabled={!devices.data.next} onClick={() => {setPrior([...prior,cursor]);setCursor(devices.data!.next);}}>Weitere Geräte</button></div>}</>}
{selected.filter(id => !devices.data?.items.some(d => d.id === id)).map(id => <p key={id}>{directory.get(id)?.name ?? id} <button className="link" onClick={() => setSelected(selected.filter(s => s !== id))}>Aus Auswahl entfernen</button></p>)}
<div className="work-actions"><span>{selected.length} ausgewählt</span><button className="primary" disabled={!selected.length || selected.length > 100 || targets.some(d => !d?.current || !d.platform)} onClick={() => {setStep(2);setError(null);}}>Weiter zum Skript</button></div>
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
{restored.data && issues.length > 0 && <ErrorBox error={issues.join(' ')}/>}
</section> :
<section><h2>Skript auswählen</h2><form onSubmit={prepare}><fieldset disabled={busy} className="work-form">
<div className="order-source"><label><input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')}/>Aus der Bibliothek</label>
<label><input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')}/>Einmaliges Skript</label></div>
{mode === 'library' ? <>
<label>Bibliotheksskript<select required value={revision?.name ?? ''} onChange={e => {const next = heads.find(h => h.name === e.target.value);choose(next?.revision_id ?? '');setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);}}>
<option value="">Skript wählen</option>{heads.map(h => <option key={h.name} value={h.name}>{h.name}</option>)}
</select></label>
{scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
{revision && <><label>Version<select value={revisionId} onChange={e => {choose(e.target.value);setRuntime(scripts.data?.find(r => r.revision_id === e.target.value)?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);}}>
{scripts.data?.filter(r => r.name === revision.name).map(r => <option key={r.revision_id} value={r.revision_id}>Version {r.version}</option>)}
</select></label><p>{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}</p>
{revision.execution_identity !== 'agent_service' && <p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>}</>}
</> : <>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false}/>}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows/>}
{linux.execution_identity === 'root' && hasLinux && <label><input type="checkbox" checked={fullRoot} onChange={e=>setFullRoot(e.target.checked)}/>Vollwartung als root anfordern</label>}
</>}
<label>Begründung<input required maxLength={1024} value={reason} onChange={e => setReason(e.target.value)}/></label>
<details><summary>Zeitfenster und Ausführungsoptionen</summary><div className="work-fields">
<label>Frühester Start<input required type="datetime-local" value={start} onChange={e => setStart(e.target.value)}/></label>
<label>Startfrist<input required type="datetime-local" value={end} onChange={e => setEnd(e.target.value)}/></label>
<label>Laufzeit je Gerät in Sekunden<input required type="number" min={1} max={maxRuntime} value={runtime} onChange={e => setRuntime(Number(e.target.value))}/></label>
<label>Ausgabelimit in Byte<input required type="number" min={1} max={identity === 'agent_service' ? 262144 : 65536} value={limit} onChange={e => setLimit(Number(e.target.value))}/></label>
<label>Geräte gleichzeitig<input required type="number" min={1} max={10} value={parallel} onChange={e => setParallel(Number(e.target.value))}/></label>
<label>Stopp nach Fehlern<input required type="number" min={1} value={halt} onChange={e => setHalt(Number(e.target.value))}/></label>
return (
<>
<div className="page-title">
<h1>Neuer Auftrag</h1>
</div>
{mode === 'once' && <><label>Erwartete Standardausgabe (optional)<textarea value={expected} onChange={e => setExpected(e.target.value)}/></label>
<label>Format<select value={expectedFormat} onChange={e => setExpectedFormat(e.target.value)}><option value="text">Text</option><option value="json">JSON-Zeichenfolge</option></select></label></>}
</details>
<ErrorBox error={issues.join(' ') || null}/>
<div className="work-actions"><button type="button" onClick={() => {setStep(1);setError(null);}}>Zurück zu Geräten</button>
<button className="primary" type="submit" disabled={!!issues.length || (mode === 'library' && !revision)}>{busy ? 'Plan wird geprüft …' : 'Zusammenfassung ansehen'}</button></div>
</fieldset></form></section>}
</>;
<ol className="order-progress" aria-label="Auftragsschritte">
{['Geräte', 'Skript', 'Zusammenfassung'].map((name, i) => (
<li key={name} aria-current={stepNumber === i + 1 ? 'step' : undefined}>
{i + 1}. {name}
</li>
))}
</ol>
<ErrorBox error={error ?? review.error ?? restored.error ?? devices.error ?? scripts.error} />
{!canPlan ? (
<section>
<p>
Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von
Skriptaufträgen.
</p>
</section>
) : ticket ? (
<section aria-label="Auftrag prüfen">
<h2>Zusammenfassung</h2>
{review.data ? (
<>
<h3>
{review.data.jobs[0]?.revision
? `${review.data.jobs[0].revision.name} · Version ${review.data.jobs[0].revision.version}`
: 'Einmaliges Skript'}
</h3>
<p>{review.data.reason}</p>
<dl className="facts">
<div>
<dt>Kunde</dt>
<dd>{customerName ?? auth.tenants.find((t) => t.tenant_id === tenantId)?.name ?? tenantId}</dd>
</div>
<div>
<dt>Ausführen als</dt>
<dd>{identityNames[review.data.jobs[0]!.identity as Identity]}</dd>
</div>
<div>
<dt>Frühester Start</dt>
<dd>{new Date(review.data.jobs[0]!.notBefore).toLocaleString('de-DE')}</dd>
</div>
<div>
<dt>Startfrist</dt>
<dd>{new Date(review.data.jobs[0]!.startBefore).toLocaleString('de-DE')}</dd>
</div>
<div>
<dt>Maximale Laufzeit pro Gerät</dt>
<dd>{review.data.jobs[0]!.runtimeSeconds} Sekunden</dd>
</div>
<div>
<dt>Parallelität</dt>
<dd>
{review.data.maxParallel} gleichzeitig · Stopp nach {review.data.halt} Fehlern
</dd>
</div>
</dl>
<h3>Zielgeräte ({review.data.jobs.length})</h3>
<ul>
{review.data.jobs.map((j) => (
<li key={j.assetId}>{directory.get(j.assetId)?.name ?? j.assetId}</li>
))}
</ul>
{review.data.jobs[0]?.identity !== 'agent_service' && (
<p className="warning">Dieser Auftrag erfordert erhöhte Rechte auf den Zielgeräten.</p>
)}
<details>
<summary>Gebundenen Skriptinhalt ansehen</summary>
{[...new Map(review.data.jobs.map((job) => [job.scriptHash, job])).values()].map((job) => (
<div key={job.scriptHash}>
<h4>{interpreterNames[job.interpreter as Interpreter]}</h4>
<pre className="script-body">{job.script}</pre>
</div>
))}
</details>
{typeof existing === 'string' ? (
<div className="work-actions">
<button className="primary" onClick={() => submitted(existing)}>
Eingereichten Auftrag öffnen
</button>
</div>
) : (
<>
<ErrorBox error={blockers(review.data).join(' · ') || null} />
<div className="work-actions">
{(!ticket.attempted || Date.parse(String(review.data.plan.expires_at)) <= Date.now()) && (
<button
disabled={busy}
onClick={() => {
saveTicket(null);
setError(null);
}}
>
Zurück zum Entwurf
</button>
)}
<button
className="primary"
disabled={busy || !!blockers(review.data).length}
onClick={() => void submit()}
>
{busy ? 'Wird eingereicht …' : 'Zur Genehmigung einreichen'}
</button>
</div>
</>
)}
</>
) : review.error ? (
<div className="work-actions">
<button onClick={review.reload}>Erneut prüfen</button>
{!ticket.attempted && <button onClick={() => saveTicket(null)}>Entwurf verwerfen</button>}
</div>
) : (
<p role="status">Gespeicherter Plan wird geprüft …</p>
)}
</section>
) : step === 1 ? (
<section aria-label="Zielgeräte">
<h2>Geräte auswählen</h2>
<label>
Hostname suchen
<input
type="search"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setCursor(null);
setPrior([]);
}}
/>
</label>
{!devices.data && !devices.error && <p role="status">Geräte werden geladen …</p>}
{devices.data && (
<>
<ul className="order-targets">
{devices.data.items.map((d) => (
<li key={d.id}>
<label>
<input type="checkbox" checked={selected.includes(d.id)} onChange={() => toggleTarget(d)} />
<strong>{d.name}</strong>
<small>
{d.os} · {d.state}
</small>
</label>
</li>
))}
</ul>
{!devices.data.items.length && (
<p>{query ? 'Kein Gerät passt zur Suche.' : 'Keine Geräte im Bestand dieses Kunden.'}</p>
)}
{(prior.length > 0 || devices.data.next) && (
<div>
<button
disabled={!prior.length}
onClick={() => {
setCursor(prior.at(-1) ?? null);
setPrior(prior.slice(0, -1));
}}
>
Vorherige Geräte
</button>
<button
disabled={!devices.data.next}
onClick={() => {
setPrior([...prior, cursor]);
setCursor(devices.data!.next);
}}
>
Weitere Geräte
</button>
</div>
)}
</>
)}
{selected
.filter((id) => !devices.data?.items.some((d) => d.id === id))
.map((id) => (
<p key={id}>
{directory.get(id)?.name ?? id}{' '}
<button className="link" onClick={() => setSelected(selected.filter((s) => s !== id))}>
Aus Auswahl entfernen
</button>
</p>
))}
<div className="work-actions">
<span>{selected.length} ausgewählt</span>
<button
className="primary"
disabled={!selected.length || selected.length > 100 || targets.some((d) => !d?.current || !d.platform)}
onClick={() => {
setStep(2);
setError(null);
}}
>
Weiter zum Skript
</button>
</div>
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
{restored.data && issues.length > 0 && <ErrorBox error={issues.join(' ')} />}
</section>
) : (
<section>
<h2>Skript auswählen</h2>
<form onSubmit={prepare}>
<fieldset disabled={busy} className="work-form">
<div className="order-source">
<label>
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
Aus der Bibliothek
</label>
<label>
<input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')} />
Einmaliges Skript
</label>
</div>
{mode === 'library' ? (
<>
<label>
Bibliotheksskript
<select
required
value={revision?.name ?? ''}
onChange={(e) => {
const next = heads.find((h) => h.name === e.target.value);
choose(next?.revision_id ?? '');
setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);
}}
>
<option value="">Skript wählen</option>
{heads.map((h) => (
<option key={h.name} value={h.name}>
{h.name}
</option>
))}
</select>
</label>
{scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
{revision && (
<>
<label>
Version
<select
value={revisionId}
onChange={(e) => {
choose(e.target.value);
setRuntime(
scripts.data?.find((r) => r.revision_id === e.target.value)?.script_sha256 ===
windowsUpdateScriptHash
? 3600
: 120
);
}}
>
{scripts.data
?.filter((r) => r.name === revision.name)
.map((r) => (
<option key={r.revision_id} value={r.revision_id}>
Version {r.version}
</option>
))}
</select>
</label>
<p>
{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}
</p>
{revision.execution_identity !== 'agent_service' && (
<p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>
)}
</>
)}
</>
) : (
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
{linux.execution_identity === 'root' && hasLinux && (
<label>
<input type="checkbox" checked={fullRoot} onChange={(e) => setFullRoot(e.target.checked)} />
Vollwartung als root anfordern
</label>
)}
</>
)}
<label>
Begründung
<input required maxLength={1024} value={reason} onChange={(e) => setReason(e.target.value)} />
</label>
<details>
<summary>Zeitfenster und Ausführungsoptionen</summary>
<div className="work-fields">
<label>
Frühester Start
<input required type="datetime-local" value={start} onChange={(e) => setStart(e.target.value)} />
</label>
<label>
Startfrist
<input required type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} />
</label>
<label>
Laufzeit je Gerät in Sekunden
<input
required
type="number"
min={1}
max={maxRuntime}
value={runtime}
onChange={(e) => setRuntime(Number(e.target.value))}
/>
</label>
<label>
Ausgabelimit in Byte
<input
required
type="number"
min={1}
max={identity === 'agent_service' ? 262144 : 65536}
value={limit}
onChange={(e) => setLimit(Number(e.target.value))}
/>
</label>
<label>
Geräte gleichzeitig
<input
required
type="number"
min={1}
max={10}
value={parallel}
onChange={(e) => setParallel(Number(e.target.value))}
/>
</label>
<label>
Stopp nach Fehlern
<input
required
type="number"
min={1}
value={halt}
onChange={(e) => setHalt(Number(e.target.value))}
/>
</label>
</div>
{mode === 'once' && (
<>
<label>
Erwartete Standardausgabe (optional)
<textarea value={expected} onChange={(e) => setExpected(e.target.value)} />
</label>
<label>
Format
<select value={expectedFormat} onChange={(e) => setExpectedFormat(e.target.value)}>
<option value="text">Text</option>
<option value="json">JSON-Zeichenfolge</option>
</select>
</label>
</>
)}
</details>
<ErrorBox error={issues.join(' ') || null} />
<div className="work-actions">
<button
type="button"
onClick={() => {
setStep(1);
setError(null);
}}
>
Zurück zu Geräten
</button>
<button
className="primary"
type="submit"
disabled={!!issues.length || (mode === 'library' && !revision)}
>
{busy ? 'Plan wird geprüft …' : 'Zusammenfassung ansehen'}
</button>
</div>
</fieldset>
</form>
</section>
)}
</>
);
}
function ScriptFieldsForPlatform({script,change,auth,windows}: {script: Script;change: (s: Script) => void;auth: Session;windows:boolean}) {
function ScriptFieldsForPlatform({
script,
change,
auth,
windows
}: {
script: Script;
change: (s: Script) => void;
auth: Session;
windows: boolean;
}) {
const ids: Identity[] = ['agent_service'];
const elevated = windows ? 'system' : 'root';
if (allowed(auth,elevated+':execute')) ids.push(elevated);
return <fieldset><legend>{windows ? 'Windows-Skript' : 'Linux-Skript'}</legend>
<ScriptFields script={script} change={change} ids={ids} interpreters={windows ? ['powershell'] : ['posix_sh','bash']}/>
</fieldset>;
if (allowed(auth, elevated + ':execute')) ids.push(elevated);
return (
<fieldset>
<legend>{windows ? 'Windows-Skript' : 'Linux-Skript'}</legend>
<ScriptFields
script={script}
change={change}
ids={ids}
interpreters={windows ? ['powershell'] : ['posix_sh', 'bash']}
/>
</fieldset>
);
}
+23 -9
View File
@@ -14,22 +14,36 @@ export interface Revision extends Script {
script_sha256: string;
}
export const interpreterNames: Record<Interpreter, string> = {
posix_sh: 'Linux · Shell', bash: 'Linux · Bash', powershell: 'Windows · PowerShell'
posix_sh: 'Linux · Shell',
bash: 'Linux · Bash',
powershell: 'Windows · PowerShell'
};
export const identityNames: Record<Identity, string> = {
agent_service: 'Agent-Dienstkonto', root: 'root', system: 'SYSTEM'
agent_service: 'Agent-Dienstkonto',
root: 'root',
system: 'SYSTEM'
};
export function parseRevision(value: unknown): Revision {
const row = record(value);
if ((row.interpreter !== 'posix_sh' && row.interpreter !== 'bash' && row.interpreter !== 'powershell') ||
(row.execution_identity !== 'agent_service' && row.execution_identity !== 'root' && row.execution_identity !== 'system') ||
typeof row.version !== 'number' || !Number.isSafeInteger(row.version) || row.version < 1) {
if (
(row.interpreter !== 'posix_sh' && row.interpreter !== 'bash' && row.interpreter !== 'powershell') ||
(row.execution_identity !== 'agent_service' &&
row.execution_identity !== 'root' &&
row.execution_identity !== 'system') ||
typeof row.version !== 'number' ||
!Number.isSafeInteger(row.version) ||
row.version < 1
) {
throw Error('Der Server meldet eine ungültige Skriptversion.');
}
return {
revision_id: objectId(row, 'revision'), name: text(row.name, 'Skriptname'), version: row.version,
interpreter: row.interpreter, execution_identity: row.execution_identity,
script_utf8: text(row.script_utf8, 'Skriptinhalt'), script_sha256: text(row.script_sha256, 'Prüfsumme')
revision_id: objectId(row, 'revision'),
name: text(row.name, 'Skriptname'),
version: row.version,
interpreter: row.interpreter,
execution_identity: row.execution_identity,
script_utf8: text(row.script_utf8, 'Skriptinhalt'),
script_sha256: text(row.script_sha256, 'Prüfsumme')
};
}
export async function loadRevisions(tenantId: string, signal: AbortSignal): Promise<Revision[]> {
@@ -37,7 +51,7 @@ export async function loadRevisions(tenantId: string, signal: AbortSignal): Prom
const cursors = new Set<string>();
let cursor: string | null = null;
do {
const params = new URLSearchParams({limit: '100'});
const params = new URLSearchParams({ limit: '100' });
if (cursor) params.set('cursor', cursor);
const batch = page(await request(tenantPath(tenantId, '/script-revisions?' + params), { signal }));
revisions.push(...batch.items.map(parseRevision));
+256 -62
View File
@@ -2,90 +2,284 @@ import { useState, type FormEvent } from 'react';
import { ApiError, request, tenantPath, type Session } from './api';
import { allowed } from './safety';
import { ErrorBox, errorText, useResource } from './resource';
import { identityNames, interpreterNames, latestRevisions, loadRevisions, parseRevision, type Identity, type Interpreter, type Revision, type Script } from './script-catalog';
import {
identityNames,
interpreterNames,
latestRevisions,
loadRevisions,
parseRevision,
type Identity,
type Interpreter,
type Revision,
type Script
} from './script-catalog';
import './script-workspace.css';
export function ScriptFields({ script, change, ids, interpreters }: {
script: Script; change: (next: Script) => void; ids: Identity[]; interpreters?: Interpreter[];
export function ScriptFields({
script,
change,
ids,
interpreters
}: {
script: Script;
change: (next: Script) => void;
ids: Identity[];
interpreters?: Interpreter[];
}) {
const possible = ids.filter(id => id === 'agent_service' || id === (script.interpreter === 'powershell' ? 'system' : 'root'));
return <>
<div className="work-fields"><label>Plattform und Interpreter
<select value={script.interpreter} onChange={e => change({...script, interpreter: e.target.value as Interpreter, execution_identity: 'agent_service'})}>
{Object.entries(interpreterNames).filter(([key]) => !interpreters || interpreters.includes(key as Interpreter)).map(([value, label]) => <option value={value} key={value}>{label}</option>)}
</select></label>
<label>Ausführen als<select value={script.execution_identity} onChange={e => change({...script, execution_identity: e.target.value as Identity})}>
{possible.map(id => <option key={id} value={id}>{identityNames[id]}</option>)}
</select></label>
</div>
{script.execution_identity !== 'agent_service' && <p className="warning">Dieses Skript fordert {identityNames[script.execution_identity]}-Rechte auf den Zielgeräten an.</p>}
<label>Skriptinhalt<textarea className="script-editor" spellCheck={false} required rows={10} value={script.script_utf8}
onChange={e => change({...script, script_utf8: e.target.value})}/></label>
{script.interpreter === 'powershell' && /[^\x00-\x7f]/.test(script.script_utf8) && !script.script_utf8.startsWith('\ufeff') &&
<p className="warning">Windows PowerShell 5.1 benötigt für diesen Text eine UTF-8-Signatur. <button type="button" className="link" onClick={() => change({...script, script_utf8: '\ufeff' + script.script_utf8})}>UTF-8-Signatur hinzufügen</button></p>}
</>;
const possible = ids.filter(
(id) => id === 'agent_service' || id === (script.interpreter === 'powershell' ? 'system' : 'root')
);
return (
<>
<div className="work-fields">
<label>
Plattform und Interpreter
<select
value={script.interpreter}
onChange={(e) =>
change({ ...script, interpreter: e.target.value as Interpreter, execution_identity: 'agent_service' })
}
>
{Object.entries(interpreterNames)
.filter(([key]) => !interpreters || interpreters.includes(key as Interpreter))
.map(([value, label]) => (
<option value={value} key={value}>
{label}
</option>
))}
</select>
</label>
<label>
Ausführen als
<select
value={script.execution_identity}
onChange={(e) => change({ ...script, execution_identity: e.target.value as Identity })}
>
{possible.map((id) => (
<option key={id} value={id}>
{identityNames[id]}
</option>
))}
</select>
</label>
</div>
{script.execution_identity !== 'agent_service' && (
<p className="warning">
Dieses Skript fordert {identityNames[script.execution_identity]}-Rechte auf den Zielgeräten an.
</p>
)}
<label>
Skriptinhalt
<textarea
className="script-editor"
spellCheck={false}
required
rows={10}
value={script.script_utf8}
onChange={(e) => change({ ...script, script_utf8: e.target.value })}
/>
</label>
{script.interpreter === 'powershell' &&
/[^\x00-\x7f]/.test(script.script_utf8) &&
!script.script_utf8.startsWith('\ufeff') && (
<p className="warning">
Windows PowerShell 5.1 benötigt für diesen Text eine UTF-8-Signatur.{' '}
<button
type="button"
className="link"
onClick={() => change({ ...script, script_utf8: '\ufeff' + script.script_utf8 })}
>
UTF-8-Signatur hinzufügen
</button>
</p>
)}
</>
);
}
export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Session }) {
const read = allowed(auth, 'operations:read');
const canPublish = allowed(auth, 'operations:plan') && allowed(auth, 'scripts:execute');
const library = useResource(signal => read ? loadRevisions(tenantId, signal) : Promise.resolve([]), [tenantId, read]);
const library = useResource(
(signal) => (read ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, read]
);
const [opened, open] = useState('');
const [draft, setDraft] = useState<Script | null>(null);
const [base, setBase] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState('');
const versions = (library.data ?? []).filter(item => item.name === opened);
const versions = (library.data ?? []).filter((item) => item.name === opened);
const latest = versions[0];
function edit(existing?: Revision) {
setBase(existing?.version ?? 0);
setDraft(existing ? { ...existing } : { name: '', interpreter: 'posix_sh', execution_identity: 'agent_service', script_utf8: '' });
setError(null); setNotice('');
setDraft(
existing
? { ...existing }
: { name: '', interpreter: 'posix_sh', execution_identity: 'agent_service', script_utf8: '' }
);
setError(null);
setNotice('');
}
async function publish(e: FormEvent) {
e.preventDefault();
if (!draft || busy) return;
setBusy(true); setError(null);
setBusy(true);
setError(null);
try {
const {name, interpreter, execution_identity, script_utf8} = draft;
const saved = parseRevision(await request(tenantPath(tenantId, '/script-revisions'), {
csrf: auth.csrf_token, body: {name: name.trim(), interpreter, execution_identity, script_utf8, expected_version: base}
}));
open(saved.name); setDraft(null); setNotice(`Version ${saved.version} veröffentlicht.`); library.reload();
const { name, interpreter, execution_identity, script_utf8 } = draft;
const saved = parseRevision(
await request(tenantPath(tenantId, '/script-revisions'), {
csrf: auth.csrf_token,
body: { name: name.trim(), interpreter, execution_identity, script_utf8, expected_version: base }
})
);
open(saved.name);
setDraft(null);
setNotice(`Version ${saved.version} veröffentlicht.`);
library.reload();
} catch (err) {
setError(err instanceof ApiError && err.code === 'SCRIPT_REVISION_CONFLICT'
? 'Unter diesem Namen gibt es bereits eine neuere Version. Öffnen Sie den aktuellen Stand vor dem Veröffentlichen.' : errorText(err));
setError(
err instanceof ApiError && err.code === 'SCRIPT_REVISION_CONFLICT'
? 'Unter diesem Namen gibt es bereits eine neuere Version. Öffnen Sie den aktuellen Stand vor dem Veröffentlichen.'
: errorText(err)
);
if (err instanceof ApiError && err.status === 409) library.reload();
} finally { setBusy(false); }
} finally {
setBusy(false);
}
}
return <>
<div className="page-title"><h1>Skripte</h1>
{canPublish && !draft && !opened && <button className="primary" onClick={() => edit()}>Neues Skript</button>}
</div>
<ErrorBox error={error ?? library.error}/>{notice && <p role="status">{notice}</p>}
{!read ? <p>Die Berechtigung zum Lesen der Skriptbibliothek fehlt.</p> :
draft ? <section><h2>{base ? 'Neue Version' : 'Neues Skript'}</h2><form onSubmit={publish}>
<fieldset className="work-form" disabled={busy}><label>Name<input autoFocus required maxLength={120} readOnly={base > 0} value={draft.name} onChange={e => setDraft({...draft,name:e.target.value})}/></label>
<ScriptFields script={draft} change={setDraft} ids={['agent_service','root','system']}/>
<div className="work-actions"><button type="button" onClick={() => {setError(null); setDraft(null);}}>Abbrechen</button><button className="primary" type="submit">Version veröffentlichen</button></div>
</fieldset>
</form></section> :
opened ? <section><button className="link" onClick={() => {open(''); setNotice('');}}>Zur Skriptbibliothek</button>
{latest ? <><div className="section-heading"><h2>{latest.name}</h2>{canPublish && <button onClick={() => edit(latest)}>Neue Version</button>}</div>
<p>{interpreterNames[latest.interpreter]} · Version {latest.version} · {identityNames[latest.execution_identity]}</p>
<pre className="script-body">{latest.script_utf8}</pre>
{versions.length > 1 && <details><summary>Frühere Versionen ({versions.length - 1})</summary>
{versions.slice(1).map(item => <details key={item.revision_id}><summary>Version {item.version} · {interpreterNames[item.interpreter]} · {identityNames[item.execution_identity]}</summary><pre className="script-body">{item.script_utf8}</pre></details>)}
</details>}</> : <p role="status">Skript wird geladen …</p>}
</section> :
<section aria-label="Skriptbibliothek">
{!library.data ? <p role="status">Bibliothek wird geladen …</p> : library.data.length ? <div className="table"><table>
<thead><tr><th>Name</th><th>Plattform</th><th>Version</th><th>Ausführen als</th></tr></thead>
<tbody>{latestRevisions(library.data).map(item => <tr key={item.name}>
<td><button className="link" onClick={() => {open(item.name); setNotice('');}}>{item.name}</button></td>
<td>{interpreterNames[item.interpreter]}</td><td>{item.version}</td><td>{identityNames[item.execution_identity]}</td>
</tr>)}</tbody>
</table></div> : <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
</section>}
</>;
return (
<>
<div className="page-title">
<h1>Skripte</h1>
{canPublish && !draft && !opened && (
<button className="primary" onClick={() => edit()}>
Neues Skript
</button>
)}
</div>
<ErrorBox error={error ?? library.error} />
{notice && <p role="status">{notice}</p>}
{!read ? (
<p>Die Berechtigung zum Lesen der Skriptbibliothek fehlt.</p>
) : draft ? (
<section>
<h2>{base ? 'Neue Version' : 'Neues Skript'}</h2>
<form onSubmit={publish}>
<fieldset className="work-form" disabled={busy}>
<label>
Name
<input
autoFocus
required
maxLength={120}
readOnly={base > 0}
value={draft.name}
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
/>
</label>
<ScriptFields script={draft} change={setDraft} ids={['agent_service', 'root', 'system']} />
<div className="work-actions">
<button
type="button"
onClick={() => {
setError(null);
setDraft(null);
}}
>
Abbrechen
</button>
<button className="primary" type="submit">
Version veröffentlichen
</button>
</div>
</fieldset>
</form>
</section>
) : opened ? (
<section>
<button
className="link"
onClick={() => {
open('');
setNotice('');
}}
>
Zur Skriptbibliothek
</button>
{latest ? (
<>
<div className="section-heading">
<h2>{latest.name}</h2>
{canPublish && <button onClick={() => edit(latest)}>Neue Version</button>}
</div>
<p>
{interpreterNames[latest.interpreter]} · Version {latest.version} ·{' '}
{identityNames[latest.execution_identity]}
</p>
<pre className="script-body">{latest.script_utf8}</pre>
{versions.length > 1 && (
<details>
<summary>Frühere Versionen ({versions.length - 1})</summary>
{versions.slice(1).map((item) => (
<details key={item.revision_id}>
<summary>
Version {item.version} · {interpreterNames[item.interpreter]} ·{' '}
{identityNames[item.execution_identity]}
</summary>
<pre className="script-body">{item.script_utf8}</pre>
</details>
))}
</details>
)}
</>
) : (
<p role="status">Skript wird geladen …</p>
)}
</section>
) : (
<section aria-label="Skriptbibliothek">
{!library.data ? (
<p role="status">Bibliothek wird geladen …</p>
) : library.data.length ? (
<div className="table">
<table>
<thead>
<tr>
<th>Name</th>
<th>Plattform</th>
<th>Version</th>
<th>Ausführen als</th>
</tr>
</thead>
<tbody>
{latestRevisions(library.data).map((item) => (
<tr key={item.name}>
<td>
<button
className="link"
onClick={() => {
open(item.name);
setNotice('');
}}
>
{item.name}
</button>
</td>
<td>{interpreterNames[item.interpreter]}</td>
<td>{item.version}</td>
<td>{identityNames[item.execution_identity]}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>
)}
</section>
)}
</>
);
}
+90 -17
View File
@@ -1,17 +1,90 @@
.work-form { display: grid; gap: 1rem; margin: 0; padding: 0; border: 0; min-width: 0; }
.work-form label { margin: 0; }
.work-form input:not([type=checkbox]), .work-form textarea, .work-form select { width: 100%; }
.work-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); gap: 1rem; }
.work-actions { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: .65rem; margin-top: 1rem; }
.work-actions button { margin: 0; }
.script-editor, .script-body { font: .9rem/1.55 ui-monospace, monospace; tab-size: 4; }
.script-body { max-height: 30rem; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.order-progress { display: flex; flex-wrap: wrap; gap: .6rem 1.2rem; list-style: none; padding: 0; margin: 0 0 1rem; color: #536863; }
.order-progress [aria-current=step] { font-weight: 700; color: #155c48; }
.order-targets { list-style: none; padding: 0; margin: .5rem 0; }
.order-targets li { border-bottom: 1px solid #dce5e2; }
.order-targets label { display: flex; align-items: center; gap: .8rem; padding: .65rem 0; cursor: pointer; }
.order-targets small { margin-left: auto; text-align: right; }
.order-source { display: flex; flex-wrap: wrap; gap: 1rem; }
.order-source label { display: inline-flex; gap: .4rem; align-items: center; }
.work-form .order-source input { width: auto; }
.work-form {
display: grid;
gap: 1rem;
margin: 0;
padding: 0;
border: 0;
min-width: 0;
}
.work-form label {
margin: 0;
}
.work-form input:not([type='checkbox']),
.work-form textarea,
.work-form select {
width: 100%;
}
.work-fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
gap: 1rem;
}
.work-actions {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 0.65rem;
margin-top: 1rem;
}
.work-actions button {
margin: 0;
}
.script-editor,
.script-body {
font:
0.9rem/1.55 ui-monospace,
monospace;
tab-size: 4;
}
.script-body {
max-height: 30rem;
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.order-progress {
display: flex;
flex-wrap: wrap;
gap: 0.6rem 1.2rem;
list-style: none;
padding: 0;
margin: 0 0 1rem;
color: #536863;
}
.order-progress [aria-current='step'] {
font-weight: 700;
color: #155c48;
}
.order-targets {
list-style: none;
padding: 0;
margin: 0.5rem 0;
}
.order-targets li {
border-bottom: 1px solid #dce5e2;
}
.order-targets label {
display: flex;
align-items: center;
gap: 0.8rem;
padding: 0.65rem 0;
cursor: pointer;
}
.order-targets small {
margin-left: auto;
text-align: right;
}
.order-source {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.order-source label {
display: inline-flex;
gap: 0.4rem;
align-items: center;
}
.work-form .order-source input {
width: auto;
}