From b196c5ac8f1af92d1a6927693d4227802a812442 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 8 Oct 2026 16:10:20 +0800 Subject: [PATCH] fix(artifacts): traverse nested PKG on extract, honor TOC header alg, fatal cpio names --- src/artifacts/CpioArtifactReader.ts | 15 ++++- src/artifacts/XarArtifactReader.ts | 29 +++++++-- .../extraction/ArtifactExtraction.ts | 61 +++++++++++++++++-- 3 files changed, 95 insertions(+), 10 deletions(-) diff --git a/src/artifacts/CpioArtifactReader.ts b/src/artifacts/CpioArtifactReader.ts index b0d3000fe..8907fd09c 100644 --- a/src/artifacts/CpioArtifactReader.ts +++ b/src/artifacts/CpioArtifactReader.ts @@ -316,7 +316,8 @@ export class CpioArtifactReader implements ArtifactReader { ), ); // cpio names require exactly one terminal NUL: a missing terminator or - // an embedded NUL with trailing bytes is malformed. + // an embedded NUL with trailing bytes is malformed. Decode without + // replacement so distinct byte names cannot collapse to one path. if ( nameBytes.length === 0 || nameBytes[nameBytes.length - 1] !== 0 || @@ -326,7 +327,17 @@ export class CpioArtifactReader implements ArtifactReader { "format", "cpio member name is not NUL-terminated", ); - const raw = nameBytes.toString("utf8", 0, nameBytes.length - 1); + let raw: string; + try { + raw = new TextDecoder("utf-8", { fatal: true }).decode( + nameBytes.subarray(0, nameBytes.length - 1), + ); + } catch { + throw new ArtifactReaderFailure( + "format", + "cpio member name is not valid UTF-8", + ); + } if (raw === TRAILER) { yield* this.#unresolvedLinks(); return; diff --git a/src/artifacts/XarArtifactReader.ts b/src/artifacts/XarArtifactReader.ts index 5a4068c6a..77a945340 100644 --- a/src/artifacts/XarArtifactReader.ts +++ b/src/artifacts/XarArtifactReader.ts @@ -328,6 +328,9 @@ export class XarArtifactReader implements ArtifactReader { const headerSize = header.readUInt16BE(4); const tocCompressed = header.readBigUInt64BE(8); const tocSize = header.readBigUInt64BE(16); + // Fixed-header checksum algorithm at offset 24: 0 is none, 1 is SHA-1, + // 2 is MD5. A declared algorithm requires a matching element. + const headerChecksumAlg = header.readUInt32BE(24); if (headerSize < 28) throw new ArtifactReaderFailure("format", "xar header is too short"); if ( @@ -371,15 +374,33 @@ export class XarArtifactReader implements ArtifactReader { const tocElement = root === null ? undefined : childElement(root, "toc"); if (tocElement === undefined) throw new ArtifactReaderFailure("format", "xar TOC has no element"); - await this.#verifyToc(tocElement, compressed); + await this.#verifyToc(tocElement, compressed, headerChecksumAlg); this.#members = collectMembers(tocElement); } /** The TOC checksum in the heap covers the compressed TOC bytes. */ - async #verifyToc(toc: Element, compressed: Buffer): Promise { + async #verifyToc( + toc: Element, + compressed: Buffer, + headerAlg: number, + ): Promise { const checksum = childElement(toc, "checksum"); - if (checksum === undefined) return; - const style = checksum?.getAttribute("style")?.toLowerCase() ?? ""; + const expectedStyle = + headerAlg === 1 ? "sha1" : headerAlg === 2 ? "md5" : undefined; + if (checksum === undefined) { + if (headerAlg !== 0) + throw new ArtifactReaderFailure( + "format", + "xar header declares a TOC checksum but the TOC has no element", + ); + return; + } + const style = checksum.getAttribute("style")?.toLowerCase() ?? ""; + if (expectedStyle !== undefined && style !== expectedStyle) + throw new ArtifactReaderFailure( + "format", + `xar TOC checksum style ${style || "(missing)"} does not match header algorithm ${expectedStyle}`, + ); const algorithm = CHECKSUM_ALGORITHMS[style]; if (algorithm === undefined) throw new ArtifactReaderFailure( diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts index 57e8a0066..fd706f90b 100644 --- a/src/artifacts/extraction/ArtifactExtraction.ts +++ b/src/artifacts/extraction/ArtifactExtraction.ts @@ -2,6 +2,8 @@ import { lstat, realpath } from "node:fs/promises"; import { canonicalDigest } from "../../domain/comparisonSemantics.js"; import { AsarArtifactReader } from "../AsarArtifactReader.js"; +import { CpioArtifactReader } from "../CpioArtifactReader.js"; +import { XarArtifactReader } from "../XarArtifactReader.js"; import { ArtifactPathRegistry, normalizeArtifactPath, @@ -125,12 +127,54 @@ const materializeSelection = async ({ const output = await SafeOutputTree.create(input.outputRoot); let readerClosed = false; const extracted: ExtractedOccurrence[] = []; + const stack: Array<{ + readonly reader: ArtifactReader; + readonly prefix: string; + readonly iterator: AsyncIterator; + readonly owned: boolean; + }> = [ + { + reader, + prefix: "", + iterator: reader.entries(signal)[Symbol.asyncIterator](), + owned: false, + }, + ]; try { const materialized: SelectedOccurrence[] = []; const registry = new ArtifactPathRegistry(); - for await (const entry of reader.entries(signal)) { - const path = normalizeArtifactPath(entry.path); + while (stack.length > 0) { + const frame = stack[stack.length - 1]; + if (frame === undefined) break; + const next = await frame.iterator.next(); + if (next.done === true) { + stack.pop(); + if (frame.owned) await frame.reader.close(); + continue; + } + const entry = next.value; + const path = normalizeArtifactPath( + frame.prefix === "" ? entry.path : `${frame.prefix}/${entry.path}`, + ); registry.add(path, entry.kind); + // Traverse expanded PKG Payload/Scripts like inventory does, so nested + // members are materialized instead of silently skipped. + if ( + entry.nestedArchive === "gzip-cpio" && + !entry.encrypted && + entry.contentUnavailable !== true + ) { + const parent = frame.reader; + const nested = new CpioArtifactReader((nestedSignal) => + parent.open(entry, nestedSignal), + ); + stack.push({ + reader: nested, + prefix: path, + iterator: nested.entries(signal)[Symbol.asyncIterator](), + owned: true, + }); + } const selectedItem = byPath.get(path); if (selectedItem === undefined) { if (entry.kind === "file" || entry.kind === "slice") @@ -141,7 +185,7 @@ const materializeSelection = async ({ continue; } preflight(entry); - const stream = await reader.open(entry, signal); + const stream = await frame.reader.open(entry, signal); const written = await output.write( path, stream, @@ -171,6 +215,14 @@ const materializeSelection = async ({ await output.commit(); return result; } catch (cause: unknown) { + await Promise.allSettled( + stack + .filter(({ owned }) => owned) + .map(async ({ reader, iterator }) => { + await iterator.return?.(); + await reader.close(); + }), + ); if (!readerClosed) await reader.close().catch((cause: unknown) => { // best-effort cleanup: reader close must not mask the extraction failure. @@ -207,7 +259,7 @@ const createExtractionResult = ( cleanup: { attempted: false, verified: true, residual_paths: [] }, provenance: [], limitations: [ - "All regular files in the active artifact were materialized; nested archive contents remain represented by their containing file.", + "All regular files in the active artifact were materialized, including members of expanded PKG Payload/Scripts archives.", ], }); }; @@ -256,6 +308,7 @@ const createReader = async ( ) return new ZipArtifactReader(path, format); if (format === "mach-o") return new MachOSliceArtifactReader(path); + if (format === "pkg") return new XarArtifactReader(path); throw new ArtifactReaderFailure( "unavailable", `Artifact format has no extraction reader: ${format}`,