diff --git a/packages/cli/src/lib/build/index.ts b/packages/cli/src/lib/build/index.ts index 4fca4a996..2c8bab508 100644 --- a/packages/cli/src/lib/build/index.ts +++ b/packages/cli/src/lib/build/index.ts @@ -23,16 +23,16 @@ */ import { - closeSync, + constants, + createWriteStream, existsSync, - openSync, readdirSync, statSync, - writeSync, } from "node:fs"; import { lstat, mkdtemp, open, readdir, readlink, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, join, posix, resolve } from "node:path"; +import { pipeline } from "node:stream/promises"; import { strToU8, Unzip, @@ -41,6 +41,12 @@ import { UnzipPassThrough, unzipSync, } from "fflate"; +import { + type Entry, + getFileNameLowLevel, + openPromise, + type ZipFile, +} from "yauzl"; import { CLI_VERSION } from "../constants.js"; import { ValidationError } from "../errors.js"; import { logger } from "../logger.js"; @@ -49,7 +55,7 @@ import { extractAssetCatalogImages, } from "./asset-catalog-extract.js"; import { collectDsymEntries } from "./dsyms.js"; -import { DeterministicZipWriter } from "./zip-writer.js"; +import { DeterministicZipWriter, type ZipEntryOptions } from "./zip-writer.js"; const log = logger.withTag("build.normalize"); @@ -542,75 +548,193 @@ function xcarchiveInfoPlist(appName: string): string { } /** A `Payload/…` file entry extracted from an IPA and staged on disk. */ -type StagedIpaEntry = { name: string; stagePath: string }; +type StagedIpaEntry = { + /** Entry path inside the IPA; always starts with `Payload/`. */ + name: string; + /** Temp file holding the entry's extracted bytes. */ + stagePath: string; + /** Host OS and attributes to store in the wrapper; see {@link ipaEntryOptions}. */ + options: ZipEntryOptions; +}; + +/** An IPA central-directory entry selected for staging. */ +type IpaPayloadEntry = { + /** Decoded entry path; always starts with `Payload/`. */ + name: string; + /** Central-directory record, used to open the entry's data. */ + entry: Entry; +}; + +/** Size of a central directory file header before its variable-length fields. */ +const CENTRAL_HEADER_FIXED_SIZE = 46; +/** Size of the end-of-central-directory record before its comment. */ +const EOCD_FIXED_SIZE = 22; +/** Size of the ZIP64 locator that directly precedes that record, if any. */ +const ZIP64_LOCATOR_SIZE = 20; +/** ZIP64 end-of-central-directory locator signature (`PK\x06\x07`). */ +const ZIP64_LOCATOR_SIG = 0x0706_4b50; + +/** + * Choose the ZIP host OS and external attributes to store for an IPA entry. + * + * The attributes are archive-controlled, so only the regular-file or symlink + * type and the `rwx` bits of a Unix entry are forwarded. Anything else (other + * file types, setuid/setgid/sticky bits, a mode without permission bits) gets + * the writer's defaults. + */ +function ipaEntryOptions(entry: Entry): ZipEntryOptions { + if (entry.versionMadeBy >>> 8 !== ZIP_OS_UNIX) { + return {}; + } + const mode = entry.externalFileAttributes >>> 16; + const type = mode & constants.S_IFMT; + const permissions = mode & 0o777; + if (type === constants.S_IFLNK) { + return { + os: ZIP_OS_UNIX, + attrs: ((constants.S_IFLNK | permissions) << 16) >>> 0, + }; + } + // Some writers store permission bits without a file type. + if ((type === constants.S_IFREG || type === 0) && permissions !== 0) { + return { + os: ZIP_OS_UNIX, + attrs: ((constants.S_IFREG | permissions) << 16) >>> 0, + }; + } + return {}; +} + +/** + * Read the central directory's byte size from the end-of-central-directory + * record, or `null` for a ZIP64 archive, whose 64-bit records hold the value. + */ +async function readDeclaredDirectorySize( + ipaPath: string, + zip: ZipFile, +): Promise { + // With `decodeStrings` off, `comment` is the raw comment (a Buffer at runtime). + const recordOffset = zip.fileSize - EOCD_FIXED_SIZE - zip.comment.length; + const start = Math.max(0, recordOffset - ZIP64_LOCATOR_SIZE); + const tail = Buffer.alloc(recordOffset + EOCD_FIXED_SIZE - start); + const src = await open(ipaPath, "r"); + try { + await src.read(tail, 0, tail.length, start); + } finally { + await src.close(); + } + const record = recordOffset - start; + if ( + record >= ZIP64_LOCATOR_SIZE && + tail.readUInt32LE(record - ZIP64_LOCATOR_SIZE) === ZIP64_LOCATOR_SIG + ) { + return null; + } + // The directory size is the 32-bit field at offset 12 of the record. + return tail.readUInt32LE(record + 12); +} /** - * Stream an IPA ZIP from disk, staging every `Payload/…` file entry to a temp - * file under `stageDir` without holding decompressed bytes in memory. + * Walk an IPA's central directory and select the `Payload/…` file entries, + * skipping directory markers, other top-level entries, and unsafe names. * - * Only file entries (not directory markers) whose name begins with `Payload/` - * are staged; other top-level entries (e.g. `iTunesMetadata.plist`) are dropped, - * matching the previous in-memory filter. Returns the staged entries in the - * order they appeared in the archive (the caller sorts for determinism). + * The directory is read in full before anything is extracted so a truncated + * one fails early: without ZIP64 records the entry count is 16 bits, and macOS + * `ditto` and Archive Utility write larger archives that way, so the parser + * stops at the wrapped count without an error. + * + * @throws {ValidationError} If the directory's size differs from the declared one. + */ +async function readIpaPayloadEntries( + ipaPath: string, + zip: ZipFile, +): Promise { + const entries: IpaPayloadEntry[] = []; + let directorySize = 0; + let unsafeNames = 0; + for await (const entry of zip.eachEntry()) { + directorySize += + CENTRAL_HEADER_FIXED_SIZE + + entry.fileNameLength + + entry.extraFieldLength + + entry.fileCommentLength; + // Strict decoding keeps backslashes, which are legal in Unix file names. + const name = getFileNameLowLevel( + entry.generalPurposeBitFlag, + entry.fileNameRaw, + entry.extraFields, + true, + ); + if (!name.startsWith("Payload/") || name.endsWith("/")) { + continue; + } + if (name.split(/[/\\]/).includes("..") || name.includes("\0")) { + unsafeNames += 1; + continue; + } + entries.push({ name, entry }); + } + + const declaredSize = await readDeclaredDirectorySize(ipaPath, zip); + if (declaredSize !== null && declaredSize !== directorySize) { + throw new ValidationError( + "The IPA's ZIP directory does not match its declared size. " + + "An archive with more than 65,535 entries or over 4 GiB needs ZIP64 records, " + + "which macOS ditto and Archive Utility do not write.", + "path", + ); + } + if (unsafeNames > 0) { + // Names are archive-controlled text, so only their count is reported. + log.warn(`Skipped ${unsafeNames} IPA file(s) with an unsafe path`); + } + return entries; +} + +/** + * Extract every `Payload/…` file entry of an IPA to a temp file under + * `stageDir`, one at a time, without holding extracted bytes in memory. + * + * Entries come from the central directory, the only place a ZIP keeps Unix + * modes, in directory order (the caller sorts for determinism). + * + * @throws {ValidationError} If the archive is truncated or unreadable as a ZIP. */ async function stageIpaPayload( ipaPath: string, stageDir: string, ): Promise { - const staged: StagedIpaEntry[] = []; - let index = 0; - - const unzip = new Unzip(); - unzip.register(UnzipInflate); - unzip.register(UnzipPassThrough); - unzip.onfile = (file: UnzipFile) => { - const wanted = !file.name.endsWith("/") && file.name.startsWith("Payload/"); - if (!wanted) { - // Still drain the entry so fflate advances past its data. - file.ondata = () => { - // Discard. - }; - file.start(); - return; - } - const stagePath = join(stageDir, `e${index++}`); - const fd = openSync(stagePath, "w"); - file.ondata = (err, chunk, final) => { - if (err) { - closeSync(fd); - throw err; - } - if (chunk.length > 0) { - writeSync(fd, chunk); - } - if (final) { - closeSync(fd); - staged.push({ name: file.name, stagePath }); - } - }; - file.start(); - }; - - const src = await open(ipaPath, "r"); try { - const buf = Buffer.allocUnsafe(1 << 20); - const size = (await src.stat()).size; - let position = 0; - while (position < size) { - const { bytesRead } = await src.read(buf, 0, buf.length, position); - if (bytesRead === 0) { - break; + const zip = await openPromise(ipaPath, { + decodeStrings: false, + autoClose: false, + }); + try { + const staged: StagedIpaEntry[] = []; + for (const { name, entry } of await readIpaPayloadEntries(ipaPath, zip)) { + const stagePath = join(stageDir, `e${staged.length}`); + await pipeline( + await zip.openReadStreamPromise(entry), + createWriteStream(stagePath), + ); + staged.push({ name, stagePath, options: ipaEntryOptions(entry) }); } - position += bytesRead; - unzip.push( - Uint8Array.prototype.slice.call(buf, 0, bytesRead), - position >= size, - ); + return staged; + } finally { + zip.close(); } - } finally { - await src.close(); + } catch (err) { + // A failing disk (e.g. a full temp directory) is not the archive's fault. + if ( + err instanceof ValidationError || + (err instanceof Error && "syscall" in err) + ) { + throw err; + } + // Names are never decoded by the parser, so its messages hold no archive text. + log.debug("Failed to read the IPA archive", err); + throw new ValidationError("Invalid or unsupported IPA archive", "path"); } - return staged; } /** @@ -631,6 +755,8 @@ async function stageIpaPayload( * @param outPath - Destination path for the normalized wrapper ZIP. * @param plugin - Optional plugin identity for the metadata file. * @param dsymPaths - Additional bundles, directories of bundles, or ZIPs. + * @throws {ValidationError} If the IPA is truncated, corrupt, or otherwise + * unreadable as a ZIP. * @throws {Error} If the IPA does not contain exactly one `.app`. */ export async function normalizeIpa( @@ -655,7 +781,16 @@ export async function normalizeIpa( // generated Info.plist — then sort so the output depends only on contents, // not on the IPA's central-directory order, keeping bytes deterministic for // chunk dedup across re-uploads. - type ArchiveItem = { name: string; stagePath?: string; data?: Uint8Array }; + type ArchiveItem = { + /** Entry path inside the wrapper ZIP. */ + name: string; + /** File on disk to stream in; unset for an in-memory item. */ + stagePath?: string; + /** Host OS and attributes of a file staged from the IPA; else defaults. */ + options?: ZipEntryOptions; + /** In-memory contents; unset for an item streamed from disk. */ + data?: Uint8Array; + }; const items: ArchiveItem[] = [ { name: `${archiveDir}/Info.plist`, @@ -671,14 +806,10 @@ export async function normalizeIpa( continue; } const stripped = entry.name.slice("Payload/".length); - // Skip path-traversal entries (a `..` segment) defensively, matching the - // legacy CLI's `enclosed_name()` guard. - if (stripped.split("/").includes("..")) { - continue; - } items.push({ name: `${archiveDir}/Products/Applications/${stripped}`, stagePath: entry.stagePath, + options: entry.options, }); } items.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); @@ -687,7 +818,7 @@ export async function normalizeIpa( try { for (const item of items) { if (item.stagePath !== undefined) { - await zip.addFile(item.name, item.stagePath); + await zip.addFile(item.name, item.stagePath, item.options); } else if (item.data !== undefined) { await zip.addData(item.name, item.data); } diff --git a/packages/cli/test/lib/build/index.test.ts b/packages/cli/test/lib/build/index.test.ts index b6ad6d1ee..d101f3918 100644 --- a/packages/cli/test/lib/build/index.test.ts +++ b/packages/cli/test/lib/build/index.test.ts @@ -16,8 +16,9 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { strToU8, unzipSync, zipSync } from "fflate"; +import { strToU8, unzipSync, type Zippable, zipSync } from "fflate"; import { afterEach, describe, expect, test, vi } from "vitest"; +import { fromBufferPromise } from "yauzl"; import { detectBuildFormat, detectBuildFormatFromFile, @@ -360,6 +361,28 @@ describe("normalizeIpa", () => { return await normalizeToBuffer((out) => normalizeIpa(src, out, null)); } + /** Where the wrapper stores the files of `Payload/MyApp.app`. */ + const APP = "archive.xcarchive/Products/Applications/MyApp.app"; + + /** Map each wrapper entry name to its `[host OS, external attributes]`. */ + async function wrapperAttributes( + wrapperBytes: Buffer, + ): Promise> { + const wrapper = await fromBufferPromise(wrapperBytes); + const attributes = new Map(); + try { + for await (const entry of wrapper.eachEntry()) { + attributes.set(entry.fileName, [ + Math.floor(entry.versionMadeBy / 0x100), + entry.externalFileAttributes, + ]); + } + } finally { + wrapper.close(); + } + return attributes; + } + test("remaps Payload into an XCArchive layout with a generated Info.plist", async () => { const zip = await normalizeIpaBytes(fakeIpaBytes()); const entries = unzipSync(zip); @@ -396,6 +419,57 @@ describe("normalizeIpa", () => { ).toEqual(strToU8("fw")); }); + test("preserves Unix permissions when remapping IPA files", async () => { + const modes = { + "Info.plist": 0o100644, + MyApp: 0o100755, + "Frameworks/X.framework/X": 0o100750, + }; + const files: Zippable = {}; + for (const [name, mode] of Object.entries(modes)) { + files[`Payload/MyApp.app/${name}`] = [ + strToU8(name), + { os: 3, attrs: mode * 0x10000 }, + ]; + } + const actual = await wrapperAttributes( + await normalizeIpaBytes(zipSync(files)), + ); + for (const [name, mode] of Object.entries(modes)) { + expect(actual.get(`${APP}/${name}`)).toEqual([3, mode * 0x10000]); + } + }); + + test("forwards only regular-file and symlink modes from IPA entries", async () => { + // [host OS, mode] stored in the IPA → [host OS, mode] expected in the wrapper. + const cases: Record = { + "Info.plist": [3, 0o100644, 3, 0o100644], + setuid: [3, 0o104755, 3, 0o100755], + symlink: [3, 0o120777, 3, 0o120777], + typeless: [3, 0o755, 3, 0o100755], + fifo: [3, 0o010644, 0, 0], + "no-permissions": [3, 0o100000, 0, 0], + "no-mode": [3, 0, 0, 0], + "not-unix": [0, 0o100755, 0, 0], + }; + const files: Zippable = {}; + for (const [name, [os, mode]] of Object.entries(cases)) { + files[`Payload/MyApp.app/${name}`] = [ + strToU8(name), + { os, attrs: mode * 0x10000 }, + ]; + } + const actual = await wrapperAttributes( + await normalizeIpaBytes(zipSync(files)), + ); + for (const [name, [, , os, mode]] of Object.entries(cases)) { + expect([name, actual.get(`${APP}/${name}`)]).toEqual([ + name, + [os, mode * 0x10000], + ]); + } + }); + test("includes only the identified app's entries", async () => { const names = Object.keys( unzipSync( @@ -423,6 +497,7 @@ describe("normalizeIpa", () => { zipSync({ "Payload/MyApp.app/Info.plist": strToU8(""), "Payload/MyApp.app/../../evil": strToU8("x"), + "Payload/MyApp.app/..\\..\\evil": strToU8("x"), }), ), ), @@ -430,6 +505,38 @@ describe("normalizeIpa", () => { expect(names.some((n) => n.includes("evil"))).toBe(false); }); + test("keeps a file whose name contains a backslash", async () => { + const entries = unzipSync( + await normalizeIpaBytes( + zipSync({ + "Payload/MyApp.app/Info.plist": strToU8(""), + "Payload/MyApp.app/Assets/a\\b.dat": strToU8("data"), + }), + ), + ); + expect(entries[`${APP}/Assets/a\\b.dat`]).toEqual(strToU8("data")); + }); + + test("rejects an IPA whose entry count wrapped instead of uploading part of it", async () => { + const bytes = Buffer.from(fakeIpaBytes()); + // Without ZIP64 records, an archive over 65,535 entries declares its count + // modulo 65,536. Declaring two of the three entries gives the same shape. + bytes.writeUInt16LE(2, bytes.length - 14); + bytes.writeUInt16LE(2, bytes.length - 12); + await expect(normalizeIpaBytes(bytes)).rejects.toMatchObject({ + name: "ValidationError", + message: expect.stringContaining("does not match its declared size"), + }); + }); + + test("reports an archive the ZIP parser rejects as a validation error", async () => { + const bytes = Buffer.concat([fakeIpaBytes(), Buffer.from("stray")]); + await expect(normalizeIpaBytes(bytes)).rejects.toMatchObject({ + name: "ValidationError", + message: "Invalid or unsupported IPA archive", + }); + }); + test("is deterministic (identical IPA → identical bytes)", async () => { const src = writeTmpFile("app.ipa", fakeIpaBytes()); const a = await normalizeToBuffer((out) => normalizeIpa(src, out, null));