From 477a63f20e914d4a26a89ce81147ee8a1c59cc63 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Tue, 17 Nov 2026 22:42:31 +0100 Subject: [PATCH] Separate script publishing, job assignment and interactive approval in the WebUI --- tests/browser/approval-inbox.spec.ts | 87 ++++++ web/src/approval-inbox.tsx | 51 +++ web/src/console-output.test.tsx | 6 +- web/src/console-output.tsx | 52 +-- web/src/devices.tsx | 6 +- web/src/main.tsx | 451 +++++++++++++++++---------- web/src/navigation.tsx | 3 +- web/src/order-composer.tsx | 306 ++++++++++++++++++ web/src/order-presentation.tsx | 66 ++++ web/src/script-catalog.ts | 66 ++++ web/src/script-library.tsx | 190 +++++------ web/src/script-workspace.css | 17 + web/src/style.css | 20 ++ 13 files changed, 1027 insertions(+), 294 deletions(-) create mode 100644 tests/browser/approval-inbox.spec.ts create mode 100644 web/src/approval-inbox.tsx create mode 100644 web/src/order-composer.tsx create mode 100644 web/src/order-presentation.tsx create mode 100644 web/src/script-catalog.ts create mode 100644 web/src/script-workspace.css diff --git a/tests/browser/approval-inbox.spec.ts b/tests/browser/approval-inbox.spec.ts new file mode 100644 index 0000000..665cd6f --- /dev/null +++ b/tests/browser/approval-inbox.spec.ts @@ -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); +}); diff --git a/web/src/approval-inbox.tsx b/web/src/approval-inbox.tsx new file mode 100644 index 0000000..16a9c87 --- /dev/null +++ b/web/src/approval-inbox.tsx @@ -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([]); + 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
{customer && }
; + if (list.data && !list.data.canReview) return

Dieses Konto hat keine Berechtigung für Genehmigungen.

; + return
+
+ {(['pending','history'] as const).map(v => )} +
+
+ + {!list.data && !list.error &&

Anträge werden geladen …

} + {list.data && (!!list.data.items.length + ? open(objectId(row,'tenant'), objectId(row,'plan'))}/> + :

{view === 'pending' ? 'Keine offenen Genehmigungen.' : 'Keine abgeschlossenen Anträge.'}

)} + {list.data && } +
; +} diff --git a/web/src/console-output.test.tsx b/web/src/console-output.test.tsx index f4288b3..cec2782 100644 --- a/web/src/console-output.test.tsx +++ b/web/src/console-output.test.tsx @@ -9,7 +9,7 @@ it('renders hostile output as inert text, reports real status and preserves exac const hostile = '\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(); - for (const expected of ['unknown', 'fixed-attempt', 'TIMEOUT', 'unknown / nicht gemeldet', 'nur ein Ausschnitt', 'keinen Live-Ausgabestream', 'Abbruch angefordert', 'neuen genehmigten Plan', '<script>', '\\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', '<script>', '\\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(); } - 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'); }); diff --git a/web/src/console-output.tsx b/web/src/console-output.tsx index 250bba0..27ace75 100644 --- a/web/src/console-output.tsx +++ b/web/src/console-output.tsx @@ -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

{name} · {raw.length} gespeicherte Bytes

{view.encoding}. Steuerzeichen werden sichtbar als \\uXXXX dargestellt; Rohbytes bleiben erhalten.

- -
{raw.length ? view.text : '(leere Ausgabe)'}
- -
{name} Originalbytes (dezimal)
{JSON.stringify(Array.from(raw))}
+ return

{name === 'stdout' ? 'Standardausgabe' : 'Fehlerausgabe'}

+
{raw.length ? view.text : '(leere Ausgabe)'}
+
Zeichensatz und Download · {name} + +

{view.encoding}. Steuerzeichen erscheinen als {'\\uXXXX'}.

