From c17cb017faa1b3eebf73c88cca11cc5ff61f22d1 Mon Sep 17 00:00:00 2001 From: 64579525 <17373302683@163.com> Date: Mon, 12 Oct 2026 23:27:26 +0800 Subject: [PATCH] fix(artifacts): complete prefix reads and share ZIP format admission --- src/application/BinaryTargetResolver.ts | 17 ++- src/artifacts/InesArtifactReader.ts | 11 +- .../extraction/ArtifactExtraction.ts | 12 +- src/artifacts/inventory/classify.ts | 9 +- src/filesystem/readFileHandlePrefix.ts | 30 +++++ .../boundary/filesystem/inesArtifact.test.ts | 125 ++++++++++++++++++ .../artifactProvider.extractionFormat.test.ts | 8 +- 7 files changed, 182 insertions(+), 30 deletions(-) create mode 100644 src/filesystem/readFileHandlePrefix.ts diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 9ab0a33a9..d600657ea 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -1,3 +1,4 @@ +import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js"; import { constants, type Stats } from "node:fs"; import { createHash } from "node:crypto"; import { @@ -297,12 +298,13 @@ const detectArtifactFormat = async ( > => { throwIfTargetResolutionCancelled(signal); const lower = path.toLowerCase(); - const magic = Buffer.alloc(16); - const observed = await handle.read(magic, 0, magic.length, 0); + const magic = await readFileHandlePrefix(handle, 16, () => + throwIfTargetResolutionCancelled(signal), + ); throwIfTargetResolutionCancelled(signal); await verifyTargetState(path, handle, initial, signal); if ( - observed.bytesRead >= 8 && + magic.length >= 8 && magic.subarray(0, 8).equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])) ) throw new BinaryTargetError( @@ -310,7 +312,7 @@ const detectArtifactFormat = async ( "WebAssembly v1 artifacts are not supported by the native opening route", { constraint: "wasm_requires_static_inspection" }, ); - const prefix = magic.subarray(0, observed.bytesRead); + const prefix = magic; const nesFormat = nesContainerFormat(prefix); if (nesFormat !== undefined) { const parsed = parseInesLayout(prefix, initial.size); @@ -328,16 +330,13 @@ const detectArtifactFormat = async ( return zipPackageFormatForPath(lower) ?? "zip"; } // Binary plists, including keyed archives, often use other extensions. - if ( - observed.bytesRead >= 8 && - magic.subarray(0, 8).equals(Buffer.from("bplist00")) - ) + if (magic.length >= 8 && magic.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist"; const named = namedArtifactFormat(lower); if (named !== undefined) return named; if ( lower.endsWith(".pkg") && - observed.bytesRead >= 4 && + magic.length >= 4 && magic.subarray(0, 4).equals(Buffer.from("xar!")) ) return "pkg"; diff --git a/src/artifacts/InesArtifactReader.ts b/src/artifacts/InesArtifactReader.ts index d7460aa18..e21c70ce1 100644 --- a/src/artifacts/InesArtifactReader.ts +++ b/src/artifacts/InesArtifactReader.ts @@ -1,3 +1,4 @@ +import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js"; import { createHash } from "node:crypto"; import { Readable } from "node:stream"; import { @@ -42,15 +43,13 @@ export class InesArtifactReader implements ArtifactReader { async *entries(signal?: AbortSignal): AsyncIterable { abortIfNeeded(signal); await this.#verifySource(signal); - const prefix = Buffer.alloc(16); - const { bytesRead } = await this.source.handle.read(prefix, 0, 16, 0); + const prefix = await readFileHandlePrefix(this.source.handle, 16, () => + abortIfNeeded(signal), + ); abortIfNeeded(signal); // Concurrent source changes take precedence over malformed header diagnostics. await this.#verifySource(signal); - const parsed = parseInesLayout( - prefix.subarray(0, bytesRead), - this.source.initial.size, - ); + const parsed = parseInesLayout(prefix, this.source.initial.size); if (!parsed.ok) throw new ArtifactReaderFailure("format", parsed.error); this.#layout = parsed.value; this.#entries.clear(); diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts index 64058903b..ada449d75 100644 --- a/src/artifacts/extraction/ArtifactExtraction.ts +++ b/src/artifacts/extraction/ArtifactExtraction.ts @@ -1,3 +1,4 @@ +import { isZipPackageFormat } from "../../domain/zipPackageFormat.js"; import { lstat, realpath } from "node:fs/promises"; import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js"; @@ -410,13 +411,6 @@ interface ExtractionInventory { readonly integrityContradictions: readonly IntegrityContradiction[]; } -const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const; - -const isZipFormat = ( - format: BinaryTarget["format"] | ArtifactGraphManifest["root_format"], -): format is (typeof ZIP_FORMATS)[number] => - (ZIP_FORMATS as readonly string[]).includes(format); - /** * Refuse a format without an extraction reader before inventory work starts. * The target kind, not the host, is unsupported by extraction. The error keeps @@ -433,7 +427,7 @@ const requireExtractableFormat = async ( format !== "asar" && format !== "ines" && !isMachOFormat(format) && - !isZipFormat(format) + !isZipPackageFormat(format) ) throw new AnalysisUnsupportedTargetError( "extract_artifact", @@ -498,7 +492,7 @@ const createReader = async ( } if (format === "directory") return new DirectoryArtifactReader(path); if (format === "asar") return new AsarArtifactReader(path); - if (isZipFormat(format)) return new ZipArtifactReader(path, format); + if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format); if (format === "mach-o" || format === "mach-o-universal") return new MachOSliceArtifactReader(path, input.environment); throw new AnalysisUnsupportedTargetError( diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index f4a860570..438c3f164 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -1,3 +1,4 @@ +import { readFileHandlePrefix } from "../../filesystem/readFileHandlePrefix.js"; import { sameRegularFileState, verifyRegularFileState, @@ -183,12 +184,14 @@ const classifyRootFormat = async ( signal?: AbortSignal, ): Promise => { abortIfNeeded(signal); - const magic = Buffer.alloc(ARTIFACT_CLASSIFICATION_PREFIX_BYTES); - const observed = await handle.read(magic, 0, magic.length, 0); + const prefix = await readFileHandlePrefix( + handle, + ARTIFACT_CLASSIFICATION_PREFIX_BYTES, + () => abortIfNeeded(signal), + ); abortIfNeeded(signal); await verifyRegularFileState(path, { handle, initial }); abortIfNeeded(signal); - const prefix = magic.subarray(0, observed.bytesRead); if (nesContainerFormat(prefix) !== undefined) { const parsed = parseInesLayout(prefix, initial.size); if (!parsed.ok) throw new ArtifactReaderFailure("format", parsed.error); diff --git a/src/filesystem/readFileHandlePrefix.ts b/src/filesystem/readFileHandlePrefix.ts new file mode 100644 index 000000000..8646a3ce5 --- /dev/null +++ b/src/filesystem/readFileHandlePrefix.ts @@ -0,0 +1,30 @@ +import type { FileHandle } from "node:fs/promises"; + +/** Fill a positional prefix until its bound or true EOF, preserving caller cancellation errors. */ +export const readFileHandlePrefix = async ( + handle: Pick, + length: number, + checkCancellation: () => void, +): Promise => { + const prefix = Buffer.alloc(length); + let offset = 0; + while (offset < length) { + checkCancellation(); + let bytesRead: number; + try { + ({ bytesRead } = await handle.read( + prefix, + offset, + length - offset, + offset, + )); + } catch (cause: unknown) { + checkCancellation(); + throw cause; + } + checkCancellation(); + if (bytesRead === 0) break; + offset += bytesRead; + } + return prefix.subarray(0, offset); +}; diff --git a/tests/boundary/filesystem/inesArtifact.test.ts b/tests/boundary/filesystem/inesArtifact.test.ts index 9720ad8f7..63d7d175d 100644 --- a/tests/boundary/filesystem/inesArtifact.test.ts +++ b/tests/boundary/filesystem/inesArtifact.test.ts @@ -1,3 +1,5 @@ +import { readFileHandlePrefix } from "../../../src/filesystem/readFileHandlePrefix.js"; +import { abortIfNeeded } from "../../../src/artifacts/ArtifactHash.js"; import { createHash } from "node:crypto"; import { lstat, @@ -543,3 +545,126 @@ it("releases an extraction-owned source descriptor on repeated close", async () await reader.close(); } }); + +it.each(["target", "inventory", "reader"])( + "fills short iNES prefix reads at the %s boundary", + async (route) => { + const root = await createTestTempDirectory("rea-ines-short-read-"); + const path = join(root, "source.nes"); + await writeFile(path, inesFixture()); + const sample = await open(path, "r"); + const initial = await sample.stat(); + const prototype = Object.getPrototypeOf(sample) as { + read( + buffer: Buffer, + offset: number, + length: number, + position: number | bigint, + ): Promise<{ bytesRead: number; buffer: Buffer }>; + }; + const originalRead = prototype.read; + const read = vi.spyOn(prototype, "read").mockImplementation(async function ( + this: typeof sample, + ...args + ) { + const [buffer, offset, length, position] = args; + return originalRead.call( + this, + buffer, + offset, + typeof position === "number" && position < 16 + ? Math.min(length, 3) + : length, + position, + ); + }); + try { + if (route === "target") { + expect(await parseBinaryTarget(path)).toMatchObject({ + ok: true, + value: { format: "ines" }, + }); + } else if (route === "inventory") { + expect( + (await inventoryArtifact(path)).ines?.reconstruction.verified, + ).toBe(true); + } else { + const reader = new InesArtifactReader(path, { + handle: sample, + initial, + }); + try { + const entries = []; + for await (const entry of reader.entries()) entries.push(entry.path); + expect(entries).toContain("prg/000.bin"); + } finally { + await reader.close(); + } + } + } finally { + read.mockRestore(); + await sample.close(); + } + }, +); + +it.each(["eof", "cancelled", "failed-and-cancelled"])( + "preserves %s while filling a short prefix", + async (mode) => { + const root = await createTestTempDirectory("rea-prefix-boundary-"); + const path = join(root, "source"); + const bytes = Buffer.from( + mode === "eof" ? "NES\x1a" : "NES\x1a123456789012", + ); + await writeFile(path, bytes); + const handle = await open(path, "r"); + const prototype = Object.getPrototypeOf(handle) as { + read( + buffer: Buffer, + offset: number, + length: number, + position: number, + ): Promise<{ bytesRead: number; buffer: Buffer }>; + }; + const original = prototype.read; + const controller = new AbortController(); + let reads = 0; + const read = vi.spyOn(prototype, "read").mockImplementation(async function ( + this: typeof handle, + buffer, + offset, + length, + position, + ) { + reads++; + if (reads === 2 && mode === "failed-and-cancelled") { + controller.abort(); + throw new Error("injected read failure"); + } + const observed = await original.call( + this, + buffer, + offset, + Math.min(length, 3), + position, + ); + if (reads === 2 && mode === "cancelled") controller.abort(); + return observed; + }); + try { + const result = readFileHandlePrefix(handle, 16, () => + abortIfNeeded(controller.signal), + ); + if (mode === "eof") { + expect(await result).toEqual(bytes); + expect(reads).toBe(3); + } else { + await expect(result).rejects.toMatchObject({ reason: "cancelled" }); + expect(reads).toBe(2); + } + } finally { + read.mockRestore(); + await handle.close(); + } + }, +); diff --git a/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts b/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts index c37b53523..68c8dbf3d 100644 --- a/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts +++ b/tests/boundary/providers/native/artifactProvider.extractionFormat.test.ts @@ -15,7 +15,7 @@ import { artifactExtractionExecutionSchema } from "../../../../src/contracts/art import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js"; describe("artifact extraction format support", () => { - it.each(["zip", "asar"] as const)( + it.each(["zip", "asar", "hap", "hsp", "app"] as const)( "extracts the scanned %s after an active iNES path is replaced", async (format) => { const root = await createTestTempDirectory("rea-extract-replaced-"); @@ -27,7 +27,7 @@ describe("artifact extraction format support", () => { const client = new ArtifactProvider(process.env).createClient( target.value, ); - if (format === "zip") { + if (format !== "asar") { await writeOrderedZip(path, ["payload.txt"]); } else { const source = join(root, "source"); @@ -44,7 +44,9 @@ describe("artifact extraction format support", () => { const extracted = artifactExtractionResultSchema.parse( result.value.result, ); - expect(extracted.manifest.root_format).toBe(format); + expect(extracted.manifest.root_format).toBe( + format === "app" ? "app-pack" : format, + ); expect( extracted.artifacts.map(({ relative_path }) => relative_path), ).toEqual(["payload.txt"]);