66 lines
10 KiB
TypeScript
66 lines
10 KiB
TypeScript
import { useEffect, useState } from 'react';
|
||
import { pretty, record, request, Session, tenantPath, page, RecordValue } from './api';
|
||
import { adminIntent, allowed, parseStrictJson, recipeInput, sha256 } from './safety';
|
||
|
||
const message = (e: unknown) => e instanceof Error ? e.message : 'Unbekannter Fehler';
|
||
function Result({ error, result }: { error: string | null; result: unknown }) { return <>{error && <div role="alert" className="error">{error}</div>}{result !== null && <pre>{pretty(result)}</pre>}</>; }
|
||
|
||
export function AdminControl({ auth, path, title, permission, warning, stopped, done }: { auth: Session; path: string; title: string; permission: string; warning: string; stopped?: boolean; done?: () => void }) {
|
||
const [nonce, setNonce] = useState(() => crypto.randomUUID()), [error, setError] = useState<string | null>(null), [result, setResult] = useState<unknown>(null), [busy, setBusy] = useState(false);
|
||
return <details><summary>{title}</summary><p className="warning">{warning}</p><p>Erforderliches Recht: {permission}. {allowed(auth, permission) ? 'Von Sitzung angekündigt; Server prüft erneut.' : 'Unbekannt oder nicht erteilt; Aktion gesperrt.'}</p>
|
||
<form onSubmit={async e => { e.preventDefault(); const form = e.currentTarget, f = new FormData(form); setError(null); setBusy(true); try {
|
||
if (!allowed(auth, permission) || !auth.csrf_token) throw new Error('Berechtigung/CSRF fehlt');
|
||
const body = adminIntent(f.get('confirmed') === 'on', String(f.get('reason') ?? ''), String(f.get('nonce') ?? ''), nonce);
|
||
const response = await request(path, { csrf: auth.csrf_token, body: stopped === undefined ? body : { ...body, stopped } });
|
||
setResult(response); form.reset(); setNonce(crypto.randomUUID()); done?.();
|
||
} catch (e) { setError(message(e)); } finally { setBusy(false); } }}>
|
||
<label>Grund für {title}<input name="reason" required maxLength={1024}/></label>
|
||
<p>Aktuelle Bestätigungskennung: <code>{nonce}</code></p><label>Bestätigungskennung eingeben<input name="nonce" autoComplete="off" required/></label>
|
||
<label className="check"><input type="checkbox" name="confirmed" required/>Ich bestätige diese konkrete administrative Wirkung ausdrücklich.</label>
|
||
<button className="danger" disabled={busy || !allowed(auth, permission)}>{title} · ausdrücklich ausführen</button><Result error={error} result={result}/>
|
||
</form></details>;
|
||
}
|
||
export function TenantControls({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||
const [status, setStatus] = useState<unknown>('unknown — kein lesender Stopstatus-Endpunkt angekündigt');
|
||
return <section><h2>Mitgliedschaft und Ausführungsstopp</h2><p>Rollen: {auth.roles?.join(', ') || 'unknown'} · Rechte: {auth.permissions?.join(', ') || 'unknown'}</p><p>Aktueller Ausführungsstopp: {typeof status === 'string' ? status : pretty(status)}</p><p>Frontendberechtigungen sind keine Sicherheitsgrenze. Aktuelle Rechte/Tenant/CSRF/Policy prüft der Server. Anmeldemodi werden über /auth/config ermittelt; die Simulationskennzeichnung stammt ausschließlich aus der Serversitzung.</p>
|
||
<AdminControl auth={auth} permission="tenant:stop" path={tenantPath(tenantId, '/execution-stop')} title="Mandantenausführung stoppen" stopped={true} warning="Sperrt neue Starts dieses Mandanten. Bereits erfolgte Wirkungen werden nicht rückgängig gemacht." done={() => setStatus('true — zuletzt erfolgreich per UI angefordert; kein unabhängiger aktueller Lesestatus')}/>
|
||
<AdminControl auth={auth} permission="tenant:stop" path={tenantPath(tenantId, '/execution-stop')} title="Mandantenausführung wieder zulassen" stopped={false} warning="Hebt den mandantenweiten Startstopp auf. Dies ist keine Genehmigung und keine Aufhebung anderer Sicherheitsprüfungen." done={() => setStatus('false — zuletzt erfolgreich per UI angefordert; kein unabhängiger aktueller Lesestatus')}/>
|
||
</section>;
|
||
}
|
||
async function downloadArtifact(path: string) {
|
||
const r = await fetch(path, { credentials: 'same-origin', cache: 'no-store' });
|
||
if (!r.ok) { const data: unknown = await r.json().catch(() => null); throw new Error(`Artefaktabruf HTTP ${r.status}: ${data ? pretty(data) : 'keine JSON-Fehlerdetails'}`); }
|
||
if (!r.headers.get('content-type')?.startsWith('application/octet-stream') || !r.body) throw new Error('Binärer Artefaktvertrag nicht erfüllt');
|
||
const reader = r.body.getReader(), chunks: Uint8Array[] = []; let size = 0;
|
||
try { while (true) { const next = await reader.read(); if (next.done) break; size += next.value.length; if (size > 262144) throw new Error('Artefakt über 256 KiB'); chunks.push(next.value); } } finally { await reader.cancel(); }
|
||
if (!size) throw new Error('Leeres Artefakt'); const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; }
|
||
return { size_bytes: size, computed_sha256: await sha256(bytes), server_metadata: 'not_provided — GET liefert Binärbytes, keinen JSON-Details-Endpunkt' };
|
||
}
|
||
export function Catalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||
const [cursor, setCursor] = useState<string | null>(null), [list, setList] = useState<unknown>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0), [recipe, setRecipe] = useState('{}'), [result, setResult] = useState<unknown>(null), [busy, setBusy] = useState(false), [receipts, setReceipts] = useState<Record<string, RecordValue>>({});
|
||
useEffect(() => { const controller = new AbortController(); setList(null); setError(null); request(tenantPath(tenantId, `/package-recipes${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal: controller.signal }).then(v => setList(page(v))).catch(e => { if (!controller.signal.aborted) setError(message(e)); }); return () => controller.abort(); }, [tenantId, cursor, revision]);
|
||
const loaded = list ? page(list) : null;
|
||
return <section><h2>Unveränderlicher Paketkatalog und Artefakte</h2><p>Exakte Paket-/Rezeptversionen, Architektur und SHA-256. Keine freie Download-URL oder LLM-URL als Installer. Import ist keine Ausführungsgenehmigung.</p>
|
||
<Result error={error} result={loaded}/>{loaded && <><button disabled={!cursor} onClick={() => setCursor(null)}>Erste Rezeptseite</button><button disabled={!loaded.next_cursor} onClick={() => setCursor(loaded.next_cursor)}>Nächste Rezeptseite</button></>}
|
||
<details><summary>Neue unveränderliche Rezeptversion importieren</summary><p>POST package-recipes, Recht catalog:write. Bestehende Versionen werden nicht bearbeitet; Plattform wird nur dargestellt, soweit geliefert, nicht aus Architektur erfunden.</p><form onSubmit={async e => { e.preventDefault(); setError(null); setResult(null); setBusy(true); try {
|
||
if (!allowed(auth, 'catalog:write')) throw new Error('catalog:write unbekannt/nicht erteilt'); const input = recipeInput(parseStrictJson(recipe));
|
||
const expected = await sha256(new TextEncoder().encode(JSON.stringify(input))); const response = record(await request(tenantPath(tenantId, '/package-recipes'), { body: input, csrf: auth.csrf_token }));
|
||
if (response.sha256 !== expected || JSON.stringify(recipeInput(response.recipe)) !== JSON.stringify(input)) throw new Error('Rezeptantwort stimmt nicht mit unveränderlichen Importbytes überein'); setResult(response); setRevision(v => v + 1);
|
||
} catch (e) { setError(message(e)); } finally { setBusy(false); } }}>
|
||
<label>Vollständiges Rezept JSON<textarea rows={10} value={recipe} onChange={e => setRecipe(e.target.value)} spellCheck={false}/></label><p>Schema 1: provider=apt, package, version, architecture=amd64, recipe_version, installation_context=system, reboot_policy=never. Leeres JSON ist nicht gültig.</p><button disabled={busy || !allowed(auth, 'catalog:write')}>Neue feste Rezeptversion importieren</button>
|
||
</form></details>
|
||
<details><summary>Öffentliches Artefakt importieren / verifizieren</summary><p className="warning">Nur ausdrücklich öffentliche Testartefakte, keine Secrets/Schlüssel/Kundenlogs. Maximal 256 KiB; Upload und Abruf zeigen nur Hash/Größe, keine Rohbytes.</p>
|
||
<form onSubmit={async e => { e.preventDefault(); const form = e.currentTarget, f = new FormData(form); setError(null); setResult(null); setBusy(true); try {
|
||
if (!allowed(auth, 'catalog:write') || f.get('public') !== 'on') throw new Error('Importrecht und ausdrückliche Public-Bestätigung erforderlich');
|
||
const file = f.get('file'); if (!(file instanceof File) || file.size < 1 || file.size > 262144) throw new Error('Datei muss 1–262144 Bytes enthalten');
|
||
const bytes = new Uint8Array(await file.arrayBuffer()), expected = await sha256(bytes), response = record(await request(tenantPath(tenantId, '/artifacts'), { csrf: auth.csrf_token, body: { bytes: Array.from(bytes), media_type: f.get('media_type') } }));
|
||
if (response.sha256 !== expected || response.size_bytes !== bytes.length || typeof response.artifact_id !== 'string') throw new Error('Artefakt-Hash/Größe/ID widersprechen Importbytes');
|
||
setReceipts(r => ({ ...r, [String(response.artifact_id)]: response })); setResult(response); form.reset();
|
||
} catch (e) { setError(message(e)); } finally { setBusy(false); } }}>
|
||
<label>Öffentliche Datei<input type="file" name="file" required/></label><label>Medientyp<select name="media_type"><option>application/octet-stream</option><option>text/plain</option></select></label><label><input type="checkbox" name="public" required/>Diese Datei ist ausdrücklich öffentlich und enthält keine Secrets.</label><button disabled={busy || !allowed(auth, 'catalog:write')}>Öffentliches Artefakt importieren</button>
|
||
</form>
|
||
<form onSubmit={async e => { e.preventDefault(); const id = String(new FormData(e.currentTarget).get('id') ?? ''); setBusy(true); setError(null); setResult(null); try { if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error('Konkrete Artefakt-UUID erforderlich'); const response = await downloadArtifact(tenantPath(tenantId, `/artifacts/${encodeURIComponent(id)}`)); const receipt = receipts[id]; if (receipt && (receipt.sha256 !== response.computed_sha256 || receipt.size_bytes !== response.size_bytes)) throw new Error('Artefaktabruf widerspricht Importbeleg'); setResult({ artifact_id: id, ...response, compared_with_import_receipt: !!receipt }); } catch (e) { setError(message(e)); } finally { setBusy(false); } }}><label>Artefakt-ID für binären Integritätsabruf<input name="id" required/></label><button disabled={busy || !allowed(auth, 'operations:read')}>Artefaktbytes abrufen und Hash prüfen</button></form>
|
||
</details><Result error={null} result={result}/>
|
||
</section>;
|
||
}
|