+ +
{name} Originalbytes (dezimal)
{JSON.stringify(Array.from(raw))}
+
; } catch (error) { return

{name}: {error instanceof Error ? error.message : 'Ausgabe nicht lesbar'}. Keine verlässliche Textansicht.

; } } export function ConsoleOutput({ job }: { job: RecordValue }) { const state = stringField(job, 'state'); return

Konsolenergebnis

-

Zustand: {state} · Versuch: {stringField(job, 'attempt_id')} · Revision: {typeof job.revision === 'number' ? job.revision : 'unknown'}

-

Die Ansicht fragt den gespeicherten Zustand alle 4 Sekunden ab. stdout/stderr erscheinen nach Eingang des Ergebnisses; es gibt keinen Live-Ausgabestream.

- {state === 'unknown' &&

Wirkung oder Ergebnis unklar. Keine automatische Wiederholung; ein neuer Versuch benötigt Abgleich und einen neuen genehmigten Plan.

} - {job.cancel_requested === true &&

Abbruch angefordert; dies bestätigt weder Prozessende noch Rollback.

} + {state === 'unknown' &&

Wirkung unklar. Ein weiterer Versuch benötigt einen Abgleich und einen neuen genehmigten Plan.

} + {job.cancel_requested === true &&

Abbruch angefordert. Die Rückmeldung des Geräts steht aus.

} {job.pending_reason != null &&

Wartegrund: {String(job.pending_reason)}

} - {job.result == null ?

Noch kein gespeichertes Ergebnis. Fehlende Ausgabe ist kein Erfolgsnachweis.

: } + {job.result == null ?

Noch kein gespeichertes Ergebnis.

: } +
Versuch und Datenstand +

Zustand {state} · Versuch {stringField(job,'attempt_id')} · Revision {typeof job.revision === 'number' ? job.revision : 'unbekannt'}.

+

Die Ansicht zeigt die gespeicherte Ausgabe und aktualisiert den Stand alle vier Sekunden.

+
; } 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 <>

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'}

-

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.'}

-

Neustartbedarf: {typeof reboot === 'boolean' ? String(reboot) : 'unknown'}. Ein Exitcode 0 bestätigt Prozessabschluss; fachliche Nachbedingungen stehen im vollständigen Ergebnis.

-

Ausgabe ist nicht vertrauenswürdiger Text vom Zielgerät. Sie erteilt keine Genehmigung und wird nicht als Anweisung ausgeführt.

- ; - } catch { return

Ergebnisformat unbekannt; vollständige Originaldaten stehen darunter.

; } + 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 <> +

Exitcode {exit}{typeof result.error_code === 'string' && result.error_code && ' · Fehlercode '+result.error_code}

+ {reboot === true &&

Ein Neustart ist erforderlich.

} + {windowsUpdate && reboot == null &&

Neustartbedarf unbekannt.

} + {windowsUpdate && reboot === false &&

Das Gerät meldet keinen Neustartbedarf.

} + {result.output_truncated === true &&

Die gespeicherte Ausgabe ist nur ein Ausschnitt.

} + {typeof result.output_truncated !== 'boolean' &&

Vollständigkeit ist nicht bestätigt.

} + + + ; + } catch { return

Unbekanntes Ergebnisformat. Die Originaldaten stehen unter „Technische Ausführungsdaten“.

; } } diff --git a/web/src/devices.tsx b/web/src/devices.tsx index 4106801..d597992 100644 --- a/web/src/devices.tsx +++ b/web/src/devices.tsx @@ -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({ - +
)} diff --git a/web/src/main.tsx b/web/src/main.tsx index fe8cb1a..3b33565 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -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
{label}
{pretty(value)}
; } +export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return
{label}
{pretty(value)}
; } 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

Vollständige feste Skriptaufträge ({jobs.length})

Diese Inhalte stammen aus den hashgeprüften gespeicherten Planbytes. Jeder Zielauftrag, Versuch und Skripthash ist fest gebunden.

- {jobs.map(job =>

Asset {job.assetId}

Agent: {job.agentId} · Job: {job.jobId} · Versuch: {job.attemptId}

- {job.revision &&

Skriptbibliothek · {job.revision.name} · Version {job.revision.version} · {job.revision.id}

} -

Interpreter: {job.interpreter} · Identität: {job.identity} · Privilegiertes Profil: {job.privilegedProfile === fullMaintenanceScriptProfile ? fullMaintenanceScriptProfile : 'bestehendes begrenztes Profil'} · Windowsprozess: {job.interpreter !== 'powershell' ? 'nicht zutreffend' : job.windowsProfile === 'powershell_51_remote_signed' ? 'Windows PowerShell5.1 RemoteSigned, nur Jobprozess' : 'geerbte Windowsrichtlinie / kein Windows-Prozessoverride'}

-

Frühester Start: {job.notBefore} · Startfrist: {job.startBefore} · Laufzeit: {job.runtimeSeconds}s · Ausgabe: höchstens {job.outputBytes} Bytes

-

Skript: {job.scriptBytes} UTF-8-Bytes · SHA256: {job.scriptHash}
Jobpayload-SHA256: {job.jobHash}

- {job.privilegedProfile === fullMaintenanceScriptProfile ?

{fullMaintenanceWarning}

: job.identity === 'root' &&

{rootWarning}

} -

Vollständiger Skripttext; Steuerzeichen, BOM und CR werden sichtbar als \uXXXX dargestellt. LF bleibt Zeilenumbruch. Kein Kürzen oder Normalisieren der gespeicherten Bytes.

-
{outputText(new TextEncoder().encode(job.script)).text}
-

Feste Argumente (JSON): {JSON.stringify(job.arguments)}

stdout-Nachbedingung (JSON): {JSON.stringify(job.expectedStdout)}{job.expectedStdout === null && ' · keine zusätzliche fachliche stdout-Prüfung gebunden'}

-
)} + const jobs = scriptPlanJobs(plan); + if (!jobs.length) return null; + const grouped = new Map(); + 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

