Files
reverse-engineering-anything/docs/macos-pkg.md
T
dbbe334ec1 feat(artifacts): inventory macOS flat installer packages offline (#11377)
* feat(artifacts): inventory macOS flat installer packages offline

* fix(artifacts): keep refused pkg members unavailable during inspection

A XAR member whose decode failed or whose decoded size contradicted the
TOC stayed a readable entry, so shared inspection reopened it, hit the
same mismatch at stream flush and aborted the whole scan. Record those
members and have open() report them as unavailable content, so the scan
keeps the partial facts and the named refusal.

* fix(artifacts): report out-of-range installKBytes as unknown

The Distribution parser accepted any safe integer for a pkg-ref's
installKBytes, but the report field is uint32. A value such as
4294967296 parsed fine and then failed schema validation, which
rejected the whole inventory report. Bound the attribute to uint32
at parse time so an out-of-range value reads as unknown.

* fix(artifacts): charge decoded pkg archive bytes against the shared budget

The shared expansion budget charged each Scripts or Payload member by its
stored XAR size, so several small gzip members could each decode toward the
per-archive allowance while barely moving the total. Decode now stops at
what remains of the shared budget, the decoded size is charged, and an
archive that would exceed it is listed as not expanded.

gunzipBounded also recognizes Node's ERR_BUFFER_TOO_LARGE, which is what
maxOutputLength raises, so an oversize gzip member is reported as a limit
rather than as invalid gzip data.

* fix(artifacts): keep expanded pkg Scripts/Payload archives in inventory

Expanding a gzip-cpio Scripts or Payload member deleted the stored XAR
entry, so its heap offset, sizes and TOC checksums dropped out of
inventory and extraction. Keep the stored occurrence at a sibling
logical path (for example Payload.cpio.gz) with sourcePath still naming
the XAR member, so it sits alongside the expanded children.

* fix(artifacts): count pkg check scripts in UTF-8 bytes

scriptLength returned the JavaScript string length, so non-ASCII
installation-check and volume-check scripts reported the wrong byte
count. Measure the selected text with Buffer.byteLength.

* fix(artifacts): keep pkg FIFO and device members non-materializable

A cpio member that is not a directory, symlink or regular file (FIFO,
character or block device, socket) was inventoried as an empty regular
file. Emit it as a metadata declaration with a limitation naming its
type, keep its mode in format metadata, and refuse open() on it.

* fix(artifacts): bound pkg member archived range before reading it

Refuse a zlib-encoded XAR member whose archived heap range exceeds the
compress bound of its decode allowance, and never read the range of an
unsupported encoding, so a package-controlled archived length cannot
reach a buffer allocation unbounded.

* fix(artifacts): refuse installer XML with an unexpected root element

Distribution must have an <installer-gui-script> root and PackageInfo a
<pkg-info> root. Any other root is now a named malformed-input refusal
instead of a product or component identity with null fields.

* fix(artifacts): keep duplicate XAR TOC paths as distinct pkg entries

Key XAR file entries by their TOC occurrence instead of their path, so a
later record at the same path no longer overwrites the earlier one.
Expanded Scripts/Payload member keys now derive from their archive key
for the same reason.

* fix(artifacts): cap streamed XAR inflate output before forwarding it

maxOutputLength does not bound a zlib stream, so count emitted bytes in
createBoundedXarInflate and fail before forwarding past the allowance.
The member stream also fails as soon as decoded bytes pass the TOC
extracted size instead of waiting for EOF.

* fix(artifacts): read XAR TOC execute bits across owner, group and other

The XAR TOC <mode> was tested only on its last octal digit, so a mode
such as 0750 reported a non-executable entry. Parse the octal text and
test (mode & 0o111) like the cpio path.

* fix(artifacts): keep XAR TOC directories and link-only symlinks as pkg entries

TOC records without a heap body were dropped from the inventory, so
directories, symlinks declared only by <link>, and empty files vanished.
They now become their own occurrences: directories stay non-openable,
symlinks open as their declared target text, empty files open as zero
bytes, and other record types are kept as non-materializable metadata.
Installer document lookup only considers heap-backed records.

The shared lifecycle cases open the first entry, so they now use the
component package fixture, whose first TOC record is a heap-backed file.

* fix(artifacts): record Scripts and Payload presence from the XAR TOC

A listed Scripts or Payload archive is now present before expansion is
attempted. When the shared budget skips it or the XAR read is refused,
its compression is reported as "unread" instead of "absent".

* fix(artifacts): keep pkg coverage unknown when content was refused

Coverage was complete whenever no archive hit the shared expansion
budget, even when a heap range, encoding, decode, cpio or pbzx refusal
left content unread. Any refusal other than the header-version notice
now keeps coverage unknown.

* fix(artifacts): only treat the cpio archive limit as a shared budget stop

A zero or oversize cpio namesize raises the name limit, whose maximum is
4096 bytes. When exactly 4096 bytes of shared budget remained, that limit
was mistaken for the budget stop and the refusal was dropped. Match the
limit name as well as its maximum.

* fix(artifacts): keep cpio members read before a damaged tail

A Scripts or Payload archive whose cpio stream ends or breaks after
complete members used to discard all of them and report an empty
inventory with false script flags. parseCpioOdcPrefix now returns the
members read before the failure along with the failure itself, and the
pkg reader keeps those members as entries while recording the refusal,
so coverage stays unknown. A failure before any complete member is
still a plain refusal.

* fix(artifacts): keep an out-of-range XAR TOC mode unknown

Parse <mode> once in the TOC reader. Octal text that does not fit a
uint32 becomes null, so one bad entry no longer fails the inventory
schema check for the whole package.

* fix(artifacts): cancel paused memory-backed pkg members

A retained member streamed into a paused consumer kept its output open
after abort, because the in-memory source has no signal and the shared
stream owner defers cancellation until production finishes. The member
output now retires on abort while its final validation has not started.

* Address review feedback

* fix(artifacts): share one expansion allowance across XAR members

* fix(artifacts): count XAR TOC nodes before building the DOM

A small TOC could hold millions of ignored elements under the byte
limits, and each became a DOM node before the file count ran. Parse
the TOC through parseXmlDocumentWithinNodeLimit with a 256-per-file
node allowance and report a capacity limit past it.

* fix(artifacts): cancel a paused XAR decoder after its source retires

A highly compressed zlib member can finish reading its archived range
while the decoder is still paused on a slow consumer. The file source's
abort listener is gone by then and ownArtifactStream deferred abort until
production finished, so cancellation waited for the consumer to resume.

Once the source closes, an abort now destroys a decoder that has not
ended. The output's final validation only starts after the decoder ends,
so it keeps failure precedence.

* fix(artifacts): reset XAR reader state when preparation retries

When one caller cancelled preparation and another retried it on the
same reader, #prepare built fresh metadata but kept #entries and
#refusedContent from the cancelled attempt. The retry then skipped
members already refused without recording their refusals, so coverage
could report complete while open() still refused the member.

#prepare now clears both maps before it reads the package.

* fix(artifacts): align macOS pkg reader with format failure API and zlib output limits

* fix(artifacts): bound XAR TOC expanded paths, preserve valid TOC records, and populate symlink linkTarget

* fix(pkg): enforce package-wide cpio caps, strict UTF-8 names, root Distribution, and stored size checks

* fix(macos-pkg): bound package-wide installer metadata bytes and records

* fix(macos-pkg): tie installer metadata budgets to artifact_limits.expanded_bytes

Wire macOS flat package Distribution/PackageInfo byte, record, and XML-node
allowances into artifact_limits.expanded_bytes via macosPkgMetadataBudget:
- Preserve the 4 MiB total, 1 MiB per-document, 4,096-record, and 65,536-node
  defaults when artifact_limits.expanded_bytes is omitted so aliased-heap
  metadata bombs remain bounded.
- Charge every Distribution and PackageInfo read (including aliased stored
  heap ranges) against the shared expanded_bytes budget alongside zlib XAR
  members and Scripts/Payload expansion.
- Raise the byte allowances and scale record (1 per 1,024 bytes, min 4,096)
  and XML-node (16 per record) allowances when artifact_limits.expanded_bytes
  is set, and report effective limits with artifact_limits.expanded_bytes
  recovery on metadata limit refusals.
- Also add qualcomm-mbn to PE_OVERLAY_LEADING_FORMATS to resolve the typecheck
  conflict introduced by merging origin/main.

* fix(macos-pkg): strip repeated ./ prefixes and tie cpio limits to expanded_bytes

- Normalize cpio member paths with withoutCurrentDirectoryPrefix (handling
  repeated leading ./ segments and archive-root entries such as ./. and ././)
  both when counting retained path bytes and when forming logical paths,
  preserving the recorded name in sourcePath.
- Derive Scripts/Payload cpio archive-byte, member-count, and expanded
  path-byte allowances from artifact_limits.expanded_bytes via
  macosPkgCpioBudget (keeping 64 MiB / 4,096 members / 4 MiB defaults when
  omitted, removing hardcoded cpio clamps, and reporting effective limits with
  artifact_limits.expanded_bytes recovery).
- Update docs/macos-pkg.md and docs/reference/limits-and-recovery.md and add
  regression tests.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Matt Van Horn <mvanhorn@MacBook-Pro-10.local>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-26 23:29:05 +00:00

102 lines
5.7 KiB
Markdown

# macOS flat installer packages
`inspect-artifact` and `extract-artifact` read local macOS flat installer
packages (`.pkg` files whose bytes start with `xar!`) without expanding them
with `pkgutil`, running installer JavaScript, or verifying the XAR signature.
The same domain facts and artifact reader serve CLI and MCP. The reader is
portable: Linux and Windows hosts inventory the same bytes as macOS.
A flat package is an XAR archive. The 28-byte header names the zlib-compressed
table of contents (TOC). The TOC XML lists each stored file's name, type, heap
offset, archived and extracted sizes, encoding, and the checksum values the
archive recorded. REA reports those recorded checksums; it does not treat them
as verified identities. Heap ranges that extend past the file are refused and
omitted; other TOC files stay visible.
A product archive carries a `Distribution` document plus nested
`*.pkg/PackageInfo` component packages. A component package carries
`PackageInfo` at the archive root. Inventory reports title, `pkg-ref`
identifiers, versions and `installKBytes`, the choices outline,
`allowed-os-versions`, and whether `installation-check` / `volume-check`
scripts are present. Script bodies are reported by byte length only and are
never executed. Each `PackageInfo` contributes identifier, version,
install-location, auth, `postinstall-action`, bundle entries, and declared
preinstall/postinstall names.
`Scripts` and `Payload` members that are gzip-compressed odc cpio (`070707`)
are expanded into nested occurrences (path, mode, uid/gid, size, symlink
target). `preinstall` and `postinstall` presence is explicit. Script bytes are
not executed. `pbzx` (xz-chunked) payloads keep the stored `Payload` member
and record a typed unsupported-compression refusal; Distribution, PackageInfo
and Scripts inventory still appear. `Bom` is reported by presence and size
only.
When the TOC names a signature or x-signature, inventory reports the
algorithm and the embedded certificate subject's and issuer's common names
through `node:crypto` `X509Certificate`. Verification is always
`not_verified`.
Malformed or truncated input keeps what was safely read: a short header, a TOC
that extends past EOF, a zlib inflate failure, an out-of-bounds heap range, a
declared extracted-size that disagrees with the decoded member, or garbage
cpio headers become named refusals on the root metadata rather than silent
zeros. Counts above the fixed TOC and cpio allowances fail as a capacity
limit.
Extraction writes stored XAR files and expanded gzip-cpio members into the
existing contained output tree. pbzx payload contents are not decoded.
## Bounded work and retained facts
These are resource policies, not format maxima. The compressed TOC is limited
to 16 MiB and the uncompressed TOC XML to 64 MiB. A TOC may declare at most
4,096 files. When `artifact_limits.expanded_bytes` is omitted, one decoded
`Scripts` or `Payload` cpio archive defaults to 64 MiB, with 4,096 retained
cpio members and 4 MiB of expanded cpio logical path bytes across the package;
`Distribution` and `PackageInfo` metadata decoding defaults to 1 MiB per
document, 4 MiB total across the package, 4,096 retained metadata records, and
65,536 XML nodes per document. Every `Distribution` and `PackageInfo` read
(including repeated or aliased stored heap ranges) is charged against the
shared `artifact_limits.expanded_bytes` budget alongside zlib XAR members and
`Scripts`/`Payload` expansion. Setting `artifact_limits.expanded_bytes` raises
both the per-archive cpio byte allowance and the per-document and package-wide
installer metadata byte allowances to that budget, and scales the package-wide
cpio member allowance (1 member per 16 KiB, minimum 4,096), expanded cpio path
byte allowance (1 byte per 16 bytes, minimum 4 MiB), metadata record allowance
(1 record per 1,024 bytes, minimum 4,096), and XML node allowance (16 nodes per
record) so larger valid installers can be retried. A TOC extracted-size above
the named allowance for that member is refused without inflating. A decoded
length that disagrees with the TOC is `extracted-size-mismatch`. Extraction
stream-decodes gzip/zlib XAR members with `artifact_limits.expanded_bytes` (the
same expansion budget as ZIP/Bun/Deno/Godot). Every component
`Scripts`/`Payload` is expanded until that budget is exhausted; remaining
component archives are named and coverage is unknown. Member streams use 64 KiB
chunks. Parsed facts are cached for one reader. Close joins active member
pipelines before releasing the descriptor.
Prefer a retained summary when only a few facts are needed:
```sh
rea inspect-artifact installer.pkg --detail summary \
--evidence_output installer.evidence.json --json
rea extract-artifact installer.pkg --json
```
With MCP, `inspect_artifact` with `detail: "summary"` retains the complete
Evidence. Coverage and limitations remain attached.
## Verification scope
Synthetic XAR fixtures cover a product archive, a component package, a signed
TOC with an embedded certificate, a pbzx payload stub, truncated headers, TOC
lengths past EOF, inflate failures, heap ranges past the heap, garbage cpio
headers, and an oversize TOC file count. Compiled CLI and MCP tests inspect
and extract the product-archive fixture. `inspect-artifact --json` was also
run against the public MacPorts 2.10.5 Sequoia installer
(`https://github.com/macports/macports-base/releases/download/v2.10.5/MacPorts-2.10.5-15-Sequoia.pkg`,
SHA-256 `574662c46ae07dc06f5b1bc7fd517c9729163cc3c4a91027a011f794dc46d65c`):
product archive, gzip cpio Payload and Scripts, Bom by size, CMS signature
named and not verified. No Apple `pkgbuild` / `productbuild` package was
produced on this host. XAR signatures are not verified. pbzx/xz payloads and
Bom files are not decoded. Installer JavaScript is never evaluated.