Plan device actions exclusively as approved scripts and provide reboot library revisions
This commit is contained in:
+17
-6
@@ -1,4 +1,4 @@
|
||||
# Linux-MVP WebUI
|
||||
# Rust Discovery WebUI
|
||||
|
||||
React/TypeScript, no runtime demo data, no desktop/PTY/hypervisor integration.
|
||||
Build assets: **`web/dist/`**; serve `index.html` and `/assets/*` from the TLS backend
|
||||
@@ -6,16 +6,27 @@ on the same origin. Do not proxy authentication to a different origin. All API U
|
||||
are relative; cookies use `credentials: same-origin`, mutations use `X-CSRF-Token`.
|
||||
No token or password persistence, raw HTML rendering, automatic approval or retry.
|
||||
|
||||
## Geräteaufträge
|
||||
|
||||
Unter **Aufträge → Neuer Auftrag** wählen Sie die Geräte und eine veröffentlichte
|
||||
Skriptversion oder geben ein einmaliges Skript ein. **Neustartskript auswählen**
|
||||
übernimmt die passende Bibliotheksversion für Windows (PowerShell als SYSTEM) oder
|
||||
Linux (Shell als root). Gebundene Skriptbytes, Zielgeräte, Rechte und Zeitgrenzen
|
||||
sind vor der Entscheidung unter **Genehmigungen** sichtbar. Frühere typisierte
|
||||
Aufträge bleiben in der Historie lesbar. Im Gerätedetail stehen die zuletzt vom
|
||||
Agenten gemeldeten Ausführungsrechte. `full_maintenance_v1` bezeichnet das
|
||||
technische Profil eines genehmigten Administratorskripts.
|
||||
|
||||
## Commands
|
||||
|
||||
From `web/`: `npm ci`, `npm run typecheck`, `npm test`, `npm run build`.
|
||||
`npm run dev` binds loopback, but is not the authenticated TLS acceptance setup.
|
||||
The current server is `discovery.ease-technologies.de`; management access uses the
|
||||
configured SSH tunnel and verified TLS. Earlier local `rmm-dev.internal:18443`
|
||||
The public management service is documented in [public access](../docs/public-access.md).
|
||||
The separate dev/test profile uses the SSH tunnel. Earlier local `rmm-dev.internal:18443`
|
||||
examples below are historical. The notebook is development only, without an RMM
|
||||
server or enrolled agent. No certificate-verification bypass is supported.
|
||||
|
||||
## Script console (specification 1.20, source implementation)
|
||||
## Historical script console and adapter contracts (specification 1.20)
|
||||
|
||||
`run_script` remains a durable plan/request, not a PTY or interactive terminal.
|
||||
The planner accepts complete fixed POSIX/Bash or Windows PowerShell5.1 scripts.
|
||||
@@ -69,7 +80,7 @@ independent scopes. Two output tests cover hostile HTML/terminal/bidi bytes,
|
||||
unknown/cancellation/truncation, invalid encodings and absent/invalid results.
|
||||
No browser, server, VM job, approval or deployment was executed in these checks.
|
||||
|
||||
## JSON adapter contract
|
||||
### JSON adapter contract at the time of the historical tests
|
||||
|
||||
`src/api.ts` is the sole transport/contract boundary. Responses missing required
|
||||
fields fail explicitly. Unknown backend fields are displayed without interpretation.
|
||||
@@ -153,7 +164,7 @@ visible; failed polling retains the old response alongside an error, never a gre
|
||||
success message. Tenant changes unmount all selection/plans/jobs and abort requests.
|
||||
List pagination uses server cursors, without pretending a truncated page is complete.
|
||||
|
||||
## Browser checks and separate acceptance gates
|
||||
### Historical browser checks and separate acceptance gates
|
||||
|
||||
`tests/browser/approval.spec.ts` uses actual UI interactions only. It never uses an
|
||||
API client to authorize, never writes storageState, and disables traces/screenshots/
|
||||
|
||||
+20
-2
@@ -15,6 +15,7 @@ import {
|
||||
import { AdminControl } from './management';
|
||||
import { allowed } from './safety';
|
||||
import { CatalogCheckNotice } from './catalog-check';
|
||||
import { devicePlatform } from './script-catalog';
|
||||
import { ErrorBox, errorText, useResource } from './resource';
|
||||
import { NavIcon, orderDetailRoute } from './navigation';
|
||||
import { orderTitle, Status } from './order-presentation';
|
||||
@@ -115,6 +116,22 @@ function devicePath(customer: string, asset: string) {
|
||||
return tenantPath(customer, '/devices/' + encodeURIComponent(asset));
|
||||
}
|
||||
|
||||
function reportedScriptProfiles(device: RecordValue) {
|
||||
const os = devicePlatform(device);
|
||||
if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet';
|
||||
const caps = new Set(device.capabilities);
|
||||
if (!caps.has('run_script')) return 'Nicht gemeldet';
|
||||
const windows = os === 'windows';
|
||||
const identity = windows ? 'system' : 'root';
|
||||
const service = windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto';
|
||||
if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet';
|
||||
if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap)))
|
||||
return 'Nicht gemeldet';
|
||||
const admin = ['rmm.sync.v1', 'script.full_maintenance/1', 'helper.' + identity + '.v1', identity + ':run_script']
|
||||
.every(capability => caps.has(capability));
|
||||
return admin ? service + ' und als Administrator (' + (windows ? 'SYSTEM' : 'root') + ')' : service;
|
||||
}
|
||||
|
||||
function DeviceDetail({
|
||||
customer,
|
||||
asset,
|
||||
@@ -158,7 +175,8 @@ function DeviceDetail({
|
||||
['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)],
|
||||
['Letzter Kontakt', time(d.last_contact_at)],
|
||||
['Inventar erhoben', time(d.observed_at)],
|
||||
['Agentversion', label(d.agent_version)]
|
||||
['Agentversion', label(d.agent_version)],
|
||||
['Vom Agenten gemeldete Skriptausführung', reportedScriptProfiles(d)]
|
||||
];
|
||||
return (
|
||||
<div className="device-detail">
|
||||
@@ -654,7 +672,7 @@ export function Devices({
|
||||
<button className="quiet" onClick={() => onSelection({ customer: '', ids: [] })}>
|
||||
Auswahl aufheben
|
||||
</button>
|
||||
<button disabled={!allowed(auth, 'operations:plan')} onClick={onCreateOrder}>Auftrag erstellen</button>
|
||||
<button disabled={!allowed(auth, 'operations:plan') || !allowed(auth, 'scripts:execute')} onClick={onCreateOrder}>Auftrag erstellen</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
+21
-60
@@ -9,10 +9,10 @@ import { ScriptLibrary } from './script-library';
|
||||
import { McpTokenManagement } from './mcp-token-management';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
import { ApiError, authConfig, approvalBlockers, objectId, page, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, windowsPowerShellRemoteSignedProfile, fullMaintenanceScriptProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, fullMaintenanceWarning } from './safety';
|
||||
import { allowed, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest, adminScriptWarning } from './safety';
|
||||
import { Login } from './login';
|
||||
import { ConsoleOutput, visibleControls } from './console-output';
|
||||
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
|
||||
@@ -53,7 +53,7 @@ export function ScriptPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
return target ? deviceName(target) : j.assetId;
|
||||
}).join(', ')}</h4>}
|
||||
<p>{job.revision ? job.revision.name+' · Version '+job.revision.version : 'Einmaliges Skript'} · {job.interpreter} · {identityName(job.identity)}</p>
|
||||
{job.privilegedProfile === fullMaintenanceScriptProfile && <p className="warning">{fullMaintenanceWarning}</p>}
|
||||
{job.privilegedProfile === fullMaintenanceScriptProfile && <p className="warning">{adminScriptWarning}</p>}
|
||||
{job.identity === 'root' && job.privilegedProfile !== fullMaintenanceScriptProfile && <p className="warning">{rootWarning}</p>}
|
||||
{job.interpreter === 'powershell' && <p>Windows PowerShell 5.1 · {job.windowsProfile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned für diesen Prozess' : 'Richtlinie des Geräts'}</p>}
|
||||
<pre aria-label="Vollständiger Skripttext">{visibleControls(job.script)}</pre>
|
||||
@@ -115,41 +115,6 @@ export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
return <aside className="warning" aria-label="Feste Live-Logfenster"><p>UI-genehmigte Liveabfrage aus hashgeprüften gespeicherten Planbytes; kein passives Inventar, keine automatische Erhebung.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Quelle: {job.source}{job.windows ? <> · Kanal: {job.channel} · Provider: {job.provider} · agent_service</> : ' · Linux-Journal'} · UTC-Fenster: [{job.since}, {job.until}) · maximal {job.maxLines} {job.windows ? 'Events' : 'Zeilen'} · {job.outputBytes} Bytes · äußere Joblaufzeit {job.runtimeSeconds}s{job.windows && ' · inneres Abfragebudget höchstens5000ms, zwischen Win32-Aufrufen kooperativ geprüft'}</li>)}</ul><p>Grenzen, Abbruch, fehlende Rechte und Teilabdeckung bleiben sichtbar. Keine Bookmarkfortschreibung durch diesen Auftrag; die Abfrage behauptet keine vollständige Sammlung aller Systemlogs.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">Logfenster ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
const initialParameters: Record<Action, RecordValue> = {
|
||||
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
|
||||
update_agent: { release_id: '' },
|
||||
};
|
||||
function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
|
||||
const choices = availableActions(auth, actions).filter(action => auth.principal.simulated || !['run_script', 'reboot'].includes(action));
|
||||
const [scriptPlatform, setScriptPlatform] = useState('linux'), [mixedVariants, setMixedVariants] = useState('[]');
|
||||
const initialAction = auth.principal.simulated ? 'run_script' : 'refresh_inventory';
|
||||
const [action, setAction] = useState<Action>(initialAction), [parameters, setParameters] = useState(pretty(initialParameters[initialAction])), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
|
||||
const [identity, setIdentity] = useState('agent_service');
|
||||
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
|
||||
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
|
||||
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')), ...(action === 'run_script' && f.get('privileged_script_profile') === fullMaintenanceScriptProfile ? { privileged_script_profile: fullMaintenanceScriptProfile } : {}) };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')), ...(scriptPlatform === 'windows' ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } : {}) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
|
||||
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
|
||||
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
|
||||
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = choices.find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{choices.map(a => <option key={a} value={a}>{auth.principal.simulated ? a : actionTitle(a)}</option>)}</select></label>
|
||||
{action === 'update_agent' && <p className="warning">{agentUpdateWarning} Nur parameters.release_id aus dem Katalog; keine freien Vorgänger-, Dateipfad-, Artefakt- oder Policywerte. Gesamtbudget600s, Ausgabelimit höchstens65536Bytes. Fehlende frische Gerätepreview ergibt keine Planung.</p>}
|
||||
{action === 'query_logs' && <p>Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.</p>}
|
||||
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
|
||||
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive. Einzelne neue Windowspläne binden fest RemoteSigned nur für den Jobprozess. Bei gemischten Varianten ist powershell_51_remote_signed ausdrücklich an der Windowsvariante zu setzen; fehlendes Profil bleibt geerbt. Jede tatsächliche Prozessoption steht vor Genehmigung je Ziel im festen Plan. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
|
||||
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={!['set_service_state', 'ensure_package', 'run_script', 'update_agent'].includes(action) || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" key={action} type="number" min="1" max="86400" defaultValue={action === 'update_agent' ? '600' : '60'} required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
|
||||
{action === 'run_script' && <><label>Privilegiertes Skriptprofil<select name="privileged_script_profile" aria-label="Privilegiertes Skriptprofil" key={identity} defaultValue=""><option value="">Bestehendes begrenztes Profil · keine volle Hostwartung</option><option value={fullMaintenanceScriptProfile} disabled={!['root', 'system'].includes(identity) || !allowed(auth, 'scripts:execute')}>full_maintenance_v1 · volle Hostautorität als root/SYSTEM</option></select></label><p className="warning">{fullMaintenanceWarning}</p><p>Die Auswahl erteilt keine Rechte und aktiviert keinen Client. Zentrale und lokale Policy, tatsächliche Zielcapabilities und die spätere Genehmigung werden unabhängig geprüft. SYSTEM erfordert dieses Profil; es gibt keinen automatischen Fallback.</p></>}
|
||||
{identity === 'root' && !['run_script', 'update_agent'].includes(action) && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && !['run_script', 'update_agent'].includes(action) && <p className="warning">{systemWarning}</p>}
|
||||
{identity === 'system' && action === 'ensure_package' && <p>MSI: provider=msi, package=rmm-windows-msi-fixture, architecture=x64, installation_context=machine, recipe_version=1 und vollständiges windows_msi_manifest aus dem getrennten MSI-Katalog. Genau zwei eigene Rezepte1.0/1.0→1.1;10–120s,1024–65536Bytes. APT-Manifest fehlt/null. Rezept-/Artefakthash und feste Nachbedingungen werden geprüft. Kein zusätzlicher Artefaktvektor.</p>}
|
||||
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
|
||||
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={action === 'update_agent' || (identity === 'system' && action === 'ensure_package')} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
|
||||
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
|
||||
</form></section>;
|
||||
}
|
||||
function localDate(date: Date) { return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }
|
||||
|
||||
function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [source, setSource] = useState('{}'), [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [receipt, setReceipt] = useState<unknown>(null);
|
||||
const list = useResource(async signal => {
|
||||
@@ -233,6 +198,7 @@ function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string;
|
||||
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
|
||||
const [issuing, setIssuing] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [adminScripts, setAdminScripts] = useState(false);
|
||||
return <section aria-label="Gerät aufnehmen"><h2>Gerät aufnehmen</h2>
|
||||
<p>Kunde <strong>{customerName}</strong> · Der Einmalcode gilt 15 Minuten.</p>
|
||||
<h3>Installation auf dem Zielgerät</h3>
|
||||
@@ -240,7 +206,12 @@ function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string;
|
||||
<li><strong>Linux</strong> · Installationsskript per HTTPS laden und mit Administratorrechten starten.</li>
|
||||
<li><strong>Windows</strong> · Installationsskript per HTTPS laden und in einer administrativen PowerShell starten.</li>
|
||||
</ul>
|
||||
<p>Die passenden Befehle erscheinen mit dem Einmalcode. Das Skript fragt den Code auf dem Zielgerät ab.</p>
|
||||
<label className="check"><input type="checkbox" checked={adminScripts} onChange={e => setAdminScripts(e.target.checked)}/>
|
||||
Installationsbefehle für Administratorskripte anzeigen
|
||||
</label>
|
||||
{adminScripts && <p>Der lokale Installer aktiviert mit <code>--enable-admin-scripts</code> unter Linux oder <code>-EnableAdministratorScripts</code> unter Windows den Skript-Helper.
|
||||
{' '}Für jeden Auftrag gelten zusätzlich die Skript- und Administratorrechte des Kunden und die Genehmigung in der WebUI.</p>}
|
||||
<p>Die passenden Befehle erscheinen mit dem Einmalcode. Geben Sie den Code bei der Abfrage auf dem Zielgerät ein.</p>
|
||||
<button disabled={issuing || !allowed(auth, 'devices:enroll')} onClick={async () => {
|
||||
setIssuing(true); setEnrollment(null); setEnrollmentError(null); setCopied(false);
|
||||
try {
|
||||
@@ -258,11 +229,11 @@ function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string;
|
||||
}}>Einmalcode kopieren</button>
|
||||
<button className="quiet" onClick={() => { setEnrollment(null); setCopied(false); }}>Code ausblenden</button>
|
||||
{copied && <p role="status">Einmalcode wurde kopiert.</p>}
|
||||
{enrollment.origin && enrollment.platforms.includes('x86_64-unknown-linux-gnu') && <><p>Linux, mit einem Administratorkonto ausführen</p><pre>{`curl --fail --show-error --silent '${enrollment.origin}/install/linux.sh' -o linux.sh && sudo sh linux.sh '${enrollment.origin}'`}</pre></>}
|
||||
{enrollment.origin && enrollment.platforms.includes('x86_64-unknown-linux-gnu') && <><p>Linux, mit einem Administratorkonto ausführen</p><pre>{`curl --fail --show-error --silent '${enrollment.origin}/install/linux.sh' -o linux.sh && sudo sh linux.sh '${enrollment.origin}'${adminScripts ? ' --enable-admin-scripts' : ''}`}</pre></>}
|
||||
{enrollment.origin && ['x86_64-pc-windows-gnu','x86_64-pc-windows-msvc'].filter(p => enrollment.platforms.includes(p)).map(platform =>
|
||||
<div key={platform}><p>Windows {platform.endsWith('-gnu') ? 'x64 (GNU)' : 'x64 (MSVC)'}, in einer administrativen Windows PowerShell ausführen</p>
|
||||
<pre>{`Invoke-WebRequest -UseBasicParsing '${enrollment.origin}/install/windows.ps1' -OutFile .\\windows.ps1
|
||||
.\\windows.ps1 -BootstrapBase '${enrollment.origin}' -Platform '${platform}'`}</pre></div>)}
|
||||
.\\windows.ps1 -BootstrapBase '${enrollment.origin}' -Platform '${platform}'${adminScripts ? ' -EnableAdministratorScripts' : ''}`}</pre></div>)}
|
||||
</>}
|
||||
|
||||
</section>;
|
||||
@@ -305,7 +276,9 @@ function PlanDetail({ tenantId, id, auth, onOperation, customerName, mode = 'rev
|
||||
const revision = saved.script_revision ? record(saved.script_revision) : null;
|
||||
const title = revision ? display(revision.name) : actionTitle(first && record(first.action).action);
|
||||
const script = first && record(first.action).action === 'run_script';
|
||||
const allScripts = payloads.length > 0 && payloads.every(p => record(p.action).action === 'run_script');
|
||||
const blockers = reviewBlockers(data);
|
||||
if (!allScripts) blockers.push('Dieser Plan enthält eine frühere Aktionsart. Erstellen Sie für die Ausführung einen neuen Skriptauftrag.');
|
||||
const pending = data.approval_state === 'pending_approval';
|
||||
const planHash = stringField(data,'plan_hash');
|
||||
const confirmed = confirmedHash === planHash;
|
||||
@@ -324,12 +297,13 @@ function PlanDetail({ tenantId, id, auth, onOperation, customerName, mode = 'rev
|
||||
try {
|
||||
await verifyReview(data, tenantId, id);
|
||||
if (decision !== 'reject') {
|
||||
if (!allScripts) throw new Error('Neue Geräteaufträge führen ausschließlich Skripte aus.');
|
||||
const problems = reviewBlockers(data);
|
||||
if (problems.length) throw new Error(problems.join(' · '));
|
||||
}
|
||||
if (decision === 'submit' && (mode !== 'submit' || !allowed(auth,'operations:submit'))) throw new Error('Einreichung nicht erlaubt.');
|
||||
if (decision !== 'submit' && (!mayDecide || !confirmed)) throw new Error('Prüfung und Berechtigung erforderlich.');
|
||||
if (decision === 'approve' && missingRights.length) throw new Error('Erforderliche Ausführungsrechte fehlen.');
|
||||
if (decision !== 'reject' && missingRights.length) throw new Error('Erforderliche Ausführungsrechte fehlen.');
|
||||
const submit = decision === 'submit';
|
||||
const result = record(await request(path + (submit ? '/submit' : '/authorizations'), {
|
||||
csrf: auth.csrf_token, body: submit ? { idempotency_key: 'web-plan-' + id } : { plan_hash: planHash, decision }
|
||||
@@ -377,8 +351,9 @@ function PlanDetail({ tenantId, id, auth, onOperation, customerName, mode = 'rev
|
||||
<JsonView value={data} label="Technische Plandaten"/>
|
||||
<ErrorBox error={error ?? plan.error}/>
|
||||
{(pending || mode === 'submit') && blockers.length > 0 && <p role="alert" className="error">{blockers.join(' · ')}</p>}
|
||||
{mode === 'submit' && !data.approval_state && missingRights.length > 0 && <p className="warning">Für die Einreichung fehlen Rechte: {missingRights.join(', ')}.</p>}
|
||||
{mode === 'submit' && !data.approval_state && allowed(auth, 'operations:submit') &&
|
||||
<button className="primary" disabled={busy || !!plan.error || !!blockers.length} onClick={() => void act('submit')}>Zur Genehmigung einreichen</button>}
|
||||
<button className="primary" disabled={busy || !!plan.error || !!blockers.length || !!missingRights.length} onClick={() => void act('submit')}>Zur Genehmigung einreichen</button>}
|
||||
{mode === 'submit' && typeof data.operation_id === 'string' && <button className="quiet" onClick={() => onOperation(objectId(data, 'operation'))}>Eingereichten Auftrag öffnen</button>}
|
||||
{mayDecide && <fieldset disabled={busy || !!plan.error}><legend>Entscheidung</legend>
|
||||
{!!missingRights.length && <p className="warning">Für die Genehmigung fehlen Rechte: {missingRights.join(', ')}.</p>}
|
||||
@@ -684,9 +659,6 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
switchCustomer(tenantId);
|
||||
go('genehmigungen', `pruefen/${tenantId}/${id}`);
|
||||
}
|
||||
function showDraft(id: string) {
|
||||
go('auftraege', `entwurf/${customer}/${id}`);
|
||||
}
|
||||
function afterSubmission(id: string) {
|
||||
refreshInbox(value => value + 1);
|
||||
openOperation(customer, id);
|
||||
@@ -822,16 +794,9 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
</> : <><div className="page-title"><h1>Genehmigungen</h1></div><ApprovalInbox ownId={auth.principal.id} open={openReview} /></>
|
||||
)}
|
||||
{route.page === 'auftraege' && (
|
||||
route.tab === 'neu' ? <>
|
||||
(route.tab === 'neu' || route.tab === 'wartung') ? <>
|
||||
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
|
||||
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} onDraft={showDraft} />
|
||||
</> : route.tab === 'wartung' ? <>
|
||||
<a href="#verwaltung/kataloge" className="back-link">← Zur erweiterten Verwaltung</a>
|
||||
<div className="page-title"><h1>Wartungsauftrag planen</h1></div>
|
||||
{allowed(scoped, 'operations:plan') ? <>
|
||||
<a className="quiet" href="#geraete">Geräte auswählen</a>
|
||||
<Planner tenantId={customer} auth={scoped} selected={selected} showPlan={showDraft} />
|
||||
</> : <p>Die Berechtigung zum Planen von Aufträgen fehlt.</p>}
|
||||
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} />
|
||||
</> : detailRoute && detailId ? <>
|
||||
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
|
||||
{detailKind === 'entwurf' ?
|
||||
@@ -841,7 +806,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
customerName={customerName} openPlan={id => openReview(customer,id)} />}
|
||||
</> : <>
|
||||
<div className="page-title"><h1>Aufträge</h1>
|
||||
{allowed(scoped, 'operations:plan') && <a className="primary-action" href="#auftraege/neu"><NavIcon name="plus" /> Neuer Auftrag</a>}
|
||||
{allowed(scoped, 'operations:plan') && allowed(scoped, 'scripts:execute') && <a className="primary-action" href="#auftraege/neu"><NavIcon name="plus" /> Neuer Auftrag</a>}
|
||||
</div>
|
||||
<Operations tenantId={customer} customerName={customerName} open={id => openOperation(customer,id)}
|
||||
filters={orderFilters} apply={setOrderFilters}/>
|
||||
@@ -868,10 +833,6 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
{adminTab === 'releases' && <AgentReleaseCatalog tenantId={customer} auth={scoped} />}
|
||||
{adminTab === 'kataloge' && (
|
||||
<>
|
||||
{allowed(scoped, 'operations:plan') && <section>
|
||||
<h2>Erweiterte Wartung</h2>
|
||||
<a className="quiet" href="#auftraege/wartung">Wartungsauftrag planen</a>
|
||||
</section>}
|
||||
<Catalog tenantId={customer} auth={scoped} />
|
||||
<WindowsMsiCatalog tenantId={customer} auth={scoped} />
|
||||
</>
|
||||
|
||||
@@ -197,7 +197,7 @@ function TokenManagement({ auth, tenantId }: { auth: Session; tenantId: string }
|
||||
const visibleTokens = listing?.tokens.filter(token => (token.revoked_at !== null || Date.parse(token.expires_at) <= now) === history) ?? [];
|
||||
return <section aria-label="MCP-Tokens">
|
||||
<h2>MCP-Tokens</h2>
|
||||
<p>Erstellen Sie einen Zugang für Ihren MCP-Client. Skript- und Wartungsaufträge benötigen weiterhin die Genehmigung in der WebUI.</p>
|
||||
<p>Erstellen Sie einen Zugang für Ihren MCP-Client. Jeder Skriptauftrag benötigt eine Genehmigung in der WebUI.</p>
|
||||
<p><code>{endpoint}</code>{' '}
|
||||
<button className="quiet" type="button" onClick={async () => {
|
||||
try { await navigator.clipboard.writeText(endpoint); setNotice('MCP-Adresse wurde kopiert.'); }
|
||||
|
||||
+86
-148
@@ -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' && (
|
||||
<>
|
||||
|
||||
+15
-2
@@ -1,7 +1,20 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
export const errorText = (error: unknown) =>
|
||||
error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
import { ApiError } from './api';
|
||||
|
||||
export function errorText(error: unknown) {
|
||||
if (error instanceof ApiError) {
|
||||
if (error.code === 'SCRIPT_ACTION_REQUIRED')
|
||||
return 'Diese frühere Aktionsart ist stillgelegt. Erstellen Sie einen Skriptauftrag.';
|
||||
if (error.code === 'SCRIPT_HELPER_SCOPE_DENIED')
|
||||
return 'Die zentrale Richtlinie erlaubt dieses Administratorskript für das gewählte Konto, Gerät oder den Skriptinhalt nicht.';
|
||||
if (error.code === 'MANAGED_SCRIPT_POLICY_INVALID')
|
||||
return 'Der Server konnte die hinterlegte Richtlinie für Administratorskripte nicht bestätigen.';
|
||||
if (error.code === 'SCRIPT_HELPER_BINDING_INVALID')
|
||||
return 'Der Server kann die gemeldete Agentversion und den zugehörigen Administrator-Helper für dieses Gerät nicht bestätigen.';
|
||||
}
|
||||
return error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
}
|
||||
export function ErrorBox({ error }: { error: string | null }) {
|
||||
return error ? (
|
||||
<div role="alert" className="error">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { actions, PlanInput, Session, request, session, windowsMsi, windowsMsiManifest, validateInput } from './api';
|
||||
import { adminIntent, allowed, availableActions, windowsMsiPlanJobs, windowsMsiApprovalBlockers, verifyWindowsMsiManifest, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { PlanInput, Session, request, session, windowsMsi, windowsMsiManifest, validateInput } from './api';
|
||||
import { adminIntent, allowed, windowsMsiPlanJobs, windowsMsiApprovalBlockers, verifyWindowsMsiManifest, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
@@ -115,9 +115,7 @@ describe('root and dedicated dev-test APT actions', () => {
|
||||
await expect(verifyPlanIntegrity({ plan_payload_bytes: Array.from(shellRaw), plan_hash: await sha256(shellRaw) })).rejects.toThrow();
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, execution_identity: 'root' } }, systemAuth)).rejects.toThrow('root:execute');
|
||||
});
|
||||
it('shows native acceptance only with explicit server simulation evidence, never upgrades identity', async () => {
|
||||
expect(availableActions(auth, actions)).toContain('apt_native_acceptance');
|
||||
expect(availableActions({ ...auth, principal: { ...auth.principal, simulated: false } }, actions)).not.toContain('apt_native_acceptance');
|
||||
it('validates the explicit simulation and root identity of historical native acceptance input', async () => {
|
||||
const value = input(await manifest());
|
||||
await validateSensitiveInput(value, auth); expect(value.parameters.execution_identity).toBe('root');
|
||||
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, execution_identity: 'agent_service' } }, auth)).rejects.toThrow('root');
|
||||
|
||||
+2
-3
@@ -1,4 +1,4 @@
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, validateWindowsReboot, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api';
|
||||
import { PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, validateWindowsReboot, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api';
|
||||
import { validateAgentUpdateAction } from './agent-updates';
|
||||
|
||||
import { bytes, hashPattern, parseStrictJson, sha256 } from './plan-bytes';
|
||||
@@ -6,10 +6,9 @@ import { verifyScriptPlan } from './script-console';
|
||||
export { bytes, hashPattern, parseStrictJson, sha256 } from './plan-bytes';
|
||||
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
|
||||
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst (running/stopped) oder eigenes festes MSI-Rezept. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
|
||||
export const fullMaintenanceWarning = 'VOLLE HOSTWARTUNG · full_maintenance_v1: Das genehmigte Skript läuft als root/SYSTEM mit vollständiger Hostautorität, einschließlich Netzwerk, Dateisystem und Diensten. Es kann auch Agent, PKI und Schutzmechanismen ändern oder einen Neustart auslösen. Keine Sandbox- oder No-Reboot-Zusage. scripts:execute plus root:execute/system:execute, lokaler und zentraler Opt-in, passende Capability, unabhängiger Helper und konkrete WebUI-Genehmigung bleiben erforderlich.';
|
||||
export const adminScriptWarning = 'Das Skript erhält volle Administratorrechte. Es kann Dateien, Dienste, den Agenten und Gerätezertifikate ändern sowie das Gerät neu starten.';
|
||||
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
|
||||
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
|
||||
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
|
||||
|
||||
function exact(r: RecordValue, fields: string[]) { if (Object.keys(r).some(k => !fields.includes(k)) || fields.some(k => !(k in r))) throw new Error('Schemafelder fehlen oder sind unbekannt'); }
|
||||
function hash(v: unknown) { if (typeof v !== 'string' || !hashPattern.test(v) || /^0{64}$/.test(v)) throw new Error('Exakter SHA-256 fehlt/Platzhalter'); }
|
||||
|
||||
@@ -113,7 +113,7 @@ it('shows full fixed script/profile/identities before approval and has no approv
|
||||
const p = plan('windows_system_full'); expect(renderToStaticMarkup(<ScriptPlanNotice plan={p}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(p); await verifyScriptPlan(p);
|
||||
const html = renderToStaticMarkup(<ScriptPlanNotice plan={p}/>), view = scriptPlanJobs(p)[0]!;
|
||||
for (const value of ['full_maintenance_v1', 'system', 'powershell', 'RemoteSigned', 'SYSTEM stdout', 'SYSTEM stderr', '\\u000d', view.assetId, view.jobId, view.attemptId, view.scriptHash, view.jobHash, '30s', '4096', 'Keine Sandbox- oder No-Reboot-Zusage', 'Agent, PKI']) expect(html).toContain(value);
|
||||
for (const value of ['full_maintenance_v1', 'system', 'powershell', 'RemoteSigned', 'SYSTEM stdout', 'SYSTEM stderr', '\\u000d', view.assetId, view.jobId, view.attemptId, view.scriptHash, view.jobHash, '30s', '4096', 'volle Administratorrechte', 'Gerätezertifikate', 'das Gerät neu starten']) expect(html).toContain(value);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user