Skriptinhalt

+ {[...grouped.values()].map(group => { + const job = group[0]!; + return
+ {grouped.size > 1 &&

{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(', ')}

} +

{job.revision ? job.revision.name+' · Version '+job.revision.version : 'Einmaliges Skript'} · {job.interpreter} · {identityName(job.identity)}

+ {job.privilegedProfile === fullMaintenanceScriptProfile &&

{fullMaintenanceWarning}

} + {job.identity === 'root' && job.privilegedProfile !== fullMaintenanceScriptProfile &&

{rootWarning}

} + {job.interpreter === 'powershell' &&

Windows PowerShell 5.1 · {job.windowsProfile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned für diesen Prozess' : 'Richtlinie des Geräts'}

} +
{outputText(new TextEncoder().encode(job.script)).text}
+ {job.arguments.length > 0 &&

Argumente {JSON.stringify(job.arguments)}

} + {job.expectedStdout !== null &&

Erwartete Ausgabe {JSON.stringify(job.expectedStdout)}

} +
Ausführungsdetails und Prüfsummen +

{job.scriptBytes} Byte · SHA256 {job.scriptHash}

+

Profil {job.privilegedProfile} · {job.identity} · Laufzeit {job.runtimeSeconds}s · Ausgabe bis {job.outputBytes} Byte

+ {group.map(j =>

Gerät {j.assetId} · Agent {j.agentId}

+

Job {j.jobId} · Versuch {j.attemptId} · SHA256 {j.jobHash}

)} +
+
; + })}
; - } catch { return ; } + } catch { return ; } } export function SystemPlanNotice({ plan }: { plan: RecordValue }) { let jobs: RecordValue[]; @@ -146,11 +170,8 @@ function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session ; } -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(null), [revision, setRevision] = useState(0), [source, setSource] = useState('{}'), [busy, setBusy] = useState(false), [error, setError] = useState(null), [receipts, setReceipts] = useState([]); - const [enrollment, setEnrollment] = useState<{ token: string; expires: string; origin: string | null; platforms: string[] } | null>(null); - const [enrollmentError, setEnrollmentError] = useState(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 }: { {receipts.length > 0 && } -
{ if (!event.currentTarget.open) setEnrollment(null); }}> - Neues Gerät aufnehmen + ; +} + +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(null); + const [issuing, setIssuing] = useState(false); + return

Gerät aufnehmen

Das HTTPS-Installationsskript fragt auf dem Gerät nach dem Einmalcode. Er gilt für {customerName} und läuft nach 15 Minuten ab.

