Plan device actions exclusively as approved scripts and provide reboot library revisions

This commit is contained in:
2026-11-18 12:04:58 +01:00
parent adc04f0148
commit cd80bfc704
31 changed files with 1014 additions and 779 deletions
+86 -148
View File
@@ -38,7 +38,6 @@ type Props = {
auth: Session;
initialAssetIds: string[];
onSubmitted: (operationId: string) => void;
onDraft: (planId: string) => void;
};
type Target = {
id: string;
@@ -112,16 +111,21 @@ function blockers(review: Review) {
...scriptApprovalBlockers(review.plan)
];
}
function issueMessage(err: unknown) {
function issueMessage(err: unknown, identity?: string) {
if (err instanceof ApiError) {
if (err.code === 'SCRIPT_HELPER_SCOPE_DENIED') return errorText(err);
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') return 'Für mindestens eines der Zielgeräte fehlt die passende Skriptplattform.';
if (err.code === 'UNSUPPORTED_CAPABILITY') {
if (identity === 'system' || identity === 'root')
return 'Mindestens ein Zielgerät hat seinen Skript-Helper für ' + identityNames[identity] + ' noch nicht als betriebsbereit gemeldet.';
return 'Mindestens ein Zielgerät hat die benötigte Skriptausführung noch nicht als betriebsbereit gemeldet.';
}
}
return errorText(err);
}
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, onDraft, customerName }: Props) {
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, customerName }: Props) {
const path = (suffix: string) => tenantPath(tenantId, suffix);
const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]);
const [savedTicket, setTicket] = useState<Ticket | null>(() => resumeTicket(key));
@@ -131,12 +135,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
const [query, setQuery] = useState('');
const [cursor, setCursor] = useState<string | null>(null);
const [prior, setPrior] = useState<(string | null)[]>([]);
const canCreate = ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit']
const canPlan = ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit', 'scripts:execute']
.every((permission) => allowed(auth, permission));
const canPlanScript = canCreate && allowed(auth, 'scripts:execute');
const canPlanReboot = canCreate && (allowed(auth, 'root:execute') || allowed(auth, 'system:execute'));
const ticket = canPlanScript ? savedTicket : null;
const [mode, setMode] = useState<'library' | 'once' | 'reboot'>(() => canPlanScript ? 'library' : 'reboot');
const ticket = canPlan ? savedTicket : null;
const [mode, setMode] = useState<'library' | 'once'>('library');
const [revisionId, choose] = useState('');
const [libraryIdentity, setLibraryIdentity] = useState<Identity | null>(null);
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
@@ -160,7 +162,6 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
mounted.current = false;
};
}, []);
const canPlan = canPlanScript || canPlanReboot;
const devices = useResource(
async (signal) => {
@@ -175,7 +176,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
);
const review = useResource(
async (signal) => {
if (!ticket || !canPlanScript) return null;
if (!ticket || !canPlan) return null;
const checked = await verifiedScriptOrder(
await request(path('/operation-plans/' + ticket.id), { signal }),
tenantId,
@@ -185,7 +186,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
return checked;
},
[tenantId, ticket?.id, ticket?.hash, auth.principal.id, canPlanScript]
[tenantId, ticket?.id, ticket?.hash, auth.principal.id, canPlan]
);
const missingIds = (review.data?.jobs.map((job) => job.assetId) ?? initialAssetIds).filter((id) => !known[id]);
const restored = useResource(
@@ -217,29 +218,20 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
const hasLinux = targets.some((d) => d?.platform === 'linux');
const hasWindows = targets.some((d) => d?.platform === 'windows');
const scripts = useResource(
(signal) => (canPlanScript && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlanScript, step, !!ticket, mode]
(signal) => (canPlan && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlan, step, !!ticket, mode]
);
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
const identity = mode === 'library'
? libraryIdentity ?? revision?.execution_identity
: (hasWindows ? windows : linux).execution_identity;
const rebootIdentity = hasWindows ? 'system' : 'root';
const rebootAsset = mode === 'reboot' && step === 2 && selected.length === 1 ? selected[0] : null;
const rebootTarget = useResource(async signal => {
if (!rebootAsset || !canPlanReboot) return null;
const device = record(await request(path('/devices/' + encodeURIComponent(rebootAsset)), { signal }));
if (device.tenant_id !== tenantId || device.asset_id !== rebootAsset || device.lifecycle !== 'current' ||
devicePlatform(device) !== (hasWindows ? 'windows' : 'linux')) {
throw Error('Das Zielgerät hat sich geändert. Wählen Sie es erneut aus.');
}
const capabilities = Array.isArray(device.capabilities) ? device.capabilities : [];
const required = hasWindows
? ['reboot', 'rmm.sync.v1', 'windows.reboot/1', 'helper.system.v1', 'system:reboot']
: ['reboot', 'rmm.sync.v1', 'helper.root.v1', 'root:reboot'];
return { agentId: objectId(device, 'agent'), ready: required.every(capability => capabilities.includes(capability)) };
}, [tenantId, rebootAsset, rebootIdentity, canPlanReboot], !!rebootAsset && canPlanReboot);
const restartPlatform = hasLinux === hasWindows ? null : hasWindows ? 'windows' : 'linux';
const restartScript = restartPlatform && heads.find(revision =>
revision.name === (hasWindows ? 'Windows neu starten' : 'Linux neu starten') &&
scriptPlatform(revision.interpreter) === restartPlatform &&
revision.execution_identity === (hasWindows ? 'system' : 'root')
);
const issues: string[] = [];
if (targets.some((d) => !d?.current))
issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
@@ -255,13 +247,6 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
if (identity && identity !== 'agent_service' && !allowed(auth, identity + ':execute'))
issues.push('Die Berechtigung für ' + identityNames[identity] + ' fehlt.');
}
if (mode === 'reboot') {
if (selected.length !== 1) issues.push('Wählen Sie ein einzelnes Gerät für den Neustart.');
if (!allowed(auth, rebootIdentity + ':execute')) issues.push('Die Berechtigung für ' + identityNames[rebootIdentity] + ' fehlt.');
if (rebootTarget.error) issues.push(issueMessage(rebootTarget.error));
else if (rebootAsset && !rebootTarget.data) issues.push('Die Neustartfähigkeit des Geräts wird geprüft.');
else if (rebootTarget.data?.ready === false) issues.push('Das Zielgerät meldet derzeit keine Neustartfähigkeit für ' + identityNames[rebootIdentity] + '.');
}
if (
mode === 'once' &&
hasLinux &&
@@ -298,7 +283,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
}
async function prepare(e: FormEvent) {
e.preventDefault();
if (lock.current || !(mode === 'reboot' ? canPlanReboot : canPlanScript) || issues.length || !selected.length) return;
if (lock.current || !canPlan || issues.length || !selected.length) return;
lock.current = true;
setBusy(true);
setError(null);
@@ -308,48 +293,6 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
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() };
if (mode === 'reboot') {
const input: PlanInput = {
...bound,
tenant_id: tenantId,
action: 'reboot',
schedule: { ...schedule, offline_policy: 'wait_until_deadline' },
rollout: { max_parallel: 1, halt_after_failures: 1 },
parameters: {
execution_identity: rebootIdentity,
reason: bound.reason,
dependency_group: 'asset-' + selected[0],
reconnect_timeout_seconds: hasWindows ? 180 : 300,
timeout_seconds: 60,
max_output_bytes: 4096
}
};
validateInput(input);
await validateSensitiveInput(input, auth);
const plan = record(await request(path('/operation-plans'), { csrf: auth.csrf_token, body: input }));
if (!Array.isArray(plan.plan_payload_bytes)) throw Error('Die gespeicherten Bytes des Neustartplans fehlen.');
await verifyPlanIntegrity(plan);
const planId = objectId(plan, 'plan');
const fixed = record(plan.plan_payload);
const jobs = Array.isArray(fixed.jobs) ? fixed.jobs : [];
const job = record(record(jobs[0]).payload);
const action = record(job.action);
if (
fixed.plan_id !== planId || fixed.tenant_id !== tenantId || fixed.principal !== auth.principal.id ||
fixed.reason !== bound.reason || fixed.max_parallel !== 1 || fixed.halt_after_failures !== 1 ||
jobs.length !== 1 || job.asset_id !== selected[0] || job.agent_id !== rebootTarget.data?.agentId ||
job.execution_identity !== rebootIdentity ||
action.action !== 'reboot' || action.reason !== bound.reason ||
action.dependency_group !== input.parameters.dependency_group ||
action.reconnect_timeout_seconds !== input.parameters.reconnect_timeout_seconds ||
job.max_runtime_seconds !== input.parameters.timeout_seconds ||
job.max_output_bytes !== input.parameters.max_output_bytes ||
Date.parse(String(job.not_before)) !== Date.parse(schedule.not_before) ||
Date.parse(String(job.start_before)) !== Date.parse(schedule.start_before)
) throw Error('Der erstellte Neustartplan weicht von diesem Entwurf ab.');
if (mounted.current) onDraft(planId);
return;
}
let raw: unknown;
if (mode === 'library') {
if (!revision) throw Error('Wählen Sie eine Skriptversion.');
@@ -426,14 +369,14 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
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));
if (mounted.current) setError(issueMessage(e, identity));
} finally {
lock.current = false;
if (mounted.current) setBusy(false);
}
}
async function submit() {
if (!ticket || !review.data || !canPlanScript || lock.current) return;
if (!ticket || !review.data || !canPlan || lock.current) return;
lock.current = true;
setBusy(true);
setError(null);
@@ -466,7 +409,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
if (mounted.current) {
if (!ticket.attempted && err instanceof ApiError && err.status >= 400 && err.status < 500)
saveTicket({ ...ticket, attempted: false });
setError(issueMessage(err));
setError(issueMessage(err, review.data?.jobs[0]?.identity));
review.reload();
}
} finally {
@@ -481,7 +424,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
<h1>Neuer Auftrag</h1>
</div>
<ol className="order-progress" aria-label="Auftragsschritte">
{['Geräte', 'Aktion', 'Zusammenfassung'].map((name, i) => (
{['Geräte', 'Skript', 'Zusammenfassung'].map((name, i) => (
<li key={name} aria-current={stepNumber === i + 1 ? 'step' : undefined}>
{i + 1}. {name}
</li>
@@ -492,10 +435,10 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
<section>
<p>
Zum Erstellen eines Auftrags benötigen Sie Gerätezugriff, Rechte zum Planen und Einreichen und das
Ausführungsrecht für die gewählte Aktion.
Ausführungsrecht für Skripte.
</p>
</section>
) : ticket && canPlanScript ? (
) : ticket ? (
<section aria-label="Auftrag prüfen">
<h2>Zusammenfassung</h2>
{review.data ? (
@@ -672,7 +615,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
setError(null);
}}
>
{canPlanReboot ? 'Weiter zur Aktion' : 'Weiter zum Skript'}
Weiter zum Skript
</button>
</div>
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
@@ -680,25 +623,26 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
</section>
) : (
<section>
<h2>{canPlanReboot ? 'Aktion auswählen' : 'Skript auswählen'}</h2>
<h2>Skript auswählen</h2>
<form onSubmit={prepare}>
<fieldset disabled={busy} className="work-form">
<div className="order-source">
{canPlanScript && <label>
<label>
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
Aus der Bibliothek
</label>}
{canPlanScript && <label>
</label>
<label>
<input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')} />
Einmaliges Skript
</label>}
{canPlanReboot && <label>
<input type="radio" name="quelle" checked={mode === 'reboot'} onChange={() => setMode('reboot')} />
Gerät neu starten
</label>}
</label>
</div>
{mode === 'library' ? (
<>
{restartScript && allowed(auth, restartScript.execution_identity + ':execute') && (
<button type="button" className="quiet" onClick={() => chooseLibrary(restartScript)}>
Neustartskript auswählen
</button>
)}
<label>
Bibliotheksskript
<select
@@ -735,6 +679,7 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
</select>
</label>
<p>{interpreterNames[revision.interpreter]}</p>
<details><summary>Skriptinhalt anzeigen</summary><pre>{revision.script_utf8}</pre></details>
<label>
Ausführen als
<select value={identity} onChange={(e) => {
@@ -754,18 +699,13 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
</>
)}
</>
) : mode === 'once' ? (
) : (
<>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false} />}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows />}
</>
) : (
<p className="warning">
Der Auftrag startet das ausgewählte Gerät nach Genehmigung neu. Ausführung als {identityNames[rebootIdentity]}.
Der Agent muss nach dem Neustart wieder Kontakt aufnehmen.
</p>
)}
{mode !== 'reboot' && identity && identity !== 'agent_service' && (
{identity && identity !== 'agent_service' && (
<p className="warning">Der genehmigte Skriptauftrag erhält volle Hostrechte als {identityNames[identity]}.</p>
)}
<label>
@@ -783,51 +723,49 @@ export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, on
Startfrist
<input required type="datetime-local" value={end} onChange={(e) => setEnd(e.target.value)} />
</label>
{mode !== 'reboot' && <>
<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>
</>}
<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' && (
<>