/** 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 { 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', 'update_agent'] as const; export type Action = typeof actions[number]; export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const; export const fullMaintenanceScriptProfile = 'full_maintenance_v1' as const; export function privilegedScriptProfile(value: RecordValue, identity: unknown): 'bounded' | typeof fullMaintenanceScriptProfile { if (!Object.hasOwn(value, 'privileged_script_profile')) return 'bounded'; if (value.privileged_script_profile !== fullMaintenanceScriptProfile || !['root', 'system'].includes(String(identity))) throw new Error('Vollwartungsprofil ausschließlich full_maintenance_v1 mit root/system; kein null oder geerbtes Privileg'); return fullMaintenanceScriptProfile; } export function validateScriptIdentityProfile(value: RecordValue, identity: unknown, interpreter: unknown): void { const profile = privilegedScriptProfile(value, identity); if (interpreter === 'powershell') { if (identity !== 'agent_service' && !(identity === 'system' && profile === fullMaintenanceScriptProfile)) throw new Error('PowerShell nur agent_service oder ausdrücklich SYSTEM/full_maintenance_v1'); } else if (!['posix_sh', 'bash'].includes(String(interpreter)) || !['agent_service', 'root'].includes(String(identity))) throw new Error('Linux-Skript benötigt agent_service/root und festen Shellinterpreter'); } /** A missing field is inherited policy; a present field is never silently coerced. */ export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof windowsPowerShellRemoteSignedProfile { if (!Object.prototype.hasOwnProperty.call(value, 'windows_execution_profile')) return 'inherited'; if (value.windows_execution_profile !== windowsPowerShellRemoteSignedProfile || value.interpreter !== 'powershell' || (value.os_family !== undefined && value.os_family !== 'windows')) throw new Error('Windows-Ausführungsprofil nur powershell_51_remote_signed für Windows PowerShell5.1'); return windowsPowerShellRemoteSignedProfile; } export const windowsEventLogFixtureSource = 'windows.eventlog.application.rustdiscovery-mvp-test'; export const windowsEventLogFixtureChannel = 'Application'; export const windowsEventLogFixtureProvider = 'RustDiscovery-MVP-Test'; /** Preserve sub-millisecond bounds; Date.parse alone would admit 24h + 1ns. */ export function logWindow(since: unknown, until: unknown): void { const instant = (value: unknown): bigint => { if (typeof value !== 'string') throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich'); const match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?(Z|[+-]\d\d:\d\d)$/.exec(value); if (!match) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich'); const seconds = Date.parse(match[1]! + match[3]!); if (!Number.isFinite(seconds)) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich'); return BigInt(seconds) * 1000000n + BigInt((match[2] ?? '').padEnd(9, '0')); }; const start = instant(since), end = instant(until); if (end <= start || end - start > 86400000000000n) throw new Error('Exaktes Log-Zeitfenster höchstens24Stunden erforderlich'); } export function validateWindowsLogLimits(identity: unknown, runtime: unknown, output: unknown, since: unknown): void { if (identity !== 'agent_service' || typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 10 || runtime > 120 || typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1024 || output > 65536 || typeof since !== 'string' || Date.parse(since) < 0) throw new Error('Windows-Fixture-Eventlog nur agent_service,10–120s und1024–65536Bytes'); } 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 const windowsMsi = { package: 'rmm-windows-msi-fixture', installRecipe: 'rmm-windows-msi-fixture-install-1.0', upgradeRecipe: 'rmm-windows-msi-fixture-upgrade-1.1', product: '{3F070B4B-9C08-4D65-BD41-13D81B884AEC}', upgradedProduct: '{D42BD387-079B-4BBF-A134-0DA7B7A97011}', family: '{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}', payload: 'C:\\Program Files\\RustDiscoveryFixtures\\msi-payload.txt', payload10: '0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0', payload11: 'ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49', } as const; export interface MsiPostcondition { product_code: string; product_version: string; payload_path: string; payload_sha256: string; payload_bytes: number } export interface WindowsMsiRecipe { schema_version: 1; recipe_id: string; recipe_version: '1'; platform: 'windows'; upgrade_code: string; architecture: 'x64'; context: 'machine'; command_profile: 'fixture_quiet_no_reboot_v1'; artifact: { artifact_id: string; sha256: string; bytes: number }; postcondition: MsiPostcondition; no_reboot: true; package_code?: string; predecessor?: MsiPostcondition; } export interface WindowsMsiManifest { recipe: WindowsMsiRecipe; recipe_sha256: string } function exactMsiFields(value: RecordValue, fields: string[]): void { if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.prototype.hasOwnProperty.call(value, key))) throw new Error('MSI-Schemafelder fehlen oder sind unbekannt'); } export function msiDigest(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw new Error('Exakter MSI-SHA256 erforderlich'); return value; } export function msiUuid(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === '00000000-0000-0000-0000-000000000000') throw new Error('Exakte MSI-UUID erforderlich'); return value; } function msiInteger(value: unknown, min: number, max: number): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) throw new Error('MSI-Limit außerhalb des festen Budgets'); return value; } /** Reconstruct every nested object in Rust declaration order before hashing. * No unknown properties, null options, enum objects or caller-supplied argv. */ export function windowsMsiManifest(value: unknown): WindowsMsiManifest { const m = record(value, 'windows_msi_manifest'); exactMsiFields(m, ['recipe', 'recipe_sha256']); const r = record(m.recipe, 'MSI-Rezept'), upgrade = r.recipe_id === windowsMsi.upgradeRecipe; exactMsiFields(r, ['schema_version', 'recipe_id', 'recipe_version', 'platform', 'upgrade_code', 'architecture', 'context', 'command_profile', 'artifact', 'postcondition', 'no_reboot', ...(upgrade ? ['package_code', 'predecessor'] : [])]); if (r.schema_version !== 1 || (!upgrade && r.recipe_id !== windowsMsi.installRecipe) || r.recipe_version !== '1' || r.platform !== 'windows' || r.upgrade_code !== windowsMsi.family || r.architecture !== 'x64' || r.context !== 'machine' || r.command_profile !== 'fixture_quiet_no_reboot_v1' || r.no_reboot !== true) throw new Error('Nur feste Windows-Machine/x64-MSI-Rezepte mit No-Reboot-Vertrag'); const a = record(r.artifact); exactMsiFields(a, ['artifact_id', 'sha256', 'bytes']); const post = (value: unknown): MsiPostcondition => { const p = record(value); exactMsiFields(p, ['product_code', 'product_version', 'payload_path', 'payload_sha256', 'payload_bytes']); if (p.payload_path !== windowsMsi.payload) throw new Error('Exakter MSI-Nutzdateipfad erforderlich'); return { product_code: text(p.product_code, 'ProductCode'), product_version: text(p.product_version, 'Produktversion'), payload_path: p.payload_path, payload_sha256: msiDigest(p.payload_sha256), payload_bytes: msiInteger(p.payload_bytes, 1, 65536) }; }; const p = post(r.postcondition); if (p.product_code !== (upgrade ? windowsMsi.upgradedProduct : windowsMsi.product) || p.product_version !== (upgrade ? '1.1.0' : '1.0.0')) throw new Error('MSI-Produkt/Version widerspricht festem Rezept'); const recipe: WindowsMsiRecipe = { schema_version: 1, recipe_id: r.recipe_id as string, recipe_version: '1', platform: 'windows', upgrade_code: windowsMsi.family, architecture: 'x64', context: 'machine', command_profile: 'fixture_quiet_no_reboot_v1', artifact: { artifact_id: msiUuid(a.artifact_id), sha256: msiDigest(a.sha256), bytes: msiInteger(a.bytes, 1, 262144) }, postcondition: p, no_reboot: true }; if (upgrade) { const code = text(r.package_code, 'PackageCode'); if (!/^\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$/.test(code) || code === '{00000000-0000-0000-0000-000000000000}' || [windowsMsi.product, windowsMsi.upgradedProduct, windowsMsi.family].some(x => x === code)) throw new Error('Exakter eigener MSI-PackageCode erforderlich'); const old = post(r.predecessor); if (p.payload_sha256 !== windowsMsi.payload11 || p.payload_bytes !== 33 || old.product_code !== windowsMsi.product || old.product_version !== '1.0.0' || old.payload_sha256 !== windowsMsi.payload10 || old.payload_bytes !== 33) throw new Error('MSI1.1 benötigt exakt den bekannten1.0-Vorgänger und die feste1.1-Nutzdatei'); recipe.package_code = code; recipe.predecessor = old; } return { recipe, recipe_sha256: msiDigest(m.recipe_sha256) }; } export function validateWindowsMsiLimits(runtime: unknown, output: unknown): void { msiInteger(runtime, 10, 120); msiInteger(output, 1024, 65536); } /** Stored Action bytes omit apt_manifest=None; WebParameters may accept null. */ export function windowsMsiAction(value: RecordValue): RecordValue { exactMsiFields(value, ['action', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest']); const m = windowsMsiManifest(value.windows_msi_manifest); if (value.action !== 'ensure_package' || value.provider !== 'msi' || value.package !== windowsMsi.package || value.version !== m.recipe.postcondition.product_version || value.architecture !== 'x64' || value.recipe_version !== m.recipe.recipe_version || value.installation_context !== 'machine' || value.recipe_id !== m.recipe.recipe_id) throw new Error('Äußere MSI-Felder widersprechen Manifest'); return { action: 'ensure_package', provider: 'msi', package: windowsMsi.package, version: value.version, architecture: 'x64', recipe_version: m.recipe.recipe_version, installation_context: 'machine', recipe_id: m.recipe.recipe_id, windows_msi_manifest: m }; } export function validateWindowsMsiInput(input: PlanInput): WindowsMsiManifest { const p = input.parameters; exactMsiFields(p, ['execution_identity', 'timeout_seconds', 'max_output_bytes', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest', ...(Object.prototype.hasOwnProperty.call(p, 'apt_manifest') ? ['apt_manifest'] : [])]); if (input.action !== 'ensure_package' || p.execution_identity !== 'system' || (input.artifact_ids?.length ?? 0) !== 0) throw new Error('MSI ausschließlich als SYSTEM-ensure_package mit automatisch genau einem Artefakt'); validateWindowsMsiLimits(p.timeout_seconds, p.max_output_bytes); if (p.apt_manifest !== undefined && p.apt_manifest !== null) throw new Error('APT-Manifest bei MSI nicht zulässig'); windowsMsiAction({ action: input.action, provider: p.provider, package: p.package, version: p.version, architecture: p.architecture, recipe_version: p.recipe_version, installation_context: p.installation_context, recipe_id: p.recipe_id, windows_msi_manifest: p.windows_msi_manifest }); return windowsMsiManifest(p.windows_msi_manifest); } /** Decode explicit escaped CRLF before planning; never alter approved output bytes. */ export function expectedStdout(value: string, format: string): string | null { if (value === '') return null; const output: unknown = format === 'json' ? JSON.parse(value) : format === 'text' ? value : undefined; if (typeof output !== 'string' || new TextEncoder().encode(output).length > 65536) throw new Error('stdout-Nachbedingung benötigt einen String (max.64KiB UTF-8)'); return output; } export function validateInput(input: PlanInput): void { if (Object.hasOwn(input.parameters, 'privileged_script_profile') && input.action !== 'run_script') throw new Error('Vollwartungsprofil ausschließlich für run_script'); if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss an der festen Windows-Skriptvariante stehen'); 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 profile = privilegedScriptProfile(input.parameters, input.parameters.execution_identity); const variants = input.parameters.variants; if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => { const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : ''; if (Object.hasOwn(variant, 'privileged_script_profile')) throw new Error('Privilegiertes Skriptprofil muss aktionsweit in parameters stehen'); windowsScriptProfile(variant); validateScriptIdentityProfile(input.parameters, input.parameters.execution_identity, variant.interpreter); const bytes = new TextEncoder().encode(script).length; const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter)) || variant.os_family === 'windows' && variant.interpreter === 'powershell'; return bytes > 0 && bytes <= 32768 && !script.includes('\0') && variant.encoding === 'utf-8' && platform && (variant.os_family !== 'windows' || /^[\x00-\x7f]*$/.test(script) || script.startsWith('\ufeff')); }) || new Set(variants.map(v => record(v).os_family)).size !== variants.length) throw new Error('Je Plattform genau eine passende UTF-8 Variante (max.32KiB); PowerShell5.1: ASCII oder explizites UTF-8-BOM vor Hashbildung'); if (profile === fullMaintenanceScriptProfile && (Number(input.parameters.timeout_seconds) > (variants.some(v => record(v).os_family === 'windows') ? 120 : 300) || Number(input.parameters.max_output_bytes) > 65536)) throw new Error('Vollwartung: Linux höchstens300s / Windows höchstens120s und65536Ausgabebytes'); } if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich'); if (input.action === 'update_agent') { const p = input.parameters; if (Object.keys(p).some(key => !['release_id', 'execution_identity', 'timeout_seconds', 'max_output_bytes'].includes(key)) || input.artifact_ids !== undefined || !['root', 'system'].includes(String(p.execution_identity)) || p.timeout_seconds !== 600 || Number(p.max_output_bytes) > 65536) throw new Error('Agentupdate: nur feste Release-ID, Root/SYSTEM,600s/64KiB; keine freien Pins/Artefakte'); msiUuid(p.release_id); return; } if (input.parameters.execution_identity === 'system') { if (input.action === 'run_script') { if (privilegedScriptProfile(input.parameters, 'system') !== fullMaintenanceScriptProfile) throw new Error('SYSTEM-Skript benötigt ausdrücklich full_maintenance_v1'); } else if (input.action === 'ensure_package') validateWindowsMsiInput(input); else { if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste oder feste MSI-Rezepte; keine SYSTEM-Shell'); validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes); if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter'); } } if (input.parameters.provider === 'msi' || Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest')) validateWindowsMsiInput(input); const required = (key: string) => text(input.parameters[key], `parameters.${key}`); if (input.action === 'refresh_inventory') required('scope'); if (input.action === 'query_logs') { const unit = required('unit'); logWindow(required('since'), required('until')); if (unit.startsWith('windows.eventlog.') && unit !== windowsEventLogFixtureSource) throw new Error('Nur die feste Windows-Fixture-Eventlogquelle ist konfiguriert'); if (unit === windowsEventLogFixtureSource) validateWindowsLogLimits(input.parameters.execution_identity, input.parameters.timeout_seconds, input.parameters.max_output_bytes, input.parameters.since); 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'); } } export function validateSystemService(unit: unknown, state: unknown, runtime: unknown, output: unknown): void { if (typeof unit !== 'string' || !/^RmmDiscoveryFixture[A-Za-z0-9_-]+$/.test(unit) || unit.length > 80) throw new Error('Exakter eigener Windows-Fixturedienst erforderlich'); if (state !== 'running' && state !== 'stopped') throw new Error('SYSTEM-Dienstzustand ausschließlich running oder stopped'); if (typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 1 || runtime > 120 || typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1 || output > 65536) throw new Error('SYSTEM-Dienstlimits maximal 120 s und 64 KiB'); } /** 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(); 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; }