+ ; } -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(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

Unveränderlicher Plan / Genehmigungsdetail

{plan.data && <> -

Plan-ID: {id}

Exakter gespeicherter Planhash: {stringField(plan.data, 'plan_hash')}

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.

- - - - - - - -

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.

- {blockers.length > 0 &&
Nicht genehmigungsfähig: {blockers.join('; ')}
} - - - -

Nur für einen bestehenden Antrag pending_approval; Server prüft interaktive Sitzung, Rechte, Tenant, Policy und Frist erneut. Keine automatische Genehmigung.

- - }
; +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(null); - const list = useResource(async signal => page(await request(tenantPath(tenantId, `/operations${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal })), [tenantId, cursor], true); - return

Anträge und Ausführungen

{list.data && <>
    {list.data.items.map(o =>
  • · Antrag: {stringField(o, 'approval_state')} · Ausführung: {stringField(o, 'execution_state')}
  • )}
{!list.data.items.length &&

Keine sichtbaren Anträge in diesem Listenabschnitt.

} }
; +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(null); + const [busy, setBusy] = useState(false); + const [confirmedHash, setConfirmedHash] = useState(''); + const data = plan.error ? null : plan.data; + if (!data) return
{!plan.error &&

Plan wird geprüft …

}
; + + 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(); + 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
+

{title}{revision ? ' · Version '+String(revision.version) : ''}

+
+ {display(customerName, display(data.customer_name, tenantId))} + + {data.approval_state ? : 'Vorbereitet'} + {display(saved.reason, 'Kein Anlass angegeben')} +
+

Zielgeräte und Zeitfenster

+
    {payloads.map(p =>
  • + {displayTarget(p)} · {identityName(p.execution_identity)} + {when(p.not_before)} bis {when(p.start_before)} · Laufzeit bis {String(p.max_runtime_seconds)} s +
  • )}
+

Höchstens {String(saved.max_parallel)} gleichzeitig · Stopp nach {String(saved.halt_after_failures)} {saved.halt_after_failures === 1 ? 'Fehler' : 'Fehlern'}

+ + + {!script && } + {!script &&
Aktionen je Gerät{payloads.map(p =>
+ {displayTarget(p)}
{pretty(p.action)}
+
)}
} + + + {(pending || mode === 'submit') && blockers.length > 0 &&

{blockers.join(' · ')}

} + {mode === 'submit' && !data.approval_state && allowed(auth, 'operations:submit') && + } + {mode === 'submit' && typeof data.operation_id === 'string' && } + {mayDecide &&
Entscheidung + {!!missingRights.length &&

Für die Genehmigung fehlen Rechte: {missingRights.join(', ')}.

} + + {' '} + +
} + {mode === 'review' && data.approval_state === 'approved' && allowed(auth,'plans:revoke') &&
Berechtigung verwalten + +
} +
; +} + +function Operations({ tenantId, open, customerName }: { tenantId: string; open: (id: string) => void; customerName?: string }) { + const [pages, setPages] = useState([]); + 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 ; + return
+ {!list.data && !list.error &&

Aufträge werden geladen …

} + {list.data && (list.data.items.length + ? open(objectId(row,'operation'))}/> + :

Für diesen Kunden gibt es noch keine Aufträge.

)} + {list.data && } +
; +} +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(null); - return

Antrag / Ausführung {id}

{op.data && <> -

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.

- - {Array.isArray(op.data.jobs) && op.data.jobs.map(v => { const job = record(v); const jid = objectId(job, 'job'); return ; })} - }{jobId && }
; + const data = op.error ? null : op.data; + if (!data) return
{!op.error &&

Auftrag wird geladen …

}
; + 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

{orderTitle(data)}

+
{display(data.customer_name, customerName)} + {when(data.created_at)} + + {display(data.reason, 'Kein Anlass angegeben')}
+

Geräte und Ergebnisse

+ {jobs.length ?
    {jobs.map(job =>
  • + +
  • )}
+ : <>

{names.map(deviceName).join(', ')}

{data.approval_state === 'pending_approval' + ? 'Nach der Genehmigung erscheint hier der Fortschritt je Gerät.' : 'Für diesen Auftrag liegen keine Ausführungen vor.'}

} + {selected && jobId && } + {allowed(auth, 'plans:approve') && } + +
; } -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(null), [busy, setBusy] = useState(false); - return

Job {id}

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.

{job.data && <>} -
{ 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); } }}>
- {job.data && stringField(job.data, 'state') === 'unknown' && }
; + if (job.error) return ; + const state = job.data?.state; + const terminal = ['succeeded','failed','cancelled','expired','unknown','closed_unknown']; + return

Ergebnis für {hostname}

+ {job.data && <>} + {job.data && allowed(auth,'jobs:cancel') && !terminal.includes(String(state)) && !job.data.cancel_requested &&
Abbruch anfordern +
{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);} + }}>
+
} + {job.data && state === 'unknown' && } +
; } 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(null); @@ -261,6 +426,7 @@ function UnknownClosure({ tenantId, id, job, auth, done }: { tenantId: string; i const pages: Record = { 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(null); - const [planId, setPlan] = useState(null), - [operationId, setOperation] = useState(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 }) { {title} + {key === 'genehmigungen' && typeof pendingCount === 'number' && pendingCount > 0 && + {pendingCount}} ))} @@ -391,7 +567,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) { {pages[route.page]} - {route.page !== 'geraete' && route.page !== 'kunden' && ( + {!['geraete', 'kunden','genehmigungen'].includes(route.page) && !detailRoute && (