2323 */
2424
2525import {
26- closeSync ,
26+ constants ,
27+ createWriteStream ,
2728 existsSync ,
28- openSync ,
2929 readdirSync ,
3030 statSync ,
31- writeSync ,
3231} from "node:fs" ;
3332import { lstat , mkdtemp , open , readdir , readlink , rm } from "node:fs/promises" ;
3433import { tmpdir } from "node:os" ;
3534import { basename , join , posix , resolve } from "node:path" ;
35+ import { pipeline } from "node:stream/promises" ;
3636import {
3737 strToU8 ,
3838 Unzip ,
@@ -41,6 +41,12 @@ import {
4141 UnzipPassThrough ,
4242 unzipSync ,
4343} from "fflate" ;
44+ import {
45+ type Entry ,
46+ getFileNameLowLevel ,
47+ openPromise ,
48+ type ZipFile ,
49+ } from "yauzl" ;
4450import { CLI_VERSION } from "../constants.js" ;
4551import { ValidationError } from "../errors.js" ;
4652import { logger } from "../logger.js" ;
@@ -49,7 +55,7 @@ import {
4955 extractAssetCatalogImages ,
5056} from "./asset-catalog-extract.js" ;
5157import { collectDsymEntries } from "./dsyms.js" ;
52- import { DeterministicZipWriter } from "./zip-writer.js" ;
58+ import { DeterministicZipWriter , type ZipEntryOptions } from "./zip-writer.js" ;
5359
5460const log = logger . withTag ( "build.normalize" ) ;
5561
@@ -542,75 +548,193 @@ function xcarchiveInfoPlist(appName: string): string {
542548}
543549
544550/** A `Payload/…` file entry extracted from an IPA and staged on disk. */
545- type StagedIpaEntry = { name : string ; stagePath : string } ;
551+ type StagedIpaEntry = {
552+ /** Entry path inside the IPA; always starts with `Payload/`. */
553+ name : string ;
554+ /** Temp file holding the entry's extracted bytes. */
555+ stagePath : string ;
556+ /** Host OS and attributes to store in the wrapper; see {@link ipaEntryOptions}. */
557+ options : ZipEntryOptions ;
558+ } ;
559+
560+ /** An IPA central-directory entry selected for staging. */
561+ type IpaPayloadEntry = {
562+ /** Decoded entry path; always starts with `Payload/`. */
563+ name : string ;
564+ /** Central-directory record, used to open the entry's data. */
565+ entry : Entry ;
566+ } ;
567+
568+ /** Size of a central directory file header before its variable-length fields. */
569+ const CENTRAL_HEADER_FIXED_SIZE = 46 ;
570+ /** Size of the end-of-central-directory record before its comment. */
571+ const EOCD_FIXED_SIZE = 22 ;
572+ /** Size of the ZIP64 locator that directly precedes that record, if any. */
573+ const ZIP64_LOCATOR_SIZE = 20 ;
574+ /** ZIP64 end-of-central-directory locator signature (`PK\x06\x07`). */
575+ const ZIP64_LOCATOR_SIG = 0x0706_4b50 ;
576+
577+ /**
578+ * Choose the ZIP host OS and external attributes to store for an IPA entry.
579+ *
580+ * The attributes are archive-controlled, so only the regular-file or symlink
581+ * type and the `rwx` bits of a Unix entry are forwarded. Anything else (other
582+ * file types, setuid/setgid/sticky bits, a mode without permission bits) gets
583+ * the writer's defaults.
584+ */
585+ function ipaEntryOptions ( entry : Entry ) : ZipEntryOptions {
586+ if ( entry . versionMadeBy >>> 8 !== ZIP_OS_UNIX ) {
587+ return { } ;
588+ }
589+ const mode = entry . externalFileAttributes >>> 16 ;
590+ const type = mode & constants . S_IFMT ;
591+ const permissions = mode & 0o777 ;
592+ if ( type === constants . S_IFLNK ) {
593+ return {
594+ os : ZIP_OS_UNIX ,
595+ attrs : ( ( constants . S_IFLNK | permissions ) << 16 ) >>> 0 ,
596+ } ;
597+ }
598+ // Some writers store permission bits without a file type.
599+ if ( ( type === constants . S_IFREG || type === 0 ) && permissions !== 0 ) {
600+ return {
601+ os : ZIP_OS_UNIX ,
602+ attrs : ( ( constants . S_IFREG | permissions ) << 16 ) >>> 0 ,
603+ } ;
604+ }
605+ return { } ;
606+ }
607+
608+ /**
609+ * Read the central directory's byte size from the end-of-central-directory
610+ * record, or `null` for a ZIP64 archive, whose 64-bit records hold the value.
611+ */
612+ async function readDeclaredDirectorySize (
613+ ipaPath : string ,
614+ zip : ZipFile ,
615+ ) : Promise < number | null > {
616+ // With `decodeStrings` off, `comment` is the raw comment (a Buffer at runtime).
617+ const recordOffset = zip . fileSize - EOCD_FIXED_SIZE - zip . comment . length ;
618+ const start = Math . max ( 0 , recordOffset - ZIP64_LOCATOR_SIZE ) ;
619+ const tail = Buffer . alloc ( recordOffset + EOCD_FIXED_SIZE - start ) ;
620+ const src = await open ( ipaPath , "r" ) ;
621+ try {
622+ await src . read ( tail , 0 , tail . length , start ) ;
623+ } finally {
624+ await src . close ( ) ;
625+ }
626+ const record = recordOffset - start ;
627+ if (
628+ record >= ZIP64_LOCATOR_SIZE &&
629+ tail . readUInt32LE ( record - ZIP64_LOCATOR_SIZE ) === ZIP64_LOCATOR_SIG
630+ ) {
631+ return null ;
632+ }
633+ // The directory size is the 32-bit field at offset 12 of the record.
634+ return tail . readUInt32LE ( record + 12 ) ;
635+ }
546636
547637/**
548- * Stream an IPA ZIP from disk, staging every `Payload/…` file entry to a temp
549- * file under `stageDir` without holding decompressed bytes in memory .
638+ * Walk an IPA's central directory and select the `Payload/…` file entries,
639+ * skipping directory markers, other top-level entries, and unsafe names .
550640 *
551- * Only file entries (not directory markers) whose name begins with `Payload/`
552- * are staged; other top-level entries (e.g. `iTunesMetadata.plist`) are dropped,
553- * matching the previous in-memory filter. Returns the staged entries in the
554- * order they appeared in the archive (the caller sorts for determinism).
641+ * The directory is read in full before anything is extracted so a truncated
642+ * one fails early: without ZIP64 records the entry count is 16 bits, and macOS
643+ * `ditto` and Archive Utility write larger archives that way, so the parser
644+ * stops at the wrapped count without an error.
645+ *
646+ * @throws {ValidationError } If the directory's size differs from the declared one.
647+ */
648+ async function readIpaPayloadEntries (
649+ ipaPath : string ,
650+ zip : ZipFile ,
651+ ) : Promise < IpaPayloadEntry [ ] > {
652+ const entries : IpaPayloadEntry [ ] = [ ] ;
653+ let directorySize = 0 ;
654+ let unsafeNames = 0 ;
655+ for await ( const entry of zip . eachEntry ( ) ) {
656+ directorySize +=
657+ CENTRAL_HEADER_FIXED_SIZE +
658+ entry . fileNameLength +
659+ entry . extraFieldLength +
660+ entry . fileCommentLength ;
661+ // Strict decoding keeps backslashes, which are legal in Unix file names.
662+ const name = getFileNameLowLevel (
663+ entry . generalPurposeBitFlag ,
664+ entry . fileNameRaw ,
665+ entry . extraFields ,
666+ true ,
667+ ) ;
668+ if ( ! name . startsWith ( "Payload/" ) || name . endsWith ( "/" ) ) {
669+ continue ;
670+ }
671+ if ( name . split ( / [ / \\ ] / ) . includes ( ".." ) || name . includes ( "\0" ) ) {
672+ unsafeNames += 1 ;
673+ continue ;
674+ }
675+ entries . push ( { name, entry } ) ;
676+ }
677+
678+ const declaredSize = await readDeclaredDirectorySize ( ipaPath , zip ) ;
679+ if ( declaredSize !== null && declaredSize !== directorySize ) {
680+ throw new ValidationError (
681+ "The IPA's ZIP directory does not match its declared size. " +
682+ "An archive with more than 65,535 entries or over 4 GiB needs ZIP64 records, " +
683+ "which macOS ditto and Archive Utility do not write." ,
684+ "path" ,
685+ ) ;
686+ }
687+ if ( unsafeNames > 0 ) {
688+ // Names are archive-controlled text, so only their count is reported.
689+ log . warn ( `Skipped ${ unsafeNames } IPA file(s) with an unsafe path` ) ;
690+ }
691+ return entries ;
692+ }
693+
694+ /**
695+ * Extract every `Payload/…` file entry of an IPA to a temp file under
696+ * `stageDir`, one at a time, without holding extracted bytes in memory.
697+ *
698+ * Entries come from the central directory, the only place a ZIP keeps Unix
699+ * modes, in directory order (the caller sorts for determinism).
700+ *
701+ * @throws {ValidationError } If the archive is truncated or unreadable as a ZIP.
555702 */
556703async function stageIpaPayload (
557704 ipaPath : string ,
558705 stageDir : string ,
559706) : Promise < StagedIpaEntry [ ] > {
560- const staged : StagedIpaEntry [ ] = [ ] ;
561- let index = 0 ;
562-
563- const unzip = new Unzip ( ) ;
564- unzip . register ( UnzipInflate ) ;
565- unzip . register ( UnzipPassThrough ) ;
566- unzip . onfile = ( file : UnzipFile ) => {
567- const wanted = ! file . name . endsWith ( "/" ) && file . name . startsWith ( "Payload/" ) ;
568- if ( ! wanted ) {
569- // Still drain the entry so fflate advances past its data.
570- file . ondata = ( ) => {
571- // Discard.
572- } ;
573- file . start ( ) ;
574- return ;
575- }
576- const stagePath = join ( stageDir , `e${ index ++ } ` ) ;
577- const fd = openSync ( stagePath , "w" ) ;
578- file . ondata = ( err , chunk , final ) => {
579- if ( err ) {
580- closeSync ( fd ) ;
581- throw err ;
582- }
583- if ( chunk . length > 0 ) {
584- writeSync ( fd , chunk ) ;
585- }
586- if ( final ) {
587- closeSync ( fd ) ;
588- staged . push ( { name : file . name , stagePath } ) ;
589- }
590- } ;
591- file . start ( ) ;
592- } ;
593-
594- const src = await open ( ipaPath , "r" ) ;
595707 try {
596- const buf = Buffer . allocUnsafe ( 1 << 20 ) ;
597- const size = ( await src . stat ( ) ) . size ;
598- let position = 0 ;
599- while ( position < size ) {
600- const { bytesRead } = await src . read ( buf , 0 , buf . length , position ) ;
601- if ( bytesRead === 0 ) {
602- break ;
708+ const zip = await openPromise ( ipaPath , {
709+ decodeStrings : false ,
710+ autoClose : false ,
711+ } ) ;
712+ try {
713+ const staged : StagedIpaEntry [ ] = [ ] ;
714+ for ( const { name, entry } of await readIpaPayloadEntries ( ipaPath , zip ) ) {
715+ const stagePath = join ( stageDir , `e${ staged . length } ` ) ;
716+ await pipeline (
717+ await zip . openReadStreamPromise ( entry ) ,
718+ createWriteStream ( stagePath ) ,
719+ ) ;
720+ staged . push ( { name, stagePath, options : ipaEntryOptions ( entry ) } ) ;
603721 }
604- position += bytesRead ;
605- unzip . push (
606- Uint8Array . prototype . slice . call ( buf , 0 , bytesRead ) ,
607- position >= size ,
608- ) ;
722+ return staged ;
723+ } finally {
724+ zip . close ( ) ;
609725 }
610- } finally {
611- await src . close ( ) ;
726+ } catch ( err ) {
727+ // A failing disk (e.g. a full temp directory) is not the archive's fault.
728+ if (
729+ err instanceof ValidationError ||
730+ ( err instanceof Error && "syscall" in err )
731+ ) {
732+ throw err ;
733+ }
734+ // Names are never decoded by the parser, so its messages hold no archive text.
735+ log . debug ( "Failed to read the IPA archive" , err ) ;
736+ throw new ValidationError ( "Invalid or unsupported IPA archive" , "path" ) ;
612737 }
613- return staged ;
614738}
615739
616740/**
@@ -631,6 +755,8 @@ async function stageIpaPayload(
631755 * @param outPath - Destination path for the normalized wrapper ZIP.
632756 * @param plugin - Optional plugin identity for the metadata file.
633757 * @param dsymPaths - Additional bundles, directories of bundles, or ZIPs.
758+ * @throws {ValidationError } If the IPA is truncated, corrupt, or otherwise
759+ * unreadable as a ZIP.
634760 * @throws {Error } If the IPA does not contain exactly one `.app`.
635761 */
636762export async function normalizeIpa (
@@ -655,7 +781,16 @@ export async function normalizeIpa(
655781 // generated Info.plist — then sort so the output depends only on contents,
656782 // not on the IPA's central-directory order, keeping bytes deterministic for
657783 // chunk dedup across re-uploads.
658- type ArchiveItem = { name : string ; stagePath ?: string ; data ?: Uint8Array } ;
784+ type ArchiveItem = {
785+ /** Entry path inside the wrapper ZIP. */
786+ name : string ;
787+ /** File on disk to stream in; unset for an in-memory item. */
788+ stagePath ?: string ;
789+ /** Host OS and attributes of a file staged from the IPA; else defaults. */
790+ options ?: ZipEntryOptions ;
791+ /** In-memory contents; unset for an item streamed from disk. */
792+ data ?: Uint8Array ;
793+ } ;
659794 const items : ArchiveItem [ ] = [
660795 {
661796 name : `${ archiveDir } /Info.plist` ,
@@ -671,14 +806,10 @@ export async function normalizeIpa(
671806 continue ;
672807 }
673808 const stripped = entry . name . slice ( "Payload/" . length ) ;
674- // Skip path-traversal entries (a `..` segment) defensively, matching the
675- // legacy CLI's `enclosed_name()` guard.
676- if ( stripped . split ( "/" ) . includes ( ".." ) ) {
677- continue ;
678- }
679809 items . push ( {
680810 name : `${ archiveDir } /Products/Applications/${ stripped } ` ,
681811 stagePath : entry . stagePath ,
812+ options : entry . options ,
682813 } ) ;
683814 }
684815 items . sort ( ( a , b ) => ( a . name < b . name ? - 1 : a . name > b . name ? 1 : 0 ) ) ;
@@ -687,7 +818,7 @@ export async function normalizeIpa(
687818 try {
688819 for ( const item of items ) {
689820 if ( item . stagePath !== undefined ) {
690- await zip . addFile ( item . name , item . stagePath ) ;
821+ await zip . addFile ( item . name , item . stagePath , item . options ) ;
691822 } else if ( item . data !== undefined ) {
692823 await zip . addData ( item . name , item . data ) ;
693824 }
0 commit comments