2026-10-04 16:02:36 +08:00
import { createHash } from "node:crypto" ;
2026-10-09 08:28:21 +00:00
import { join } from "node:path" ;
2026-10-06 23:58:59 -07:00
import { parseBinary } from "plist" ;
2026-10-04 16:02:36 +08:00
import { z } from "zod" ;
2026-10-09 08:28:21 +00:00
import {
AnalysisInputError ,
AnalysisUnsupportedTargetError ,
} from "../../domain/analysisErrorCore.js" ;
2026-10-07 21:09:33 +08:00
import { projectPlistValue } from "../../domain/apple/plistValue.js" ;
2026-10-09 07:13:13 +08:00
import { createPlistNumberProjection } from "../../domain/apple/plistNumbers.js" ;
import {
binaryPlistNumberLiterals ,
xmlPlistNumberLiterals ,
} from "./PlistNumberLiterals.js" ;
2026-10-06 23:58:59 -07:00
import {
omittedPrototypeKeysLimitation ,
parseXmlPropertyList ,
2026-10-07 21:09:33 +08:00
} from "../../domain/propertyListKeys.js" ;
2026-10-04 16:02:36 +08:00
import {
2026-10-09 08:28:21 +00:00
KeyedArchiveKindError ,
2026-10-04 16:02:36 +08:00
keyedArchiveInputSchema ,
keyedArchiveResultSchema ,
projectKeyedArchive ,
2026-10-07 21:09:33 +08:00
} from "../../domain/apple/keyedArchive.js" ;
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js" ;
import { ArtifactReaderFailure } from "../ArtifactReader.js" ;
2026-10-10 04:58:25 +08:00
import type { ArtifactEntry } from "../ArtifactReader.js" ;
2026-10-04 16:02:36 +08:00
2026-10-09 05:50:49 +08:00
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js" ;
2026-10-10 01:44:46 -07:00
import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js" ;
2026-10-08 13:11:49 -04:00
2026-10-04 16:02:36 +08:00
const MAX_BYTES = 64 * 1024 * 1024 ;
2026-10-10 01:44:46 -07:00
/** Decoded representation budget, the same 8:1 ratio Interface Builder uses. */
const MAX_DECODE_BYTES = 8 * MAX_BYTES ;
2026-10-04 16:02:36 +08:00
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
export const decodeKeyedArchiveBytes = (
bytes : Buffer ,
selection : { root? : string | undefined ; offset : number ; limit : number },
) => {
if ( bytes . length > MAX_BYTES )
throw new RangeError ( "Keyed archive exceeds 64 MiB" );
2026-10-08 13:43:30 +00:00
if ( bytes . subarray ( 0 , 10 ). toString ( "ascii" ) === "NIBArchive" )
2026-10-09 08:28:21 +00:00
throw new KeyedArchiveKindError (
2026-10-08 13:43:30 +00:00
"Selected file is a compiled NIBArchive, not a Foundation plist archive; decode it with decode_interface_builder" ,
2026-10-09 08:40:45 +00:00
"nib-archive" ,
2026-10-08 13:43:30 +00:00
);
2026-10-04 16:02:36 +08:00
const binary = bytes . subarray ( 0 , 8 ). toString ( "ascii" ) === "bplist00" ;
2026-10-09 07:13:13 +08:00
const xmlText = binary ? undefined : decodeXmlPlistText ( bytes );
2026-10-10 01:44:46 -07:00
// plist.parseBinary recurses on every object reference and copies shared
// containers, so a few hundred bytes can exhaust memory or the stack.
// RangeError reports a resource limit; a reference cycle is malformed.
2026-10-11 07:02:39 +08:00
const binaryExpansion = binary
? estimateBinaryPlistExpansion ( bytes , MAX_DECODE_BYTES , {
budget : "the keyed archive decode budget" ,
fail : ( kind , message ) =>
kind === "cycle"
? new TypeError (
"binary plist object references form a cycle, which a property list cannot represent" ,
)
: new RangeError ( message ),
bounds : "decoder" ,
})
: undefined ;
const parsed =
binaryExpansion !== undefined
? {
value : parseBinary ( bytes ),
omittedPrototypeKeys : binaryExpansion.binaryPrototypeKeyObserved
? null
: 0 ,
}
: parseXmlPropertyList ( xmlText ?? "" );
2026-10-10 04:58:25 +08:00
const { value : plistValue , unknownRealCount } = projectPlistValue (
parsed . value ,
);
const graph = projectKeyedArchive ( plistValue , selection );
2026-10-09 07:13:13 +08:00
const numbers = createPlistNumberProjection (
binary
? binaryPlistNumberLiterals ( bytes )
: xmlPlistNumberLiterals ( xmlText ?? "" ),
);
// Classify the serialized graph before projecting values to typed decimals.
// Numeric IDs, node kinds, references and pagination retain their original meaning.
const roots = Object . fromEntries (
Object . entries ( graph . roots ). map (([ name , value ]) => [
name ,
numbers . project ( value ),
]),
);
const objects = graph . objects . map (( object ) => ({
... object ,
value : numbers.project ( object . value ),
}));
2026-10-04 16:02:36 +08:00
return {
archive_format : binary ? ( "binary-plist" as const ) : ( "xml-plist" as const ),
2026-10-06 23:58:59 -07:00
... graph ,
2026-10-09 07:13:13 +08:00
roots ,
objects ,
2026-10-06 23:58:59 -07:00
limitations : [
... graph . limitations ,
2026-10-09 07:13:13 +08:00
... numbers . limitations (),
2026-10-06 23:58:59 -07:00
...( parsed . omittedPrototypeKeys === 0
? []
: [ omittedPrototypeKeysLimitation ( parsed . omittedPrototypeKeys )]),
2026-10-10 04:58:25 +08:00
...( unknownRealCount === 0
? []
: [
` ${ String ( unknownRealCount ) } non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because JSON evidence cannot preserve NaN vs infinity.` ,
]),
2026-10-06 23:58:59 -07:00
],
2026-10-04 16:02:36 +08:00
};
};
2026-10-09 08:40:45 +00:00
/**
* Point to the workflow that reads the selected kind of file on this host.
* decode_interface_builder is portable; inspect_plist requires macOS.
*/
const keyedArchiveKindRemediation = (
kind : KeyedArchiveKindError [ "kind" ],
platform : NodeJS.Platform ,
) : string => {
if ( kind === "nib-archive" )
return "Decode compiled NIBArchive files with decode_interface_builder on the app bundle." ;
return platform === "darwin"
? "Inspect an ordinary property list with inspect_plist; inspect_keyed_archive decodes NSKeyedArchiver archives only."
: "Select an NSKeyedArchiver archive; inspect_keyed_archive decodes only those. inspect_plist, which reads ordinary property lists, requires a macOS host." ;
};
2026-10-04 16:02:36 +08:00
/** Read exactly one regular, contained bundle entry without following symlinks. */
export const inspectBundleKeyedArchive = async ( input : {
bundlePath : string ;
targetSha256 : string ;
parameters : unknown ;
signal? : AbortSignal ;
2026-10-09 08:40:45 +00:00
/** Host whose available workflows the remediation names. */
platform? : NodeJS.Platform ;
2026-10-04 16:02:36 +08:00
}) => {
const selected = keyedArchiveInputSchema . parse ( input . parameters );
if (
selected . path . startsWith ( "/" ) ||
selected . path
. split ( "/" )
. some (( part ) => part === ".." || part === "." || part . length === 0 )
)
2026-10-08 13:43:30 +00:00
throw archivePathError (
"invalid_format" ,
selected . path === "."
? "Select a keyed archive path relative to the active app bundle."
: `Archive path must be a canonical relative bundle path without empty, '.', or '..' segments: ${ selected . path } ` ,
2026-10-04 16:02:36 +08:00
);
const reader = new DirectoryArtifactReader ( input . bundlePath );
try {
2026-10-10 04:58:25 +08:00
// Match inventory spelling while retaining the raw path for I/O and evidence.
const wanted = selected . path . normalize ( "NFC" );
2026-10-11 00:03:18 +08:00
let entry : ArtifactEntry | undefined ;
for await ( const candidate of reader . entries ( input . signal , ( directory ) =>
2026-10-09 19:15:24 -04:00
wanted . startsWith ( ` ${ directory . normalize ( "NFC" ) } /` ),
)) {
2026-10-11 00:03:18 +08:00
if ( candidate . path . normalize ( "NFC" ) !== wanted ) continue ;
if ( candidate . kind !== "file" )
2026-10-09 19:15:24 -04:00
throw archivePathError (
"invalid_value" ,
2026-10-11 00:03:18 +08:00
`Archive path selects a ${ candidate . kind } , not a regular file: ${ selected . path } ` ,
2026-10-09 19:15:24 -04:00
);
2026-10-11 00:03:18 +08:00
if (( candidate . declaredSize ?? 0 ) > MAX_BYTES )
2026-10-09 19:15:24 -04:00
throw new ArtifactReaderFailure (
"limit" ,
"Keyed archive exceeds 64 MiB" ,
);
2026-10-11 00:03:18 +08:00
if ( entry !== undefined )
throw archivePathError (
"invalid_value" ,
`Archive path matches multiple Unicode-equivalent bundle entries; selection is ambiguous: ${ selected . path } ` ,
);
entry = candidate ;
2026-10-10 04:58:25 +08:00
}
if ( entry === undefined )
throw archivePathError (
"invalid_value" ,
`No regular file exists at ${ selected . path } in the active app bundle.` ,
);
const stream = await reader . open ( entry , input . signal );
const chunks : Buffer [] = [];
let size = 0 ;
for await ( const chunk of stream ) {
if ( input . signal ? . aborted ) {
stream . destroy ();
throw new ArtifactReaderFailure (
"cancelled" ,
"Archive inspection cancelled" ,
2026-10-04 16:02:36 +08:00
);
2026-10-10 04:58:25 +08:00
}
const bytes = z . instanceof ( Buffer ). parse ( chunk );
size += bytes . length ;
if ( size > MAX_BYTES ) {
stream . destroy ();
2026-10-04 16:02:36 +08:00
throw new ArtifactReaderFailure (
"limit" ,
"Keyed archive exceeds 64 MiB" ,
);
}
2026-10-10 04:58:25 +08:00
chunks . push ( bytes );
}
const bytes = Buffer . concat ( chunks , size );
try {
return keyedArchiveResultSchema . parse ({
target_sha256 : input.targetSha256 ,
archive_path : entry.path ,
archive_sha256 : createHash ( "sha256" ). update ( bytes ). digest ( "hex" ),
... decodeKeyedArchiveBytes ( bytes , selected ),
});
} catch ( cause ) {
if ( cause instanceof AnalysisInputError ) throw cause ;
// An intact file of another kind is not a damaged archive.
if ( cause instanceof KeyedArchiveKindError )
throw new AnalysisUnsupportedTargetError (
"inspect_keyed_archive" ,
join ( input . bundlePath , entry . path ),
cause . message ,
{
cause ,
remediationAction : keyedArchiveKindRemediation (
cause . kind ,
input . platform ?? process . platform ,
),
},
2026-10-04 16:02:36 +08:00
);
2026-10-10 04:58:25 +08:00
throw new ArtifactReaderFailure (
cause instanceof RangeError ? "limit" : "format" ,
`Cannot decode selected Foundation keyed archive: ${ cause instanceof Error ? cause.message : String ( cause ) } ` ,
{ cause },
);
2026-10-04 16:02:36 +08:00
}
} finally {
await reader . close ();
}
};
2026-10-08 13:43:30 +00:00
/** A caller-selected archive path, not the artifact, failed its constraint. */
const archivePathError = (
reason : "invalid_format" | "invalid_value" ,
message : string ,
) =>
new AnalysisInputError ( "inspect_keyed_archive" , undefined , [
{ path : [ "path" ], reason , message },
]);