Add versioned script library, reconcile permit refusals and compact helper captures

This commit is contained in:
2026-11-17 15:45:56 +01:00
parent a576c10e8a
commit 8e2fef7007
29 changed files with 1225 additions and 50 deletions
+110
View File
@@ -0,0 +1,110 @@
import React, { FormEvent, useEffect, useState } from 'react';
import { objectId, page, record, request, Session, tenantPath, text } from './api';
import { allowed } from './safety';
interface Draft {
name: string;
interpreter: 'posix_sh' | 'bash' | 'powershell';
execution_identity: 'agent_service' | 'root' | 'system';
script_utf8: string;
}
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); }
}
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) {
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.`);
});
}
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 limit = 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>
<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={Math.min(limit,120)} required/></label>
<button disabled={!selected.length}>Plan vorbereiten</button>
</fieldset></form>}
</section>;
}