Separate script publishing, job assignment and interactive approval in the WebUI

This commit is contained in:
2026-11-17 22:42:31 +01:00
parent 2100e6a4ce
commit 477a63f20e
13 changed files with 1027 additions and 294 deletions
+87
View File
@@ -0,0 +1,87 @@
import { test, expect } from '../../web/node_modules/@playwright/test/index.js';
import { createServer, type ViteDevServer } from '../../web/node_modules/vite/dist/node/index.js';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { createHash } from 'node:crypto';
let server: ViteDevServer;
let origin: string;
test.beforeAll(async () => {
server = await createServer({ root: resolve(__dirname,'../../web'), configFile:false, server:{host:'127.0.0.1', port:0}, logLevel:'silent' });
await server.listen();
const address = server.httpServer!.address();
if (!address || typeof address === 'string') throw new Error('Lokaler Testserver fehlt');
origin = 'http://127.0.0.1:' + address.port;
});
test.afterAll(async () => { await server?.close(); });
test('reviews the fixed MCP request, rejects it once and blocks a changed hash', async ({page}) => {
const cases = JSON.parse(readFileSync(resolve(__dirname,'../script_console/codec-golden.json'),'utf8'));
const saved = JSON.parse(Buffer.from(cases.find((entry: {name: string}) => entry.name === 'legacy_linux_agent').plan_payload_bytes).toString('utf8'));
const job = saved.jobs[0], payload = job.payload;
const created = new Date().toISOString(), expires = new Date(Date.now() + 60000).toISOString();
payload.not_before = created; payload.start_before = expires;
const hash = (data: string) => createHash('sha256').update(data).digest('hex');
job.job_payload_hash = hash(JSON.stringify(payload));
saved.principal = 'mcp:example:readonly-client'; saved.reason = 'Linux-Version prüfen';
const raw = JSON.stringify(saved);
const key = hash(raw);
const customer = { tenant_id:saved.tenant_id, name:'Werkstatt' };
const other = { tenant_id:'aaaaaaa0-0000-0000-0000-000000000000', name:'Nur Inventar' };
const target = {asset_id:payload.asset_id,agent_id:payload.agent_id};
const summary = { title:'Freies Skript', action:'run_script', requester:saved.principal, reason:saved.reason, ...customer,
customer_name:customer.name, plan_id:saved.plan_id, operation_id:'22222222-2222-4222-8222-222222222222',
targets:[{...target,hostname:'WERK-LINUX'}], created_at:created, jobs:[], job_count:0, execution_state:null };
const path = '/api/v1/tenants/'+saved.tenant_id;
let approval = 'pending_approval', corrupt = false, rights = true;
const decisions: unknown[] = [];
const listing = (items: unknown[]) => ({items,next_cursor:null,completeness:'complete',truncated:false,as_of:created});
await page.route(origin+'/auth/config', r => r.fulfill({json:{dev_login_enabled:true,local_login_enabled:false,oidc_configured:false,oidc_login_url:null}}));
await page.route(origin+'/auth/session', r => r.fulfill({json:{principal:'Marta',testsimulation:true,csrf_token:'fixture',tenant_id:customer.tenant_id,permissions:['inventory:read','operations:read','plans:approve','scripts:execute']}}));
await page.route(origin+'/api/v1/**', async route => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === '/api/v1/tenants') return route.fulfill({json:listing([customer,other])});
if (url.pathname === '/api/v1/approvals') {
const pending = approval === 'pending_approval';
const visible = rights && !url.searchParams.has('count_only') && (url.searchParams.get('status') === 'pending') === pending;
return route.fulfill({json:{...listing(visible ? [{...summary,approval_state:approval}]:[]), customers:rights?[customer]:[],
can_review:rights,pending_count:rights && pending?1:0}});
}
if (url.pathname === path+'/operation-plans/'+saved.plan_id) return route.fulfill({json:{
...summary, plan_payload:saved, payload:saved, plan_hash:corrupt?'f'.repeat(64):key,plan_payload_bytes:[...Buffer.from(raw)],
resolved_targets:[target], excluded_targets:[], jobs:[{...job,...target,job_id:payload.job_id,attempt_id:payload.attempt_id}],
expires_at:expires, approval_state:approval, authorization_status:'required'
}});
if (url.pathname === path+'/operation-plans/'+saved.plan_id+'/authorizations' && req.method() === 'POST') {
decisions.push(req.postDataJSON()); approval='rejected';
return route.fulfill({json:{...summary,approval_state:approval}});
}
if (url.pathname === path+'/operations/'+summary.operation_id) return route.fulfill({json:{...summary,approval_state:approval}});
return route.fulfill({status:404,json:{code:'UNEXPECTED_FIXTURE_REQUEST'}});
});
await page.goto(origin+'/#genehmigungen');
const inbox = page.getByRole('region',{name:'Genehmigungseingang'});
await expect(inbox.getByRole('option',{name:other.name})).toHaveCount(0);
await inbox.getByRole('button',{name:'Freies Skript'}).click();
await expect(page.locator('.review-targets')).toContainText('WERK-LINUX');
await expect(page.getByLabel('Vollständiger Skripttext')).toHaveText(payload.action.script_utf8);
const reject = page.getByRole('button',{name:'SIMULIERT: Ablehnen',exact:true});
await expect(reject).toBeDisabled();
await page.getByRole('checkbox',{name:'Ich habe die Geräte',exact:false}).check();
await expect(page.getByRole('button',{name:'SIMULIERT: Genehmigen',exact:true})).toBeEnabled();
await reject.click();
await expect(page.locator('section[data-operation-id] .order-status')).toHaveText('Abgelehnt');
expect(decisions).toEqual([{plan_hash:key,decision:'reject'}]);
await page.getByRole('link',{name:/^Genehmigungen/}).click();
await expect(inbox.getByText('Keine offenen Genehmigungen.')).toBeVisible();
await inbox.getByRole('button',{name:'Verlauf'}).click();
await inbox.getByRole('button',{name:'Freies Skript'}).click();
await expect(page.locator('section[data-plan-id] .order-status')).toHaveText('Abgelehnt');
await expect(reject).toHaveCount(0);
corrupt=true; approval='pending_approval'; await page.reload();
await expect(page.getByRole('alert')).toContainText('Planhash');
await expect(page.getByRole('checkbox',{name:'Ich habe die Geräte',exact:false})).toHaveCount(0);
rights=false; await page.goto(origin+'/#genehmigungen');
await expect(inbox.getByText('Dieses Konto hat keine Berechtigung für Genehmigungen.')).toBeVisible();
expect(decisions).toHaveLength(1);
});
+51
View File
@@ -0,0 +1,51 @@
import { useState } from 'react';
import { page, record, request, objectId, tenant, type Tenant } from './api';
import { ErrorBox, useResource } from './resource';
import { OrderRows, PageButtons } from './order-presentation';
function count(value: unknown) {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) throw new Error('Anzahl offener Anträge fehlt.');
return value;
}
export function usePendingApprovals(enabled: boolean, revision = 0) {
const resource = useResource(async signal => {
if (!enabled) return null;
const result = record(await request('/api/v1/approvals?count_only=true', { signal }));
return result.can_review === true ? count(result.pending_count) : null;
}, [enabled, revision], enabled);
return resource.error ? null : resource.data;
}
export function ApprovalInbox({ open }: { customers?: Tenant[]; open: (tenantId: string, planId: string) => void }) {
const [view, setView] = useState<'pending'|'history'>('pending');
const [customer, setCustomer] = useState('');
const [pages, setPages] = useState<string[]>([]);
const cursor = pages[pages.length-1];
const list = useResource(async signal => {
const params = new URLSearchParams({ status: view, limit: '30' });
if (customer) params.set('tenant_id', customer);
if (cursor) params.set('cursor', cursor);
const result = record(await request('/api/v1/approvals?' + params, { signal }));
if (typeof result.can_review !== 'boolean' || !Array.isArray(result.customers)) throw new Error('Der Server konnte die Kundenberechtigungen nicht ausweisen.');
return { ...page(result), canReview: result.can_review, customers: result.customers.map(tenant) };
}, [view, customer, cursor], true);
if (list.error) return <section aria-label="Genehmigungseingang"><ErrorBox error={list.error}/>{customer && <button className="quiet" onClick={() => {setCustomer(''); setPages([]);}}>Alle berechtigten Kunden anzeigen</button>}</section>;
if (list.data && !list.data.canReview) return <section aria-label="Genehmigungseingang"><p>Dieses Konto hat keine Berechtigung für Genehmigungen.</p></section>;
return <section aria-label="Genehmigungseingang" className="fleet">
<div className="fleet-tabs">
{(['pending','history'] as const).map(v => <button key={v} aria-pressed={view === v} onClick={() => {setView(v); setPages([]);}}>
{v === 'pending' ? 'Offen' : 'Verlauf'}
</button>)}
</div>
<div className="filters"><label>Kunde<select aria-label="Kunde im Genehmigungseingang" value={customer}
onChange={e => { setCustomer(e.target.value); setPages([]); }}>
<option value="">Alle berechtigten Kunden</option>
{list.data?.customers.map(c => <option key={c.tenant_id} value={c.tenant_id}>{c.name}</option>)}
</select></label></div>
<ErrorBox error={list.error}/>
{!list.data && !list.error && <p className="list-message">Anträge werden geladen …</p>}
{list.data && (!!list.data.items.length
? <OrderRows items={list.data.items} decisionList open={row => open(objectId(row,'tenant'), objectId(row,'plan'))}/>
: <p className="list-message">{view === 'pending' ? 'Keine offenen Genehmigungen.' : 'Keine abgeschlossenen Anträge.'}</p>)}
{list.data && <PageButtons pages={pages} next={list.data.next_cursor} change={setPages}/>}
</section>;
}
+3 -3
View File
@@ -9,7 +9,7 @@ it('renders hostile output as inert text, reports real status and preserves exac
const hostile = '<script>fetch("/approve")</script>\r\n\x1b[2J\u202eapprove', raw = Array.from(new TextEncoder().encode(hostile));
const job = { state: 'unknown', attempt_id: 'fixed-attempt', revision: 4, cancel_requested: true, result: { stdout: raw, stderr: [], exit_code: null, error_code: 'TIMEOUT', output_truncated: true, reboot_required: false } };
const before = JSON.stringify(job), html = renderToStaticMarkup(<ConsoleOutput job={job}/>);
for (const expected of ['unknown', 'fixed-attempt', 'TIMEOUT', 'unknown / nicht gemeldet', 'nur ein Ausschnitt', 'keinen Live-Ausgabestream', 'Abbruch angefordert', 'neuen genehmigten Plan', '&lt;script&gt;', '\\u000d', '\\u001b', '\\u202e', JSON.stringify(raw)]) expect(html).toContain(expected);
for (const expected of ['unknown', 'fixed-attempt', 'TIMEOUT', 'Nicht gemeldet', 'nur ein Ausschnitt', 'gespeicherte Ausgabe', 'Abbruch angefordert', 'neuen genehmigten Plan', '&lt;script&gt;', '\\u000d', '\\u001b', '\\u202e', JSON.stringify(raw)]) expect(html).toContain(expected);
expect(html).not.toMatch(/<(script|img|iframe|form|input)\b/i);
expect(html).not.toContain('onclick='); expect(fetch).not.toHaveBeenCalled(); expect(JSON.stringify(job)).toBe(before);
} finally { vi.unstubAllGlobals(); }
@@ -34,8 +34,8 @@ it('shows unknown restart state for an incomplete Windows Update summary', () =>
}};
return renderToStaticMarkup(<ConsoleOutput job={{ result }}/>);
}
expect(rendered(windowsUpdateScriptHash)).toContain('Neustartbedarf: unknown');
expect(rendered('ordinary script')).toContain('Neustartbedarf: false');
expect(rendered(windowsUpdateScriptHash)).toContain('Neustartbedarf unbekannt');
expect(rendered('ordinary script')).not.toContain('Neustartbedarf unbekannt');
});
+32 -20
View File
@@ -42,26 +42,31 @@ function OutputChannel({ value, name, nativePowerShell }: { value: unknown; name
const [selected, setSelected] = useState<'auto' | 'utf-8' | 'cp850'>('auto');
try {
const raw = outputBytes(value), view = outputText(raw, selected === 'auto' ? nativePowerShell ? 'powershell' : 'utf-8' : selected);
return <div><h4>{name} · {raw.length} gespeicherte Bytes</h4><p className="muted">{view.encoding}. Steuerzeichen werden sichtbar als \\uXXXX dargestellt; Rohbytes bleiben erhalten.</p>
<label>{name} Textdekodierung<select aria-label={`${name} Textdekodierung`} value={selected} onChange={event => setSelected(event.target.value as typeof selected)}>
<option value="auto">{nativePowerShell ? 'Automatisch · UTF-8, sonst CP850' : 'Automatisch · UTF-8'}</option>
<option value="utf-8">UTF-8</option><option value="cp850">Windows OEM 850 (CP850)</option>
</select></label>
<pre className="console-output" aria-label={`${name} Textansicht`}>{raw.length ? view.text : '(leere Ausgabe)'}</pre>
<button type="button" onClick={() => download(raw, name)}>{name} als unveränderte Rohbytes herunterladen</button>
<details><summary>{name} Originalbytes (dezimal)</summary><pre>{JSON.stringify(Array.from(raw))}</pre></details>
return <div><h4>{name === 'stdout' ? 'Standardausgabe' : 'Fehlerausgabe'}</h4>
<pre className="console-output" aria-label={name + ' Textansicht'}>{raw.length ? view.text : '(leere Ausgabe)'}</pre>
<details><summary>Zeichensatz und Download · {name}</summary>
<label>{name} Textdekodierung<select aria-label={name + ' Textdekodierung'} value={selected} onChange={event => setSelected(event.target.value as typeof selected)}>
<option value="auto">{nativePowerShell ? 'Automatisch · UTF-8, sonst CP850' : 'Automatisch · UTF-8'}</option>
<option value="utf-8">UTF-8</option><option value="cp850">Windows OEM 850 (CP850)</option>
</select></label>
<p className="muted">{view.encoding}. Steuerzeichen erscheinen als {'\\uXXXX'}.</p>
<button className="quiet" type="button" onClick={() => download(raw, name)}>{name} als unveränderte Rohbytes herunterladen</button>
<details><summary>{name} Originalbytes (dezimal)</summary><pre>{JSON.stringify(Array.from(raw))}</pre></details>
</details>
</div>;
} catch (error) { return <p role="alert" className="error">{name}: {error instanceof Error ? error.message : 'Ausgabe nicht lesbar'}. Keine verlässliche Textansicht.</p>; }
}
export function ConsoleOutput({ job }: { job: RecordValue }) {
const state = stringField(job, 'state');
return <section aria-label="Gespeichertes Konsolenergebnis"><h3>Konsolenergebnis</h3>
<p role="status">Zustand: <strong>{state}</strong> · Versuch: {stringField(job, 'attempt_id')} · Revision: {typeof job.revision === 'number' ? job.revision : 'unknown'}</p>
<p>Die Ansicht fragt den gespeicherten Zustand alle 4 Sekunden ab. stdout/stderr erscheinen nach Eingang des Ergebnisses; es gibt keinen Live-Ausgabestream.</p>
{state === 'unknown' && <p className="warning">Wirkung oder Ergebnis unklar. Keine automatische Wiederholung; ein neuer Versuch benötigt Abgleich und einen neuen genehmigten Plan.</p>}
{job.cancel_requested === true && <p className="warning">Abbruch angefordert; dies bestätigt weder Prozessende noch Rollback.</p>}
{state === 'unknown' && <p className="warning">Wirkung unklar. Ein weiterer Versuch benötigt einen Abgleich und einen neuen genehmigten Plan.</p>}
{job.cancel_requested === true && <p className="warning">Abbruch angefordert. Die Rückmeldung des Geräts steht aus.</p>}
{job.pending_reason != null && <p>Wartegrund: {String(job.pending_reason)}</p>}
{job.result == null ? <p>Noch kein gespeichertes Ergebnis. Fehlende Ausgabe ist kein Erfolgsnachweis.</p> : <Result key={`${stringField(job, 'job_id')}/${stringField(job, 'attempt_id')}`} value={job.result}/>}
{job.result == null ? <p>Noch kein gespeichertes Ergebnis.</p> : <Result key={stringField(job,'job_id')+'/'+stringField(job,'attempt_id')} value={job.result}/>}
<details><summary>Versuch und Datenstand</summary>
<p>Zustand {state} · Versuch {stringField(job,'attempt_id')} · Revision {typeof job.revision === 'number' ? job.revision : 'unbekannt'}.</p>
<p>Die Ansicht zeigt die gespeicherte Ausgabe und aktualisiert den Stand alle vier Sekunden.</p>
</details>
</section>;
}
function Result({ value }: { value: unknown }) {
@@ -69,11 +74,18 @@ function Result({ value }: { value: unknown }) {
const result = record(value, 'Jobergebnis');
const evidence = result.evidence && typeof result.evidence === 'object' && !Array.isArray(result.evidence) ? record(result.evidence) : {};
const nativePowerShell = evidence.interpreter === 'powershell' && evidence.output_encoding === 'raw_native_bytes';
const reboot = evidence.script_sha256 === windowsUpdateScriptHash && Object.hasOwn(evidence, 'windows_update_reboot_required') ? evidence.windows_update_reboot_required : result.reboot_required;
return <><p>Exitcode: {typeof result.exit_code === 'number' && Number.isInteger(result.exit_code) ? result.exit_code : 'unknown / nicht gemeldet'} · Fehlercode: {typeof result.error_code === 'string' && result.error_code ? result.error_code : 'nicht gemeldet'}</p>
<p className={result.output_truncated === false ? 'muted' : 'warning'}>Ausgabe begrenzt: {typeof result.output_truncated === 'boolean' ? String(result.output_truncated) : 'unknown'}. {result.output_truncated === true ? 'Die gespeicherten Bytes sind nur ein Ausschnitt.' : result.output_truncated !== false ? 'Vollständigkeit ist nicht bestätigt.' : 'Keine Trunkierung gemeldet.'}</p>
<p>Neustartbedarf: {typeof reboot === 'boolean' ? String(reboot) : 'unknown'}. Ein Exitcode 0 bestätigt Prozessabschluss; fachliche Nachbedingungen stehen im vollständigen Ergebnis.</p>
<p>Ausgabe ist nicht vertrauenswürdiger Text vom Zielgerät. Sie erteilt keine Genehmigung und wird nicht als Anweisung ausgeführt.</p>
<OutputChannel name="stdout" value={result.stdout} nativePowerShell={nativePowerShell}/><OutputChannel name="stderr" value={result.stderr} nativePowerShell={nativePowerShell}/></>;
} catch { return <p className="error" role="alert">Ergebnisformat unbekannt; vollständige Originaldaten stehen darunter.</p>; }
const windowsUpdate = evidence.script_sha256 === windowsUpdateScriptHash;
const reboot = windowsUpdate && Object.hasOwn(evidence, 'windows_update_reboot_required') ? evidence.windows_update_reboot_required : result.reboot_required;
const exit = typeof result.exit_code === 'number' && Number.isInteger(result.exit_code) ? String(result.exit_code) : 'Nicht gemeldet';
return <>
<p><strong>Exitcode {exit}</strong>{typeof result.error_code === 'string' && result.error_code && ' · Fehlercode '+result.error_code}</p>
{reboot === true && <p className="warning">Ein Neustart ist erforderlich.</p>}
{windowsUpdate && reboot == null && <p className="warning">Neustartbedarf unbekannt.</p>}
{windowsUpdate && reboot === false && <p>Das Gerät meldet keinen Neustartbedarf.</p>}
{result.output_truncated === true && <p className="warning">Die gespeicherte Ausgabe ist nur ein Ausschnitt.</p>}
{typeof result.output_truncated !== 'boolean' && <p className="muted">Vollständigkeit ist nicht bestätigt.</p>}
<OutputChannel name="stdout" value={result.stdout} nativePowerShell={nativePowerShell}/>
<OutputChannel name="stderr" value={result.stderr} nativePowerShell={nativePowerShell}/>
</>;
} catch { return <p className="error" role="alert">Unbekanntes Ergebnisformat. Die Originaldaten stehen unter „Technische Ausführungsdaten“.</p>; }
}
+3 -3
View File
@@ -105,7 +105,7 @@ type Props = {
onFilter: (id: string) => void;
selection: Target;
onSelection: (s: Target) => void;
onScripts: () => void;
onCreateOrder: () => void;
onEnroll: () => void;
onOperation: (customer: string, id: string) => void;
};
@@ -298,7 +298,7 @@ export function Devices({
selection,
onSelection,
onEnroll,
onScripts,
onCreateOrder,
onOperation
}: Props) {
const [search, setSearch] = useState(''),
@@ -596,7 +596,7 @@ export function Devices({
<button className="quiet" onClick={() => onSelection({ customer: '', ids: [] })}>
Auswahl aufheben
</button>
<button onClick={onScripts}>Skript auswählen</button>
<button disabled={!allowed(auth, 'operations:plan')} onClick={onCreateOrder}>Auftrag erstellen</button>
</div>
)}
</>
+290 -161
View File
@@ -1,7 +1,10 @@
import { actionTitle, deviceName, display, Fact, identityName, OrderRows, orderTitle, PageButtons, Requester, Status, statusOf, targets, when } from './order-presentation';
import { Devices } from './devices';
import { CustomerManagement } from './customer-management';
import { ErrorBox, useResource, errorText } from './resource';
import { NavIcon, type NavKey } from './navigation';
import { OrderComposer } from './order-composer';
import { ApprovalInbox, usePendingApprovals } from './approval-inbox';
import { ScriptLibrary } from './script-library';
import { McpTokenManagement } from './mcp-token-management';
import React, { useEffect, useState } from 'react';
@@ -15,7 +18,7 @@ import { ConsoleOutput, outputText } from './console-output';
import { scriptApprovalBlockers, scriptPlanJobs, verifyScriptPlan } from './script-console';
import { agentUpdateWarning, agentUpdatePlanJobs, agentUpdateApprovalBlockers, verifyAgentUpdatePlan, verifyReleaseMetadata, releaseEnvelope, uploadAgentUpdateArtifact } from './agent-updates';
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre aria-label={label}>{pretty(value)}</pre></details>; }
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details><summary>{label}</summary><pre aria-label={label}>{pretty(value)}</pre></details>; }
export function AgentUpdatePlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = agentUpdatePlanJobs(plan); if (!jobs.length) return null;
@@ -31,20 +34,41 @@ export function AgentUpdatePlanNotice({ plan }: { plan: RecordValue }) {
}
export function ScriptPlanNotice({ plan }: { plan: RecordValue }) {
try {
const jobs = scriptPlanJobs(plan); if (!jobs.length) return null;
return <article aria-label="Feste Skriptkonsole vor Genehmigung"><h3>Vollständige feste Skriptaufträge ({jobs.length})</h3><p>Diese Inhalte stammen aus den hashgeprüften gespeicherten Planbytes. Jeder Zielauftrag, Versuch und Skripthash ist fest gebunden.</p>
{jobs.map(job => <article key={job.jobId}><h4>Asset {job.assetId}</h4><p>Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId}</p>
{job.revision && <p>Skriptbibliothek · <strong>{job.revision.name} · Version {job.revision.version}</strong> · {job.revision.id}</p>}
<p>Interpreter: {job.interpreter} · Identität: <strong>{job.identity}</strong> · Privilegiertes Profil: <strong>{job.privilegedProfile === fullMaintenanceScriptProfile ? fullMaintenanceScriptProfile : 'bestehendes begrenztes Profil'}</strong> · Windowsprozess: {job.interpreter !== 'powershell' ? 'nicht zutreffend' : job.windowsProfile === 'powershell_51_remote_signed' ? 'Windows PowerShell5.1 RemoteSigned, nur Jobprozess' : 'geerbte Windowsrichtlinie / kein Windows-Prozessoverride'}</p>
<p>Frühester Start: {job.notBefore} · Startfrist: {job.startBefore} · Laufzeit: {job.runtimeSeconds}s · Ausgabe: höchstens {job.outputBytes} Bytes</p>
<p>Skript: {job.scriptBytes} UTF-8-Bytes · SHA256: <code>{job.scriptHash}</code><br/>Jobpayload-SHA256: <code>{job.jobHash}</code></p>
{job.privilegedProfile === fullMaintenanceScriptProfile ? <p className="warning">{fullMaintenanceWarning}</p> : job.identity === 'root' && <p className="warning">{rootWarning}</p>}
<p>Vollständiger Skripttext; Steuerzeichen, BOM und CR werden sichtbar als \uXXXX dargestellt. LF bleibt Zeilenumbruch. Kein Kürzen oder Normalisieren der gespeicherten Bytes.</p>
<pre aria-label={`Vollständiges Skript für ${job.assetId}`}>{outputText(new TextEncoder().encode(job.script)).text}</pre>
<p>Feste Argumente (JSON): <code>{JSON.stringify(job.arguments)}</code></p><p>stdout-Nachbedingung (JSON): <code>{JSON.stringify(job.expectedStdout)}</code>{job.expectedStdout === null && ' · keine zusätzliche fachliche stdout-Prüfung gebunden'}</p>
</article>)}
const jobs = scriptPlanJobs(plan);
if (!jobs.length) return null;
const grouped = new Map<string, typeof jobs>();
for (const job of jobs) {
const key = JSON.stringify([job.scriptHash, job.interpreter, job.identity, job.windowsProfile, job.privilegedProfile,
job.arguments, job.expectedStdout, job.notBefore, job.startBefore, job.runtimeSeconds, job.outputBytes]);
const group = grouped.get(key);
if (group) group.push(job); else grouped.set(key,[job]);
}
const names = targets(plan);
return <article aria-label="Skriptinhalt"><h3>Skriptinhalt</h3>
{[...grouped.values()].map(group => {
const job = group[0]!;
return <article key={job.jobId}>
{grouped.size > 1 && <h4>{group.map(j => {
const target = names.find(t => t.asset_id === j.assetId && t.agent_id === j.agentId);
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.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">{outputText(new TextEncoder().encode(job.script)).text}</pre>
{job.arguments.length > 0 && <p>Argumente <code>{JSON.stringify(job.arguments)}</code></p>}
{job.expectedStdout !== null && <p>Erwartete Ausgabe <code>{JSON.stringify(job.expectedStdout)}</code></p>}
<details><summary>Ausführungsdetails und Prüfsummen</summary>
<p>{job.scriptBytes} Byte · SHA256 <code>{job.scriptHash}</code></p>
<p>Profil {job.privilegedProfile} · {job.identity} · Laufzeit {job.runtimeSeconds}s · Ausgabe bis {job.outputBytes} Byte</p>
{group.map(j => <div key={j.jobId}><p>Gerät <code>{j.assetId}</code> · Agent <code>{j.agentId}</code></p>
<p>Job <code>{j.jobId}</code> · Versuch <code>{j.attemptId}</code> · SHA256 <code>{j.jobHash}</code></p></div>)}
</details>
</article>;
})}
</article>;
} catch { return <aside role="alert" className="error">Skriptplan ist nicht vollständig aus unveränderten gespeicherten Bytes verifiziert. Keine Genehmigung möglich.</aside>; }
} catch { return <aside role="alert" className="error">Die gespeicherten Skriptbytes konnten nicht verifiziert werden.</aside>; }
}
export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
let jobs: RecordValue[];
@@ -146,11 +170,8 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session
</section>;
}
function AgentReleaseCatalog({ tenantId, auth, customerName, enrollmentOpen }: { tenantId: string; auth: Session; customerName: string; enrollmentOpen: boolean }) {
function AgentReleaseCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
const [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [receipts, setReceipts] = useState<unknown[]>([]);
const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null; platforms: string[] } | null>(null);
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
const [issuing, setIssuing] = useState(false);
const list = useResource(async signal => {
const result = page(await request(tenantPath(tenantId, `/agent-releases${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal }));
const items: RecordValue[] = [];
@@ -176,8 +197,14 @@ function AgentReleaseCatalog({ tenantId, auth, customerName, enrollmentOpen }: {
<button disabled={busy || !allowed(auth, 'catalog:write')}>Release für Clients veröffentlichen</button><ErrorBox error={error}/>{receipts.length > 0 && <JsonView value={receipts} label="Tatsächliche Teilimport- und Veröffentlichungsbelege"/>}
</form>
</details>
<details open={enrollmentOpen || undefined} onToggle={event => { if (!event.currentTarget.open) setEnrollment(null); }}>
<summary>Neues Gerät aufnehmen</summary>
</section>;
}
function DeviceEnrollment({ tenantId, auth, customerName }: { tenantId: string; auth: Session; customerName: string }) {
const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null; platforms: string[] } | null>(null);
const [enrollmentError, setEnrollmentError] = useState<string | null>(null);
const [issuing, setIssuing] = useState(false);
return <section aria-label="Gerät aufnehmen"><h2>Gerät aufnehmen</h2>
<p>Das HTTPS-Installationsskript fragt auf dem Gerät nach dem Einmalcode. Er gilt für <strong>{customerName}</strong> und läuft nach 15 Minuten ab.</p>
<button disabled={issuing || !allowed(auth, 'devices:enroll')} onClick={async () => {
setIssuing(true); setEnrollment(null); setEnrollmentError(null);
@@ -196,56 +223,194 @@ function AgentReleaseCatalog({ tenantId, auth, customerName, enrollmentOpen }: {
<pre>{`Invoke-WebRequest -UseBasicParsing '${enrollment.origin}/install/windows.ps1' -OutFile .\\windows.ps1
.\\windows.ps1 -BootstrapBase '${enrollment.origin}' -Platform '${platform}'`}</pre></div>)}
</>}
</details>
</section>;
}
function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id: string; auth: Session; onOperation: (id: string) => void }) {
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); await verifyScriptPlan(result); await verifyAgentUpdatePlan(result); return result; }, [tenantId, id]);
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [confirmed, setConfirmed] = useState(false), [submitted, setSubmitted] = useState(false), [pending, setPending] = useState(false);
const [idempotency] = useState(() => crypto.randomUUID());
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data), ...agentUpdateApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); await verifyScriptPlan(plan.data); await verifyAgentUpdatePlan(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data), ...scriptApprovalBlockers(plan.data), ...agentUpdateApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
<AgentUpdatePlanNotice plan={plan.data}/><ScriptPlanNotice plan={plan.data}/>
<SystemPlanNotice plan={plan.data}/>
<WindowsRebootPlanNotice plan={plan.data}/>
<WindowsMsiPlanNotice plan={plan.data}/>
<PowerShellPlanNotice plan={plan.data}/>
<QueryLogsPlanNotice plan={plan.data}/>
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews, Ausführungsprofile/Prozessumfänge und Auswirkungen dieses Plans geprüft.</label>
<button className="danger" disabled={!confirmed || busy || !!plan.error || blockers.length > 0 || !(pending || plan.data.approval_state === 'pending_approval')} onClick={async () => { setBusy(true); setError(null); try {
await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen' : 'Diesen festen Plan ausdrücklich genehmigen'}</button>
<p>Nur für einen bestehenden Antrag pending_approval; Server prüft interaktive Sitzung, Rechte, Tenant, Policy und Frist erneut. Keine automatische Genehmigung.</p>
<AdminControl auth={auth} path={tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/revocation`)} permission="plans:revoke" title="Planberechtigung widerrufen" warning="Sperrt neue Starts dieses Plans; laufende Wirkungen folgen sicheren Abbruchregeln, kein Rollback. Ein widerrufener Antrag wird nicht reaktiviert." done={plan.reload}/>
</>}</section>;
async function verifyReview(plan: RecordValue, tenantId: string, id: string) {
await verifyPlanIntegrity(plan);
await verifyScriptPlan(plan);
await verifyAgentUpdatePlan(plan);
const saved = record(plan.plan_payload);
if (plan.plan_id !== id || saved.plan_id !== id || saved.tenant_id !== tenantId || !Array.isArray(plan.plan_payload_bytes)) {
throw new Error('Der gespeicherte Plan gehört nicht zu diesem Auftrag und Kunden.');
}
}
function Operations({ tenantId, open }: { tenantId: string; open: (id: string) => void }) {
const [cursor, setCursor] = useState<string | null>(null);
const list = useResource(async signal => page(await request(tenantPath(tenantId, `/operations${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal })), [tenantId, cursor], true);
return <section><h2>Anträge und Ausführungen</h2><ErrorBox error={list.error}/>{list.data && <><PageStatus data={list.data}/><ul>{list.data.items.map(o => <li key={objectId(o, 'operation')}><button className="link" onClick={() => open(objectId(o, 'operation'))}>{objectId(o, 'operation')}</button> · Antrag: {stringField(o, 'approval_state')} · Ausführung: {stringField(o, 'execution_state')}</li>)}</ul>{!list.data.items.length && <p>Keine sichtbaren Anträge in diesem Listenabschnitt.</p>}<button disabled={!cursor} onClick={() => setCursor(null)}>Erste Seite</button> <button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste Seite</button></>}</section>;
function reviewBlockers(plan: RecordValue) {
return [
...approvalBlockers(plan), ...powerShellApprovalBlockers(plan), ...queryLogsApprovalBlockers(plan),
...windowsMsiApprovalBlockers(plan), ...scriptApprovalBlockers(plan), ...agentUpdateApprovalBlockers(plan)
];
}
function OperationDetail({ tenantId, id, auth, openPlan }: { tenantId: string; id: string; auth: Session; openPlan: (id: string) => void }) {
const op = useResource(async signal => record(await request(tenantPath(tenantId, `/operations/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true);
function PlanDetail({ tenantId, id, auth, onOperation, customerName, mode = 'review' }: {
tenantId: string; id: string; auth: Session; onOperation: (id: string) => void;
customerName?: string; mode?: 'review' | 'submit';
}) {
const path = tenantPath(tenantId, '/operation-plans/' + encodeURIComponent(id));
const plan = useResource(async signal => {
const value = record(await request(path, { signal }));
await verifyReview(value, tenantId, id);
return value;
}, [tenantId, id], mode === 'review');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [confirmedHash, setConfirmedHash] = useState('');
const data = plan.error ? null : plan.data;
if (!data) return <section data-plan-id={id}><ErrorBox error={plan.error ?? error}/>{!plan.error && <p>Plan wird geprüft …</p>}</section>;
const saved = record(data.plan_payload);
const payloads = (saved.jobs as unknown[]).map(job => record(record(job).payload));
const first = payloads[0];
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 blockers = reviewBlockers(data);
const pending = data.approval_state === 'pending_approval';
const planHash = stringField(data,'plan_hash');
const confirmed = confirmedHash === planHash;
const mayDecide = mode === 'review' && pending && !!auth.csrf_token && allowed(auth, 'plans:approve');
const rights = new Set<string>();
payloads.forEach(p => {
const action = record(p.action).action;
if (action === 'run_script') rights.add('scripts:execute');
if (action === 'update_agent') rights.add('updates:apply');
if (p.execution_identity === 'system' || p.execution_identity === 'root') rights.add(p.execution_identity + ':execute');
});
const missingRights = [...rights].filter(permission => !allowed(auth, permission));
async function act(decision: 'submit'|'approve'|'reject') {
if (busy || !data || plan.error) return;
setBusy(true); setError(null);
try {
await verifyReview(data, tenantId, id);
if (decision !== 'reject') {
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.');
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 }
}));
setConfirmedHash('');
onOperation(objectId(result, 'operation'));
plan.reload();
} catch (e) {
setError(errorText(e)); setConfirmedHash(''); plan.reload();
} finally { setBusy(false); }
}
const names = targets(data);
const duplicateNames = new Set(names.filter((t,i) => t.hostname && names.some((other,j) => j !== i && other.hostname === t.hostname)).map(t => t.hostname));
const displayTarget = (p: RecordValue) => {
const target = names.find(t => t.asset_id === p.asset_id && t.agent_id === p.agent_id);
if (!target?.hostname) return display(p.asset_id);
return display(target.hostname) + (duplicateNames.has(target.hostname) ? ' (' + String(p.asset_id) + ')' : '');
};
return <section data-plan-id={id} className="request-review">
<h2>{title}{revision ? ' · Version '+String(revision.version) : ''}</h2>
<dl className="facts">
<Fact label="Kunde">{display(customerName, display(data.customer_name, tenantId))}</Fact>
<Fact label="Antragsteller"><Requester id={saved.principal} ownId={auth.principal.id}/></Fact>
<Fact label="Status">{data.approval_state ? <Status value={data.approval_state}/> : 'Vorbereitet'}</Fact>
<Fact label="Anlass">{display(saved.reason, 'Kein Anlass angegeben')}</Fact>
</dl>
<h3>Zielgeräte und Zeitfenster</h3>
<ul className="review-targets">{payloads.map(p => <li key={String(p.job_id)}>
<strong>{displayTarget(p)}</strong> · {identityName(p.execution_identity)}
<small>{when(p.not_before)} bis {when(p.start_before)} · Laufzeit bis {String(p.max_runtime_seconds)} s</small>
</li>)}</ul>
<p>Höchstens {String(saved.max_parallel)} gleichzeitig · Stopp nach {String(saved.halt_after_failures)} {saved.halt_after_failures === 1 ? 'Fehler' : 'Fehlern'}</p>
<AgentUpdatePlanNotice plan={data}/><ScriptPlanNotice plan={data}/>
<SystemPlanNotice plan={data}/><WindowsRebootPlanNotice plan={data}/><WindowsMsiPlanNotice plan={data}/>
{!script && <PowerShellPlanNotice plan={data}/>}<QueryLogsPlanNotice plan={data}/>
{!script && <details><summary>Aktionen je Gerät</summary>{payloads.map(p => <article key={String(p.job_id)}>
<strong>{displayTarget(p)}</strong><pre>{pretty(p.action)}</pre>
</article>)}</details>}
<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 && allowed(auth, 'operations:submit') &&
<button className="primary" disabled={busy || !!plan.error || !!blockers.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>}
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmedHash(e.target.checked ? planHash : '')}/>
Ich habe die Geräte, den Inhalt und die Ausführungsrechte geprüft.</label>
<button className="primary" disabled={!confirmed || !!blockers.length || !!missingRights.length} onClick={() => void act('approve')}>
{auth.principal.simulated ? 'SIMULIERT: Genehmigen' : 'Genehmigen'}
</button>{' '}
<button disabled={!confirmed} onClick={() => void act('reject')}>{auth.principal.simulated ? 'SIMULIERT: Ablehnen' : 'Ablehnen'}</button>
</fieldset>}
{mode === 'review' && data.approval_state === 'approved' && allowed(auth,'plans:revoke') && <details><summary>Berechtigung verwalten</summary>
<AdminControl auth={auth} path={path + '/revocation'} permission="plans:revoke" title="Planberechtigung widerrufen"
warning="Ein Widerruf sperrt neue Starts dieses Plans." done={plan.reload}/>
</details>}
</section>;
}
function Operations({ tenantId, open, customerName }: { tenantId: string; open: (id: string) => void; customerName?: string }) {
const [pages, setPages] = useState<string[]>([]);
const cursor = pages[pages.length - 1];
const list = useResource(async signal => page(await request(tenantPath(tenantId,
'/operations?sort=recent' + (cursor ? '&cursor=' + encodeURIComponent(cursor) : '')), { signal })), [tenantId, cursor], true);
if (list.error) return <ErrorBox error={list.error}/>;
return <section aria-label="Auftragsliste" className="fleet">
{!list.data && !list.error && <p className="list-message">Aufträge werden geladen …</p>}
{list.data && (list.data.items.length
? <OrderRows items={list.data.items} customerName={customerName} open={row => open(objectId(row,'operation'))}/>
: <p className="list-message">Für diesen Kunden gibt es noch keine Aufträge.</p>)}
{list.data && <PageButtons pages={pages} next={list.data.next_cursor} change={setPages}/>}
</section>;
}
function OperationDetail({ tenantId, id, auth, openPlan, customerName }: {
tenantId: string; id: string; auth: Session; openPlan: (id: string) => void; customerName?: string
}) {
const op = useResource(async signal => record(await request(tenantPath(tenantId, '/operations/' + encodeURIComponent(id)), { signal })), [tenantId, id], true);
const [jobId, setJobId] = useState<string | null>(null);
return <section><h2>Antrag / Ausführung {id}</h2><ErrorBox error={op.error}/>{op.data && <>
<p className="warning">Antrag: {stringField(op.data, 'approval_state')} · Ausführung: {stringField(op.data, 'execution_state')}. pending_approval bedeutet keine ausführbaren Jobs. Teilzustände und unknown sind kein Gesamterfolg.</p>
<button onClick={() => openPlan(objectId(op.data ?? {}, 'plan'))}>Unveränderlichen Plan zur Prüfung öffnen</button><JsonView value={op.data} label="Antrag, Zähler pro Zustand, geplante und ausführbare Jobs, Ergebnis"/>
{Array.isArray(op.data.jobs) && op.data.jobs.map(v => { const job = record(v); const jid = objectId(job, 'job'); return <button key={jid} onClick={() => setJobId(jid)}>Job {jid} · {stringField(job, 'state')}</button>; })}
</>}{jobId && <JobDetail key={jobId} tenantId={tenantId} id={jobId} auth={auth}/>}</section>;
const data = op.error ? null : op.data;
if (!data) return <section data-operation-id={id}><ErrorBox error={op.error}/>{!op.error && <p>Auftrag wird geladen …</p>}</section>;
const names = targets(data);
const jobs = Array.isArray(data.jobs) ? data.jobs.map(j => record(j)) : [];
const name = (job: RecordValue) => {
const target = names.find(t => t.asset_id === job.asset_id && t.agent_id === job.agent_id);
return target ? deviceName(target) : display(job.asset_id, 'Gerät unbekannt');
};
const selected = jobs.find(job => job.job_id === jobId);
return <section data-operation-id={id}><ErrorBox error={op.error}/><h2>{orderTitle(data)}</h2>
<dl className="facts"><Fact label="Kunde">{display(data.customer_name, customerName)}</Fact>
<Fact label="Status"><Status value={statusOf(data)}/></Fact><Fact label="Eingereicht">{when(data.created_at)}</Fact>
<Fact label="Antragsteller"><Requester id={data.requester} ownId={auth.principal.id}/></Fact>
<Fact label="Anlass">{display(data.reason, 'Kein Anlass angegeben')}</Fact></dl>
<h3>Geräte und Ergebnisse</h3>
{jobs.length ? <ul className="job-list">{jobs.map(job => <li key={objectId(job,'job')}>
<button className="link" data-job-id={job.job_id} onClick={() => setJobId(objectId(job,'job'))}>{name(job)}</button>
<Status value={job.state}/></li>)}</ul>
: <><p>{names.map(deviceName).join(', ')}</p><p className="muted">{data.approval_state === 'pending_approval'
? 'Nach der Genehmigung erscheint hier der Fortschritt je Gerät.' : 'Für diesen Auftrag liegen keine Ausführungen vor.'}</p></>}
{selected && jobId && <JobDetail key={jobId} tenantId={tenantId} id={jobId} hostname={name(selected)} auth={auth}/>}
{allowed(auth, 'plans:approve') && <button className="quiet" onClick={() => openPlan(objectId(data,'plan'))}>
{data.approval_state === 'pending_approval' ? 'Antrag prüfen' : 'Genehmigungsdetail öffnen'}
</button>}
<JsonView value={data} label="Technische Auftragsdaten"/>
</section>;
}
function JobDetail({ tenantId, id, auth }: { tenantId: string; id: string; auth: Session }) {
const job = useResource(async signal => record(await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}`), { signal })), [tenantId, id], true);
function JobDetail({ tenantId, id, auth, hostname }: { tenantId: string; id: string; auth: Session; hostname: string }) {
const job = useResource(async signal => record(await request(tenantPath(tenantId, '/jobs/'+encodeURIComponent(id)), { signal })), [tenantId, id], true);
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
return <article><h3>Job {id}</h3><ErrorBox error={job.error}/><ErrorBox error={error}/><p>verifying = Nachprüfung läuft · unknown = Wirkung unklar, kein Retry · closed_unknown = von einem Menschen abgeschlossen, Wirkung weiterhin unbekannt, kein Retry · awaiting_reboot = Neustart oder Wiederanmeldung zur Nachprüfung ausstehend. Neue Neustartjobs benötigen eine eigene Genehmigung. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <><ConsoleOutput job={job.data}/><JsonView value={job.data} label="Vollständige Originaldaten: Versuch, Zustand, Ausgabe, Trunkierung, Nachprüfungen und Ergebnis"/></>}
<form onSubmit={async e => { e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null); try { await request(tenantPath(tenantId, `/jobs/${encodeURIComponent(id)}/cancel`), { csrf: auth.csrf_token, body: { reason } }); job.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}><label>Abbruchgrund<input name="reason" required/></label><button disabled={busy}>Abbruch anfordern · nicht zurückrollen</button></form>
{job.data && stringField(job.data, 'state') === 'unknown' && <UnknownClosure tenantId={tenantId} id={id} job={job.data} auth={auth} done={job.reload}/>}</article>;
if (job.error) return <ErrorBox error={job.error}/>;
const state = job.data?.state;
const terminal = ['succeeded','failed','cancelled','expired','unknown','closed_unknown'];
return <article data-job-id={id}><h3>Ergebnis für {hostname}</h3><ErrorBox error={job.error ?? error}/>
{job.data && <><ConsoleOutput job={job.data}/><JsonView value={job.data} label="Technische Ausführungsdaten"/></>}
{job.data && allowed(auth,'jobs:cancel') && !terminal.includes(String(state)) && !job.data.cancel_requested && <details><summary>Abbruch anfordern</summary>
<form onSubmit={async e => {e.preventDefault(); const reason = new FormData(e.currentTarget).get('reason'); setBusy(true); setError(null);
try {await request(tenantPath(tenantId, '/jobs/'+encodeURIComponent(id)+'/cancel'), { csrf:auth.csrf_token, body:{reason} }); job.reload();}
catch (e) {setError(errorText(e));} finally {setBusy(false);}
}}><label>Abbruchgrund<input name="reason" required/></label><button disabled={busy}>Abbruch anfordern</button></form>
</details>}
{job.data && state === 'unknown' && <UnknownClosure tenantId={tenantId} id={id} job={job.data} auth={auth} done={job.reload}/>}
</article>;
}
function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; id: string; job: RecordValue; auth: Session; done: () => void }) {
const [confirmed, setConfirmed] = useState(false), [reason, setReason] = useState(''), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null);
@@ -261,6 +426,7 @@ function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; i
const pages: Record<NavKey, string> = {
geraete: 'Geräte',
auftraege: 'Aufträge',
genehmigungen: 'Genehmigungen',
skripte: 'Skripte',
kunden: 'Kunden',
verwaltung: 'Verwaltung'
@@ -294,20 +460,22 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
[auth.principal.id]
);
const customers = tenants.data?.items ?? auth.tenants;
const [customer, setCustomer] = useState(auth.tenants[0]?.tenant_id ?? '');
const [selectedCustomer, setCustomer] = useState(auth.tenants[0]?.tenant_id ?? '');
const [detailKind, detailTenant, detailId] = route.tab.split('/');
const detailRoute = (route.page === 'genehmigungen' && detailKind === 'pruefen')
|| (route.page === 'auftraege' && (detailKind === 'ansehen' || detailKind === 'entwurf'));
const customer = detailRoute && detailTenant ? detailTenant : selectedCustomer;
const [inboxRevision, refreshInbox] = useState(0);
const pendingCount = usePendingApprovals(true, inboxRevision);
const [fleetFilter, setFleetFilter] = useState('');
const [selection, setSelection] = useState<{ customer: string; ids: string[] }>({
customer: '',
ids: []
});
const [error, setError] = useState<string | null>(null);
const [planId, setPlan] = useState<string | null>(null),
[operationId, setOperation] = useState<string | null>(null);
function switchCustomer(id: string) {
if (id === customer) return;
if (id === selectedCustomer && !detailRoute) return;
setSelection({ customer: '', ids: [] });
setPlan(null);
setOperation(null);
setCustomer(id);
}
function selectFleetCustomer(id: string) {
@@ -327,20 +495,26 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
// Gate rendering during a tenant change; a previously loaded session is scoped to its own customer.
const scoped = current.data?.id === customer ? current.data.auth : null;
const customerName = customers.find((c) => c.tenant_id === customer)?.name ?? '';
const openOperation = (id: string) => {
setPlan(null);
setOperation(id);
go('auftraege');
};
const showPlan = (id: string) => {
setOperation(null);
setPlan(id);
go('auftraege');
};
function openOperation(tenantId: string, id: string) {
switchCustomer(tenantId);
go('auftraege', `ansehen/${tenantId}/${id}`);
}
function openReview(tenantId: string, id: string) {
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);
}
const selected = selection.customer === customer ? selection.ids : [];
const tabs: [string, string][] = [
['zugang', 'MCP-Tokens'],
['aufnahme', 'Agent-Releases & Aufnahme'],
['aufnahme', 'Geräteaufnahme'],
['releases', 'Agent-Releases'],
['kataloge', 'Paketkataloge'],
['rechte', 'Rechte & Ausführungsstopp']
];
@@ -361,6 +535,8 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
<a key={key} href={'#' + key} aria-current={route.page === key ? 'page' : undefined}>
<NavIcon name={key} />
<span>{title}</span>
{key === 'genehmigungen' && typeof pendingCount === 'number' && pendingCount > 0 &&
<b className="nav-count" aria-label={`${pendingCount} offene Anträge`}>{pendingCount}</b>}
</a>
))}
</nav>
@@ -391,7 +567,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
<i aria-hidden="true">/</i>
<b>{pages[route.page]}</b>
</div>
{route.page !== 'geraete' && route.page !== 'kunden' && (
{!['geraete', 'kunden','genehmigungen'].includes(route.page) && !detailRoute && (
<label className="context">
<span>Kunde</span>
<select aria-label="Kunde" value={customer} onChange={(e) => switchCustomer(e.target.value)}>
@@ -427,11 +603,8 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
setSelection(value);
}}
onEnroll={() => go('verwaltung', 'aufnahme')}
onScripts={() => go('skripte')}
onOperation={(tenantId, id) => {
switchCustomer(tenantId);
openOperation(id);
}}
onCreateOrder={() => go('auftraege', 'neu')}
onOperation={openOperation}
/>
)}
{route.page === 'kunden' && (
@@ -456,77 +629,39 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
)}
{scoped && (
<React.Fragment key={customer}>
{route.page === 'skripte' && (
<>
<div className="page-title">
<h1>Skripte</h1>
<a className="soft-button" href="#geraete">
Geräte auswählen
</a>
</div>
{selected.length > 0 && (
<p className="target-note">
{selected.length} {selected.length === 1 ? 'Zielgerät' : 'Zielgeräte'} für{' '}
{customerName} ausgewählt
</p>
)}
<ScriptLibrary
tenantId={customer}
auth={scoped}
selected={selected}
showPlan={showPlan}
/>
</>
{route.page === 'skripte' && <ScriptLibrary tenantId={customer} auth={scoped} />}
{route.page === 'genehmigungen' && (
detailRoute && detailId ? <>
<a href="#genehmigungen" className="back-link">← Zu den Genehmigungen</a>
<PlanDetail key={detailId} tenantId={customer} id={detailId} auth={scoped}
customerName={customerName} mode="review" onOperation={afterSubmission} />
</> : <><div className="page-title"><h1>Genehmigungen</h1></div><ApprovalInbox customers={customers} open={openReview} /></>
)}
{route.page === 'auftraege' && (
<>
<div className="page-title">
<h1>Aufträge</h1>
{route.tab !== 'neu' && (
<a className="soft-button" href="#auftraege/neu">
<NavIcon name="plus" /> Auftrag planen
</a>
)}
route.tab === 'neu' ? <>
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
<OrderComposer tenantId={customer} customerName={customerName} auth={scoped} initialAssetIds={selected} onSubmitted={afterSubmission} />
<details className="advanced-order"><summary>Weitere Wartungsaktionen</summary>
<p>Inventur, Dienstverwaltung und weitere Wartungsaufträge planen.</p>
<a className="quiet" href="#auftraege/wartung">Wartungsauftrag planen</a>
</details>
</> : route.tab === 'wartung' ? <>
<a href="#auftraege/neu" className="back-link">← Zum neuen Auftrag</a>
<div className="page-title"><h1>Wartungsauftrag planen</h1></div>
<a className="quiet" href="#geraete">Geräte auswählen</a>
<Planner tenantId={customer} auth={scoped} selected={selected} showPlan={showDraft} />
</> : detailRoute && detailId ? <>
<a href="#auftraege" className="back-link">← Zu den Aufträgen</a>
{detailKind === 'entwurf' ?
<PlanDetail key={detailId} tenantId={customer} id={detailId} auth={scoped}
customerName={customerName} mode="submit" onOperation={afterSubmission} />
: <OperationDetail key={detailId} tenantId={customer} id={detailId} auth={scoped}
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>}
</div>
{route.tab === 'neu' ? (
<>
<a className="quiet" href="#geraete">
Geräte auswählen
</a>
<p className="target-note">
{selected.length} {selected.length === 1 ? 'Zielgerät' : 'Zielgeräte'} für{' '}
{customerName} ausgewählt
</p>
<Planner
tenantId={customer}
auth={scoped}
selected={selected}
showPlan={showPlan}
/>
</>
) : (
<>
{operationId && (
<OperationDetail
key={operationId}
tenantId={customer}
id={operationId}
auth={scoped}
openPlan={(id) => setPlan(id)}
/>
)}
{planId && (
<PlanDetail
key={planId}
tenantId={customer}
id={planId}
auth={scoped}
onOperation={setOperation}
/>
)}
<Operations tenantId={customer} open={openOperation} />
</>
)}
<Operations tenantId={customer} customerName={customerName} open={id => openOperation(customer,id)} />
</>
)}
{route.page === 'verwaltung' && (
@@ -546,14 +681,8 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
))}
</nav>
{adminTab === 'zugang' && <McpTokenManagement tenantId={customer} auth={scoped} />}
{adminTab === 'aufnahme' && (
<AgentReleaseCatalog
tenantId={customer}
auth={scoped}
customerName={customerName}
enrollmentOpen
/>
)}
{adminTab === 'aufnahme' && <DeviceEnrollment tenantId={customer} auth={scoped} customerName={customerName} />}
{adminTab === 'releases' && <AgentReleaseCatalog tenantId={customer} auth={scoped} />}
{adminTab === 'kataloge' && (
<>
<Catalog tenantId={customer} auth={scoped} />
+2 -1
View File
@@ -1,7 +1,8 @@
export type NavKey = 'geraete' | 'auftraege' | 'skripte' | 'kunden' | 'verwaltung';
export type NavKey = 'geraete' | 'auftraege' | 'genehmigungen' | 'skripte' | 'kunden' | 'verwaltung';
const glyphs = {
geraete: 'M3 4h18v12H3z M8 20h8 M12 16v4',
auftraege: 'M8 5H5v16h14V5h-3 M9 3h6v4H9z M8 12h8 M8 16h5',
genehmigungen: 'M12 2 3 6v6c0 5 5 8 9 10 4-2 9-5 9-10V6z M8 12l3 3 5-6',
skripte: 'M7 7l-5 5 5 5 M17 7l5 5-5 5 M14 4l-4 16',
kunden: 'M4 21V5l10-2v18 M14 10h6v11 M2 21h20 M7 8h1 M10 8h1 M7 12h1 M10 12h1 M8 21v-4h3v4',
verwaltung: 'M3 6h7 M14 6h7 M3 12h12 M19 12h2 M3 18h3 M10 18h11 M10 3v6 M16 9v6 M8 15v6',
+306
View File
@@ -0,0 +1,306 @@
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 };
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, customerName }: Props) {
const path = (suffix: string) => tenantPath(tenantId, suffix);
const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]);
const [ticket, 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 [mode, setMode] = useState<'library' | 'once'>('library');
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 = ['inventory:read','operations:read','operations:plan','scripts:execute','operations:submit'].every(p => allowed(auth, p));
const devices = useResource(async signal => {
if (!canPlan || ticket || step !== 1) return null;
const params = new URLSearchParams({limit:'40',view:'current'});
if (query.trim()) params.set('q',query.trim());
if (cursor) params.set('cursor',cursor);
const batch = page(await request(path('/devices?' + params), {signal}));
return {items: batch.items.map(target), next: batch.next_cursor};
}, [tenantId, canPlan, query, cursor, step, !!ticket]);
const review = useResource(async signal => {
if (!ticket) return null;
const checked = await verifiedScriptOrder(await request(path('/operation-plans/' + ticket.id), {signal}), tenantId, auth.principal.id);
if (checked.plan.plan_hash !== ticket.hash || objectId(checked.plan,'plan') !== ticket.id) throw Error('Der gespeicherte Plan entspricht nicht dem ausgewählten Auftrag.');
return checked;
}, [tenantId, ticket?.id, ticket?.hash, auth.principal.id]);
const missingIds = (review.data?.jobs.map(job => job.assetId) ?? initialAssetIds).filter(id => !known[id]);
const restored = useResource(async signal => {
if (!canPlan) return [];
const ids = missingIds;
const results: Target[] = [];
for (let i = 0; i < ids.length; i += 8) {
const chunk = await Promise.all(ids.slice(i, i + 8).map(async id => {
try { return target(record(await request(path('/devices/' + encodeURIComponent(id)), {signal}))); }
catch (err) { if (err instanceof ApiError && err.status === 404) return null; throw err; }
}));
for (const item of chunk) if (item) results.push(item);
}
return results;
}, [tenantId, canPlan, missingIds.join('/')]);
const directory = new Map([...restored.data ?? [], ...Object.values(known), ...devices.data?.items ?? []].map(d => [d.id, d]));
const targets = selected.map(id => directory.get(id));
const hasLinux = targets.some(d => d?.platform === 'linux');
const hasWindows = targets.some(d => d?.platform === 'windows');
const scripts = useResource(signal => canPlan && step === 2 && !ticket ? loadRevisions(tenantId, signal) : Promise.resolve([]), [tenantId, canPlan, step, !!ticket]);
const revision = scripts.data?.find(r => r.revision_id === revisionId);
const heads = latestRevisions(scripts.data ?? []);
const issues: string[] = [];
if (targets.some(d => !d?.current)) issues.push('Ein Zielgerät fehlt im aktuellen Bestand. Entfernen Sie es aus der Auswahl.');
const unidentified = targets.filter(d => d && !d.platform);
if (unidentified.length) issues.push('Das Betriebssystem ist noch nicht bestätigt: ' + unidentified.map(d => d?.name).join(', '));
if (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 === '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 || !canPlan || 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()};
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 || !canPlan || 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','Skript','Zusammenfassung'].map((name,i) => <li key={name} aria-current={stepNumber === i+1 ? 'step' : undefined}>{i+1}. {name}</li>)}</ol>
<ErrorBox error={error ?? review.error ?? restored.error ?? devices.error ?? scripts.error}/>
{!canPlan ? <section><p>Zum Erstellen eines Skriptauftrags benötigen Sie Gerätezugriff sowie Rechte zum Planen und Einreichen von Skriptaufträgen.</p></section> :
ticket ? <section aria-label="Auftrag prüfen"><h2>Zusammenfassung</h2>
{review.data ? <>
<h3>{review.data.jobs[0]?.revision ? `${review.data.jobs[0].revision.name} · Version ${review.data.jobs[0].revision.version}` : 'Einmaliges Skript'}</h3>
<p>{review.data.reason}</p>
<dl className="facts"><div><dt>Kunde</dt><dd>{customerName ?? auth.tenants.find(t => t.tenant_id === tenantId)?.name ?? tenantId}</dd></div>
<div><dt>Ausführen als</dt><dd>{identityNames[review.data.jobs[0]!.identity as Identity]}</dd></div>
<div><dt>Frühester Start</dt><dd>{new Date(review.data.jobs[0]!.notBefore).toLocaleString('de-DE')}</dd></div>
<div><dt>Startfrist</dt><dd>{new Date(review.data.jobs[0]!.startBefore).toLocaleString('de-DE')}</dd></div>
<div><dt>Maximale Laufzeit pro Gerät</dt><dd>{review.data.jobs[0]!.runtimeSeconds} Sekunden</dd></div>
<div><dt>Parallelität</dt><dd>{review.data.maxParallel} gleichzeitig · Stopp nach {review.data.halt} Fehlern</dd></div>
</dl>
<h3>Zielgeräte ({review.data.jobs.length})</h3>
<ul>{review.data.jobs.map(j => <li key={j.assetId}>{directory.get(j.assetId)?.name ?? j.assetId}</li>)}</ul>
{review.data.jobs[0]?.identity !== 'agent_service' && <p className="warning">Dieser Auftrag erfordert erhöhte Rechte auf den Zielgeräten.</p>}
<details><summary>Gebundenen Skriptinhalt ansehen</summary>
{[...new Map(review.data.jobs.map(job => [job.scriptHash,job])).values()].map(job => <div key={job.scriptHash}><h4>{interpreterNames[job.interpreter as Interpreter]}</h4><pre className="script-body">{job.script}</pre></div>)}
</details>
{typeof existing === 'string' ? <div className="work-actions"><button className="primary" onClick={() => submitted(existing)}>Eingereichten Auftrag öffnen</button></div> :
<><ErrorBox error={blockers(review.data).join(' · ') || null}/><div className="work-actions">
{(!ticket.attempted || Date.parse(String(review.data.plan.expires_at)) <= Date.now()) && <button disabled={busy} onClick={() => {saveTicket(null);setError(null);}}>Zurück zum Entwurf</button>}
<button className="primary" disabled={busy || !!blockers(review.data).length} onClick={() => void submit()}>{busy ? 'Wird eingereicht …' : 'Zur Genehmigung einreichen'}</button>
</div></>}
</> : review.error ? <div className="work-actions"><button onClick={review.reload}>Erneut prüfen</button>
{!ticket.attempted && <button onClick={() => saveTicket(null)}>Entwurf verwerfen</button>}</div> : <p role="status">Gespeicherter Plan wird geprüft …</p>}
</section> :
step === 1 ? <section aria-label="Zielgeräte"><h2>Geräte auswählen</h2>
<label>Hostname suchen<input type="search" value={query} onChange={e => {setQuery(e.target.value);setCursor(null);setPrior([]);}}/></label>
{!devices.data && !devices.error && <p role="status">Geräte werden geladen …</p>}
{devices.data && <><ul className="order-targets">{devices.data.items.map(d => <li key={d.id}><label>
<input type="checkbox" checked={selected.includes(d.id)} onChange={() => toggleTarget(d)}/>
<strong>{d.name}</strong><small>{d.os} · {d.state}</small>
</label></li>)}</ul>{!devices.data.items.length && <p>{query ? 'Kein Gerät passt zur Suche.' : 'Keine Geräte im Bestand dieses Kunden.'}</p>}
{(prior.length > 0 || devices.data.next) && <div><button disabled={!prior.length} onClick={() => {setCursor(prior.at(-1) ?? null);setPrior(prior.slice(0,-1));}}>Vorherige Geräte</button>
<button disabled={!devices.data.next} onClick={() => {setPrior([...prior,cursor]);setCursor(devices.data!.next);}}>Weitere Geräte</button></div>}</>}
{selected.filter(id => !devices.data?.items.some(d => d.id === id)).map(id => <p key={id}>{directory.get(id)?.name ?? id} <button className="link" onClick={() => setSelected(selected.filter(s => s !== id))}>Aus Auswahl entfernen</button></p>)}
<div className="work-actions"><span>{selected.length} ausgewählt</span><button className="primary" disabled={!selected.length || selected.length > 100 || targets.some(d => !d?.current || !d.platform)} onClick={() => {setStep(2);setError(null);}}>Weiter zum Skript</button></div>
{selected.length > 100 && <p role="alert">Ein Auftrag kann bis zu 100 Geräte enthalten.</p>}
{restored.data && issues.length > 0 && <ErrorBox error={issues.join(' ')}/>}
</section> :
<section><h2>Skript auswählen</h2><form onSubmit={prepare}><fieldset disabled={busy} className="work-form">
<div className="order-source"><label><input type="radio" name="quelle" checked={mode === 'library'} onChange={() => setMode('library')}/>Aus der Bibliothek</label>
<label><input type="radio" name="quelle" checked={mode === 'once'} onChange={() => setMode('once')}/>Einmaliges Skript</label></div>
{mode === 'library' ? <>
<label>Bibliotheksskript<select required value={revision?.name ?? ''} onChange={e => {const next = heads.find(h => h.name === e.target.value);choose(next?.revision_id ?? '');setRuntime(next?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);}}>
<option value="">Skript wählen</option>{heads.map(h => <option key={h.name} value={h.name}>{h.name}</option>)}
</select></label>
{scripts.data && !heads.length && <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
{revision && <><label>Version<select value={revisionId} onChange={e => {choose(e.target.value);setRuntime(scripts.data?.find(r => r.revision_id === e.target.value)?.script_sha256 === windowsUpdateScriptHash ? 3600 : 120);}}>
{scripts.data?.filter(r => r.name === revision.name).map(r => <option key={r.revision_id} value={r.revision_id}>Version {r.version}</option>)}
</select></label><p>{interpreterNames[revision.interpreter]} · {identityNames[revision.execution_identity]}</p>
{revision.execution_identity !== 'agent_service' && <p className="warning">Das Skript benötigt erhöhte Rechte auf den ausgewählten Geräten.</p>}</>}
</> : <>
{hasLinux && <ScriptFieldsForPlatform script={linux} change={setLinux} auth={auth} windows={false}/>}
{hasWindows && <ScriptFieldsForPlatform script={windows} change={setWindows} auth={auth} windows/>}
{linux.execution_identity === 'root' && hasLinux && <label><input type="checkbox" checked={fullRoot} onChange={e=>setFullRoot(e.target.checked)}/>Vollwartung als root anfordern</label>}
</>}
<label>Begründung<input required maxLength={1024} value={reason} onChange={e => setReason(e.target.value)}/></label>
<details><summary>Zeitfenster und Ausführungsoptionen</summary><div className="work-fields">
<label>Frühester Start<input required type="datetime-local" value={start} onChange={e => setStart(e.target.value)}/></label>
<label>Startfrist<input required type="datetime-local" value={end} onChange={e => setEnd(e.target.value)}/></label>
<label>Laufzeit je Gerät in Sekunden<input required type="number" min={1} max={maxRuntime} value={runtime} onChange={e => setRuntime(Number(e.target.value))}/></label>
<label>Ausgabelimit in Byte<input required type="number" min={1} max={identity === 'agent_service' ? 262144 : 65536} value={limit} onChange={e => setLimit(Number(e.target.value))}/></label>
<label>Geräte gleichzeitig<input required type="number" min={1} max={10} value={parallel} onChange={e => setParallel(Number(e.target.value))}/></label>
<label>Stopp nach Fehlern<input required type="number" min={1} value={halt} onChange={e => setHalt(Number(e.target.value))}/></label>
</div>
{mode === 'once' && <><label>Erwartete Standardausgabe (optional)<textarea value={expected} onChange={e => setExpected(e.target.value)}/></label>
<label>Format<select value={expectedFormat} onChange={e => setExpectedFormat(e.target.value)}><option value="text">Text</option><option value="json">JSON-Zeichenfolge</option></select></label></>}
</details>
<ErrorBox error={issues.join(' ') || null}/>
<div className="work-actions"><button type="button" onClick={() => {setStep(1);setError(null);}}>Zurück zu Geräten</button>
<button className="primary" type="submit" disabled={!!issues.length || (mode === 'library' && !revision)}>{busy ? 'Plan wird geprüft …' : 'Zusammenfassung ansehen'}</button></div>
</fieldset></form></section>}
</>;
}
function ScriptFieldsForPlatform({script,change,auth,windows}: {script: Script;change: (s: Script) => void;auth: Session;windows:boolean}) {
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>;
}
+66
View File
@@ -0,0 +1,66 @@
import { type ReactNode } from 'react';
import { objectId, record, type RecordValue } from './api';
const states: Record<string, string> = {
pending_approval: 'Wartet auf Genehmigung', approved: 'Genehmigt', rejected: 'Abgelehnt',
expired: 'Abgelaufen', revoked: 'Widerrufen', queued: 'Eingereiht', delivered: 'Zugestellt',
offered: 'Angeboten', accepted: 'Angenommen', running: 'Läuft', verifying: 'Ergebnis wird geprüft',
awaiting_reboot: 'Wartet auf Neustart', succeeded: 'Erfolgreich', partially_succeeded: 'Teilweise erfolgreich',
failed: 'Fehlgeschlagen', cancelled: 'Abgebrochen', cancel_requested: 'Abbruch angefordert',
unknown: 'Wirkung unklar', closed_unknown: 'Mit unklarer Wirkung abgeschlossen', needs_attention: 'Prüfung erforderlich'
};
const actions: Record<string, string> = {
run_script: 'Freies Skript', refresh_inventory: 'Inventar aktualisieren', query_logs: 'Protokolle abrufen',
set_service_state: 'Dienst verwalten', ensure_package: 'Paket installieren', apply_updates: 'Updates installieren',
apt_native_acceptance: 'Paketinstallation prüfen', reboot: 'Gerät neu starten', update_agent: 'Agent aktualisieren'
};
const formatter = new Intl.DateTimeFormat('de-DE', { dateStyle: 'short', timeStyle: 'short' });
export function display(value: unknown, fallback = 'Unbekannt') { return typeof value === 'string' && value.trim() ? value : fallback; }
export function when(value: unknown) { const ms = Date.parse(String(value)); return Number.isFinite(ms) ? formatter.format(ms) : 'Unbekannt'; }
export function statusText(value: unknown) { return states[String(value)] ?? display(value); }
export function actionTitle(value: unknown) { return actions[String(value)] ?? display(value, 'Auftrag'); }
export function orderTitle(row: RecordValue) { return display(row.title, actionTitle(row.action)); }
export function targets(row: RecordValue): RecordValue[] { return Array.isArray(row.targets) ? row.targets.map(v => record(v)) : []; }
export function deviceName(row: RecordValue) { return display(row.hostname, display(row.asset_id, 'Gerät unbekannt')); }
export function statusOf(row: RecordValue) { return row.approval_state === 'approved' && row.execution_state ? row.execution_state : row.approval_state; }
export function identityName(value: unknown) {
if (value === 'system') return 'SYSTEM (Administratorrechte)';
if (value === 'root') return 'root (Administratorrechte)';
return value === 'agent_service' ? 'Agent-Dienstkonto' : display(value);
}
export function Requester({ id, ownId }: { id: unknown; ownId?: string }) {
const name = display(id);
if (name.startsWith('local:') || name.startsWith('mcp:')) return <span title={name}>
{name === ownId ? 'Mein Konto' : name.startsWith('mcp:') ? 'MCP-Client' : 'Lokales Konto'} · {name.slice(-8)}
</span>;
return <>{name}</>;
}
export function Status({ value }: { value: unknown }) { return <span className={'order-status state-' + String(value)}>{statusText(value)}</span>; }
export function Fact({ label, children }: { label: string; children: ReactNode }) { return <div><dt>{label}</dt><dd>{children}</dd></div>; }
export function OrderRows({ items, customerName, decisionList, open }: {
items: RecordValue[]; customerName?: string; decisionList?: boolean; open: (row: RecordValue) => void
}) {
return <div className="table fleet-table order-list"><table><thead><tr>
<th>Auftrag</th><th>Kunde</th><th>Geräte</th><th>{decisionList ? 'Eingereicht von' : 'Erstellt'}</th><th>Status</th>
</tr></thead><tbody>{items.map(row => {
const all = targets(row);
const devices = all.slice(0, 2).map(deviceName).join(', ');
const revision = row.script_revision ? record(row.script_revision) : null;
return <tr key={String(row.tenant_id) + objectId(row, 'operation')} data-operation-id={row.operation_id} data-plan-id={row.plan_id}>
<td className="hostname"><button type="button" className="host-link" onClick={() => open(row)}>{orderTitle(row)}</button>
{revision && <small>Version {String(revision.version)}</small>}</td>
<td data-label="Kunde">{display(row.customer_name, customerName)}</td>
<td data-label="Geräte">{devices || (typeof row.planned_job_count === 'number' ? String(row.planned_job_count) : 'Unbekannt')}{all.length > 2 && ' und '+(all.length-2)+' weitere'}</td>
<td data-label={decisionList ? 'Eingereicht von' : 'Erstellt'}>{decisionList ? <Requester id={row.requester}/> : when(row.created_at)}</td>
<td data-label="Status"><Status value={decisionList ? row.approval_state : statusOf(row)}/></td>
</tr>;
})}</tbody></table></div>;
}
export function PageButtons({ pages, next, change }: { pages: string[]; next: string | null; change: (pages: string[]) => void }) {
if (!next && !pages.length) return null;
return <div className="list-footer"><button className="quiet" disabled={!pages.length} onClick={() => change(pages.slice(0,-1))}>Zurück</button>
<button className="quiet" disabled={!next} onClick={() => next && change([...pages, next])}>Weiter</button></div>;
}
+66
View File
@@ -0,0 +1,66 @@
import { objectId, page, record, request, tenantPath, text, type RecordValue } from './api';
export type Interpreter = 'posix_sh' | 'bash' | 'powershell';
export type Identity = 'agent_service' | 'root' | 'system';
export interface Script {
name: string;
interpreter: Interpreter;
execution_identity: Identity;
script_utf8: string;
}
export interface Revision extends Script {
revision_id: string;
version: number;
script_sha256: string;
}
export const interpreterNames: Record<Interpreter, string> = {
posix_sh: 'Linux · Shell', bash: 'Linux · Bash', powershell: 'Windows · PowerShell'
};
export const identityNames: Record<Identity, string> = {
agent_service: 'Agent-Dienstkonto', root: 'root', system: 'SYSTEM'
};
export function parseRevision(value: unknown): Revision {
const row = record(value);
if ((row.interpreter !== 'posix_sh' && row.interpreter !== 'bash' && row.interpreter !== 'powershell') ||
(row.execution_identity !== 'agent_service' && row.execution_identity !== 'root' && row.execution_identity !== 'system') ||
typeof row.version !== 'number' || !Number.isSafeInteger(row.version) || row.version < 1) {
throw Error('Der Server meldet eine ungültige Skriptversion.');
}
return {
revision_id: objectId(row, 'revision'), name: text(row.name, 'Skriptname'), version: row.version,
interpreter: row.interpreter, execution_identity: row.execution_identity,
script_utf8: text(row.script_utf8, 'Skriptinhalt'), script_sha256: text(row.script_sha256, 'Prüfsumme')
};
}
export async function loadRevisions(tenantId: string, signal: AbortSignal): Promise<Revision[]> {
const revisions: Revision[] = [];
const cursors = new Set<string>();
let cursor: string | null = null;
do {
const params = new URLSearchParams({limit: '100'});
if (cursor) params.set('cursor', cursor);
const batch = page(await request(tenantPath(tenantId, '/script-revisions?' + params), { signal }));
revisions.push(...batch.items.map(parseRevision));
cursor = batch.next_cursor;
if (cursor && cursors.has(cursor)) throw Error('Die nächste Bibliotheksseite konnte nicht geladen werden.');
if (cursor) cursors.add(cursor);
} while (cursor);
return revisions.sort((a, b) => a.name.localeCompare(b.name, 'de') || b.version - a.version);
}
export function latestRevisions(revisions: Revision[]) {
const heads = new Map<string, Revision>();
for (const item of revisions) {
const previous = heads.get(item.name);
if (!previous || previous.version < item.version) heads.set(item.name, item);
}
return [...heads.values()].sort((a, b) => a.name.localeCompare(b.name, 'de'));
}
export function devicePlatform(row: RecordValue) {
if (row.source_id === 'windows.base') return 'windows';
if (row.source_id === 'linux.base') return 'linux';
return null;
}
export function scriptPlatform(interpreter: Interpreter) {
return interpreter === 'powershell' ? 'windows' : 'linux';
}
+84 -106
View File
@@ -1,113 +1,91 @@
import React, { FormEvent, useEffect, useState } from 'react';
import { objectId, page, record, request, Session, tenantPath, text } from './api';
import { useState, type FormEvent } from 'react';
import { ApiError, request, tenantPath, type Session } from './api';
import { allowed } from './safety';
import { windowsUpdateScriptHash } from './script-console';
import { ErrorBox, errorText, useResource } from './resource';
import { identityNames, interpreterNames, latestRevisions, loadRevisions, parseRevision, type Identity, type Interpreter, type Revision, type Script } from './script-catalog';
import './script-workspace.css';
interface Draft {
name: string;
interpreter: 'posix_sh' | 'bash' | 'powershell';
execution_identity: 'agent_service' | 'root' | 'system';
script_utf8: string;
export function ScriptFields({ script, change, ids, interpreters }: {
script: Script; change: (next: Script) => void; ids: Identity[]; interpreters?: Interpreter[];
}) {
const possible = ids.filter(id => id === 'agent_service' || id === (script.interpreter === 'powershell' ? 'system' : 'root'));
return <>
<div className="work-fields"><label>Plattform und Interpreter
<select value={script.interpreter} onChange={e => change({...script, interpreter: e.target.value as Interpreter, execution_identity: 'agent_service'})}>
{Object.entries(interpreterNames).filter(([key]) => !interpreters || interpreters.includes(key as Interpreter)).map(([value, label]) => <option value={value} key={value}>{label}</option>)}
</select></label>
<label>Ausführen als<select value={script.execution_identity} onChange={e => change({...script, execution_identity: e.target.value as Identity})}>
{possible.map(id => <option key={id} value={id}>{identityNames[id]}</option>)}
</select></label>
</div>
{script.execution_identity !== 'agent_service' && <p className="warning">Dieses Skript fordert {identityNames[script.execution_identity]}-Rechte auf den Zielgeräten an.</p>}
<label>Skriptinhalt<textarea className="script-editor" spellCheck={false} required rows={10} value={script.script_utf8}
onChange={e => change({...script, script_utf8: e.target.value})}/></label>
{script.interpreter === 'powershell' && /[^\x00-\x7f]/.test(script.script_utf8) && !script.script_utf8.startsWith('\ufeff') &&
<p className="warning">Windows PowerShell 5.1 benötigt für diesen Text eine UTF-8-Signatur. <button type="button" className="link" onClick={() => change({...script, script_utf8: '\ufeff' + script.script_utf8})}>UTF-8-Signatur hinzufügen</button></p>}
</>;
}
interface Revision extends Draft { revision_id: string; version: number; script_sha256: string }
const blank: Draft = { name: '', interpreter: 'posix_sh', execution_identity: 'agent_service', script_utf8: '' };
function revision(input: unknown): Revision {
const row = record(input);
if ((row.interpreter !== 'posix_sh' && row.interpreter !== 'bash' && row.interpreter !== 'powershell') ||
(row.execution_identity !== 'agent_service' && row.execution_identity !== 'root' && row.execution_identity !== 'system') ||
typeof row.version !== 'number' || !Number.isSafeInteger(row.version) || row.version < 1) throw Error('Ungültige Skriptversion');
return { name: text(row.name, 'Name'), interpreter: row.interpreter, execution_identity: row.execution_identity,
script_utf8: text(row.script_utf8, 'Skript'), revision_id: objectId(row, 'revision'), version: row.version,
script_sha256: text(row.script_sha256, 'SHA256') };
}
export function ScriptLibrary({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
const path = tenantPath(tenantId, '/script-revisions');
const canRead = allowed(auth, 'operations:read'), canPlan = allowed(auth, 'operations:plan') && allowed(auth, 'scripts:execute');
const [items, setItems] = useState<Revision[]>([]), [cursor, setCursor] = useState<string | null>(null);
const [chosen, setChosen] = useState(''), [draft, setDraft] = useState<Draft | null>(null), [base, setBase] = useState(0);
const [busy, setBusy] = useState(false), [error, setError] = useState(''), [notice, setNotice] = useState('');
const stored = items.find(row => row.revision_id === chosen);
useEffect(() => {
if (!canRead) return;
const controller = new AbortController();
setBusy(true);
request(path, { signal: controller.signal }).then(value => {
if (controller.signal.aborted) return;
const result = page(value), rows = result.items.map(revision);
setItems(rows); setCursor(result.next_cursor); setChosen(rows[0]?.revision_id ?? '');
}).catch(err => { if (!controller.signal.aborted) setError(String(err)); })
.finally(() => { if (!controller.signal.aborted) setBusy(false); });
return () => controller.abort();
}, [path, canRead]);
async function action(work: () => Promise<void>) {
setBusy(true); setError(''); setNotice('');
try { await work(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); }
finally { setBusy(false); }
export function ScriptLibrary({ tenantId, auth }: { tenantId: string; auth: Session }) {
const read = allowed(auth, 'operations:read');
const canPublish = allowed(auth, 'operations:plan') && allowed(auth, 'scripts:execute');
const library = useResource(signal => read ? loadRevisions(tenantId, signal) : Promise.resolve([]), [tenantId, read]);
const [opened, open] = useState('');
const [draft, setDraft] = useState<Script | null>(null);
const [base, setBase] = useState(0);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState('');
const versions = (library.data ?? []).filter(item => item.name === opened);
const latest = versions[0];
function edit(existing?: Revision) {
setBase(existing?.version ?? 0);
setDraft(existing ? { ...existing } : { name: '', interpreter: 'posix_sh', execution_identity: 'agent_service', script_utf8: '' });
setError(null); setNotice('');
}
async function more() {
const result = page(await request(path + '?cursor=' + encodeURIComponent(cursor!)));
const rows = result.items.map(revision);
setItems(old => [...old, ...rows.filter(row => !old.some(saved => saved.revision_id === row.revision_id))]); setCursor(result.next_cursor);
}
async function save(e: FormEvent) {
async function publish(e: FormEvent) {
e.preventDefault();
if (!draft) return;
await action(async () => {
const saved = revision(await request(path, { csrf: auth.csrf_token, body: { ...draft, expected_version: base } }));
setItems(old => [...old.filter(row => row.revision_id !== saved.revision_id), saved]); setChosen(saved.revision_id);
setDraft(null); setNotice(`Version ${saved.version} gespeichert.`);
});
if (!draft || busy) return;
setBusy(true); setError(null);
try {
const {name, interpreter, execution_identity, script_utf8} = draft;
const saved = parseRevision(await request(tenantPath(tenantId, '/script-revisions'), {
csrf: auth.csrf_token, body: {name: name.trim(), interpreter, execution_identity, script_utf8, expected_version: base}
}));
open(saved.name); setDraft(null); setNotice(`Version ${saved.version} veröffentlicht.`); library.reload();
} catch (err) {
setError(err instanceof ApiError && err.code === 'SCRIPT_REVISION_CONFLICT'
? 'Unter diesem Namen gibt es bereits eine neuere Version. Öffnen Sie den aktuellen Stand vor dem Veröffentlichen.' : errorText(err));
if (err instanceof ApiError && err.status === 409) library.reload();
} finally { setBusy(false); }
}
function edit(row?: Revision) {
setBase(row?.version ?? 0);
setDraft(row ? { name: row.name, interpreter: row.interpreter, execution_identity: row.execution_identity, script_utf8: row.script_utf8 } : { ...blank });
setError(''); setNotice('');
}
async function plan(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!stored || !selected.length) return;
const form = new FormData(e.currentTarget);
await action(async () => {
const now = Date.now(), expires = now + Number(form.get('minutes')) * 60000;
const body = { targets: { asset_ids: selected }, reason: String(form.get('reason')),
schedule: { not_before: new Date(now).toISOString(), start_before: new Date(expires).toISOString() },
rollout: { max_parallel: 1, halt_after_failures: 1 }, max_runtime_seconds: Number(form.get('runtime')), max_output_bytes: 65536 };
const result = record(await request(path + '/' + encodeURIComponent(stored.revision_id) + '/plan', { csrf: auth.csrf_token, body }));
showPlan(objectId(result, 'plan')); setNotice('Plan zur Prüfung geöffnet.');
});
}
if (!canRead) return null;
const windowsUpdate = stored?.execution_identity === 'system' && stored.interpreter === 'powershell' && stored.script_sha256 === windowsUpdateScriptHash;
const limit = windowsUpdate ? 3600 : stored?.execution_identity === 'system' ? 120 : stored?.execution_identity === 'root' ? 300 : 3600;
return <section aria-label="Skriptbibliothek"><h2>Skriptbibliothek</h2>
{error && <p role="alert" className="error">{error}</p>}{notice && <p role="status">{notice}</p>}
{items.length > 0 && <label>Gespeicherte Skriptversion<select value={chosen} disabled={busy || !!draft} onChange={e => setChosen(e.target.value)}>
{[...items].sort((a,b) => a.name.localeCompare(b.name) || b.version - a.version).map(row => <option key={row.revision_id} value={row.revision_id}>{row.name} · v{row.version}</option>)}
</select></label>}
{cursor && <button disabled={busy || !!draft} onClick={() => void action(more)}>Weitere Versionen laden</button>}
{stored && !draft && <><p>{stored.interpreter === 'powershell' ? 'Windows PowerShell' : stored.interpreter === 'bash' ? 'Linux bash' : 'Linux sh'} · {stored.execution_identity} · SHA256 <code>{stored.script_sha256}</code></p>
<details><summary>Gespeicherten Skripttext anzeigen</summary><pre>{stored.script_utf8}</pre></details></>}
{canPlan && !draft && <div><button disabled={busy} onClick={() => edit()}>Neues Skript</button>
{stored && <button disabled={busy} onClick={() => edit(stored)}>Neue Version bearbeiten</button>}</div>}
{draft && <form onSubmit={save}><fieldset disabled={busy}><legend>{base ? `Neue Version von ${draft.name}` : 'Neues Skript'}</legend>
<label>Name<input required maxLength={120} readOnly={base > 0} value={draft.name} onChange={e => setDraft({...draft,name:e.target.value})}/></label>
<label>Interpreter<select value={draft.interpreter} onChange={e => setDraft({...draft,interpreter:e.target.value as Draft['interpreter'],execution_identity:'agent_service'})}>
<option value="posix_sh">Linux sh</option><option value="bash">Linux bash</option><option value="powershell">Windows PowerShell</option></select></label>
<label>Ausführungsidentität<select value={draft.execution_identity} onChange={e => setDraft({...draft,execution_identity:e.target.value as Draft['execution_identity']})}>
<option value="agent_service">agent_service</option>{draft.interpreter === 'powershell' ? <option value="system">system</option> : <option value="root">root</option>}</select></label>
<label>Skripttext<textarea required rows={9} value={draft.script_utf8} onChange={e => setDraft({...draft,script_utf8:e.target.value})}/></label>
<button>Version speichern</button><button type="button" onClick={() => setDraft(null)}>Abbrechen</button>
</fieldset></form>}
{canPlan && stored && !draft && <form key={stored.revision_id} onSubmit={plan}><fieldset disabled={busy}><legend>Auftrag für {stored.name} · v{stored.version} vorbereiten</legend>
<p>{selected.length} ausgewählte Geräte · Ein Gerät gleichzeitig · Stopp beim ersten Fehler · 65536 Byte Ausgabe je Gerät</p>
{windowsUpdate && <p>Diese Version installiert verfügbare Softwareupdates ohne eigenen Neustart. Sie meldet Neustartbedarf. Laufzeiten über 120 Sekunden erfordern die passende Windows-Update-Freigabe in Server- und Helperpolicy.</p>}
<label>Begründung<input name="reason" required maxLength={1024}/></label>
<label>Startfrist in Minuten<input name="minutes" type="number" min={1} max={1440} defaultValue={60} required/></label>
<label>Laufzeit je Gerät in Sekunden<input name="runtime" type="number" min={1} max={limit} defaultValue={windowsUpdate ? 3600 : Math.min(limit,120)} required/></label>
<button disabled={!selected.length}>Plan vorbereiten</button>
</fieldset></form>}
</section>;
return <>
<div className="page-title"><h1>Skripte</h1>
{canPublish && !draft && !opened && <button className="primary" onClick={() => edit()}>Neues Skript</button>}
</div>
<ErrorBox error={error ?? library.error}/>{notice && <p role="status">{notice}</p>}
{!read ? <p>Die Berechtigung zum Lesen der Skriptbibliothek fehlt.</p> :
draft ? <section><h2>{base ? 'Neue Version' : 'Neues Skript'}</h2><form onSubmit={publish}>
<fieldset className="work-form" disabled={busy}><label>Name<input autoFocus required maxLength={120} readOnly={base > 0} value={draft.name} onChange={e => setDraft({...draft,name:e.target.value})}/></label>
<ScriptFields script={draft} change={setDraft} ids={['agent_service','root','system']}/>
<div className="work-actions"><button type="button" onClick={() => {setError(null); setDraft(null);}}>Abbrechen</button><button className="primary" type="submit">Version veröffentlichen</button></div>
</fieldset>
</form></section> :
opened ? <section><button className="link" onClick={() => {open(''); setNotice('');}}>Zur Skriptbibliothek</button>
{latest ? <><div className="section-heading"><h2>{latest.name}</h2>{canPublish && <button onClick={() => edit(latest)}>Neue Version</button>}</div>
<p>{interpreterNames[latest.interpreter]} · Version {latest.version} · {identityNames[latest.execution_identity]}</p>
<pre className="script-body">{latest.script_utf8}</pre>
{versions.length > 1 && <details><summary>Frühere Versionen ({versions.length - 1})</summary>
{versions.slice(1).map(item => <details key={item.revision_id}><summary>Version {item.version} · {interpreterNames[item.interpreter]} · {identityNames[item.execution_identity]}</summary><pre className="script-body">{item.script_utf8}</pre></details>)}
</details>}</> : <p role="status">Skript wird geladen …</p>}
</section> :
<section aria-label="Skriptbibliothek">
{!library.data ? <p role="status">Bibliothek wird geladen …</p> : library.data.length ? <div className="table"><table>
<thead><tr><th>Name</th><th>Plattform</th><th>Version</th><th>Ausführen als</th></tr></thead>
<tbody>{latestRevisions(library.data).map(item => <tr key={item.name}>
<td><button className="link" onClick={() => {open(item.name); setNotice('');}}>{item.name}</button></td>
<td>{interpreterNames[item.interpreter]}</td><td>{item.version}</td><td>{identityNames[item.execution_identity]}</td>
</tr>)}</tbody>
</table></div> : <p>Für diesen Kunden sind noch keine Skripte veröffentlicht.</p>}
</section>}
</>;
}
+17
View File
@@ -0,0 +1,17 @@
.work-form { display: grid; gap: 1rem; margin: 0; padding: 0; border: 0; min-width: 0; }
.work-form label { margin: 0; }
.work-form input:not([type=checkbox]), .work-form textarea, .work-form select { width: 100%; }
.work-fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr)); gap: 1rem; }
.work-actions { display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; gap: .65rem; margin-top: 1rem; }
.work-actions button { margin: 0; }
.script-editor, .script-body { font: .9rem/1.55 ui-monospace, monospace; tab-size: 4; }
.script-body { max-height: 30rem; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.order-progress { display: flex; flex-wrap: wrap; gap: .6rem 1.2rem; list-style: none; padding: 0; margin: 0 0 1rem; color: #536863; }
.order-progress [aria-current=step] { font-weight: 700; color: #155c48; }
.order-targets { list-style: none; padding: 0; margin: .5rem 0; }
.order-targets li { border-bottom: 1px solid #dce5e2; }
.order-targets label { display: flex; align-items: center; gap: .8rem; padding: .65rem 0; cursor: pointer; }
.order-targets small { margin-left: auto; text-align: right; }
.order-source { display: flex; flex-wrap: wrap; gap: 1rem; }
.order-source label { display: inline-flex; gap: .4rem; align-items: center; }
.work-form .order-source input { width: auto; }
+20
View File
@@ -133,3 +133,23 @@ section.fleet { padding:0; overflow:hidden; }
}
@media(max-width:450px) { .sidebar nav a {flex-direction:column;gap:2px;} .crumb span,.crumb i {display:none;} .login {margin:18px 12px;} .facts {grid-template-columns:1fr;} }
@media(prefers-reduced-motion:no-preference) { a, button {transition:background-color 100ms,color 100ms;} }
.nav-count { display:inline-flex; align-items:center; justify-content:center; min-width:1.55em; padding:0 .35em; margin-left:auto; border-radius:12px; font-size:.73rem; color:#15382d; background:#b5e9c7; }
.sidebar nav a:has(.nav-count) { gap:7px; padding-inline:9px; }
.back-link { display:inline-block; margin:0 0 16px; font-size:.9rem; text-decoration:none; }
.back-link:hover { text-decoration:underline; }
.primary-action { display:inline-flex; align-items:center; gap:7px; padding:9px 14px; border-radius:6px; background:var(--accent); color:white; font-weight:600; text-decoration:none; }
.advanced-order { border-top:1px solid var(--line); padding-top:14px; margin-top:24px; }
.content fieldset { min-width:0; border:1px solid var(--line); border-radius:8px; padding:12px 18px 16px; margin:12px 0; }
.content legend { font-weight:650; padding:0 5px; }
.content textarea { min-height:5.5rem; }
@media(max-width:500px) {
.sidebar nav { display:grid; grid-template-columns:repeat(3, minmax(0,1fr)); gap:2px; }
.sidebar nav a,.sidebar nav a:has(.nav-count) { flex-direction:row; padding:6px 2px; gap:4px; font-size:.78rem; }
.nav-count { margin-left:0; }
}
.order-status { display:inline-block; padding:2px 9px; border-radius:20px; color:#435a53; background:#edf2ef; font-size:.8rem; font-weight:630; }
.state-pending_approval,.state-awaiting_reboot,.state-unknown,.state-closed_unknown,.state-needs_attention { color:#77581a; background:#fcf1d5; }
.state-approved,.state-succeeded { color:#236343; background:#e6f4e9; }
.state-rejected,.state-failed,.state-revoked { color:#873c36; background:#faeae6; }
.state-running,.state-verifying { color:#285b70; background:#e6f1f6; }
@media(min-width:761px) { .order-list th:first-child { width:30%; } .order-list th:nth-child(2) {width:17%;} .order-list th:nth-child(3) {width:21%;} }