import { ApiError, record, RecordValue, text, tenantPath } from './api'; export const agentUpdateWarning = 'AGENT-SELBSTUPDATE: Agent und privilegierte Helper werden vorübergehend gestoppt; die Geräteverwaltung kann ausfallen. Genau dieses signierte Codepaar und der gespeicherte Vorgänger sind gebunden. Einmalige Rückkehr nur zum erlaubten exakten Vorgängercode; keine Rücksetzung von Datenbank, Identität oder Historie. Kein Hostneustart und keine automatische Genehmigung. Ein unklarer Ausgang bleibt unknown.'; function exact(value: RecordValue, fields: string[]) { if (Object.keys(value).some(k => !fields.includes(k)) || fields.some(k => !Object.hasOwn(value, k))) throw new Error('Agentupdate: vollständige bekannte Schemafelder erforderlich'); } function integer(value: unknown, minimum = 1, maximum = Number.MAX_SAFE_INTEGER): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error('Agentupdate: festes Ganzzahllimit erforderlich'); return value; } function digest(value: unknown): string { const hash = text(value, 'Agentupdate-SHA256'); if (!/^[a-f0-9]{64}$/.test(hash)) throw new Error('Agentupdate: exakter SHA256 erforderlich'); return hash; } function uuid(value: unknown): string { const id = text(value, 'Agentupdate-ID'); if (!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(id) || id === '00000000-0000-0000-0000-000000000000') throw new Error('Agentupdate: feste UUID erforderlich'); return id; } function same(left: unknown, right: unknown): boolean { const canonical = (v: unknown): string => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : v && typeof v === 'object' ? `{${Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}` : JSON.stringify(v); return canonical(left) === canonical(right); } async function hash(bytes: Uint8Array): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), n => n.toString(16).padStart(2, '0')).join(''); } const utf8 = (value: unknown): Uint8Array => new TextEncoder().encode(JSON.stringify(value)); function base64url(value: unknown, maximum: number): Uint8Array { if (typeof value !== 'string' || !value || value.length > maximum || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error('Agentupdate: kanonisches Base64url erforderlich'); const bytes = Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/') + '='.repeat((4 - value.length % 4) % 4)), c => c.charCodeAt(0)); if (btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '') !== value) throw new Error('Agentupdate: nichtkanonisches Base64url'); return bytes; } export interface ReleaseView { envelope: RecordValue; manifest: RecordValue; bytes: Uint8Array } export function releaseEnvelope(value: unknown): ReleaseView { const envelope = record(value); exact(envelope, ['schema_version', 'key_id', 'payload_bytes', 'signature']); if (envelope.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Envelopeschema'); const bytes = base64url(envelope.payload_bytes, 21846), signature = base64url(envelope.signature, 86); if (!bytes.length || bytes.length > 16384 || signature.length !== 64) throw new Error('Agentupdate: Manifest-/Signaturlimit'); const m = record(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))); exact(m, ['schema_version', 'release_id', 'release_sequence', 'version', 'platform', 'published_at', 'expires_at', 'protocol_major', 'state_schema', 'minimum_updater_version', 'artifacts']); if (m.schema_version !== 1 || !['x86_64-unknown-linux-gnu', 'x86_64-pc-windows-msvc', 'x86_64-pc-windows-gnu'].includes(String(m.platform)) || typeof m.version !== 'string' || !/^[A-Za-z0-9.+_-]{1,64}$/.test(m.version) || !Array.isArray(m.artifacts) || m.artifacts.length !== 2) throw new Error('Agentupdate: festes x64-Codepaar erforderlich'); const artifacts = m.artifacts.map((value, index) => { const a = record(value); exact(a, ['role', 'artifact_id', 'sha256', 'bytes']); if (a.role !== ['agent', 'helper'][index]) throw new Error('Agentupdate: Agent-/Helperreihenfolge'); return { role: a.role, artifact_id: uuid(a.artifact_id), sha256: digest(a.sha256), bytes: integer(a.bytes, 1, 268435456) }; }); if (artifacts[0]!.artifact_id === artifacts[1]!.artifact_id) throw new Error('Agentupdate: doppelte Artefakt-ID'); const manifest = { schema_version: 1, release_id: uuid(m.release_id), release_sequence: integer(m.release_sequence), version: m.version, platform: m.platform, published_at: integer(m.published_at, 0), expires_at: integer(m.expires_at), protocol_major: integer(m.protocol_major), state_schema: integer(m.state_schema), minimum_updater_version: integer(m.minimum_updater_version), artifacts }; if (manifest.expires_at <= manifest.published_at || new TextDecoder().decode(utf8(manifest)) !== new TextDecoder('utf-8', { fatal: true }).decode(bytes)) throw new Error('Agentupdate: exakte kanonische Manifestbytes erforderlich'); return { envelope: { schema_version: 1, key_id: digest(envelope.key_id), payload_bytes: envelope.payload_bytes, signature: envelope.signature }, manifest, bytes }; } export async function verifyReleaseMetadata(value: unknown, expectedHash: unknown): Promise { const release = releaseEnvelope(value); if (await hash(release.bytes) !== digest(expectedHash)) throw new Error('Agentupdate: Kataloghash widerspricht originalen Manifestbytes'); return release; } /** Browser sends the File body directly. It does not allocate a complete binary * ArrayBuffer or export a session/token. Server verifies complete hash and EOF. */ export async function uploadAgentUpdateArtifact(tenantId: string, descriptor: RecordValue, file: File, csrf: string): Promise { const id = uuid(descriptor.artifact_id), expectedHash = digest(descriptor.sha256), size = integer(descriptor.bytes, 1, 268435456); if (file.size !== size || !csrf) throw new Error('Agentupdate: ausgewählte Dateigröße oder interaktive Sitzung stimmt nicht'); const query = new URLSearchParams({ artifact_id: id, sha256: expectedHash, size_bytes: String(size) }); const response = await fetch(tenantPath(tenantId, `/agent-update-artifacts?${query}`), { method: 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: { 'Content-Type': 'application/octet-stream', 'X-CSRF-Token': csrf }, body: file }); const result = record(await response.json()); if (!response.ok) throw new ApiError(response.status, String(result.code ?? 'HTTP_ERROR'), String(result.message ?? 'Import fehlgeschlagen'), String(result.correlation_id ?? '')); exact(result, ['artifact_id', 'sha256', 'size_bytes']); if (result.artifact_id !== id || result.sha256 !== expectedHash || result.size_bytes !== size) throw new Error('Agentupdate: Importbeleg widerspricht festem Artefakt'); return result; } /** Shape only; signatures remain independently checked against provisioned trust * at server and local helper. No public key from a job is trusted by the UI. */ export function validateAgentUpdateAction(value: unknown, identity: unknown): RecordValue { const action = record(value); exact(action, ['action', 'update']); if (action.action !== 'update_agent') throw new Error('Agentupdate: typisierte Aktion erforderlich'); const u = record(action.update); exact(u, ['schema_version', 'profile', 'release_envelope', 'release_envelope_sha256', 'manifest_sha256', 'predecessor', 'updater', 'peer_pin_transition', 'recovery', 'health_profile', 'health_timeout_seconds', 'no_reboot']); if (u.schema_version !== 1 || u.profile !== 'fixed_code_pair_v1' || u.recovery !== 'restore_exact_predecessor_once' || u.health_profile !== 'mtls_inventory_sync_v1' || u.health_timeout_seconds !== 180 || u.no_reboot !== true) throw new Error('Agentupdate: fester Apply-/Health-/No-Reboot-Vertrag erforderlich'); const release = releaseEnvelope(u.release_envelope), linux = release.manifest.platform === 'x86_64-unknown-linux-gnu'; if (identity !== (linux ? 'root' : 'system')) throw new Error('Agentupdate: Plattform und Root-/SYSTEM-Identität widersprechen sich'); const old = record(u.predecessor); exact(old, ['release_id', 'release_sequence', 'manifest_sha256', 'installed_record_sha256', 'agent_sha256', 'helper_sha256']); const predecessor = { release_id: uuid(old.release_id), release_sequence: integer(old.release_sequence), manifest_sha256: digest(old.manifest_sha256), installed_record_sha256: digest(old.installed_record_sha256), agent_sha256: digest(old.agent_sha256), helper_sha256: digest(old.helper_sha256) }; if (predecessor.release_id === release.manifest.release_id || predecessor.release_sequence >= Number(release.manifest.release_sequence)) throw new Error('Agentupdate: exakter älterer Vorgänger erforderlich'); const binding = record(u.updater); exact(binding, ['binary_sha256', 'policy_sha256', 'keyring_generation', 'keyring_sha256', 'health_public_key_hex', 'health_key_pin_sha256']); const updater = { binary_sha256: digest(binding.binary_sha256), policy_sha256: digest(binding.policy_sha256), keyring_generation: integer(binding.keyring_generation), keyring_sha256: digest(binding.keyring_sha256), health_public_key_hex: digest(binding.health_public_key_hex), health_key_pin_sha256: digest(binding.health_key_pin_sha256) }; const p = record(u.peer_pin_transition); let transition: RecordValue; if (p.profile === 'unchanged_general_pin_v1') { exact(p, ['profile', 'general_pin_sha256']); if (!linux) throw new Error('Agentupdate: Linux-Pinprofil auf Windows'); transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256) }; } else if (p.profile === 'linux_general_full_v1') { exact(p, ['profile', 'general_pin_sha256', 'full']); if (!linux) throw new Error('Agentupdate: Linux-Fullprofil auf Windows'); const f = record(p.full); exact(f, ['schema_version', 'old_config_sha256', 'new_config_sha256', 'old_pin_sha256', 'new_pin_sha256', 'old_policy_sha256', 'new_policy_sha256', 'old_helper_sha256', 'new_helper_sha256', 'effective_signing_key_id']); if (f.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Fullpinschema'); const full = { schema_version: 1, old_config_sha256: digest(f.old_config_sha256), new_config_sha256: digest(f.new_config_sha256), old_pin_sha256: digest(f.old_pin_sha256), new_pin_sha256: digest(f.new_pin_sha256), old_policy_sha256: digest(f.old_policy_sha256), new_policy_sha256: digest(f.new_policy_sha256), old_helper_sha256: digest(f.old_helper_sha256), new_helper_sha256: digest(f.new_helper_sha256), effective_signing_key_id: digest(f.effective_signing_key_id) }; if (full.old_helper_sha256 !== predecessor.helper_sha256 || full.new_helper_sha256 !== record((release.manifest.artifacts as unknown[])[1]).sha256 || full.old_config_sha256 === full.new_config_sha256 || full.old_pin_sha256 === full.new_pin_sha256) throw new Error('Agentupdate: Fullpin-Codepaarbindung fehlt'); transition = { profile: p.profile, general_pin_sha256: digest(p.general_pin_sha256), full }; } else if (p.profile === 'windows_code_pair_v1') { const hasTime = Object.prototype.hasOwnProperty.call(p, 'time_profile'); exact(p, ['profile', 'old_settings_sha256', 'new_settings_sha256', 'old_pin_sha256', 'new_pin_sha256', ...(hasTime ? ['time_profile'] : [])]); if (linux) throw new Error('Agentupdate: Windows-Pinprofil auf Linux'); transition = { profile: p.profile, old_settings_sha256: digest(p.old_settings_sha256), new_settings_sha256: digest(p.new_settings_sha256), old_pin_sha256: digest(p.old_pin_sha256), new_pin_sha256: digest(p.new_pin_sha256) }; if (transition.old_settings_sha256 === transition.new_settings_sha256 || transition.old_pin_sha256 === transition.new_pin_sha256) throw new Error('Agentupdate: unveränderte Windows-Pinübergabe'); if (hasTime) { const t = record(p.time_profile); exact(t, ['schema_version', 'old_time_profile_sha256', 'new_time_profile_sha256', 'agent_qualification_sha256', 'helper_qualification_sha256']); if (t.schema_version !== 1) throw new Error('Agentupdate: unbekanntes Windows-Zeitprofilschema'); transition.time_profile = { schema_version: 1, old_time_profile_sha256: digest(t.old_time_profile_sha256), new_time_profile_sha256: digest(t.new_time_profile_sha256), agent_qualification_sha256: digest(t.agent_qualification_sha256), helper_qualification_sha256: digest(t.helper_qualification_sha256) }; if (t.old_time_profile_sha256 === t.new_time_profile_sha256) throw new Error('Agentupdate: unverändertes Windows-Zeitprofil'); } } else throw new Error('Agentupdate: unbekannter Peerpinübergang'); return { action: 'update_agent', update: { schema_version: 1, profile: 'fixed_code_pair_v1', release_envelope: release.envelope, release_envelope_sha256: digest(u.release_envelope_sha256), manifest_sha256: digest(u.manifest_sha256), predecessor, updater, peer_pin_transition: transition, recovery: 'restore_exact_predecessor_once', health_profile: 'mtls_inventory_sync_v1', health_timeout_seconds: 180, no_reboot: true } }; } export interface UpdatePlanJob { assetId: string; agentId: string; jobId: string; attemptId: string; identity: string; jobHash: string; update: RecordValue; manifest: RecordValue } const verified = new WeakMap(); const snapshot = (plan: RecordValue) => JSON.stringify(plan); export async function verifyAgentUpdatePlan(plan: RecordValue): Promise { const before = snapshot(plan), raw = plan.plan_payload_bytes; if (!Array.isArray(raw) || !raw.length || raw.length > 1048576 || raw.some(n => !Number.isInteger(n) || n < 0 || n > 255) || await hash(new Uint8Array(raw)) !== digest(plan.plan_hash)) throw new Error('Agentupdate: gespeicherte Planbytes/Hash fehlen'); const original = new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(raw)), parsed = record(JSON.parse(original)); if (!Array.isArray(parsed.jobs)) throw new Error('Agentupdate: feste Jobs fehlen'); const list = parsed.jobs.map(value => record(value)); if (!list.some(job => record(record(job.payload).action).action === 'update_agent')) { if (snapshot(plan) !== before) throw new Error('Plan während Prüfung verändert'); verified.set(plan, { snapshot: before, jobs: [] }); return; } exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', 'artifact_references']); if (parsed.schema_version !== 1 || !list.length || list.length > 100 || !Array.isArray(parsed.artifact_references) || parsed.artifact_references.length !== list.length * 2) throw new Error('Agentupdate: vollständige feste Codepaarmenge erforderlich'); const jobs: UpdatePlanJob[] = [], payloads: RecordValue[] = [], fixedJobs: RecordValue[] = [], refs: RecordValue[] = [], seen = new Set(); for (const job of list) { exact(job, ['payload', 'job_payload_hash', 'script_sha256']); const p = record(job.payload); exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']); const assetId = uuid(p.asset_id), jobId = uuid(p.job_id), attemptId = uuid(p.attempt_id), identity = text(p.execution_identity, 'Identität'); if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || seen.has(assetId) || seen.has(jobId) || seen.has(attemptId) || job.script_sha256 !== null || p.max_runtime_seconds !== 600) throw new Error('Agentupdate: feste Geräte-/Versuchsbindung oder Gesamtbudget fehlt'); [assetId, jobId, attemptId].forEach(id => seen.add(id)); integer(p.max_output_bytes, 1, 65536); const action = validateAgentUpdateAction(p.action, identity), update = record(action.update), release = releaseEnvelope(update.release_envelope); if (await hash(release.bytes) !== update.manifest_sha256 || await hash(utf8(release.envelope)) !== update.release_envelope_sha256) throw new Error('Agentupdate: originale Manifest-/Envelopehashbindung fehlt'); const notBefore = text(p.not_before, 'Startzeit'), startBefore = text(p.start_before, 'Startfrist'); if (!Number.isFinite(Date.parse(notBefore)) || !Number.isFinite(Date.parse(startBefore)) || Date.parse(startBefore) <= Date.parse(notBefore) || startBefore !== plan.expires_at) throw new Error('Agentupdate: feste Fristen widersprechen sich'); const payload = { schema_version: 1, tenant_id: uuid(p.tenant_id), asset_id: assetId, agent_id: uuid(p.agent_id), enrollment_generation: integer(p.enrollment_generation), assignment_version: integer(p.assignment_version), job_id: jobId, attempt_id: attemptId, action, execution_identity: identity, not_before: notBefore, start_before: startBefore, max_runtime_seconds: 600, max_output_bytes: p.max_output_bytes }; if (await hash(utf8(payload)) !== digest(job.job_payload_hash)) throw new Error('Agentupdate: feste Jobpayloadbytes stimmen nicht'); payloads.push(payload); fixedJobs.push({ payload, job_payload_hash: job.job_payload_hash, script_sha256: null }); for (const value of release.manifest.artifacts as unknown[]) { const a = record(value); refs.push({ job_id: jobId, attempt_id: attemptId, artifact: { artifact_id: a.artifact_id, sha256: a.sha256, size_bytes: a.bytes } }); } jobs.push({ assetId, agentId: payload.agent_id, jobId, attemptId, identity, jobHash: String(job.job_payload_hash), update, manifest: release.manifest }); } if (!same(refs, parsed.artifact_references)) throw new Error('Agentupdate: zusätzliche/fehlende/doppelte Artefaktberechtigung'); const rebuilt = { schema_version: 1, plan_id: uuid(parsed.plan_id), tenant_id: uuid(parsed.tenant_id), principal: text(parsed.principal, 'Antragsteller'), reason: text(parsed.reason, 'Begründung'), jobs: fixedJobs, max_parallel: integer(parsed.max_parallel, 1, 10), halt_after_failures: integer(parsed.halt_after_failures), artifact_references: refs }; if (new TextDecoder().decode(utf8(rebuilt)) !== original || plan.plan_id !== parsed.plan_id) throw new Error('Agentupdate: exakte kanonische Planbytes erforderlich'); for (const alias of ['payload', 'plan_payload']) if (plan[alias] !== undefined && !same(plan[alias], parsed)) throw new Error('Agentupdate: Planansicht widerspricht gespeicherten Bytes'); if (!Array.isArray(plan.jobs) || plan.jobs.length !== jobs.length || !Array.isArray(plan.resolved_targets) || plan.resolved_targets.length !== jobs.length) throw new Error('Agentupdate: vollständige Zielansicht fehlt'); for (let index = 0; index < jobs.length; index++) { const fixed = jobs[index]!, view = record(plan.jobs[index]), target = record(plan.resolved_targets[index]); if (!same(view.payload, payloads[index]) || view.job_payload_hash !== fixed.jobHash || ['asset_id', 'agent_id', 'job_id', 'attempt_id'].some(field => view[field] !== undefined && view[field] !== record(payloads[index])[field]) || Object.keys(target).some(key => !['asset_id', 'agent_id'].includes(key)) || target.asset_id !== fixed.assetId || target.agent_id !== fixed.agentId) throw new Error('Agentupdate: Zielpreview widerspricht gespeicherten Bytes'); } if (snapshot(plan) !== before) throw new Error('Agentupdate: Plan während Prüfung verändert'); verified.set(plan, { snapshot: before, jobs }); } export function agentUpdatePlanJobs(plan: RecordValue): UpdatePlanJob[] { const result = verified.get(plan); if (!result || result.snapshot !== snapshot(plan)) throw new Error('Agentupdateplan nicht unverändert verifiziert'); return structuredClone(result.jobs); } export function agentUpdateApprovalBlockers(plan: RecordValue): string[] { try { agentUpdatePlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'Agentupdateplan nicht verifiziert']; } }