import { createReadStream } from "node:fs"; import { join } from "node:path"; import type { z } from "zod"; import { SafeOutputTree } from "../artifacts/SafeOutputTree.js"; import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { firmwareResultSchemas } from "../domain/firmware/firmwareAnalysis.js"; import { hashFirmwareFile, type FirmwareEntry } from "./FirmwareFiles.js"; import type { normalizeUnblobReport } from "./FirmwareReports.js"; /** Publish verified regular files, preserving links as metadata and rolling back failed writes. */ export const publishFirmwareExtraction = async (context: { outputDirectory: string; entries: readonly FirmwareEntry[]; normalized: ReturnType; selection: { offset: number; length: number; sha256: string }; engine: z.infer["engine"]; signal: AbortSignal; }) => { let tree: SafeOutputTree | undefined; try { const materialized = new Set( context.entries .filter((entry) => entry.kind === "file") .map((entry) => `$output/${entry.relativePath}`), ); for (const path of context.normalized.files.keys()) { if (path !== "$input" && !materialized.has(path)) throw new AnalysisOutputError( "extract_firmware", `Reported regular file is absent from materialized output: ${path}`, ); } const files = []; const unpublished = []; tree = await SafeOutputTree.create(context.outputDirectory); for (const entry of context.entries) { if (entry.kind !== "file") { unpublished.push({ relative_path: entry.relativePath, kind: entry.kind, link_target: entry.linkTarget, }); continue; } const logicalPath = `$output/${entry.relativePath}`; const reported = context.normalized.files.get(logicalPath); const sha256 = await hashFirmwareFile(entry.path, context.signal); if ( (reported?.sha256 !== null && reported?.sha256 !== undefined && reported.sha256 !== sha256) || (context.normalized.sizes.has(logicalPath) && context.normalized.sizes.get(logicalPath) !== entry.size) ) throw new AnalysisOutputError( "extract_firmware", `Extracted bytes disagree with provider report: ${entry.relativePath}`, ); await tree.write( entry.relativePath, createReadStream(entry.path), sha256, context.signal, ); files.push({ relative_path: entry.relativePath, path: join(tree.outputRoot, entry.relativePath), size: entry.size, sha256, reported_sha256: reported?.sha256 ?? null, mime_type: reported?.mimeType ?? null, analysis_depth: reported?.depth ?? null, runtime_address: null, original_file_range: null, }); } const result = firmwareResultSchemas.extract_firmware.parse({ engine: context.engine, selection: context.selection, output_directory: tree.outputRoot, coverage: unpublished.length > 0 ? "partial" : context.normalized.coverage, files, unpublished_entries: unpublished, chunks: context.normalized.chunks, derivations: context.normalized.derivations, depth_limited_paths: context.normalized.depth_limited_paths, diagnostics: context.normalized.diagnostics, published_bytes: files.reduce((sum, file) => sum + file.size, 0), }); context.signal.throwIfAborted(); await tree.commit(); return result; } catch (cause: unknown) { try { await tree?.rollback(); } catch (cleanupCause: unknown) { throw new ProviderCleanupError( "unblob", [context.outputDirectory], { reason: cleanupCause instanceof Error ? cleanupCause.message : String(cleanupCause), previous_error: cause instanceof Error ? cause.message : String(cause), }, { cause: cleanupCause }, ); } throw cause; } };