Files
rust-discovery/web/src/order-composer.tsx
T

898 lines
37 KiB
TypeScript

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 { 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 { ScriptFields } from './script-library';
type Props = {
tenantId: string;
customerName?: string;
auth: Session;
initialAssetIds: string[];
onSubmitted: (operationId: string) => void;
onDraft: (planId: 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'
};
}
function emptyScript(interpreter: Interpreter): Script {
return { name: '', interpreter, execution_identity: 'agent_service', script_utf8: '' };
}
function localDate(ms: number) {
const d = new Date(ms);
return new Date(ms - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
}
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
type Ticket = { id: string; hash: string; attempted: boolean };
function resumeTicket(key: string): Ticket | null {
let data;
try {
const raw = sessionStorage.getItem(key);
if (!raw) return null;
data = JSON.parse(raw);
} 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;
}
return data;
}
async function verifiedScriptOrder(value: unknown, tenantId: string, principal: string) {
const plan = record(value, 'Auftragsplan');
await verifyPlanIntegrity(plan);
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)
};
}
type Review = Awaited<ReturnType<typeof verifiedScriptOrder>>;
function blockers(review: Review) {
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;
}
return errorText(err);
}
export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, onDraft, 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));
const [step, setStep] = useState<1 | 2>(1);
const [selected, setSelected] = useState<string[]>(() => [...new Set(initialAssetIds)]);
const [known, setKnown] = useState<Record<string, Target>>({});
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']
.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 [revisionId, choose] = useState('');
const [linux, setLinux] = useState<Script>(() => emptyScript('posix_sh'));
const [windows, setWindows] = useState<Script>(() => emptyScript('powershell'));
const [fullRoot, setFullRoot] = useState(false);
const [reason, setReason] = useState('');
const [start, setStart] = useState(() => localDate(Date.now()));
const [end, setEnd] = useState(() => localDate(Date.now() + 3600000));
const [runtime, setRuntime] = useState(120);
const [limit, setLimit] = useState(65536);
const [parallel, setParallel] = useState(1);
const [halt, setHalt] = useState(1);
const [expected, setExpected] = useState('');
const [expectedFormat, setExpectedFormat] = useState('text');
const [busy, setBusy] = useState(false);
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 = canPlanScript || canPlanReboot;
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 || !canPlanScript) 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, canPlanScript]
);
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) => (canPlanScript && step === 2 && !ticket && mode === 'library' ? loadRevisions(tenantId, signal) : Promise.resolve([])),
[tenantId, canPlanScript, step, !!ticket, mode]
);
const revision = scripts.data?.find((r) => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
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 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 (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 identity = revision.execution_identity;
if (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 &&
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]));
}
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 || !(mode === 'reboot' ? canPlanReboot : canPlanScript) || issues.length || !selected.length) return;
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() };
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.');
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 }
});
} 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 });
}
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)
);
});
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 || !canPlanScript || lock.current) return;
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(' · '));
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'));
} 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();
}
} 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', 'Aktion', '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 Auftrags benötigen Sie Gerätezugriff, Rechte zum Planen und Einreichen und das
Ausführungsrecht für die gewählte Aktion.
</p>
</section>
) : ticket && canPlanScript ? (
<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>
{!query && allowed(auth, 'devices:enroll') && <a className="quiet" href="#verwaltung/aufnahme">Gerät aufnehmen</a>}
</>}
{(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);
}}
>
{canPlanReboot ? 'Weiter zur Aktion' : '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>{canPlanReboot ? 'Aktion auswählen' : 'Skript auswählen'}</h2>
<form onSubmit={prepare}>
<fieldset disabled={busy} className="work-form">
<div className="order-source">
{canPlanScript && <label>
<input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')} />
Aus der Bibliothek
</label>}
{canPlanScript && <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>}
</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>
)}
</>
)}
</>
) : mode === 'once' ? (
<>
{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>
)}
</>
) : (
<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>
)}
<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>
{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>
</>}
</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;
}) {
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>
);
}