feat: snapshot Linux-first RMM MVP and pause handover
Rust development slice / linux (push) Failing after 1m10s

This commit is contained in:
BuTzZ
2026-11-12 22:06:25 +01:00
commit 6c3203d725
194 changed files with 49234 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { approvalBlockers, page, PlanInput, request, session, validateInput } from './api';
afterEach(() => vi.unstubAllGlobals());
describe('JSON contract boundary', () => {
it('refuses missing simulation identity metadata', () => {
expect(() => session({ principal: { id: 'a', display_name: 'name' }, tenants: [], csrf_token: 'csrf' })).toThrow('Sitzungsprofil');
expect(session({ principal: { id: 'sim', display_name: 'SIMULIERT', simulated: true }, tenants: [], csrf_token: 'csrf' }).principal.simulated).toBe(true);
});
it('does not present absent completeness as a complete result', () => {
expect(page({ items: [], next_cursor: null }).completeness).toBe('unknown');
expect(page({ items: [], next_cursor: null }).truncated).toBe(true);
expect(() => page({ devices: [] })).toThrow('items');
});
const preview = { asset_id: 'asset', job_payload_hash: 'hash', payload: { action: 'refresh_inventory', asset_id: 'asset' } };
const plan = { plan_id: 'p', plan_hash: 'hash', expires_at: new Date(Date.now() + 60000).toISOString(), resolved_targets: [preview], excluded_targets: [], plan_payload: { targets: [preview] } };
it('accepts immutable target previews without execution job or attempt IDs', () => {
expect(approvalBlockers(plan)).toEqual([]);
expect(approvalBlockers({ ...plan, resolved_targets: [{ ...preview, plan_target_id: 'target' }] })).toEqual([]);
expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], payloads: [preview] })).toEqual([]);
expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [preview] })).toEqual([]);
expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [{ ...preview, job_id: 'reserved', attempt_id: 'reserved-attempt' }] })).toEqual([]);
expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], jobs: [{ job_payload_hash: 'hash', payload: preview.payload }] })).toEqual([]);
});
it('fails closed for missing, partial, malformed or contradictory previews', () => {
expect(approvalBlockers({ plan_id: 'p', plan_hash: 'hash' })).toContain('Unveränderliche Zielpreviews fehlen');
for (const value of [
{ ...plan, resolved_targets: [{ ...preview, job_payload_hash: '' }] },
{ ...plan, resolved_targets: [{ ...preview, payload: {} }] },
{ ...plan, resolved_targets: [{ ...preview, payload: null }] },
{ ...plan, resolved_targets: [{ ...preview, asset_id: '' }] },
{ ...plan, resolved_targets: [{ ...preview, payload: { asset_id: 'foreign' } }] },
{ ...plan, resolved_targets: ['asset', 'missing'], payloads: [preview] },
{ ...plan, resolved_targets: ['foreign'], payloads: [preview] },
{ ...plan, resolved_targets: ['asset'], payloads: [null] },
{ ...plan, resolved_targets: [null], payloads: [preview] },
{ ...plan, excluded_targets: ['missing'] },
{ ...plan, resolved_targets: ['asset'], payloads: 'invalid', jobs: [preview] },
{ ...plan, resolved_targets: [{ ...preview, payload: null }], jobs: [preview] },
]) expect(approvalBlockers(value).length).toBeGreaterThan(0);
});
it('rejects duplicate assets in both fixed targets and preview lists', () => {
expect(approvalBlockers({ ...plan, resolved_targets: [preview, preview] })).toContain('Doppelte asset_id in fester Zielmenge');
expect(approvalBlockers({ ...plan, resolved_targets: ['asset'], payloads: [preview, preview] })).toContain('Doppelte asset_id in Zielpreviews');
expect(approvalBlockers({ ...plan, resolved_targets: ['asset', 'asset'], payloads: [preview] })).toContain('Doppelte asset_id in fester Zielmenge');
});
it('preserves script UTF-8 bytes and refuses duplicate/dynamic targets', () => {
const variant = { script_utf8: 'printf hi\r\n', os_family: 'linux', encoding: 'utf-8', interpreter: 'posix_sh' };
const input: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['asset'] }, parameters: { variants: [variant], execution_identity: 'agent_service', timeout_seconds: 60, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'test' };
validateInput(input); expect(input.parameters.variants).toEqual([variant]);
expect(() => validateInput({ ...input, targets: { asset_ids: ['a', 'a'] } })).toThrow('eindeutige');
});
it('accepts explicit existing dev simulation evidence but not a principal-name guess', () => {
expect(session({ principal: 'sim-test', tenant_id: 't', testsimulation: true, csrf_token: 'csrf' }).principal.simulated).toBe(true);
expect(() => session({ principal: 'sim-test', tenant_id: 't', csrf_token: 'csrf' })).toThrow();
});
});
describe('same-origin cookie transport', () => {
it('sends CSRF and same-origin credentials, never bearer', async () => {
const fetch = vi.fn().mockResolvedValue(new Response('{}', { status: 200 })); vi.stubGlobal('fetch', fetch);
await request('/api/v1/test', { csrf: 'csrf', body: { plan_hash: 'exact' } });
expect(fetch).toHaveBeenCalledWith('/api/v1/test', expect.objectContaining({ method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'csrf' }, body: '{"plan_hash":"exact"}' }));
await expect(request('//external.invalid')).rejects.toThrow('gleiche Origin');
expect(fetch).toHaveBeenCalledTimes(1);
});
it('retains backend errors and correlation rather than returning fake success', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'POLICY_DENIED', message: 'denied', correlation_id: 'correlation' }), { status: 403 })));
await expect(request('/api/v1/test')).rejects.toThrow('POLICY_DENIED: denied (Korrelation correlation)');
});
});
+125
View File
@@ -0,0 +1,125 @@
/** Single JSON boundary. Unknown/partial backend fields remain visible; never synthesize evidence. */
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
export type RecordValue = { [key: string]: unknown };
export function record(value: unknown, context = 'Antwort'): RecordValue {
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`CONTRACT_ERROR: ${context} ist kein Objekt`);
return value as RecordValue;
}
export function text(value: unknown, context: string): string {
if (typeof value !== 'string' || !value) throw new Error(`CONTRACT_ERROR: ${context} fehlt`);
return value;
}
export function stringField(value: RecordValue, key: string): string { return typeof value[key] === 'string' ? value[key] : 'unknown'; }
export interface Tenant { tenant_id: string; name: string }
export interface Session { principal: { id: string; display_name: string; simulated: boolean }; tenants: Tenant[]; csrf_token: string; permissions?: string[]; roles?: string[] }
export interface Page { items: RecordValue[]; next_cursor: string | null; completeness: string; truncated: boolean; as_of: string }
export interface AuthConfig { oidc_configured: boolean; oidc_login_url: '/auth/oidc/login' | null; dev_login_enabled: boolean }
export function authConfig(value: unknown): AuthConfig {
const r = record(value, 'Auth-Konfiguration');
if (typeof r.oidc_configured !== 'boolean' || typeof r.dev_login_enabled !== 'boolean') throw new Error('CONTRACT_ERROR: Anmeldemodi nicht ausdrücklich konfiguriert');
// Only the canonical same-origin server entrypoint is allowed. No issuer,
// return URL, query, fragment, credentials or externally supplied redirect.
if (r.oidc_configured ? r.oidc_login_url !== '/auth/oidc/login' : r.oidc_login_url !== null) throw new Error('CONTRACT_ERROR: OIDC-Anmeldepfad ungültig');
return { oidc_configured: r.oidc_configured, dev_login_enabled: r.dev_login_enabled, oidc_login_url: r.oidc_configured ? '/auth/oidc/login' : null };
}
export function tenant(value: unknown): Tenant { const r = record(value); return { tenant_id: text(r.tenant_id ?? r.id, 'tenant_id'), name: text(r.name, 'tenant.name') }; }
export function session(value: unknown): Session {
const r = record(value);
const strings = (v: unknown): string[] | undefined => Array.isArray(v) && v.every(x => typeof x === 'string') ? v : undefined;
const membership = { permissions: strings(r.permissions), roles: strings(r.roles) };
// Both OIDC humans and dev/test principals use this DTO. Only the server's
// explicit boolean marks a simulation; names/roles never imply that identity.
if (typeof r.principal === 'string' && typeof r.testsimulation === 'boolean') {
const id = text(r.principal, 'principal'), tenantId = text(r.tenant_id, 'tenant_id');
return { principal: { id, display_name: id, simulated: r.testsimulation }, tenants: [{ tenant_id: tenantId, name: tenantId }], csrf_token: text(r.csrf_token, 'csrf_token'), ...membership };
}
const p = record(r.principal, 'principal');
if (typeof p.simulated !== 'boolean' || !Array.isArray(r.tenants)) throw new Error('CONTRACT_ERROR: Sitzungsprofil unvollständig');
return { principal: { id: text(p.id, 'principal.id'), display_name: text(p.display_name, 'principal.display_name'), simulated: p.simulated }, tenants: r.tenants.map(tenant), csrf_token: text(r.csrf_token, 'csrf_token'), ...membership };
}
export function page(value: unknown): Page {
const r = record(value);
if (!Array.isArray(r.items)) throw new Error('CONTRACT_ERROR: items fehlt');
if (r.next_cursor !== null && typeof r.next_cursor !== 'string') throw new Error('CONTRACT_ERROR: next_cursor fehlt');
return { items: r.items.map(v => record(v)), next_cursor: r.next_cursor, completeness: stringField(r, 'completeness'), truncated: r.truncated !== false, as_of: stringField(r, 'as_of') };
}
export class ApiError extends Error { constructor(public status: number, public code: string, message: string, public correlation: string) { super(`${code}: ${message}${correlation ? ` (Korrelation ${correlation})` : ''}`); } }
export async function request(path: string, options: { body?: unknown; csrf?: string; signal?: AbortSignal } = {}): Promise<unknown> {
if (!path.startsWith('/') || path.startsWith('//')) throw new Error('Nur gleiche Origin erlaubt');
const changing = options.body !== undefined;
const response = await fetch(path, { method: changing ? 'POST' : 'GET', credentials: 'same-origin', cache: 'no-store', signal: options.signal,
headers: changing ? { 'Content-Type': 'application/json', ...(options.csrf ? { 'X-CSRF-Token': options.csrf } : {}) } : {}, body: changing ? JSON.stringify(options.body) : undefined });
const raw: unknown = response.status === 204 ? {} : await response.json().catch(() => { throw new ApiError(response.status, 'HTTP_ERROR', 'keine JSON-Antwort', ''); });
if (!response.ok) { const r = record(raw); throw new ApiError(response.status, stringField(r, 'code'), stringField(r, 'message'), typeof r.correlation_id === 'string' ? r.correlation_id : ''); }
return raw;
}
export const tenantPath = (id: string, suffix = '') => `/api/v1/tenants/${encodeURIComponent(id)}${suffix}`;
export const objectId = (r: RecordValue, kind: string) => text(r[`${kind}_id`] ?? r.id, `${kind}_id`);
export const pretty = (v: unknown) => JSON.stringify(v, null, 2);
export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const;
export type Action = typeof actions[number];
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
export function validateInput(input: PlanInput): void {
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
if (!input.reason.trim()) throw new Error('Begründung erforderlich');
const start = Date.parse(input.schedule.not_before), end = Date.parse(input.schedule.start_before);
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || end <= Date.now()) throw new Error('Ungültige oder abgelaufene Frist');
for (const n of [input.rollout.max_parallel, input.rollout.halt_after_failures, input.parameters.timeout_seconds, input.parameters.max_output_bytes]) if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 1) throw new Error('Limits müssen positive Ganzzahlen sein');
if (input.action === 'run_script') {
const variants = input.parameters.variants;
if (!Array.isArray(variants) || !variants.length || !variants.every(v => {
const variant = record(v), bytes = typeof variant.script_utf8 === 'string' ? new TextEncoder().encode(variant.script_utf8).length : 0;
return bytes > 0 && bytes <= 32768 && !String(variant.script_utf8).includes('\0') && variant.os_family === 'linux' && variant.encoding === 'utf-8' && ['posix_sh', 'bash'].includes(String(variant.interpreter));
})) throw new Error('Exakte Linux UTF-8 Skriptbytes und Interpreter erforderlich (max. 32 KiB)');
}
if (!['agent_service', 'root'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
if (input.action === 'refresh_inventory') required('scope');
if (input.action === 'query_logs') { required('unit'); const since = Date.parse(required('since')), until = Date.parse(required('until')); if (!Number.isFinite(since) || !Number.isFinite(until) || until <= since) throw new Error('Exaktes Log-Zeitfenster erforderlich'); if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein'); }
if (input.action === 'set_service_state') { required('unit'); if (!['running', 'stopped', 'restarted'].includes(required('state'))) throw new Error('Ungültiger Dienstzustand'); }
if (input.action === 'ensure_package') { for (const key of ['provider', 'recipe_version', 'package', 'version', 'architecture', 'installation_context']) required(key); }
if (input.action === 'apply_updates') { required('provider'); if (!Array.isArray(input.parameters.packages) || !input.parameters.packages.length || !input.parameters.packages.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Feste Updatepakete erforderlich'); if (input.parameters.reboot_policy !== 'never') throw new Error('Kein impliziter Reboot; eigenen festen Plan erstellen'); }
if (input.action === 'reboot') { required('reason'); required('dependency_group'); const n = input.parameters.reconnect_timeout_seconds; if (typeof n !== 'number' || !Number.isSafeInteger(n) || n < 60 || n > 3600) throw new Error('Reboot-Wiederanmeldefrist muss 60–3600 s sein'); }
}
/** These are immutable target definitions, never evidence of executable jobs. */
export function planTargetPreviews(plan: RecordValue): unknown[] | null {
if (Array.isArray(plan.resolved_targets) && plan.resolved_targets.some(value =>
value !== null && typeof value === 'object' && !Array.isArray(value) && ('payload' in value || 'job_payload_hash' in value))) return plan.resolved_targets;
if (plan.payloads !== undefined) return Array.isArray(plan.payloads) ? plan.payloads : null;
// Legacy DTO name: jobs here contains previews, not pre-approval execution rows.
return Array.isArray(plan.jobs) ? plan.jobs : null;
}
export function approvalBlockers(plan: RecordValue): string[] {
const errors: string[] = [];
for (const key of ['plan_id', 'plan_hash', 'expires_at']) if (typeof plan[key] !== 'string' || !plan[key]) errors.push(`${key} fehlt`);
if (!Number.isFinite(Date.parse(String(plan.expires_at))) || Date.parse(String(plan.expires_at)) <= Date.now()) errors.push('Planfrist ungültig/abgelaufen');
if (!Array.isArray(plan.resolved_targets) || !plan.resolved_targets.length) errors.push('Vollständige feste Zielmenge fehlt');
if (!Array.isArray(plan.excluded_targets) || plan.excluded_targets.length) errors.push('Ausgeschlossene Ziele oder unbekannte Zielabdeckung');
const isRecord = (value: unknown): value is RecordValue => value !== null && typeof value === 'object' && !Array.isArray(value);
const targetIds: string[] = [];
if (Array.isArray(plan.resolved_targets)) for (const value of plan.resolved_targets) {
const id = typeof value === 'string' ? value : isRecord(value) ? value.asset_id : undefined;
if (typeof id !== 'string' || !id.trim()) errors.push('Ziel: asset_id fehlt');
else targetIds.push(id);
}
if (new Set(targetIds).size !== targetIds.length) errors.push('Doppelte asset_id in fester Zielmenge');
const previews = planTargetPreviews(plan), previewTargets = new Set<string>();
if (!previews?.length) errors.push('Unveränderliche Zielpreviews fehlen');
else for (const value of previews) {
if (!isRecord(value)) { errors.push('Ungültige Zielpreview'); continue; }
const payload = value.payload;
const id = value.asset_id ?? (isRecord(payload) ? payload.asset_id : undefined);
if (typeof id !== 'string' || !id.trim()) errors.push('Zielpreview: asset_id fehlt');
else {
if (previewTargets.has(id)) errors.push('Doppelte asset_id in Zielpreviews');
previewTargets.add(id);
if (isRecord(payload) && payload.asset_id !== undefined && payload.asset_id !== id) errors.push('Zielpreview und Payload widersprechen sich bei asset_id');
}
if (typeof value.job_payload_hash !== 'string' || !value.job_payload_hash.trim()) errors.push('Zielpreview: job_payload_hash fehlt');
if (!isRecord(payload) || !Object.keys(payload).length) errors.push('Exakter Zielpayload fehlt');
}
if (targetIds.some(id => !previewTargets.has(id)) || [...previewTargets].some(id => !targetIds.includes(id))) errors.push('Feste Ziele und Zielpreviews stimmen nicht vollständig überein');
if (plan.plan_payload_bytes === undefined && plan.plan_payload === undefined) errors.push('Gespeicherter Planpayload fehlt');
return errors;
}
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import { diagnostic } from '../../tests/browser/diagnostics';
describe('privacy-safe browser diagnostics', () => {
it('only emits fixed labels, allowlisted exception names and numeric source lines', () => {
const secret = 'SECRET_CANARY_password_token_host_payload';
const safe = diagnostic('management:native-hint', { name: secret, message: `expect(locator).toBeVisible() ${secret} https://secret.invalid` }, 24);
expect(safe).toBe('failure_step=management:native-hint exception=Error kind=assertion source_line=24');
expect(safe).not.toContain(secret); expect(safe).not.toContain('https://');
expect(diagnostic(secret, { name: 'Error', message: secret }, 42)).toBeNull();
expect(diagnostic('management:login-banner', { name: 'TimeoutError', message: `Timeout ${secret}` }, NaN)).toBe('failure_step=management:login-banner exception=TimeoutError kind=timeout source_line=unknown');
expect(diagnostic('management:logout', undefined, 1)).toBeNull();
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, it } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { authConfig, session } from './api';
import { Login } from './login';
const onLogin = () => {};
describe('server-announced auth configuration', () => {
it('allows only the fixed same-origin OIDC entrypoint with explicit boolean modes', () => {
expect(authConfig({ oidc_configured: true, oidc_login_url: '/auth/oidc/login', dev_login_enabled: false }).oidc_login_url).toBe('/auth/oidc/login');
for (const url of ['//evil.invalid/auth/oidc/login', 'https://evil.invalid/auth/oidc/login', 'javascript:alert(1)', '/auth/oidc/login?return=https://evil.invalid', '/auth/oidc/login#token', '/auth/oidc/callback', '/auth/oidc/../oidc/login', '/auth/oidc/login\\evil', null]) expect(() => authConfig({ oidc_configured: true, oidc_login_url: url, dev_login_enabled: true })).toThrow();
expect(() => authConfig({ oidc_configured: false, oidc_login_url: '/auth/oidc/login', dev_login_enabled: true })).toThrow();
expect(() => authConfig({ oidc_configured: false, oidc_login_url: null })).toThrow();
expect(() => authConfig({ oidc_configured: 'true', oidc_login_url: '/auth/oidc/login', dev_login_enabled: true })).toThrow();
});
it('renders production SSO only, without password form or simulation impersonation', () => {
const config = authConfig({ oidc_configured: true, oidc_login_url: '/auth/oidc/login', dev_login_enabled: false });
const html = renderToStaticMarkup(<Login config={config} configError={null} onLogin={onLogin}/>);
expect(html).toContain('href="/auth/oidc/login"'); expect(html).toContain('Mit SSO anmelden');
expect(html).not.toContain('type="password"'); expect(html).not.toContain('SIMULIERTER'); expect(html).not.toContain('/auth/oidc/callback?');
});
it('shows dev form only when enabled and explicitly labels the simulated profile', () => {
const html = renderToStaticMarkup(<Login config={authConfig({ oidc_configured: false, oidc_login_url: null, dev_login_enabled: true })} configError={null} onLogin={onLogin}/>);
expect(html).toContain('type="password"'); expect(html).toContain('SIMULIERTER TESTPRINCIPAL'); expect(html).toContain('OIDC: not_configured'); expect(html).not.toContain('Mit SSO anmelden');
});
it('fails closed on loading/config failure or no announced modes; never defaults to dev auth', () => {
const enabled = authConfig({ oidc_configured: false, oidc_login_url: null, dev_login_enabled: true });
for (const props of [{ config: null, configError: null }, { config: enabled, configError: 'DEPENDENCY_UNAVAILABLE' }, { config: authConfig({ oidc_configured: false, oidc_login_url: null, dev_login_enabled: false }), configError: null }]) {
const html = renderToStaticMarkup(<Login {...props} onLogin={onLogin}/>); expect(html).not.toContain('type="password"'); expect(html).not.toContain('href=');
}
});
it('accepts explicit non-simulated OIDC sessions without deriving simulation from a name or role', () => {
const auth = session({ principal: 'simulated-name-is-not-authority', tenant_id: 't', testsimulation: false, csrf_token: 'csrf', roles: ['member'], permissions: ['operations:read'], approval_origin: 'human_webui' });
expect(auth.principal.simulated).toBe(false); expect(auth.roles).toEqual(['member']); expect(auth.permissions).toEqual(['operations:read']);
expect(() => session({ principal: 'simulated-testprincipal-a', tenant_id: 't', csrf_token: 'csrf', roles: ['dev_test_member'] })).toThrow();
});
});
+19
View File
@@ -0,0 +1,19 @@
import { useState } from 'react';
import { AuthConfig, request, session, Session } from './api';
export function Login({ config, configError, onLogin }: { config: AuthConfig | null; configError: string | null; onLogin: (s: Session) => void }) {
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
return <main className="login"><h1>RMM · Linux Verwaltung</h1>
{configError ? <div role="alert" className="error">Anmeldekonfiguration nicht verfügbar: {configError}. Keine unsichere Standardanmeldung. Bitte nach Behebung neu laden.</div> : !config ? <p>Anmeldemodi werden über die geschützte gleiche Origin geprüft …</p> : <>
{config.oidc_configured && config.oidc_login_url ? <section><h2>Single Sign-on</h2><p>Anmeldung über den serverseitig konfigurierten Identitätsanbieter. Zugangscodes und Tokens verarbeitet ausschließlich der Backend-Callback.</p><a href={config.oidc_login_url} rel="noreferrer">Mit SSO anmelden</a></section> : <p>OIDC: not_configured · kein Identitätsanbieter angekündigt.</p>}
{config.dev_login_enabled && <><p className="warning">DEV/TEST · SIMULIERTER TESTPRINCIPAL · ausschließlich Entwicklungsanmeldung, kein Produktionslogin und kein menschlicher Produktions-Freigabenachweis.</p><form onSubmit={async e => { e.preventDefault(); const form = e.currentTarget; const data = new FormData(form); setBusy(true); setError(null); try {
await request('/auth/dev/login', { body: { username: data.get('username'), password: data.get('password') } });
form.reset(); onLogin(session(await request('/auth/session')));
} catch (e) { setError(e instanceof Error ? e.message : 'Anmeldung fehlgeschlagen'); } finally { form.reset(); setBusy(false); } }}>
<label>Benutzername<input name="username" autoComplete="username" required maxLength={128}/></label>
<label>Passwort<input name="password" type="password" autoComplete="current-password" required maxLength={256}/></label>
<button disabled={busy}>Anmelden</button>{error && <div role="alert" className="error">{error}</div>}</form></>}
{!config.oidc_configured && !config.dev_login_enabled && <p className="warning">Anmeldung: not_configured · kein freigegebener Anmeldemodus verfügbar. Administrator kontaktieren.</p>}
</>}
</main>;
}
+126
View File
@@ -0,0 +1,126 @@
import React, { useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { actions, Action, ApiError, authConfig, approvalBlockers, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
import './style.css';
import { AdminControl, Catalog, TenantControls } from './management';
import { allowed, availableActions, parseStrictJson, rootWarning, validateSensitiveInput, verifyPlanIntegrity } from './safety';
import { Login } from './login';
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre>{pretty(value)}</pre></details>; }
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
useEffect(() => {
let active = true; const controller = new AbortController(); let timer: ReturnType<typeof setTimeout> | undefined;
setData(null); setError(null);
const run = async () => { try { const result = await load(controller.signal); if (active) { setData(result); setError(null); } } catch (e) { if (active) setError(errorText(e)); }
finally { if (active && poll) timer = setTimeout(run, 4000); } };
void run(); return () => { active = false; controller.abort(); clearTimeout(timer); };
}, [...deps, revision]);
return { data, error, reload: () => setRevision(v => v + 1) };
}
function PageStatus({ data }: { data: Page }) { return <p className={data.completeness === 'complete' && !data.truncated ? 'muted' : 'warning'}>Listenstand: {data.as_of} · Vollständigkeit: {data.completeness} · begrenzt: {String(data.truncated)}. Fehlende Einträge sind kein Löschungsnachweis.</p>; }
function Age({ value }: { value: unknown }) { const ms = typeof value === 'string' ? Date.parse(value) : NaN; return <span>{Number.isFinite(ms) ? `${Math.max(0, Math.floor((Date.now() - ms) / 1000))} s` : 'unknown'}</span>; }
function Devices({ tenantId, auth, selected, setSelected }: { tenantId: string; auth: Session; selected: string[]; setSelected: (ids: string[]) => void }) {
const [cursor, setCursor] = useState<string | null>(null), [asset, setAsset] = useState<string | null>(null);
const list = useResource(async signal => page(await request(tenantPath(tenantId, `/devices${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal })), [tenantId, cursor], true);
const detail = useResource(async signal => asset ? record(await request(tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}`), { signal })) : null, [tenantId, asset], true);
return <section><h2>Geräte und gespeichertes Inventar</h2><p>Präsenz, Datenfrische und fachliche Gesundheit sind unabhängig. „unreachable“ bedeutet nicht „ausgeschaltet“.</p><ErrorBox error={list.error}/>
{!list.data ? <p>Lade Geräte …</p> : <><PageStatus data={list.data}/><div className="table"><table><thead><tr><th>Fest auswählen</th><th>Gerät / Asset-ID</th><th>Präsenz / Gesundheit</th><th>Quelle / Qualität</th><th>Erhebung / Alter / Empfang</th></tr></thead><tbody>{list.data.items.map(d => { const id = objectId(d, 'asset'); return <tr key={id}><td><input aria-label={`Ziel ${id}`} type="checkbox" checked={selected.includes(id)} onChange={e => setSelected(e.target.checked ? [...selected, id] : selected.filter(v => v !== id))}/></td><td><button className="link" onClick={() => setAsset(id)}>{typeof d.hostname === 'string' ? d.hostname : id}</button><small>{id}</small></td><td>{stringField(d, 'presence')} / {stringField(d, 'health')}<small>Kontakt: {stringField(d, 'last_contact_at')}</small></td><td>{stringField(d, 'source_id')} / {stringField(d, 'quality')}<small>{stringField(d, 'completeness')}</small></td><td>{stringField(d, 'observed_at')}<small>Alter: <Age value={d.observed_at}/> · empfangen: {stringField(d, 'received_at')}</small></td></tr>; })}</tbody></table></div>{!list.data.items.length && <p>Keine sichtbaren Geräte 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></>}
<p>Fester Auswahlsnapshot ({selected.length}): {selected.join(', ') || 'keine Ziele'}</p>
{asset && <article><h3>Inventardetail {asset}</h3><ErrorBox error={detail.error}/>{detail.data && <JsonView value={detail.data} label="Inventar, Capabilities, Metriken, Dienste, Software, Updates, Logs und Quellen (soweit geliefert)"/>}<AdminControl auth={auth} path={tenantPath(tenantId, `/devices/${encodeURIComponent(asset)}/revocation`)} permission="devices:revoke" title="Geräteidentität widerrufen" warning="ACHTUNG: Widerruf unterbricht die Geräteverwaltung und sperrt neue Starts. Kein Entfernen aus einer Liste, kein Rollback. Wiederaufnahme erfordert einen gesonderten sicheren Enrollment-/Recoveryprozess." done={detail.reload}/></article>}
</section>;
}
const initialParameters: Record<Action, RecordValue> = {
run_script: {}, refresh_inventory: { scope: 'linux.base' }, query_logs: { unit: '', since: '', until: '', max_lines: 1000 }, set_service_state: { unit: '', state: 'running' }, ensure_package: { provider: 'apt', recipe_version: '', package: '', version: '', architecture: 'amd64', installation_context: 'system', apt_manifest: null }, apply_updates: { provider: 'apt', packages: [], reboot_policy: 'never', apt_manifest: null }, reboot: { reason: '', dependency_group: '', reconnect_timeout_seconds: 300 }, apt_native_acceptance: { recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest: null },
};
function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; auth: Session; selected: string[]; showPlan: (id: string) => void }) {
const [action, setAction] = useState<Action>('run_script'), [parameters, setParameters] = useState('{}'), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);
const [identity, setIdentity] = useState('agent_service');
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
const params = action === 'run_script' ? { ...common, variants: [{ os_family: 'linux', interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: f.get('expected') === '' ? null : String(f.get('expected')) } : { ...record(parseStrictJson(parameters)), ...common };
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
{action === 'run_script' ? <><label>Interpreter<select name="interpreter"><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></select></label><label>Exakte UTF-8 Skriptbytes (LF; keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label><label>Erwartete stdout-Ausgabe (exakt, optional)<textarea name="expected" rows={2} spellCheck={false}/></label></> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
{identity === 'root' && <p className="warning">{rootWarning}</p>}
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" placeholder="UUIDs durch Komma getrennt; keine URL"/></label>
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
</form></section>;
}
function localDate(date: Date) { return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }
function 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); 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) : ['Plan noch nicht geladen'];
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>
<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 { 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 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 {
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>;
}
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 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);
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>;
}
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);
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 · awaiting_reboot = autorisierter Folgejob nötig. cancel_requested ist kein bestätigter Abbruch, keine Rollbackzusage.</p>{job.data && <JsonView value={job.data} label="Versuch, Zustand, pending_reason, Output/stdout/stderr, 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></article>;
}
function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
const tenants = useResource(async signal => page(await request('/api/v1/tenants', { signal })), []);
const [tenantId, setTenant] = useState(auth.tenants[0]?.tenant_id ?? ''), [error, setError] = useState<string | null>(null);
const options = tenants.data?.items.map(tenant) ?? auth.tenants;
useEffect(() => { if (!tenantId && options[0]) setTenant(options[0].tenant_id); }, [options, tenantId]);
return <><header><div><h1>RMM <span>Linux Verwaltung</span></h1><p>{auth.principal.display_name} · {auth.principal.id}</p></div><button onClick={async () => { try { await request('/auth/logout', { csrf: auth.csrf_token, body: {} }); logout(); } catch (e) { setError(errorText(e)); } }}>Abmelden</button></header>
{auth.principal.simulated && <aside className="simulation" role="status">SIMULIERT · dev/test-Testprincipal · Genehmigung ist eine Entwicklungs-Browsersimulation, kein menschlicher Produktions-Freigabenachweis.</aside>}
<main><ErrorBox error={error}/><ErrorBox error={tenants.error}/><label>Mandant<select aria-label="Mandant" value={tenantId} onChange={e => setTenant(e.target.value)}><option value="" disabled>Mandant wählen</option>{options.map(t => <option key={t.tenant_id} value={t.tenant_id}>{t.name} · {t.tenant_id}</option>)}</select></label>{tenantId && <TenantWorkspace key={tenantId} tenantId={tenantId} auth={auth}/>}</main></>;
}
function TenantWorkspace({ tenantId, auth }: { tenantId: string; auth: Session }) {
const [selected, setSelected] = useState<string[]>([]), [planId, setPlan] = useState<string | null>(null), [operationId, setOperation] = useState<string | null>(null);
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
}
function App() {
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
const config = useResource(async signal => authConfig(await request('/auth/config', { signal })), []);
useEffect(() => { request('/auth/session').then(v => setAuth(session(v))).catch(e => { if (!(e instanceof ApiError && e.status === 401)) setError(errorText(e)); }).finally(() => setLoading(false)); }, []);
if (loading) return <main>Sitzung wird geprüft …</main>;
return <><ErrorBox error={error}/>{auth ? <><ErrorBox error={config.error}/><Workspace auth={auth} logout={() => { setAuth(null); setError(null); config.reload(); }}/></> : <Login config={config.data} configError={config.error} onLogin={s => { setError(null); setAuth(s); }}/>}</>;
}
class Boundary extends React.Component<{ children: React.ReactNode }, { error: string | null }> {
state: { error: string | null } = { error: null };
static getDerivedStateFromError(e: unknown) { return { error: errorText(e) }; }
render() { return this.state.error ? <main><h1>Darstellung blockiert</h1><ErrorBox error={this.state.error}/><p>Keine verlässliche Anzeige möglich. Nach Vertragskorrektur Seite neu laden.</p></main> : this.props.children; }
}
createRoot(document.getElementById('root')!).render(<Boundary><App/></Boundary>);
+65
View File
@@ -0,0 +1,65 @@
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>;
}
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from 'react-dom/server';
import { actions, PlanInput, Session, request, session } from './api';
import { adminIntent, allowed, availableActions, parseStrictJson, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
import { AdminControl } from './management';
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
async function manifest(acceptance = true) {
const transaction = { schema_version: 1, recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', platform: 'ubuntu-24.04-amd64', resolver_config_version: 'rmm-apt-local-v1', no_reboot: true, status_fingerprint: 'a'.repeat(64), baseline_sha256: 'b'.repeat(64), packages: [{ name: 'rmm-mvp-test', architecture: 'all', old_version: null, new_version: '1.0', origin: 'rmm-test', sha256: '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', size: 20672, archive_path: '/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb' }] };
const raw = new TextEncoder().encode(JSON.stringify(transaction));
return { type: 'rmm.apt.helper-action', schema_version: 2, action: acceptance ? 'apt-native-acceptance' : 'apt-execute', execution_profile: 'dev-test', transaction_sha256: await sha256(raw), transaction_bytes: Array.from(raw), resolved_apt_transaction: transaction, provider_sha256: 'c'.repeat(64), hook_sha256: 'd'.repeat(64), apt_config_sha256: 'e'.repeat(64), runtime_sha256: 'f'.repeat(64), test_result_id: 'unit-test-only-not-native-evidence' };
}
function input(apt_manifest: unknown): PlanInput { return { tenant_id: 't', action: 'apt_native_acceptance', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'root', recipe_id: 'rmm-apt-fixture-install-1.0', recipe_version: '1', apt_manifest }, schedule: { not_before: '', start_before: '', offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'unit only' }; }
describe('immutable catalog and strict import contracts', () => {
it('only accepts full immutable exact APT package metadata, never URLs or unknown fields', () => {
const r = { schema_version: 1, provider: 'apt', package: 'rmm-test', version: '1.0+test1', architecture: 'amd64', recipe_version: '1', installation_context: 'system', reboot_policy: 'never' };
expect(recipeInput(r)).toEqual(r);
expect(() => recipeInput({ ...r, url: 'https://example.invalid' })).toThrow();
expect(() => recipeInput({ ...r, package: 'https://example.invalid/a.deb' })).toThrow();
expect(() => recipeInput({ ...r, version: '' })).toThrow();
expect(() => parseStrictJson('{"version":"1","version":"2"}')).toThrow('Doppeltes');
expect(() => parseStrictJson('{"a":{"\u0078":1,"x":2}}')).toThrow('Doppeltes');
});
});
describe('root and dedicated dev-test APT actions', () => {
it('shows native acceptance only with explicit server simulation evidence, never upgrades identity', async () => {
expect(availableActions(auth, actions)).toContain('apt_native_acceptance');
expect(availableActions({ ...auth, principal: { ...auth.principal, simulated: false } }, actions)).not.toContain('apt_native_acceptance');
const value = input(await manifest());
await validateSensitiveInput(value, auth); expect(value.parameters.execution_identity).toBe('root');
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, execution_identity: 'agent_service' } }, auth)).rejects.toThrow('root');
await expect(validateSensitiveInput(value, { ...auth, permissions: [] })).rejects.toThrow('root:execute');
await expect(validateSensitiveInput(value, { ...auth, principal: { ...auth.principal, simulated: false } })).rejects.toThrow('simuliert');
expect(rootWarning).toContain('HOHES RISIKO'); expect(rootWarning).toContain('Keine automatische Rechteerhöhung');
});
it('checks schema2, full closure, exact bytes, pinned versions/hashes/origins and placeholders', async () => {
const m = await manifest(); await verifyAptManifest(m, true);
expect(() => validateAptManifest({ ...m, schema_version: 1 }, true)).toThrow();
expect(() => validateAptManifest({ ...m, provider_sha256: '<placeholder>' }, true)).toThrow();
expect(() => validateAptManifest({ ...m, transaction_bytes: [] }, true)).toThrow();
expect(() => validateAptManifest({ ...m, resolved_apt_transaction: { ...m.resolved_apt_transaction, packages: [] } }, true)).toThrow();
expect(() => validateAptManifest({ ...m, unknown: true }, true)).toThrow();
await expect(verifyAptManifest({ ...m, transaction_sha256: 'a'.repeat(64) }, true)).rejects.toThrow('Transaktionshash');
await expect(validateSensitiveInput({ ...input(m), parameters: { ...input(m).parameters, recipe_id: 'other' } }, auth)).rejects.toThrow('Rezept');
});
it('preserves ordinary package manifest closure unchanged, validates outer package identity', async () => {
const m = await manifest(false), value = input(m); value.action = 'ensure_package'; value.parameters = { ...value.parameters, provider: 'apt', package: 'rmm-mvp-test', version: '1.0', architecture: 'all', installation_context: 'system' };
const before = JSON.stringify(value); await validateSensitiveInput(value, auth); expect(JSON.stringify(value)).toBe(before);
await expect(validateSensitiveInput({ ...value, parameters: { ...value.parameters, version: '2' } }, auth)).rejects.toThrow('Paketidentität');
});
it('checks exact plan byte hash and manifest consistency without demanding execution IDs', async () => {
const p = { targets: ['asset'], jobs: [{ payload: { asset_id: 'asset', action: { action: 'apt_native_acceptance', apt_manifest: await manifest() } } }] }, raw = new TextEncoder().encode(JSON.stringify(p));
const plan = { plan_payload: p, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: p.jobs };
await verifyPlanIntegrity(plan);
await expect(verifyPlanIntegrity({ ...plan, plan_hash: 'a'.repeat(64) })).rejects.toThrow('Planhash');
await expect(verifyPlanIntegrity({ ...plan, plan_payload: { ...p, targets: ['foreign'] } })).rejects.toThrow('widerspricht');
});
});
describe('interactive administrative boundary', () => {
it('retains explicit membership permissions and never treats roles as implicit rights', () => {
const s = session({ principal: 'test', tenant_id: 't', csrf_token: 'csrf', testsimulation: true, permissions: ['devices:revoke'], roles: ['dev_test_member'] });
expect(allowed(s, 'devices:revoke')).toBe(true); expect(allowed({ ...s, permissions: undefined }, 'devices:revoke')).toBe(false);
});
it('requires explicit click confirmation, reason and current nonce; rendering causes no request', () => {
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
const html = renderToStaticMarkup(<AdminControl auth={auth} path="/api/v1/tenants/t/devices/a/revocation" title="Widerrufen" permission="devices:revoke" warning="Unterbricht Verwaltung"/>);
expect(html).toContain('Unterbricht Verwaltung'); expect(html).toContain('Bestätigungskennung'); expect(fetch).not.toHaveBeenCalled();
expect(() => adminIntent(false, 'reason', 'nonce', 'nonce')).toThrow(); expect(() => adminIntent(true, '', 'nonce', 'nonce')).toThrow(); expect(() => adminIntent(true, 'reason', 'old', 'nonce')).toThrow();
expect(adminIntent(true, 'reason', 'nonce', 'nonce')).toEqual({ reason: 'reason' }); vi.unstubAllGlobals();
});
it('sends exact admin JSON with cookie credentials and CSRF, never a secret-bearing nonce API field', async () => {
const fetch = vi.fn().mockResolvedValue(new Response('{}')); vi.stubGlobal('fetch', fetch);
await request('/api/v1/tenants/t/execution-stop', { csrf: 'csrf', body: { ...adminIntent(true, 'test only', 'nonce', 'nonce'), stopped: true } });
expect(fetch).toHaveBeenCalledWith('/api/v1/tenants/t/execution-stop', expect.objectContaining({ credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'csrf' }, body: '{"reason":"test only","stopped":true}' })); vi.unstubAllGlobals();
});
});
+97
View File
@@ -0,0 +1,97 @@
import { Action, PlanInput, RecordValue, Session, record, text } from './api';
export const hashPattern = /^[0-9a-f]{64}$/;
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
export function parseStrictJson(source: string): unknown {
if (new TextEncoder().encode(source).length > 1048576) throw new Error('JSON über 1 MiB');
let i = 0;
const space = () => { while (/\s/.test(source[i] ?? '') && i < source.length) i++; };
const string = (): string => { const start = i++; while (i < source.length) { if (source[i] === '\\') i += 2; else if (source[i++] === '"') return JSON.parse(source.slice(start, i)); } throw new Error('Ungültiger JSON-String'); };
const value = (depth: number): void => {
if (depth > 64) throw new Error('JSON zu tief verschachtelt'); space();
if (source[i] === '{') { i++; space(); const keys = new Set<string>(); if (source[i] === '}') { i++; return; }
while (i < source.length) { space(); if (source[i] !== '"') throw new Error('JSON-Objektschlüssel erwartet'); const key = string(); if (keys.has(key)) throw new Error(`Doppeltes JSON-Feld: ${key}`); keys.add(key); space(); if (source[i++] !== ':') throw new Error('JSON-Doppelpunkt erwartet'); value(depth + 1); space(); const end = source[i++]; if (end === '}') return; if (end !== ',') throw new Error('Ungültiges JSON-Objekt'); } throw new Error('Unvollständiges JSON-Objekt'); }
if (source[i] === '[') { i++; space(); if (source[i] === ']') { i++; return; } while (i < source.length) { value(depth + 1); space(); const end = source[i++]; if (end === ']') return; if (end !== ',') throw new Error('Ungültiges JSON-Array'); } throw new Error('Unvollständiges JSON-Array'); }
if (source[i] === '"') { string(); return; }
const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(i)); if (!token) throw new Error('Ungültiger JSON-Wert'); i += token[0].length;
};
value(0); space(); if (i !== source.length) throw new Error('Zusätzliche JSON-Daten'); return JSON.parse(source);
}
function exact(r: RecordValue, fields: string[]) { if (Object.keys(r).some(k => !fields.includes(k)) || fields.some(k => !(k in r))) throw new Error('Schemafelder fehlen oder sind unbekannt'); }
function hash(v: unknown) { if (typeof v !== 'string' || !hashPattern.test(v) || /^0{64}$/.test(v)) throw new Error('Exakter SHA-256 fehlt/Platzhalter'); }
export function bytes(value: unknown): Uint8Array<ArrayBuffer> { if (!Array.isArray(value) || !value.length || value.length > 1048576 || value.some(n => !Number.isInteger(n) || n < 0 || n > 255)) throw new Error('Exakte Bytefolge fehlt'); return new Uint8Array(value); }
export async function sha256(value: Uint8Array<ArrayBuffer>): Promise<string> { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', value)), n => n.toString(16).padStart(2, '0')).join(''); }
function canonical(v: unknown): string { if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`; if (v !== null && typeof v === 'object') return `{${Object.entries(v).sort(([a], [b]) => a.localeCompare(b)).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}`; return JSON.stringify(v); }
export function validateAptManifest(value: unknown, acceptance: boolean): RecordValue {
const m = record(value, 'apt_manifest');
exact(m, ['type', 'schema_version', 'action', 'execution_profile', 'transaction_sha256', 'resolved_apt_transaction', 'transaction_bytes', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256', 'test_result_id']);
if (m.type !== 'rmm.apt.helper-action' || m.schema_version !== 2 || m.execution_profile !== 'dev-test' || m.action !== (acceptance ? 'apt-native-acceptance' : 'apt-execute')) throw new Error('APT Schema 2 / explizites dev-test-Profil erforderlich');
for (const k of ['transaction_sha256', 'provider_sha256', 'hook_sha256', 'apt_config_sha256', 'runtime_sha256']) hash(m[k]);
if (typeof m.test_result_id !== 'string' || !/^[A-Za-z0-9_.-]{1,128}$/.test(m.test_result_id)) throw new Error('Exakte Testnachweis-ID erforderlich');
const transaction = record(m.resolved_apt_transaction);
exact(transaction, ['schema_version', 'recipe_id', 'recipe_version', 'platform', 'resolver_config_version', 'no_reboot', 'status_fingerprint', 'baseline_sha256', 'packages']);
if (transaction.schema_version !== 1 || transaction.recipe_version !== '1' || transaction.platform !== 'ubuntu-24.04-amd64' || transaction.resolver_config_version !== 'rmm-apt-local-v1' || transaction.no_reboot !== true) throw new Error('APT Transaktionsschema/Plattform/No-Reboot ungültig');
text(transaction.recipe_id, 'recipe_id'); hash(transaction.status_fingerprint); hash(transaction.baseline_sha256);
if (!Array.isArray(transaction.packages) || !transaction.packages.length || transaction.packages.length > 128) throw new Error('Vollständige Paketclosure erforderlich');
const identities = new Set<string>();
for (const value of transaction.packages) {
const p = record(value); exact(p, ['name', 'architecture', 'old_version', 'new_version', 'origin', 'sha256', 'size', 'archive_path']);
for (const k of ['name', 'architecture', 'new_version', 'origin']) text(p[k], k);
if (p.old_version !== null) text(p.old_version, 'old_version'); hash(p.sha256);
if (typeof p.size !== 'number' || !Number.isSafeInteger(p.size) || p.size < 1 || p.archive_path !== `/var/lib/rmm-apt-transaction/archives/${p.sha256}.deb`) throw new Error('APT Archivgröße/Pfadbindung fehlt');
const id = `${p.name}:${p.architecture}`; if (identities.has(id)) throw new Error('Doppelte Paketidentität'); identities.add(id);
}
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes(m.transaction_bytes)));
if (canonical(parsed) !== canonical(transaction)) throw new Error('Exakte Transaktionsbytes widersprechen Manifestobjekt');
if (acceptance) {
const install = transaction.recipe_id === 'rmm-apt-fixture-install-1.0', update = transaction.recipe_id === 'rmm-apt-fixture-update-1.1';
if ((!install && !update) || transaction.packages.length !== 1) throw new Error('Nur genaue native Fixture-Rezepte erlaubt');
const p = record(transaction.packages[0]);
if (p.name !== 'rmm-mvp-test' || p.architecture !== 'all' || p.origin !== 'rmm-test' || p.size !== 20672 || p.old_version !== (install ? null : '1.0') || p.new_version !== (install ? '1.0' : '1.1') || p.sha256 !== (install ? '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867' : 'ef67c9fe0ba1443fcfe465768e1204763063c369a2a1da04af6027d8a9c00491')) throw new Error('Native Fixture-Bytes/Version/Origin stimmen nicht überein');
}
return m;
}
export async function verifyAptManifest(value: unknown, acceptance: boolean) { const m = validateAptManifest(value, acceptance); if (await sha256(bytes(m.transaction_bytes)) !== m.transaction_sha256) throw new Error('APT Transaktionshash stimmt nicht überein'); }
export async function validateSensitiveInput(input: PlanInput, auth: Session) {
if (input.parameters.execution_identity === 'root' && !allowed(auth, 'root:execute')) throw new Error('root:execute unbekannt oder nicht erteilt; keine Rechteerhöhung');
if (input.action === 'apt_native_acceptance') {
if (!auth.principal.simulated || input.parameters.execution_identity !== 'root') throw new Error('APT-Abnahme ausschließlich explizit simuliert und root');
const m = validateAptManifest(input.parameters.apt_manifest, true), t = record(m.resolved_apt_transaction);
if (input.parameters.recipe_id !== t.recipe_id || input.parameters.recipe_version !== t.recipe_version) throw new Error('Äußeres Rezept widerspricht Manifest');
await verifyAptManifest(m, true);
} else if (input.action === 'ensure_package' || input.action === 'apply_updates') {
if (input.parameters.apt_manifest !== undefined && input.parameters.apt_manifest !== null) {
const m = validateAptManifest(input.parameters.apt_manifest, false), t = record(m.resolved_apt_transaction), packages = t.packages;
if (!Array.isArray(packages)) throw new Error('Paketclosure fehlt');
if (input.action === 'ensure_package' && (input.parameters.recipe_version !== t.recipe_version || (input.parameters.recipe_id !== undefined && input.parameters.recipe_id !== t.recipe_id))) throw new Error('Äußere Rezeptbindung widerspricht Manifest');
if (input.action === 'ensure_package' && !packages.some(v => { const p = record(v); return p.name === input.parameters.package && p.new_version === input.parameters.version && p.architecture === input.parameters.architecture; })) throw new Error('Exakte Paketidentität fehlt in Closure');
if (input.action === 'apply_updates' && (!Array.isArray(input.parameters.packages) || !input.parameters.packages.every(v => typeof v === 'string' && packages.some(x => { const p = record(x); return v === `${p.name}=${p.new_version}`; })))) throw new Error('Feste Updateversionen fehlen in Closure');
await verifyAptManifest(m, false);
}
}
}
export async function verifyPlanIntegrity(plan: RecordValue) {
if (plan.plan_payload_bytes !== undefined) {
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
}
const jobs = Array.isArray(plan.jobs) ? plan.jobs : Array.isArray(plan.resolved_targets) ? plan.resolved_targets : [];
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
}
}
export function recipeInput(value: unknown): RecordValue {
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
if (r.schema_version !== 1 || r.provider !== 'apt' || r.architecture !== 'amd64' || r.installation_context !== 'system' || r.reboot_policy !== 'never') throw new Error('Nur unveränderliches APT/amd64/system/never-Rezept unterstützt');
for (const k of ['package', 'version', 'recipe_version']) { const v = text(r[k], k); if (!/^[A-Za-z0-9_.:+~-]+$/.test(v) || v.startsWith('-')) throw new Error('Exakte Paket-/Rezeptidentität erforderlich; keine URL/Installerargumente'); }
return { schema_version: 1, provider: r.provider, package: r.package, version: r.version, architecture: r.architecture, recipe_version: r.recipe_version, installation_context: r.installation_context, reboot_policy: r.reboot_policy };
}
export function adminIntent(confirmed: boolean, reason: string, nonce: string, expected: string): { reason: string } {
if (!confirmed || !reason.trim() || new TextEncoder().encode(reason).length > 1024 || nonce !== expected || !expected) throw new Error('Explizite Bestätigung, aktuelle Bestätigungskennung und Grund erforderlich');
return { reason };
}
+1
View File
@@ -0,0 +1 @@
:root{font-family:system-ui,-apple-system,sans-serif;color:#dfe9f3;background:#101824;color-scheme:dark;font-size:15px;line-height:1.55}*{box-sizing:border-box}body{margin:0}header{display:flex;justify-content:space-between;align-items:center;padding:20px 4%;background:#172536;border-bottom:1px solid #36485d}h1{font-size:25px;margin:0}h1 span{font-size:17px;font-weight:400;color:#a6bad0}h2{font-size:21px;margin-top:0}h3{font-size:18px}main{max-width:1400px;margin:auto;padding:28px}section{border:1px solid #35485e;border-radius:10px;padding:24px;margin:24px 0;background:#172230}article{padding:18px;border:1px solid #506178;margin-top:18px}label{display:block;margin:12px 0;font-weight:600}input,select,textarea{display:block;width:100%;margin-top:5px;border:1px solid #586f87;background:#101a28;color:#f0f5fc;border-radius:5px;padding:10px;font:inherit}textarea,pre,code{font-family:ui-monospace,monospace}textarea{tab-size:2}button{background:#a5d7ff;color:#10243a;border:0;border-radius:5px;padding:10px 15px;font:inherit;font-weight:600;cursor:pointer;margin:4px 3px 4px 0}button:disabled{opacity:.45;cursor:not-allowed}.danger{background:#ffbb83}.link{background:none;color:#a5d7ff;padding:0;text-align:left;text-decoration:underline}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid #facc66;outline-offset:3px}.simulation{background:#52380a;color:#ffdd85;padding:16px 4%;font-weight:750;border-bottom:2px solid #ffc96e}.warning{padding:12px;border-left:4px solid #ffc96e;background:#332e22;color:#ffe1a0}.error{white-space:pre-wrap;overflow-wrap:anywhere;padding:14px;background:#452b31;border:1px solid #f08c9c;color:#ffd9df;margin:12px 0}.muted,small{color:#b4c3d3}small{display:block}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#101a28;padding:16px;max-height:650px;overflow:auto}summary{cursor:pointer;color:#bddfff}details{margin:14px 0}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(230px,1fr));gap:5px 22px}.table{overflow-x:auto}table{border-collapse:collapse;width:100%}td,th{text-align:left;vertical-align:top;padding:12px;border-bottom:1px solid #3c4e64}input[type=checkbox]{width:20px;height:20px;display:inline-block;vertical-align:middle;margin:0 10px 0 0}.check{padding:15px;border:1px solid #8a7956}.login{max-width:560px;margin:6vh auto}@media(max-width:600px){main{padding:12px}section{padding:14px}header{align-items:flex-start}h1 span{display:block}}