Merge branch 'feat/dylib-resolution' into feat/dyld-shared-cache

Carry #952's Apple ownership into the cache work: the cache reader and
fixture move to src/artifacts/apple/, the cache facts, platforms and
resolution schema to src/domain/apple/, the cache service to
src/application/apple/, and the lane to scripts/verify/apple/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 13:32:48 +00:00
co-authored by Claude Opus 5.5
90 changed files with 1354 additions and 289 deletions
+497
View File
@@ -0,0 +1,497 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { projectAppleApplication } from "./appleApplication.js";
import { canonicalDigest } from "../comparisonSemantics.js";
import { createEvidence, type Evidence } from "../evidence.js";
import { jsonValueSchema } from "../jsonValue.js";
type EntryKind = "file" | "directory" | "symlink";
type RootFormat = "ipa" | "zip" | "dmg" | "directory" | "asar";
interface FixtureEntry {
readonly path: string;
readonly kind?: EntryKind;
readonly format?: string;
}
const sha = (text: string): string =>
createHash("sha256").update(text).digest("hex");
const artifactId = (sha256: string): string =>
`art_${canonicalDigest({ sha256 }, "Artifact inventory")}`;
/** Build one complete, content-addressed inventory page for pure projection tests. */
const inventoryEvidence = (
rootFormat: RootFormat,
subjectName: string,
entries: readonly FixtureEntry[],
): Evidence => {
const rootSha = sha(`${rootFormat}:${subjectName}`);
const rootId = artifactId(rootSha);
const node = (sha256: string, format: string) => ({
artifact_id: artifactId(sha256),
kind: "resource",
format,
sha256,
size: 1,
media_type: null,
architecture: null,
executable: false,
content_state: "materialized",
limitations: [],
});
const occurrence = (path: string, kind: EntryKind, id: string | null) => ({
occurrence_id:
path === "."
? `occ_${canonicalDigest({ root: rootId }, "Artifact inventory")}`
: `occ_${canonicalDigest(
{ root_artifact_id: rootId, logical_path: path, entry_kind: kind },
"Artifact inventory",
)}`,
artifact_id: id,
parent_occurrence_id: null,
logical_path: path,
entry_kind: kind,
declared_size: null,
compressed_size: null,
executable: false,
encrypted: false,
hash_status: "verified",
source_location: null,
limitations: [],
});
const nodes = new Map([[rootId, node(rootSha, rootFormat)]]);
const occurrences = [occurrence(".", "file", rootId)];
for (const { path, kind = "file", format = "file" } of entries) {
if (kind === "symlink") {
occurrences.push(occurrence(path, kind, null));
continue;
}
const contentSha = sha(`${kind}:${path}`);
const id = artifactId(contentSha);
nodes.set(
id,
node(contentSha, kind === "directory" ? "directory" : format),
);
occurrences.push(occurrence(path, kind, id));
}
const sortedNodes = [...nodes.values()].sort((left, right) =>
left.artifact_id.localeCompare(right.artifact_id),
);
const sortedOccurrences = occurrences.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path, "en"),
);
const graphSha256 = canonicalDigest(
{
nodes: sortedNodes,
occurrences: sortedOccurrences,
edges: [],
integrity_contradictions: [],
},
"Artifact inventory",
);
return createEvidence(
{
path: `/fixtures/${subjectName}`,
sha256: rootSha,
format: rootFormat,
},
{ id: "rea-artifact-graph", name: "fixture", version: "1" },
{
operation: "inventory_artifact",
parameters: {},
confidence: "observed",
authority: "shipped-artifact",
result: jsonValueSchema.parse({
manifest: {
manifest_id: `agm_${canonicalDigest(
{ root_artifact_id: rootId, graph_sha256: graphSha256 },
"Artifact inventory",
)}`,
root_artifact_id: rootId,
root_sha256: rootSha,
root_format: rootFormat,
graph_sha256: graphSha256,
node_count: sortedNodes.length,
occurrence_count: sortedOccurrences.length,
edge_count: 0,
},
nodes: sortedNodes,
occurrences: sortedOccurrences,
edges: [],
provenance: [],
limitations: [],
}),
},
);
};
const project = (evidence: Evidence) =>
projectAppleApplication({ inventory_evidence: [evidence] });
const macho = (path: string): FixtureEntry => ({ path, format: "mach-o" });
describe("macOS application roots and bundle roles", () => {
it("treats an inventoried .app directory as its own application root", () => {
const result = project(
inventoryEvidence("directory", "Fixture.app", [
{ path: "Contents/Info.plist" },
macho("Contents/MacOS/Fixture"),
{ path: "Contents/_CodeSignature/CodeResources" },
{ path: "Contents/embedded.provisionprofile" },
macho("Contents/Library/LaunchServices/com.example.helper"),
{ path: "Contents/Library/LaunchDaemons/com.example.helper.plist" },
{ path: "Contents/Library/LaunchAgents/com.example.agent.plist" },
macho("Contents/Helpers/tool"),
macho("Contents/Helpers/Assistant.app/Contents/MacOS/Assistant"),
macho(
"Contents/Library/SystemExtensions/com.example.filter.systemextension/Contents/MacOS/com.example.filter",
),
macho(
"Contents/Library/SystemExtensions/com.example.driver.dext/driver",
),
{ path: "Contents/PlugIns/Preview.qlgenerator", kind: "directory" },
macho("Contents/PlugIns/Bridge.bundle/Contents/MacOS/Bridge"),
{ path: "Contents/Resources/Strings.bundle/Info.plist" },
{ path: "Contents/SharedSupport/Data.bundle", kind: "directory" },
macho("Contents/Resources/Embedded.app/Contents/MacOS/Embedded"),
]),
);
expect(result).toMatchObject({
root_format: "directory",
platforms: ["macos"],
application_roots: ["."],
});
expect(
result.bundles.map(({ path, role, layout, parent_path: parent }) => ({
path,
role,
layout,
parent,
})),
).toEqual([
{ path: ".", role: "application", layout: "macos-deep", parent: null },
{
path: "Contents/Helpers/Assistant.app",
role: "helper-application",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/Library/SystemExtensions/com.example.driver.dext",
role: "driver-extension",
layout: "shallow",
parent: ".",
},
{
path: "Contents/Library/SystemExtensions/com.example.filter.systemextension",
role: "system-extension",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/PlugIns/Bridge.bundle",
role: "plug-in",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/PlugIns/Preview.qlgenerator",
role: "plug-in",
layout: "shallow",
parent: ".",
},
{
path: "Contents/Resources/Embedded.app",
role: "nested-application",
layout: "macos-deep",
parent: ".",
},
{
path: "Contents/Resources/Strings.bundle",
role: "resource-bundle",
layout: "shallow",
parent: ".",
},
{
path: "Contents/SharedSupport/Data.bundle",
role: "bundle",
layout: "shallow",
parent: ".",
},
]);
expect(result.bundles[0]).toMatchObject({
info_plist_path: "Contents/Info.plist",
executable_candidates: ["Contents/MacOS/Fixture"],
signing_paths: [
"Contents/_CodeSignature/CodeResources",
"Contents/embedded.provisionprofile",
],
});
expect(
result.components.privileged_helpers.map(({ path }) => path),
).toEqual(["Contents/Library/LaunchServices/com.example.helper"]);
expect(
result.components.launchd_plists.map(({ path, domain }) => [
path,
domain,
]),
).toEqual([
["Contents/Library/LaunchAgents/com.example.agent.plist", "agent"],
["Contents/Library/LaunchDaemons/com.example.helper.plist", "daemon"],
]);
expect(result.components.helpers.map(({ path }) => path)).toEqual([
"Contents/Helpers/tool",
]);
});
it("does not make a non-application bundle directory an application root", () => {
const result = project(
inventoryEvidence("directory", "Service.xpc", [
{ path: "Contents/Info.plist" },
macho("Contents/MacOS/Service"),
]),
);
expect(result.application_roots).toEqual([]);
expect(result.bundles).toEqual([]);
expect(result.limitations).toContain(
"No application bundle (Payload/*.app or *.app/Contents) was present in the supplied inventory pages.",
);
});
});
describe("Apple bundle layouts and containers", () => {
it("follows versioned frameworks without resolving Versions/Current", () => {
const framework = "Fixture.app/Contents/Frameworks/Core.framework";
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Core`, kind: "symlink" },
{ path: `${framework}/Versions/Current`, kind: "symlink" },
macho(`${framework}/Versions/A/Core`),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/A/_CodeSignature/CodeResources` },
macho(
`${framework}/Versions/A/XPCServices/Fetch.xpc/Contents/MacOS/Fetch`,
),
]),
);
const core = result.bundles.find(({ path }) => path === framework);
expect(core).toEqual({
path: framework,
parent_path: "Fixture.app",
layout: "versioned-framework",
role: "framework",
role_basis: "path-convention",
info_plist_path: `${framework}/Versions/A/Resources/Info.plist`,
executable_candidates: [`${framework}/Versions/A/Core`],
signing_paths: [`${framework}/Versions/A/_CodeSignature/CodeResources`],
});
expect(
result.bundles.find(({ role }) => role === "xpc-service")?.parent_path,
).toBe(framework);
expect(result.symlinks).toEqual([
`${framework}/Core`,
`${framework}/Versions/Current`,
]);
});
it("reports an unknown Info.plist when several framework versions exist", () => {
const framework = "Fixture.app/Contents/Frameworks/Core.framework";
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/B/Resources/Info.plist` },
]),
);
expect(
result.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBeNull();
// Files beside the only real version are not versions.
const withFiles = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
{ path: `${framework}/Versions/.DS_Store` },
{ path: `${framework}/Versions/Current`, kind: "symlink" },
]),
);
expect(
withFiles.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBe(`${framework}/Versions/A/Resources/Info.plist`);
// Only A has a plist, but Versions/Current may select B.
const onlyA = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: `${framework}/Versions/A/Resources/Info.plist` },
macho(`${framework}/Versions/B/Core`),
]),
);
expect(
onlyA.bundles.find(({ path }) => path === framework)?.info_plist_path,
).toBeNull();
expect(result.limitations).toContainEqual(
expect.stringContaining("Versions/Current selects is unknown"),
);
});
it("excludes AppleDouble sidecars from roots and roles", () => {
const result = project(
inventoryEvidence("zip", "Fixture.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
{ path: "Fixture.app/Contents/Library/LaunchDaemons/._helper.plist" },
{ path: "Fixture.app/Contents/Library/LaunchDaemons/helper.plist" },
{ path: "__MACOSX/Other.app/Contents/._Info.plist" },
]),
);
expect(result.application_roots).toEqual(["Fixture.app"]);
expect(result.components.launchd_plists.map(({ path }) => path)).toEqual([
"Fixture.app/Contents/Library/LaunchDaemons/helper.plist",
]);
expect(result.limitations).toContainEqual(
expect.stringContaining("AppleDouble sidecar entries"),
);
});
it("reports a DMG without inventoried contents as partial", () => {
const result = project(inventoryEvidence("dmg", "Fixture.dmg", []));
expect(result.coverage).toEqual({
status: "partial",
inventory_complete: true,
});
expect(result.limitations).toContain(
"The DMG's contents were not inventoried on this host; bundle absence is unknown.",
);
});
it("keeps IPA applications shallow and iOS", () => {
const result = project(
inventoryEvidence("ipa", "Fixture.ipa", [
{ path: "Payload/Fixture.app/Info.plist" },
macho("Payload/Fixture.app/Fixture"),
{ path: "Payload/Fixture.app/embedded.mobileprovision" },
macho("Payload/Fixture.app/PlugIns/Share.appex/Share"),
macho("SwiftSupport/iphoneos/libswiftCore.dylib"),
]),
);
expect(result.platforms).toEqual(["ios"]);
// IPA projection still lists archive components outside Payload/.
expect(result.components.native_libraries.map(({ path }) => path)).toEqual([
"SwiftSupport/iphoneos/libswiftCore.dylib",
]);
expect(
result.bundles.map(({ path, role, layout }) => [path, role, layout]),
).toEqual([
["Payload/Fixture.app", "application", "shallow"],
["Payload/Fixture.app/PlugIns/Share.appex", "app-extension", "shallow"],
]);
expect(result.bundles[0]?.executable_candidates).toEqual([
"Payload/Fixture.app/Fixture",
]);
});
it("rejects inventories that cannot contain an Apple application", () => {
expect(() => project(inventoryEvidence("asar", "app.asar", []))).toThrow(
"Apple application projection requires IPA, directory, ZIP, or DMG inventory Evidence (got asar)",
);
});
});
describe("macOS application scope", () => {
it("attributes only components inside the application roots", () => {
const result = project(
inventoryEvidence("zip", "Distribution.zip", [
macho("Fixture.app/Contents/MacOS/Fixture"),
macho("Fixture.app/Contents/Frameworks/Core.framework/Versions/A/Core"),
{
path: "Fixture.app/Contents/Resources/app.js",
format: "javascript-bundle",
},
macho("Extras/Plugin.framework/Versions/A/Plugin"),
macho("Extras/libextra.dylib"),
{ path: "Extras/installer.js", format: "javascript-bundle" },
{ path: "Extras/Info.plist" },
]),
);
const paths = (components: readonly { readonly path: string }[]) =>
components.map(({ path }) => path);
expect(paths(result.components.frameworks)).toEqual([
"Fixture.app/Contents/Frameworks/Core.framework/Versions/A/Core",
]);
expect(paths(result.components.native_libraries)).toEqual([]);
expect(paths(result.components.javascript)).toEqual([
"Fixture.app/Contents/Resources/app.js",
]);
expect(paths(result.components.bundle_metadata)).toEqual([]);
expect(
result.bridge_candidates.every(
({ source_path: source, native_path: target }) =>
[source, target].every((path) => path.startsWith("Fixture.app/")),
),
).toBe(true);
expect(result.limitations).toContain(
"4 inventoried entries outside every application root are not attributed to the application.",
);
});
it("keeps a selected .app directory as the root when its contents are missing", () => {
const empty = project(inventoryEvidence("directory", "Fixture.app", []));
expect(empty).toMatchObject({
application_roots: ["."],
platforms: [],
bundles: [
{
path: ".",
role: "application",
layout: "shallow",
info_plist_path: null,
},
],
});
const partial = project(
inventoryEvidence("directory", "Fixture.app", [
{ path: "Contents/Resources/Localizable.strings" },
]),
);
expect(partial).toMatchObject({
application_roots: ["."],
platforms: ["macos"],
});
});
});
describe("Apple application bridge candidates", () => {
it("pairs scripts and native code only within one application root", () => {
const result = project(
inventoryEvidence("zip", "Suite.zip", [
macho("First.app/Contents/MacOS/First"),
{
path: "First.app/Contents/Resources/first.js",
format: "javascript-bundle",
},
macho("Second.app/Contents/MacOS/Second"),
{
path: "Second.app/Contents/Resources/second.js",
format: "javascript-bundle",
},
]),
);
expect(result.application_roots).toEqual(["First.app", "Second.app"]);
expect(
result.bridge_candidates.map(
({ source_path: source, native_path: target }) => [source, target],
),
).toEqual([
[
"First.app/Contents/Resources/first.js",
"First.app/Contents/MacOS/First",
],
[
"Second.app/Contents/Resources/second.js",
"Second.app/Contents/MacOS/Second",
],
]);
});
});
+403
View File
@@ -0,0 +1,403 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
appleBundleSchema,
appleComponentSchema,
applicationRoots,
detectBundles,
isMachOFormat,
isSidecar,
isWithin,
platformsOf,
type AppleInventoryEntry,
} from "./appleBundleAnatomy.js";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const pathSchema = z.string().min(1);
const APPLE_ROOT_FORMATS = ["ipa", "directory", "zip", "dmg"] as const;
/** Authenticated artifact inventory pages projected as one Apple application. */
export const appleApplicationProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
});
/** Deterministic, execution-free Apple application inventory projection. */
export const appleApplicationProjectionResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("aap"),
root_sha256: digestSchema,
root_format: z.enum(APPLE_ROOT_FORMATS),
platforms: z.array(z.enum(["ios", "macos"])),
source_evidence_ids: z.array(evidenceIdSchema).min(1),
application_roots: z.array(pathSchema),
bundles: z.array(appleBundleSchema),
components: z.strictObject({
bundle_metadata: z.array(appleComponentSchema),
executables: z.array(appleComponentSchema),
frameworks: z.array(appleComponentSchema),
native_libraries: z.array(appleComponentSchema),
javascript: z.array(appleComponentSchema),
signing: z.array(appleComponentSchema),
privileged_helpers: z.array(appleComponentSchema),
launchd_plists: z.array(
appleComponentSchema.extend({ domain: z.enum(["agent", "daemon"]) }),
),
helpers: z.array(appleComponentSchema),
}),
symlinks: z.array(pathSchema),
runtime_families: z.array(
z.enum([
"native",
"swift-objective-c",
"javascript",
"react-native",
"flutter",
"unity",
]),
),
bridge_candidates: z.array(
z.strictObject({
source_path: pathSchema,
native_path: pathSchema,
basis: z.enum([
"javascript-and-native-content",
"react-native-convention",
"flutter-convention",
"unity-convention",
]),
}),
),
coverage: z.strictObject({
status: z.enum(["complete-within-inventory", "partial"]),
inventory_complete: z.boolean(),
}),
limitations: z.array(z.string().min(1)),
});
export type AppleApplicationProjectionInput = z.infer<
typeof appleApplicationProjectionInputSchema
>;
export type AppleApplicationProjectionResult = z.infer<
typeof appleApplicationProjectionResultSchema
>;
type Component = z.infer<typeof appleComponentSchema>;
type RootFormat = (typeof APPLE_ROOT_FORMATS)[number];
/** Project exact Apple application paths and hashes without parsing or executing target code. */
export const projectAppleApplication = (
input: AppleApplicationProjectionInput,
): AppleApplicationProjectionResult => {
const parsed = appleApplicationProjectionInputSchema.parse(input);
const { evidence, inventory } = parseArtifactInventoryEvidence(
parsed.inventory_evidence,
);
const rootFormat = appleRootFormat(inventory.manifest.root_format);
const nodes = new Map(
inventory.nodes.map((node) => [node.artifact_id, node]),
);
const entries: AppleInventoryEntry[] = inventory.occurrences
.filter(({ logical_path: path }) => path !== ".")
.map((occurrence) => {
if (occurrence.artifact_id === null)
return {
path: occurrence.logical_path,
kind: occurrence.entry_kind,
component: undefined,
};
const node = nodes.get(occurrence.artifact_id);
if (node === undefined)
throw new TypeError(
"Apple application occurrence has no artifact node",
);
return {
path: occurrence.logical_path,
kind: occurrence.entry_kind,
component: {
path: occurrence.logical_path,
artifact_id: node.artifact_id,
sha256: node.sha256,
format: node.format,
},
};
});
const inventoried = entries.flatMap(({ component }) =>
component === undefined ? [] : [component],
);
const roots = applicationRoots(entries, {
name: evidence[0]?.subject?.name ?? "",
format: rootFormat,
});
const { all, unattributed } = attributeComponents(
inventoried,
roots,
rootFormat,
);
const bundles = detectBundles(entries, roots);
const classified = classifyComponents(entries, all, roots);
const runtimeFamilies = identifyRuntimeFamilies(all);
const bridgeProjection = identifyBridgeCandidates(
classified.javascript,
deduplicateComponents([
...classified.executables,
...classified.native_libraries,
]),
roots,
);
const uninventoriedImage =
rootFormat === "dmg" && inventory.occurrences.length === 1;
const complete = inventory.complete && !uninventoriedImage;
const limitations = projectionLimitations({
complete: inventory.complete,
uninventoriedImage,
roots,
bundles,
sidecars: entries.some(({ path }) => isSidecar(path)),
symlinks: entries.some(({ kind }) => kind === "symlink"),
unattributed,
});
const withoutId = {
root_sha256: inventory.manifest.root_sha256,
root_format: rootFormat,
platforms: platformsOf(bundles),
source_evidence_ids: evidence
.map(({ evidence_id: id }) => id)
.sort(compare),
application_roots: roots,
bundles,
components: classified,
symlinks: entries
.filter(({ kind }) => kind === "symlink")
.map(({ path }) => path)
.sort(compare),
runtime_families: runtimeFamilies,
bridge_candidates: bridgeProjection.candidates,
coverage: {
status: complete
? ("complete-within-inventory" as const)
: ("partial" as const),
inventory_complete: inventory.complete,
},
limitations,
};
return appleApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `aap_${digest(withoutId)}`,
});
};
/**
* IPA projection keeps every archive component, as before. Directory, ZIP,
* and DMG inventories can hold installers and other siblings, so only
* components inside an application root are attributed to it.
*/
const attributeComponents = (
inventoried: readonly Component[],
roots: readonly string[],
rootFormat: RootFormat,
): { readonly all: Component[]; readonly unattributed: number } => {
if (rootFormat === "ipa") return { all: [...inventoried], unattributed: 0 };
const visible = inventoried.filter(({ path }) => !isSidecar(path));
const all = visible.filter(({ path }) =>
roots.some((root) => isWithin(path, root)),
);
return { all, unattributed: visible.length - all.length };
};
const appleRootFormat = (format: string): RootFormat => {
const root = APPLE_ROOT_FORMATS.find((candidate) => candidate === format);
if (root === undefined)
throw new TypeError(
`Apple application projection requires IPA, directory, ZIP, or DMG inventory Evidence (got ${format})`,
);
return root;
};
const classifyComponents = (
entries: readonly AppleInventoryEntry[],
all: readonly Component[],
roots: readonly string[],
) => {
const withinApp = (path: string): boolean =>
roots.some((root) => isWithin(path, root));
const anatomy = (pattern: RegExp): Component[] =>
entries.flatMap(({ path, kind, component }) =>
kind === "file" &&
component !== undefined &&
!isSidecar(path) &&
withinApp(path) &&
pattern.test(path)
? [component]
: [],
);
return {
bundle_metadata: all.filter(({ path }) =>
/(?:^|\/)Info\.plist$/u.test(path),
),
executables: all.filter(
({ path, format }) => withinApp(path) && isMachOFormat(format),
),
frameworks: all.filter(({ path }) => /\.framework\//u.test(path)),
native_libraries: all.filter(({ path }) => /\.(?:dylib|so)$/iu.test(path)),
javascript: all.filter(({ format }) => format === "javascript-bundle"),
signing: all.filter(({ path }) =>
/(?:^|\/)(?:embedded\.(?:mobileprovision|provisionprofile)|_CodeSignature\/CodeResources)$/u.test(
path,
),
),
privileged_helpers: anatomy(
/(?:^|\/)Contents\/Library\/LaunchServices\/[^/]+$/u,
),
launchd_plists: anatomy(
/(?:^|\/)Contents\/Library\/Launch(?:Agents|Daemons)\/[^/]+\.plist$/u,
).map((component) => ({
...component,
domain: component.path.includes("/LaunchDaemons/")
? ("daemon" as const)
: ("agent" as const),
})),
helpers: anatomy(/(?:^|\/)Contents\/Helpers\/[^/]+$/u),
};
};
const deduplicateComponents = (values: readonly Component[]): Component[] =>
[...new Map(values.map((value) => [value.path, value])).values()].sort(
(left, right) => compare(left.path, right.path),
);
const identifyRuntimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
z.infer<
typeof appleApplicationProjectionResultSchema
>["runtime_families"][number]
>();
if (all.some(({ format }) => ["mach-o", "mach-o-universal"].includes(format)))
families.add("native");
if (paths.some((path) => /\.(?:dylib|framework\/[^/]+)$/u.test(path)))
families.add("swift-objective-c");
if (all.some(({ format }) => format === "javascript-bundle"))
families.add("javascript");
if (
paths.some(
(path) =>
path.includes("reactnative") ||
path.includes("react.framework") ||
path.includes("hermes"),
)
)
families.add("react-native");
if (
paths.some(
(path) =>
path.includes("flutter.framework") || path.includes("app.framework"),
)
)
families.add("flutter");
if (paths.some((path) => path.includes("unityframework.framework")))
families.add("unity");
return [...families].sort(compare);
};
/** Pair scripts and native code only within the same application root. */
const identifyBridgeCandidates = (
scripts: readonly Component[],
native: readonly Component[],
roots: readonly string[],
) => {
const owner = (path: string): string | null =>
roots.find((root) => isWithin(path, root)) ?? null;
return {
candidates: scripts.flatMap((script) => {
const root = owner(script.path);
return native
.filter(({ path }) => owner(path) === root)
.map((item) => ({
source_path: script.path,
native_path: item.path,
basis: bridgeBasis(item.path),
}));
}),
};
};
const bridgeBasis = (
path: string,
):
| "javascript-and-native-content"
| "react-native-convention"
| "flutter-convention"
| "unity-convention" => {
const lower = path.toLowerCase();
if (lower.includes("react")) return "react-native-convention";
if (lower.includes("flutter") || lower.includes("app.framework"))
return "flutter-convention";
if (lower.includes("unity")) return "unity-convention";
return "javascript-and-native-content";
};
const projectionLimitations = (facts: {
readonly complete: boolean;
readonly uninventoriedImage: boolean;
readonly roots: readonly string[];
readonly bundles: readonly z.infer<typeof appleBundleSchema>[];
readonly sidecars: boolean;
readonly symlinks: boolean;
readonly unattributed: number;
}): string[] => [
...(!facts.complete
? ["Source inventory pages are incomplete; absence is unknown."]
: []),
...(facts.uninventoriedImage
? [
"The DMG's contents were not inventoried on this host; bundle absence is unknown.",
]
: []),
...(facts.roots.length === 0
? [
"No application bundle (Payload/*.app or *.app/Contents) was present in the supplied inventory pages.",
]
: []),
...(facts.bundles.some(
({ layout, info_plist_path: plist }) =>
layout === "versioned-framework" && plist === null,
)
? [
"A versioned framework has several version directories or no Versions/*/Resources/Info.plist; the Info.plist that Versions/Current selects is unknown because symlink targets are not inventoried.",
]
: []),
...(facts.symlinks
? [
"Symlinks are reported by path only; their targets are not inventoried, so bundles are reported at their real paths.",
]
: []),
...(facts.unattributed > 0
? [
`${facts.unattributed} inventoried entries outside every application root are not attributed to the application.`,
]
: []),
...(facts.sidecars
? [
"AppleDouble sidecar entries (._* files and __MACOSX/) describe neighbouring files and are excluded from bundle roles.",
]
: []),
"Bundle roles follow path conventions. Read each info_plist_path with inspect_plist for CFBundleExecutable, identifiers, and declared services.",
"Bundle identifiers and signing claims require dedicated plist and CMS parsing; this projection reports only exact paths and hashes.",
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
];
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Apple application projection is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from "vitest";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "./appleAssetCatalog.js";
describe("compiled Apple asset catalog projection", () => {
it("preserves metadata and paginates across catalog boundaries", () => {
const catalogs = [
{
path: "Resources/A/Assets.car",
sha256: "a".repeat(64),
records: parseAppleAssetCatalogRecords([
{ AssetStorageVersion: 1, Platform: "ios" },
{
Name: "Toolbar",
RenditionName: "toolbar@2x.png",
Scale: 2,
Idiom: "iphone",
Locale: "en",
Appearance: "dark",
},
]),
},
{
path: "Resources/B/Assets.car",
sha256: "b".repeat(64),
records: parseAppleAssetCatalogRecords([
{
Name: "Toolbar",
RenditionName: "toolbar~ipad.png",
PixelWidth: 64,
},
]),
},
];
const first = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 0,
limit: 2,
resourceReferences: [
{
sourceNodeId: "ib:Main.nib:object:1",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Missing",
},
],
});
expect(first.records.map(({ kind }) => kind)).toEqual([
"catalog",
"rendition",
]);
expect(first.records[1]?.metadata.Scale).toBe(2);
expect(first.records[1]?.metadata.Idiom).toBe("iphone");
expect(first.records[1]?.metadata.Locale).toBe("en");
expect(first.records[1]?.metadata.Appearance).toBe("dark");
expect(first.resource_key_matches).toEqual([
expect.objectContaining({ status: "ambiguous", key: "Toolbar" }),
expect.objectContaining({ status: "unmatched", key: "Missing" }),
]);
expect(first.next_offset).toBe(2);
expect(first.truncated).toBe(true);
const second = projectAppleAssetCatalogPage({
targetSha256: "c".repeat(64),
catalogs,
offset: 2,
limit: 2,
});
expect(second.records[0]?.catalog_path).toBe("Resources/B/Assets.car");
expect(second.next_offset).toBeNull();
expect(second.total_records).toBe(3);
});
it("rejects malformed pages and invalid utility data", () => {
expect(appleAssetCatalogInputSchema.safeParse({ offset: -1 }).success).toBe(
false,
);
expect(() =>
parseAppleAssetCatalogRecords({ Name: "not an array" }),
).toThrow(
expect.objectContaining({
_tag: "AnalysisOutputError",
reason: "assetutil output must be a JSON array",
}),
);
expect(() => parseAppleAssetCatalogRecords([null])).toThrow(
expect.objectContaining({
_tag: "AnalysisOutputError",
reason: "assetutil record 0 is not a JSON object",
}),
);
});
});
+174
View File
@@ -0,0 +1,174 @@
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(10_000).default(1_000),
});
const catalogSchema = z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_count: z.number().int().nonnegative(),
});
const recordSchema = z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
index: z.number().int().nonnegative(),
kind: z.enum(["catalog", "rendition"]),
asset_name: z.string().nullable(),
rendition_name: z.string().nullable(),
metadata: z.record(z.string(), jsonValueSchema),
});
const resourceKeyMatchSchema = z.strictObject({
source_node_id: z.string().min(1),
source_path: z.string().min(1),
source_archive_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
field: z.string().min(1),
key: z.string().min(1),
status: z.enum(["matched", "ambiguous", "unmatched"]),
renditions: z.array(
z.strictObject({
catalog_path: z.string().min(1),
catalog_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
record_index: z.number().int().nonnegative(),
rendition_name: z.string().nullable(),
}),
),
});
/** Normalized result returned by asset catalog inspection. */
export const appleAssetCatalogResultSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
catalogs: z.array(catalogSchema),
total_records: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
limit: z.number().int().positive(),
records: z.array(recordSchema),
resource_key_matches: z.array(resourceKeyMatchSchema),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
export type AppleAssetCatalogRecord = z.infer<typeof recordSchema>;
/** Parse assetutil JSON records without discarding format-specific metadata. */
export const parseAppleAssetCatalogRecords = (
value: unknown,
): readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[] => {
if (!Array.isArray(value))
throw new AnalysisOutputError(
"inspect_asset_catalog",
"assetutil output must be a JSON array",
);
return value.map((record, index) => {
const parsed = z.record(z.string(), jsonValueSchema).safeParse(record);
if (!parsed.success)
throw new AnalysisOutputError(
"inspect_asset_catalog",
`assetutil record ${index} is not a JSON object`,
{ cause: parsed.error },
);
return parsed.data;
});
};
/** Project catalog records and apply stable global pagination. */
export const projectAppleAssetCatalogPage = (input: {
readonly targetSha256: string;
readonly catalogs: readonly {
readonly path: string;
readonly sha256: string;
readonly records: readonly Readonly<
Record<string, ReturnType<typeof jsonValueSchema.parse>>
>[];
}[];
readonly offset: number;
readonly limit: number;
readonly resourceReferences?: readonly {
readonly sourceNodeId: string;
readonly sourcePath: string;
readonly sourceArchiveSha256: string;
readonly field: string;
readonly key: string;
}[];
}) => {
const all = input.catalogs.flatMap((catalog) =>
catalog.records.map((metadata, index): AppleAssetCatalogRecord => ({
catalog_path: catalog.path,
catalog_sha256: catalog.sha256,
index,
kind:
typeof metadata.RenditionName === "string" ||
typeof metadata.Name === "string"
? "rendition"
: "catalog",
asset_name: typeof metadata.Name === "string" ? metadata.Name : null,
rendition_name:
typeof metadata.RenditionName === "string"
? metadata.RenditionName
: null,
metadata,
})),
);
const records = all.slice(input.offset, input.offset + input.limit);
const next = input.offset + records.length;
const recordsByAssetName = new Map<string, typeof all>();
for (const record of all) {
if (record.kind !== "rendition" || record.asset_name === null) continue;
const matches = recordsByAssetName.get(record.asset_name) ?? [];
matches.push(record);
recordsByAssetName.set(record.asset_name, matches);
}
const resourceKeyMatches = (input.resourceReferences ?? []).map((source) => {
const matches = recordsByAssetName.get(source.key) ?? [];
return {
source_node_id: source.sourceNodeId,
source_path: source.sourcePath,
source_archive_sha256: source.sourceArchiveSha256,
field: source.field,
key: source.key,
status:
matches.length === 0
? ("unmatched" as const)
: matches.length === 1
? ("matched" as const)
: ("ambiguous" as const),
renditions: matches.map((record) => ({
catalog_path: record.catalog_path,
catalog_sha256: record.catalog_sha256,
record_index: record.index,
rendition_name: record.rendition_name,
})),
};
});
return appleAssetCatalogResultSchema.parse({
target_sha256: input.targetSha256,
catalogs: input.catalogs.map(
({ path, sha256, records: catalogRecords }) => ({
path,
sha256,
record_count: catalogRecords.length,
}),
),
total_records: all.length,
offset: input.offset,
limit: input.limit,
records,
resource_key_matches: resourceKeyMatches,
next_offset: next < all.length ? next : null,
truncated: input.offset > 0 || next < all.length,
limitations: [
"Rendition metadata is reported as emitted by the installed assetutil version; private fields and platform-specific interpretations are not normalized.",
"Asset catalog inspection does not decode or extract rendition image bytes.",
],
});
};
+307
View File
@@ -0,0 +1,307 @@
import { z } from "zod";
import { digestSchema, prefixedDigestSchema } from "../digests.js";
const pathSchema = z.string().min(1);
const BUNDLE_EXTENSION =
/\.(?:app|appex|xpc|framework|systemextension|dext|bundle|plugin|qlgenerator|mdimporter)$/iu;
const MACH_O_FORMATS: readonly string[] = ["mach-o", "mach-o-universal"];
/** One inventoried file or directory with its content identity. */
export const appleComponentSchema = z.strictObject({
path: pathSchema,
artifact_id: prefixedDigestSchema("art"),
sha256: digestSchema,
format: z.string().min(1),
});
/** One application root or nested bundle classified by path convention. */
export const appleBundleSchema = z.strictObject({
path: pathSchema,
parent_path: pathSchema.nullable(),
layout: z.enum(["shallow", "macos-deep", "versioned-framework"]),
role: z.enum([
"application",
"app-extension",
"xpc-service",
"framework",
"login-item",
"system-extension",
"driver-extension",
"plug-in",
"resource-bundle",
"bundle",
"helper-application",
"nested-application",
]),
role_basis: z.literal("path-convention"),
info_plist_path: pathSchema.nullable(),
executable_candidates: z.array(pathSchema),
signing_paths: z.array(pathSchema),
});
type Component = z.infer<typeof appleComponentSchema>;
type Bundle = z.infer<typeof appleBundleSchema>;
/** One inventory occurrence; symlinks and directories may lack content identity. */
export interface AppleInventoryEntry {
readonly path: string;
readonly kind: "file" | "directory" | "symlink" | "slice";
readonly component: Component | undefined;
}
type Entry = AppleInventoryEntry;
/** Report whether an inventory format is a thin or universal Mach-O. */
export const isMachOFormat = (format: string): boolean =>
MACH_O_FORMATS.includes(format);
/** AppleDouble metadata written beside archived files (`._name`, `__MACOSX/`). */
export const isSidecar = (path: string): boolean => {
const segments = path.split("/");
return (
segments.includes("__MACOSX") || (segments.at(-1) ?? "").startsWith("._")
);
};
export const isWithin = (path: string, root: string): boolean =>
root === "." || path === root || path.startsWith(`${root}/`);
/**
* Outermost iOS (`Payload/X.app`) and macOS (`X.app/Contents/…`) applications.
* An inventoried `.app` directory is its own root, `.`.
*/
export const applicationRoots = (
entries: readonly Entry[],
subject: { readonly name: string; readonly format: string },
): string[] => {
// A selected `.app` directory is the application, even when its inventory
// is partial or lacks Contents/; coverage and limitations describe that.
if (subject.format === "directory" && /\.app$/iu.test(subject.name))
return ["."];
const found = new Set<string>();
for (const { path } of entries) {
if (isSidecar(path)) continue;
const ios = /^(Payload\/[^/]+\.app)(?:\/|$)/u.exec(path);
if (ios?.[1] !== undefined) {
found.add(ios[1]);
continue;
}
const segments = path.split("/");
const index = segments.findIndex(
(segment, position) =>
/\.app$/iu.test(segment) && segments[position + 1] === "Contents",
);
if (index >= 0) found.add(segments.slice(0, index + 1).join("/"));
}
const roots = [...found];
return roots
.filter(
(root) => !roots.some((other) => other !== root && isWithin(root, other)),
)
.sort(compare);
};
export const detectBundles = (
entries: readonly Entry[],
roots: readonly string[],
): Bundle[] => {
const paths = new Set<string>(roots);
for (const { path, kind } of entries) {
if (isSidecar(path)) continue;
const root = roots.find((candidate) => isWithin(path, candidate));
if (root === undefined) continue;
const segments = path.split("/");
const start = root === "." ? 0 : root.split("/").length;
for (let index = start; index < segments.length; index++) {
const segment = segments[index] ?? "";
const leaf = index === segments.length - 1;
// A symlink or file named like a bundle has no observed contents.
if (BUNDLE_EXTENSION.test(segment) && (!leaf || kind === "directory"))
paths.add(segments.slice(0, index + 1).join("/"));
}
}
const tree = indexTree(entries);
return [...paths].sort(compare).map((path) => {
const layout = bundleLayout(path, tree);
return {
path,
parent_path: enclosingBundle(path, paths),
layout,
role: roots.includes(path) ? "application" : bundleRole(path),
role_basis: "path-convention",
info_plist_path: infoPlistPath(path, layout, tree),
executable_candidates: executableCandidates(path, layout, tree),
signing_paths: signingPaths(path, layout, tree),
} satisfies Bundle;
});
};
/** Directory children (including implied ancestors) and files, indexed once. */
interface Tree {
readonly children: ReadonlyMap<string, ReadonlySet<string>>;
readonly files: ReadonlyMap<string, Component>;
/** Paths observed as directories, or implied by a deeper path. */
readonly directories: ReadonlySet<string>;
}
const indexTree = (entries: readonly Entry[]): Tree => {
const children = new Map<string, Set<string>>();
const files = new Map<string, Component>();
const directories = new Set<string>();
for (const { path, kind, component } of entries) {
if (isSidecar(path)) continue;
if (kind === "file" && component !== undefined) files.set(path, component);
if (kind === "directory") directories.add(path);
const segments = path.split("/");
let parent = "";
for (const segment of segments) {
const names = children.get(parent) ?? new Set<string>();
names.add(segment);
children.set(parent, names);
parent = joinPath(parent, segment);
if (parent !== path) directories.add(parent);
}
}
return { children, files, directories };
};
const joinPath = (directory: string, name: string): string =>
directory === "" ? name : `${directory}/${name}`;
const directoryOf = (bundle: string): string => (bundle === "." ? "" : bundle);
const enclosingBundle = (
path: string,
bundles: ReadonlySet<string>,
): string | null => {
if (path === ".") return null;
const segments = path.split("/");
for (let length = segments.length - 1; length > 0; length--) {
const candidate = segments.slice(0, length).join("/");
if (bundles.has(candidate)) return candidate;
}
return bundles.has(".") ? "." : null;
};
const bundleLayout = (bundle: string, tree: Tree): Bundle["layout"] => {
const names = tree.children.get(directoryOf(bundle));
if (names?.has("Contents") === true) return "macos-deep";
if (names?.has("Versions") === true) return "versioned-framework";
return "shallow";
};
const bundleRole = (bundle: string): Bundle["role"] => {
const segments = bundle.split("/");
const name = (segments.at(-1) ?? "").toLowerCase();
const container = segments.at(-2);
if (name.endsWith(".appex")) return "app-extension";
if (name.endsWith(".xpc")) return "xpc-service";
if (name.endsWith(".framework")) return "framework";
if (name.endsWith(".systemextension")) return "system-extension";
if (name.endsWith(".dext")) return "driver-extension";
if (name.endsWith(".bundle")) {
if (container === "PlugIns") return "plug-in";
return container === "Resources" ? "resource-bundle" : "bundle";
}
if (!name.endsWith(".app")) return "plug-in";
if (container === "LoginItems" && segments.at(-3) === "Library")
return "login-item";
if (container === "Helpers") return "helper-application";
return "nested-application";
};
/** Files directly inside one directory; nested bundles are deeper paths. */
const directFiles = (directory: string, tree: Tree): string[] =>
[...(tree.children.get(directory) ?? [])]
.map((name) => joinPath(directory, name))
.filter((path) => tree.files.has(path))
.sort(compare);
/** Content directories; `Versions/Current` is a symlink outside the inventory. */
const contentDirectories = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] => {
const directory = directoryOf(bundle);
if (layout === "macos-deep") return [joinPath(directory, "Contents")];
if (layout === "shallow") return [directory];
const versions = joinPath(directory, "Versions");
// Only real version directories count: Current is a symlink, and files
// such as .DS_Store are not versions.
return [...(tree.children.get(versions) ?? [])]
.filter((version) => version !== "Current")
.map((version) => joinPath(versions, version))
.filter((version) => tree.directories.has(version))
.sort(compare);
};
const infoPlistPath = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string | null => {
const directories = contentDirectories(bundle, layout, tree);
// With several real versions, Versions/Current (a symlink outside the
// inventory) decides which plist applies, so the plist stays unknown.
if (directories.length !== 1) return null;
const candidates = directories
.map((directory) =>
joinPath(
directory,
layout === "versioned-framework"
? "Resources/Info.plist"
: "Info.plist",
),
)
.filter((path) => tree.files.has(path));
return candidates.length === 1 ? (candidates[0] ?? null) : null;
};
const executableCandidates = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] =>
contentDirectories(bundle, layout, tree)
.flatMap((directory) =>
directFiles(
layout === "macos-deep" ? joinPath(directory, "MacOS") : directory,
tree,
),
)
.filter((path) =>
MACH_O_FORMATS.includes(tree.files.get(path)?.format ?? ""),
);
const signingPaths = (
bundle: string,
layout: Bundle["layout"],
tree: Tree,
): string[] =>
contentDirectories(bundle, layout, tree)
.flatMap((directory) => [
joinPath(directory, "_CodeSignature/CodeResources"),
joinPath(directory, "embedded.provisionprofile"),
joinPath(directory, "embedded.mobileprovision"),
])
.filter((path) => tree.files.has(path))
.sort(compare);
/** Platforms of application roots whose layout was observed, not assumed. */
export const platformsOf = (bundles: readonly Bundle[]): ("ios" | "macos")[] =>
[
...new Set(
bundles.flatMap(({ role, layout, info_plist_path: plist }) => {
if (role !== "application") return [];
if (layout === "macos-deep") return ["macos" as const];
// An empty or partial root has no Contents/ either; require Info.plist.
if (layout === "shallow" && plist !== null) return ["ios" as const];
return [];
}),
),
].sort(compare);
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
+35
View File
@@ -0,0 +1,35 @@
import { z } from "zod";
/** `PLATFORM_*` values from Apple's `mach-o/loader.h`. */
const APPLE_PLATFORM_NAMES: Readonly<Record<number, string>> = {
1: "macos",
2: "ios",
3: "tvos",
4: "watchos",
5: "bridgeos",
6: "maccatalyst",
7: "ios-simulator",
8: "tvos-simulator",
9: "watchos-simulator",
10: "driverkit",
11: "visionos",
12: "visionos-simulator",
};
/** A reported platform number and its `loader.h` name, when known. */
export const applePlatformSchema = z.strictObject({
id: z.number().int(),
name: z.string().nullable(),
});
export type ApplePlatform = z.infer<typeof applePlatformSchema>;
/** Name a reported platform number without discarding unknown values. */
export const applePlatform = (id: number): ApplePlatform => ({
id,
name: APPLE_PLATFORM_NAMES[id] ?? null,
});
/** Display one platform, falling back to its number. */
export const applePlatformLabel = ({ id, name }: ApplePlatform): string =>
name ?? `platform ${id}`;
+120
View File
@@ -0,0 +1,120 @@
import type {
DylibTreeEntry,
DylibTreeView,
MachoSlice,
} from "./dylibResolution.js";
const MAX_SYMLINK_HOPS = 32;
export type PathLookup =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "absent" | "escapes" | "not-file" };
/**
* Resolve a root-relative path one segment at a time, as `open` would:
* symlinks are followed inside the root, `..` applies to the real parent,
* and any escape above the root or through an absolute link stops.
*/
export const resolveTreePath = async (
view: DylibTreeView,
input: string,
): Promise<PathLookup> => {
const pending = segmentsOf(input);
const resolved: string[] = [];
let last: DylibTreeEntry | undefined;
let hops = 0;
while (pending.length > 0) {
const segment = pending.shift() ?? "";
if (segment === "..") {
if (resolved.length === 0) return { kind: "escapes" };
resolved.pop();
last = { kind: "directory" };
continue;
}
const path = [...resolved, segment].join("/");
const entry = await view.entry(path);
if (entry === undefined) return { kind: "absent" };
if (entry.kind === "symlink") {
hops += 1;
if (hops > MAX_SYMLINK_HOPS) return { kind: "absent" };
if (entry.target.startsWith("/")) return { kind: "escapes" };
pending.unshift(...segmentsOf(entry.target));
continue;
}
if (entry.kind === "file" && pending.length > 0) return { kind: "absent" };
resolved.push(segment);
last = entry;
}
return last?.kind === "file"
? { kind: "file", path: resolved.join("/") }
: { kind: "not-file" };
};
const segmentsOf = (path: string): string[] =>
path.split("/").filter((segment) => segment !== "" && segment !== ".");
export const directoryOf = (path: string): string => {
const index = path.lastIndexOf("/");
return index < 0 ? "" : path.slice(0, index);
};
export const joinPath = (directory: string, rest: string): string =>
directory === "" ? rest : rest === "" ? directory : `${directory}/${rest}`;
export type Expansion =
| { readonly scope: "target"; readonly path: string }
| { readonly scope: "outside"; readonly path: string }
| { readonly scope: "undetermined"; readonly path: string };
/** Expand one dyld path prefix relative to its owning image. */
export const expandPrefix = (
raw: string,
context: {
readonly ownerDirectory: string;
readonly executable: string | null;
},
): Expansion => {
const variable = /^@(executable_path|loader_path)(?:\/(.*))?$/u.exec(raw);
if (variable !== null) {
const rest = variable[2] ?? "";
if (variable[1] === "loader_path")
return { scope: "target", path: joinPath(context.ownerDirectory, rest) };
return context.executable === null
? { scope: "undetermined", path: raw }
: {
scope: "target",
path: joinPath(directoryOf(context.executable), rest),
};
}
if (raw.startsWith("/")) return { scope: "outside", path: raw };
return { scope: "undetermined", path: raw };
};
/**
* Slices a process may load, best first, following dyld's graded
* architectures: an x86_64h process also accepts generic x86_64.
*/
const COMPATIBLE_ARCHITECTURES: Readonly<Record<string, readonly string[]>> = {
x86_64h: ["x86_64h", "x86_64"],
};
export const compatibleSlice = (
slices: readonly MachoSlice[],
process: string,
): MachoSlice | undefined => {
for (const architecture of COMPATIBLE_ARCHITECTURES[process] ?? [process]) {
const slice = slices.find((item) => item.architecture === architecture);
if (slice !== undefined) return slice;
}
return undefined;
};
/**
* Whether a cache serves a process architecture. Compatibility is directional:
* an arm64e cache also serves arm64 processes and an x86_64h cache also serves
* x86_64 ones, but a generic cache lacks the arm64e or x86_64h ABI.
*/
export const cacheServes = (cache: string, process: string): boolean =>
cache === process ||
(cache === "arm64e" && process === "arm64") ||
(cache === "x86_64h" && process === "x86_64");
+85
View File
@@ -0,0 +1,85 @@
import { z } from "zod";
import { applePlatformSchema } from "./applePlatforms.js";
import { digestSchema } from "../digests.js";
import { machoSliceSchema } from "./dylibResolution.js";
const hexSchema = z.string().regex(/^0x[0-9a-f]+$/u);
const uuidSchema = z
.string()
.regex(/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/u);
/** One cached image selected by its exact install path. */
export const inspectDyldSharedCacheInputSchema = z.strictObject({
cache_path: z.string().min(1),
images: z.array(z.string().min(1)).min(1).optional(),
});
const mappingSchema = z.object({
file: z.string(),
address: hexSchema,
size: hexSchema,
file_offset: hexSchema,
max_protection: z.number().int(),
initial_protection: z.number().int(),
});
const subcacheSchema = z.object({
suffix: z.string(),
uuid: uuidSchema,
vm_offset: hexSchema,
status: z.enum(["present", "missing", "uuid-mismatch"]),
observed_uuid: uuidSchema.nullable(),
});
const headerSchema = z.object({
magic: z.string(),
architecture: z.string(),
uuid: z.string(),
platform: applePlatformSchema.nullable(),
os_version: z.string().nullable(),
alt_platform: applePlatformSchema.nullable(),
alt_os_version: z.string().nullable(),
cache_type: z.enum(["development", "production", "multi-cache"]).nullable(),
shared_region: z.object({ start: hexSchema, size: hexSchema }).nullable(),
max_slide: hexSchema.nullable(),
mappings: z.array(mappingSchema),
subcaches: z.array(subcacheSchema),
symbols_file_uuid: uuidSchema.nullable(),
});
const inspectedImageSchema = z.object({
path: z.string(),
status: z.enum(["parsed", "malformed", "unsupported", "absent", "unmapped"]),
address: hexSchema.nullable(),
file: z.string().nullable(),
reason: z.string().nullable(),
slices: z.array(machoSliceSchema),
});
/** Header, mappings, subcaches, and the complete image list of one cache. */
export const dyldSharedCacheResultSchema = z.object({
cache_path: z.string(),
main_file_sha256: digestSchema,
...headerSchema.shape,
images_total: z.number().int().nonnegative(),
images: z.array(z.object({ path: z.string(), address: hexSchema })),
inspected_images: z.array(inspectedImageSchema),
coverage: z.object({
status: z.enum(["complete", "partial"]),
unreadable_subcaches: z.array(z.string()),
}),
limitations: z.array(z.string()),
});
export type DyldCacheMapping = z.infer<typeof mappingSchema>;
export type DyldCacheSubcache = z.infer<typeof subcacheSchema>;
export type DyldSharedCacheHeader = z.infer<typeof headerSchema>;
export type DyldSharedCacheResult = z.infer<typeof dyldSharedCacheResultSchema>;
export type InspectedCacheImage = z.infer<typeof inspectedImageSchema>;
/** Limitations that bound claims made from one cache file set. */
export const DYLD_SHARED_CACHE_LIMITATIONS = [
"The cache describes the operating system it was built for; it is evidence about this cache file set, not about another host.",
"Image headers are read through the cache's VM mappings; slide info, local symbols, and code signatures are not parsed, and images are not extracted.",
];
+785
View File
@@ -0,0 +1,785 @@
import { describe, expect, it } from "vitest";
import {
traceDylibLoading,
type DylibSharedCacheView,
type DylibTreeEntry,
type DylibTreeView,
type MachoDependency,
type MachoImageFacts,
type MachoSlice,
} from "./dylibResolution.js";
const slice = (overrides: Partial<MachoSlice> = {}): MachoSlice => ({
architecture: "arm64",
file_type: "dylib",
install_name: null,
dependencies: [],
rpaths: [],
dyld_environment: [],
code_signature_present: true,
platforms: [{ id: 1, name: "macos" }],
...overrides,
});
const dependency = (
installName: string,
overrides: Partial<MachoDependency> = {},
): MachoDependency => ({
command: "LC_LOAD_DYLIB",
encoding: "dylib_command",
install_name: installName,
weak: false,
upward: false,
reexport: false,
delayed_init: false,
current_version: "1.0.0",
compatibility_version: "1.0.0",
...overrides,
});
const parsed = (...slices: MachoSlice[]): MachoImageFacts => ({
status: "parsed",
slices,
});
const executable = (overrides: Partial<MachoSlice> = {}): MachoImageFacts =>
parsed(slice({ file_type: "execute", ...overrides }));
/** In-memory tree: files are images (or "data"), symlinks map to targets. */
const memoryView = (
files: Readonly<Record<string, MachoImageFacts | "data">>,
symlinks: Readonly<Record<string, string>> = {},
): DylibTreeView => {
const entries = new Map<string, DylibTreeEntry>();
const addParents = (path: string): void => {
const segments = path.split("/");
for (let length = 1; length < segments.length; length++)
entries.set(segments.slice(0, length).join("/"), { kind: "directory" });
};
for (const path of Object.keys(files)) {
addParents(path);
entries.set(path, { kind: "file" });
}
for (const [path, target] of Object.entries(symlinks)) {
addParents(path);
entries.set(path, { kind: "symlink", target });
}
return {
entry: (path) => Promise.resolve(entries.get(path)),
image: (path) => {
const facts = files[path];
return Promise.resolve(
facts === undefined || facts === "data"
? { status: "not-mach-o" as const }
: facts,
);
},
};
};
const MAIN = "Contents/MacOS/App";
const edgeFor = (
trace: Awaited<ReturnType<typeof traceDylibLoading>>,
loader: string,
installName: string,
) => {
const edge = trace.edges.find(
(candidate) =>
candidate.loader === loader && candidate.install_name === installName,
);
if (edge === undefined)
throw new Error(`missing ${loader} -> ${installName}`);
return edge;
};
describe("dyld path expansion", () => {
it("searches the loading image's rpaths before its loaders'", async () => {
const core = "Contents/Frameworks/Core.framework/Versions/A/Core";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [dependency("@rpath/Core.framework/Versions/A/Core")],
}),
[core]: parsed(
slice({
rpaths: ["@loader_path/Libraries"],
dependencies: [dependency("@rpath/libchain.dylib")],
}),
),
"Contents/Frameworks/libchain.dylib": parsed(slice()),
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib":
parsed(slice()),
}),
{ roots: [MAIN] },
);
const chain = edgeFor(trace, core, "@rpath/libchain.dylib");
expect(chain.via).toEqual([MAIN, core]);
expect(chain.candidates).toEqual([
expect.objectContaining({
source: "rpath",
rpath: "@loader_path/Libraries",
rpath_owner: core,
outcome: "resolved",
}),
]);
expect(chain.resolution).toEqual({
status: "resolved",
image:
"Contents/Frameworks/Core.framework/Versions/A/Libraries/libchain.dylib",
});
});
it("expands @loader_path in an rpath relative to the image that owns it", async () => {
const plugin = "Contents/PlugIns/Tool.bundle/Contents/MacOS/Tool";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@loader_path/../Shared"],
dependencies: [
dependency(
`@executable_path/../PlugIns/Tool.bundle/Contents/MacOS/Tool`,
),
],
}),
[plugin]: parsed(
slice({
file_type: "bundle",
dependencies: [dependency("@rpath/libshared.dylib")],
}),
),
"Contents/Shared/libshared.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, plugin, "@rpath/libshared.dylib").candidates).toEqual(
[
expect.objectContaining({
path: "Contents/MacOS/../Shared/libshared.dylib",
rpath_owner: MAIN,
outcome: "resolved",
resolved_path: "Contents/Shared/libshared.dylib",
}),
],
);
});
it("gives each executable root its own @executable_path", async () => {
const service = "Contents/XPCServices/Fetch.xpc/Contents/MacOS/Fetch";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("@executable_path/libhere.dylib")],
}),
[service]: executable({
dependencies: [dependency("@executable_path/libhere.dylib")],
}),
"Contents/MacOS/libhere.dylib": parsed(slice()),
}),
{ roots: [MAIN, service] },
);
expect(
edgeFor(trace, MAIN, "@executable_path/libhere.dylib").resolution.status,
).toBe("resolved");
expect(
edgeFor(trace, service, "@executable_path/libhere.dylib"),
).toMatchObject({
candidates: [
{
path: "Contents/XPCServices/Fetch.xpc/Contents/MacOS/libhere.dylib",
outcome: "absent",
},
],
resolution: { status: "unresolved", image: null },
});
});
it("follows Versions/Current inside the root and stops at escaping links", async () => {
const trace = await traceDylibLoading(
memoryView(
{
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/Core.framework/Core"),
dependency("@rpath/Escape.framework/Escape"),
dependency("@executable_path/../../../outside.dylib"),
],
}),
"Contents/Frameworks/Core.framework/Versions/A/Core": parsed(slice()),
},
{
"Contents/Frameworks/Core.framework/Versions/Current": "A",
"Contents/Frameworks/Core.framework/Core": "Versions/Current/Core",
"Contents/Frameworks/Escape.framework":
"/Library/Frameworks/Escape.framework",
},
),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, MAIN, "@rpath/Core.framework/Core").resolution,
).toEqual({
status: "resolved",
image: "Contents/Frameworks/Core.framework/Versions/A/Core",
});
for (const name of [
"@rpath/Escape.framework/Escape",
"@executable_path/../../../outside.dylib",
])
expect(edgeFor(trace, MAIN, name)).toMatchObject({
candidates: [{ outcome: "escapes-target" }],
resolution: { status: "undetermined", image: null },
});
});
});
describe("dyld resolution outcomes", () => {
it("keeps paths outside the root undetermined and in-root fallbacks conditional", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/usr/lib/swift", "@executable_path/../Frameworks"],
dependencies: [
dependency("/usr/lib/libSystem.B.dylib"),
dependency("@rpath/libswiftCore.dylib"),
dependency("libleaf.dylib"),
],
}),
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, MAIN, "/usr/lib/libSystem.B.dylib")).toMatchObject({
candidates: [
{ outcome: "outside-target", path: "/usr/lib/libSystem.B.dylib" },
],
resolution: { status: "undetermined", image: null },
});
expect(edgeFor(trace, MAIN, "@rpath/libswiftCore.dylib")).toMatchObject({
candidates: [
{
outcome: "outside-target",
path: "/usr/lib/swift/libswiftCore.dylib",
},
{ outcome: "resolved" },
],
resolution: {
status: "conditional",
image: "Contents/Frameworks/libswiftCore.dylib",
},
});
expect(edgeFor(trace, MAIN, "libleaf.dylib").resolution.status).toBe(
"undetermined",
);
});
it("derives unresolved and earlier-candidate findings separately for weak loads", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: [
"@executable_path/../Overrides",
"@executable_path/../Frameworks",
],
dependencies: [
dependency("@rpath/libfound.dylib"),
dependency("@rpath/libgone.dylib", {
command: "LC_LOAD_WEAK_DYLIB",
weak: true,
}),
dependency("@rpath/libmissing.dylib"),
],
dyld_environment: ["DYLD_LIBRARY_PATH=/tmp"],
}),
"Contents/Frameworks/libfound.dylib": parsed(slice()),
}),
{ roots: [MAIN] },
);
expect(
trace.findings.map(({ kind, edge_index: index }) => [kind, index]),
).toEqual([
["earlier-rpath-candidate-absent", 0],
["weak-load-unresolved", 1],
["required-load-unresolved", 2],
["dyld-environment-present", null],
]);
expect(trace.findings[0]?.explanation).toContain(
"Contents/MacOS/../Overrides/libfound.dylib",
);
});
it("reports non-Mach-O, malformed and wrong-architecture candidates", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: [
"@executable_path/a",
"@executable_path/b",
"@executable_path/c",
],
dependencies: [dependency("@rpath/lib.dylib")],
}),
"Contents/MacOS/a/lib.dylib": "data",
"Contents/MacOS/b/lib.dylib": {
status: "malformed",
reason: "load command 0 has invalid cmdsize 0",
},
"Contents/MacOS/c/lib.dylib": parsed(slice({ architecture: "x86_64" })),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, MAIN, "@rpath/lib.dylib").candidates.map(
({ outcome }) => outcome,
),
).toEqual(["not-mach-o", "malformed", "architecture-missing"]);
expect(trace.coverage).toEqual({
status: "partial",
unparsed_images: ["Contents/MacOS/b/lib.dylib"],
roots_without_architecture: [],
unverified_shared_cache_images: [],
});
expect(trace.images.map(({ path }) => path)).toEqual([
MAIN,
"Contents/MacOS/b/lib.dylib",
"Contents/MacOS/c/lib.dylib",
]);
});
});
describe("dyld load order", () => {
it("loads each image once per process and reuses matching install names", async () => {
const a = "Contents/Frameworks/libA.dylib";
const b = "Contents/Frameworks/libB.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/libA.dylib"),
dependency("@rpath/libB.dylib"),
],
}),
[a]: parsed(
slice({
install_name: "@rpath/libA.dylib",
dependencies: [
dependency("@rpath/libB.dylib"),
dependency("@rpath/libA.dylib"),
],
}),
),
[b]: parsed(
slice({
install_name: "@rpath/libB.dylib",
dependencies: [dependency("@rpath/libA.dylib")],
}),
),
}),
{ roots: [MAIN] },
);
expect(
trace.edges.map(
({ loader, install_name: name }) =>
`${loader.split("/").at(-1)}>${name}`,
),
).toEqual([
"App>@rpath/libA.dylib",
"App>@rpath/libB.dylib",
"libA.dylib>@rpath/libB.dylib",
"libA.dylib>@rpath/libA.dylib",
"libB.dylib>@rpath/libA.dylib",
]);
expect(edgeFor(trace, b, "@rpath/libA.dylib").candidates).toEqual([
expect.objectContaining({ source: "already-loaded", resolved_path: a }),
]);
expect(edgeFor(trace, a, "@rpath/libA.dylib").install_name_matches).toBe(
true,
);
});
it("leaves @executable_path undetermined for a library root and filters architectures", async () => {
const library = "Contents/Frameworks/libroot.dylib";
const trace = await traceDylibLoading(
memoryView({
[library]: parsed(
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
),
[MAIN]: executable(),
}),
{ roots: [library, MAIN], architecture: "x86_64" },
);
expect(trace.roots).toEqual([]);
expect(trace.coverage.roots_without_architecture).toEqual([library, MAIN]);
const arm = await traceDylibLoading(
memoryView({
[library]: parsed(
slice({ dependencies: [dependency("@executable_path/x.dylib")] }),
),
}),
{ roots: [library] },
);
expect(arm.edges[0]?.candidates).toEqual([
expect.objectContaining({
source: "executable_path",
outcome: "undetermined",
}),
]);
});
it("stops when cancelled", async () => {
const controller = new AbortController();
controller.abort();
await expect(
traceDylibLoading(memoryView({ [MAIN]: executable() }), {
roots: [MAIN],
signal: controller.signal,
}),
).rejects.toThrow();
});
});
describe("dyld slice compatibility and coverage", () => {
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
const files = {
[MAIN]: parsed(
slice({
architecture: "x86_64h",
file_type: "execute",
dependencies: [dependency("@executable_path/libgeneric.dylib")],
}),
slice({
architecture: "arm64e",
file_type: "execute",
dependencies: [dependency("@executable_path/libgeneric.dylib")],
}),
),
"Contents/MacOS/libgeneric.dylib": parsed(
slice({ architecture: "x86_64" }),
slice({ architecture: "arm64" }),
),
};
const trace = await traceDylibLoading(memoryView(files), { roots: [MAIN] });
expect(
trace.edges.map(({ architecture, candidates, resolution }) => [
architecture,
candidates[0]?.outcome,
resolution.status,
]),
).toEqual([
["x86_64h", "resolved", "resolved"],
["arm64e", "architecture-missing", "unresolved"],
]);
});
it("keeps unsupported candidates undeterminable rather than malformed", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("@executable_path/libbig.dylib")],
}),
"Contents/MacOS/libbig.dylib": {
status: "unsupported",
reason: "big-endian Mach-O images are not supported",
},
}),
{ roots: [MAIN] },
);
expect(trace.edges[0]).toMatchObject({
candidates: [{ outcome: "unsupported" }],
resolution: { status: "undetermined", image: null },
});
expect(
trace.images.find(({ path }) => path.endsWith("libbig.dylib")),
).toMatchObject({
parse_status: "unsupported",
});
});
it("reports unclassified Mach-O files as partial coverage", async () => {
const broken = "Contents/Helpers/broken";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable(),
[broken]: {
status: "malformed",
reason: "load command 0 has invalid cmdsize 0",
},
}),
{ roots: [MAIN], unclassified: [broken] },
);
expect(trace.coverage).toEqual({
status: "partial",
unparsed_images: [broken],
roots_without_architecture: [],
unverified_shared_cache_images: [],
});
expect(trace.images.find(({ path }) => path === broken)?.reason).toBe(
"load command 0 has invalid cmdsize 0",
);
});
});
/** A macOS arm64e cache that lists libSystem and libswiftCore. */
const cache = (
overrides: Partial<DylibSharedCacheView> = {},
): DylibSharedCacheView => ({
architecture: "arm64e",
platforms: [
{ id: 1, name: "macos" },
{ id: 6, name: "maccatalyst" },
],
unavailableSubcaches: [],
lookup: (path: string) =>
[
"/usr/lib/libSystem.B.dylib",
"/usr/lib/swift/libswiftCore.dylib",
].includes(path)
? "mapped"
: "absent",
...overrides,
});
describe("shared cache resolution", () => {
it("resolves cached system paths before bundled fallbacks", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/usr/lib/swift", "@executable_path/../Frameworks"],
dependencies: [
dependency("/usr/lib/libSystem.B.dylib"),
dependency("@rpath/libswiftCore.dylib"),
dependency("/usr/lib/libgone.dylib"),
],
}),
"Contents/Frameworks/libswiftCore.dylib": parsed(slice()),
}),
{ roots: [MAIN], sharedCache: cache() },
);
expect(
trace.edges.map(({ install_name: name, resolution, candidates }) => [
name,
resolution,
candidates.map(({ outcome }) => outcome),
]),
).toEqual([
[
"/usr/lib/libSystem.B.dylib",
{ status: "shared-cache", image: "/usr/lib/libSystem.B.dylib" },
["shared-cache"],
],
[
"@rpath/libswiftCore.dylib",
{ status: "shared-cache", image: "/usr/lib/swift/libswiftCore.dylib" },
["shared-cache"],
],
[
"/usr/lib/libgone.dylib",
{ status: "undetermined", image: null },
["outside-target"],
],
]);
expect(trace.images.map(({ path }) => path)).toEqual([MAIN]);
expect(trace.coverage.status).toBe("complete");
expect(trace.limitations).toContainEqual(
expect.stringContaining(
"looked up only in the supplied dyld shared cache",
),
);
expect(trace.limitations).not.toContainEqual(
expect.stringContaining("are not evaluated, including /System"),
);
});
it("keeps a cache hit conditional after an earlier undeterminable candidate", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/opt/vendor/lib", "/usr/lib/swift"],
dependencies: [dependency("@rpath/libswiftCore.dylib")],
}),
}),
{ roots: [MAIN], sharedCache: cache() },
);
expect(trace.edges[0]?.resolution).toEqual({
status: "conditional",
image: "/usr/lib/swift/libswiftCore.dylib",
});
expect(trace.edges[0]?.candidates.map(({ outcome }) => outcome)).toEqual([
"outside-target",
"shared-cache",
]);
});
});
describe("shared cache applicability", () => {
it("does not consult a cache for another CPU family or platform", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
architecture: "x86_64",
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
"Contents/MacOS/Phone": executable({
platforms: [{ id: 2, name: "ios" }],
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
"Contents/MacOS/Old": executable({
platforms: [],
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
}),
{
roots: [MAIN, "Contents/MacOS/Phone", "Contents/MacOS/Old"],
sharedCache: cache(),
},
);
expect(trace.edges.map(({ candidates }) => candidates[0]?.outcome)).toEqual(
["outside-target", "outside-target", "outside-target"],
);
expect(trace.limitations).toEqual(
expect.arrayContaining([
`The supplied shared cache was not used for ${MAIN} (x86_64): the arm64e cache does not serve x86_64 processes. Its absolute paths stay outside-target.`,
"The supplied shared cache was not used for Contents/MacOS/Phone (arm64): the cache serves macos and maccatalyst processes, not ios. Its absolute paths stay outside-target.",
"The supplied shared cache was not used for Contents/MacOS/Old (arm64): the process records no LC_BUILD_VERSION or LC_VERSION_MIN platform. Its absolute paths stay outside-target.",
]),
);
const generic = await traceDylibLoading(
memoryView({
[MAIN]: executable({
architecture: "arm64e",
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
}),
{ roots: [MAIN], sharedCache: cache({ architecture: "arm64" }) },
);
// A generic arm64 cache lacks the arm64e ABI.
expect(generic.edges[0]?.candidates[0]?.outcome).toBe("outside-target");
const unknownPlatform = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
}),
{ roots: [MAIN], sharedCache: cache({ platforms: [] }) },
);
expect(unknownPlatform.edges[0]?.candidates[0]?.outcome).toBe(
"outside-target",
);
});
it("leaves images in unavailable subcaches undetermined", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [dependency("/usr/lib/libSystem.B.dylib")],
}),
}),
{
roots: [MAIN],
sharedCache: cache({
unavailableSubcaches: [".01 (missing)"],
lookup: () => "unverified",
}),
},
);
expect(trace.edges[0]?.resolution).toEqual({
status: "undetermined",
image: null,
});
expect(trace.coverage).toMatchObject({
status: "partial",
unverified_shared_cache_images: ["/usr/lib/libSystem.B.dylib"],
});
expect(trace.limitations).toContainEqual(
expect.stringContaining("Subcaches .01 (missing)"),
);
});
it("states that absolute paths are not evaluated without a cache", async () => {
const trace = await traceDylibLoading(
memoryView({ [MAIN]: executable({}) }),
{ roots: [MAIN] },
);
expect(trace.limitations).toContainEqual(
expect.stringContaining("Pass shared_cache"),
);
});
});
describe("lazily loaded dependencies", () => {
it("resolves lazy loads without traversing them or reporting launch failure", async () => {
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/liblazy.dylib", {
command: "LC_LAZY_LOAD_DYLIB",
}),
dependency("@rpath/libmissing.dylib", {
command: "LC_LAZY_LOAD_DYLIB",
}),
],
}),
"Contents/Frameworks/liblazy.dylib": parsed(
slice({ dependencies: [dependency("@rpath/libdeep.dylib")] }),
),
}),
{ roots: [MAIN] },
);
expect(trace.edges.map(({ loader }) => loader)).toEqual([MAIN, MAIN]);
expect(trace.edges[0]?.resolution.status).toBe("resolved");
expect(trace.findings.map(({ kind }) => kind)).toEqual([
"lazy-load-unresolved",
]);
});
});
describe("conditional loads", () => {
it("carries a conditional fallback's uncertainty to its dependents and reuses", async () => {
const VENDOR = "Contents/Frameworks/libvendor.dylib";
const OTHER = "Contents/Frameworks/libother.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
rpaths: ["/opt/vendor/lib", "@executable_path/../Frameworks"],
dependencies: [
dependency("@rpath/libvendor.dylib"),
dependency("@executable_path/../Frameworks/libother.dylib"),
],
}),
[VENDOR]: parsed(
slice({
install_name: "@rpath/libvendor.dylib",
dependencies: [dependency("@loader_path/libgone.dylib")],
}),
),
[OTHER]: parsed(
slice({ dependencies: [dependency("@rpath/libvendor.dylib")] }),
),
}),
{ roots: [MAIN] },
);
expect(edgeFor(trace, MAIN, "@rpath/libvendor.dylib")).toMatchObject({
resolution: { status: "conditional", image: VENDOR },
loader_conditional: false,
});
expect(edgeFor(trace, VENDOR, "@loader_path/libgone.dylib")).toMatchObject({
resolution: { status: "unresolved" },
loader_conditional: true,
});
expect(edgeFor(trace, OTHER, "@rpath/libvendor.dylib")).toMatchObject({
candidates: [{ source: "already-loaded" }],
resolution: { status: "conditional", image: VENDOR },
loader_conditional: false,
});
expect(
trace.findings.find(({ kind }) => kind === "required-load-unresolved")
?.explanation,
).toContain(`${VENDOR} loads only conditionally`);
});
});
+428
View File
@@ -0,0 +1,428 @@
import {
compatibleSlice,
directoryOf,
expandPrefix,
joinPath,
resolveTreePath,
type Expansion,
} from "./dyldPaths.js";
import {
DYLIB_RESOLUTION_LIMITATIONS,
deriveFindings,
cacheMismatch,
sharedCacheLimitations,
type UnservedRoot,
} from "./dylibResolutionFindings.js";
import type {
MachoDependency,
MachoSlice,
MachoImageFacts,
DylibTreeView,
DylibSharedCacheView,
DylibCandidate,
DylibEdge,
DylibTrace,
} from "./dylibResolutionSchema.js";
export {
dylibResolutionInputSchema,
machoSliceSchema,
dylibResolutionResultSchema,
type MachoDependency,
type MachoSlice,
type MachoImageFacts,
type DylibTreeEntry,
type DylibTreeView,
type DylibSharedCacheView,
type DylibResolutionResult,
type DylibCandidate,
type DylibEdge,
type DylibFinding,
type DylibTrace,
} from "./dylibResolutionSchema.js";
type Candidate = DylibCandidate;
type Edge = DylibEdge;
interface LoadedImage {
readonly slice: MachoSlice;
/** Images from the process root to this image; the rpath stack, outermost first. */
readonly chain: readonly string[];
/** Some edge on the chain was conditional: an unknown earlier candidate may load instead. */
readonly conditional: boolean;
}
interface ProcessContext {
readonly view: DylibTreeView;
readonly root: string;
readonly architecture: string;
readonly executable: string | null;
readonly loaded: Map<string, LoadedImage>;
readonly byInstallName: Map<string, string>;
readonly images: Map<string, MachoImageFacts>;
/** The supplied cache, when it serves this process's architecture and platform. */
readonly sharedCache: DylibSharedCacheView | undefined;
/** Cached install paths whose subcache bytes were unavailable, across processes. */
readonly unverifiedCacheImages: Set<string>;
}
interface CandidateTemplate {
readonly expansion: Expansion;
readonly source: Candidate["source"];
readonly rpath: string | null;
readonly rpathOwner: string | null;
}
const candidateTemplates = (
dependency: MachoDependency,
loader: string,
context: ProcessContext,
): CandidateTemplate[] => {
const name = dependency.install_name;
if (!name.startsWith("@rpath/")) {
const source = name.startsWith("@executable_path")
? "executable_path"
: name.startsWith("@loader_path")
? "loader_path"
: "literal";
return [
{
expansion: expandPrefix(name, {
ownerDirectory: directoryOf(loader),
executable: context.executable,
}),
source,
rpath: null,
rpathOwner: null,
},
];
}
const rest = name.slice("@rpath/".length);
const owners = [...(context.loaded.get(loader)?.chain ?? [loader])].reverse();
return owners.flatMap((owner) =>
(context.loaded.get(owner)?.slice.rpaths ?? []).map((rpath) => {
const base = expandPrefix(rpath, {
ownerDirectory: directoryOf(owner),
executable: context.executable,
});
const expansion: Expansion = {
scope: base.scope,
path:
base.scope === "outside"
? `${base.path.replace(/\/+$/u, "")}/${rest}`
: joinPath(base.path, rest),
};
return { expansion, source: "rpath" as const, rpath, rpathOwner: owner };
}),
);
};
const evaluateCandidate = async (
template: CandidateTemplate,
context: ProcessContext,
): Promise<Candidate> => {
const base = {
path: template.expansion.path,
source: template.source,
rpath: template.rpath,
rpath_owner: template.rpathOwner,
};
if (template.expansion.scope === "outside") {
const cached =
context.sharedCache?.lookup(template.expansion.path) ?? "absent";
if (cached === "mapped")
return {
...base,
outcome: "shared-cache",
resolved_path: template.expansion.path,
};
// Listed in the cache, but its subcache is unavailable: dyld might load it.
if (cached === "unverified") {
context.unverifiedCacheImages.add(template.expansion.path);
return { ...base, outcome: "undetermined", resolved_path: null };
}
return { ...base, outcome: "outside-target", resolved_path: null };
}
if (template.expansion.scope === "undetermined")
return { ...base, outcome: "undetermined", resolved_path: null };
const lookup = await resolveTreePath(context.view, template.expansion.path);
if (lookup.kind === "escapes")
return { ...base, outcome: "escapes-target", resolved_path: null };
if (lookup.kind !== "file")
return { ...base, outcome: "absent", resolved_path: null };
const facts = await imageFacts(context, lookup.path);
const outcome: Candidate["outcome"] =
facts.status !== "parsed"
? facts.status
: compatibleSlice(facts.slices, context.architecture) === undefined
? "architecture-missing"
: "resolved";
return { ...base, outcome, resolved_path: lookup.path };
};
const imageFacts = async (
context: ProcessContext,
path: string,
): Promise<MachoImageFacts> => {
const known = context.images.get(path);
if (known !== undefined) return known;
const facts = await context.view.image(path);
context.images.set(path, facts);
return facts;
};
const resolution = (candidates: readonly Candidate[]): Edge["resolution"] => {
let external = false;
for (const candidate of candidates) {
if (candidate.outcome === "resolved")
return {
status: external ? "conditional" : "resolved",
image: candidate.resolved_path,
};
if (candidate.outcome === "shared-cache")
return {
status: external ? "conditional" : "shared-cache",
image: candidate.resolved_path,
};
// dyld might load these; REA cannot decide them from the analyzed root.
if (
candidate.outcome === "outside-target" ||
candidate.outcome === "escapes-target" ||
candidate.outcome === "unsupported" ||
candidate.outcome === "undetermined"
)
external = true;
}
return { status: external ? "undetermined" : "unresolved", image: null };
};
const resolveDependency = async (
dependency: MachoDependency,
loader: string,
context: ProcessContext,
): Promise<Edge> => {
const current = context.loaded.get(loader);
const chain = current?.chain ?? [loader];
const loaded = context.byInstallName.get(dependency.install_name);
const candidates: Candidate[] = [];
if (loaded !== undefined)
candidates.push({
path: dependency.install_name,
source: "already-loaded",
rpath: null,
rpath_owner: null,
outcome: "resolved",
resolved_path: loaded,
});
else
for (const template of candidateTemplates(dependency, loader, context)) {
const candidate = await evaluateCandidate(template, context);
candidates.push(candidate);
// dyld stops at the first loadable candidate.
if (
candidate.outcome === "resolved" ||
candidate.outcome === "shared-cache"
)
break;
}
const searched = resolution(candidates);
// Reusing an image that itself loads only conditionally is conditional too.
const resolved: Edge["resolution"] =
loaded !== undefined &&
context.loaded.get(loaded)?.conditional === true &&
searched.status === "resolved"
? { ...searched, status: "conditional" }
: searched;
const image =
resolved.image === null ? undefined : context.images.get(resolved.image);
const slice =
image?.status === "parsed"
? compatibleSlice(image.slices, context.architecture)
: undefined;
return {
root: context.root,
architecture: context.architecture,
loader,
via: [...chain],
...dependency,
candidates,
resolution: resolved,
install_name_matches:
slice === undefined || slice.install_name === null
? null
: slice.install_name === dependency.install_name,
loader_conditional: current?.conditional ?? false,
};
};
/**
* Follow dyld4's dependents-first order: resolve every dependency of one
* image, then recurse into the images it newly loaded, in load-command order.
*/
const traceProcess = async (
context: ProcessContext,
rootSlice: MachoSlice,
signal?: AbortSignal,
): Promise<Edge[]> => {
const edges: Edge[] = [];
context.loaded.set(context.root, {
slice: rootSlice,
chain: [context.root],
conditional: false,
});
if (rootSlice.install_name !== null)
context.byInstallName.set(rootSlice.install_name, context.root);
const pending = [context.root];
while (pending.length > 0) {
signal?.throwIfAborted();
const loader = pending.pop() ?? "";
const current = context.loaded.get(loader);
if (current === undefined) continue;
const created: string[] = [];
for (const dependency of current.slice.dependencies) {
const edge = await resolveDependency(dependency, loader, context);
edges.push(edge);
// dyld loads LC_LAZY_LOAD_DYLIB images on first use, not at launch.
if (dependency.command === "LC_LAZY_LOAD_DYLIB") continue;
const image = edge.resolution.image;
if (image === null || context.loaded.has(image)) continue;
const facts = context.images.get(image);
const slice =
facts?.status === "parsed"
? compatibleSlice(facts.slices, context.architecture)
: undefined;
if (slice === undefined) continue;
context.loaded.set(image, {
slice,
chain: [...current.chain, image],
// dyld may load an unknown earlier candidate instead of this fallback.
conditional:
current.conditional || edge.resolution.status === "conditional",
});
if (
slice.install_name !== null &&
!context.byInstallName.has(slice.install_name)
)
context.byInstallName.set(slice.install_name, image);
created.push(image);
}
pending.push(...created.reverse());
}
return edges;
};
/** Trace dyld load paths from each process root through the analyzed root. */
export const traceDylibLoading = async (
view: DylibTreeView,
request: {
readonly roots: readonly string[];
/** Mach-O files whose root role could not be classified because they did not parse. */
readonly unclassified?: readonly string[];
readonly architecture?: string;
readonly sharedCache?: DylibSharedCacheView;
readonly signal?: AbortSignal;
},
): Promise<DylibTrace> => {
const images = new Map<string, MachoImageFacts>();
for (const path of request.unclassified ?? [])
images.set(path, await view.image(path));
const roots: DylibTrace["roots"][number][] = [];
const edges: Edge[] = [];
const withoutArchitecture: string[] = [];
const unserved: UnservedRoot[] = [];
const unverifiedCacheImages = new Set<string>();
for (const root of request.roots) {
const facts = await view.image(root);
images.set(root, facts);
if (facts.status !== "parsed") continue;
const slices = facts.slices.filter(
({ architecture }) =>
request.architecture === undefined ||
architecture === request.architecture,
);
if (slices.length === 0) withoutArchitecture.push(root);
for (const slice of slices) {
roots.push({ image: root, architecture: slice.architecture });
const mismatch =
request.sharedCache === undefined
? undefined
: cacheMismatch(request.sharedCache, slice);
if (mismatch !== undefined)
unserved.push({
image: root,
architecture: slice.architecture,
reason: mismatch,
});
edges.push(
...(await traceProcess(
{
view,
root,
architecture: slice.architecture,
executable: slice.file_type === "execute" ? root : null,
loaded: new Map(),
byInstallName: new Map(),
images,
sharedCache:
mismatch === undefined ? request.sharedCache : undefined,
unverifiedCacheImages,
},
slice,
request.signal,
)),
);
}
}
const reported = [...images.entries()]
.filter(([, facts]) => facts.status !== "not-mach-o")
.sort(([left], [right]) => compare(left, right));
const unparsed = reported
.filter(([, facts]) => facts.status !== "parsed")
.map(([path]) => path);
return {
roots,
images: reported.map(([path, facts]) => ({
path,
parse_status:
facts.status === "not-mach-o" ? "unsupported" : facts.status,
reason:
facts.status === "parsed" || facts.status === "not-mach-o"
? null
: facts.reason,
slices:
facts.status === "parsed" ? facts.slices.map(withoutDependencies) : [],
})),
edges,
findings: deriveFindings(edges, roots, images),
coverage: {
status:
unparsed.length === 0 &&
withoutArchitecture.length === 0 &&
unverifiedCacheImages.size === 0
? "complete"
: "partial",
unparsed_images: unparsed,
roots_without_architecture: withoutArchitecture,
unverified_shared_cache_images: [...unverifiedCacheImages].sort(compare),
},
limitations: [
...DYLIB_RESOLUTION_LIMITATIONS,
...sharedCacheLimitations(request.sharedCache, unserved),
],
};
};
const withoutDependencies = (
slice: MachoSlice,
): Omit<MachoSlice, "dependencies"> => ({
architecture: slice.architecture,
file_type: slice.file_type,
install_name: slice.install_name,
rpaths: slice.rpaths,
dyld_environment: slice.dyld_environment,
code_signature_present: slice.code_signature_present,
platforms: slice.platforms,
});
const compare = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
+145
View File
@@ -0,0 +1,145 @@
import { applePlatformLabel } from "./applePlatforms.js";
import { cacheServes } from "./dyldPaths.js";
import type {
DylibEdge as Edge,
DylibFinding as Finding,
DylibSharedCacheView,
DylibTrace,
MachoImageFacts,
MachoSlice,
} from "./dylibResolution.js";
export const deriveFindings = (
edges: readonly Edge[],
roots: DylibTrace["roots"],
images: ReadonlyMap<string, MachoImageFacts>,
): Finding[] => {
const findings: Finding[] = [];
edges.forEach((edge, index) => {
if (edge.resolution.status === "unresolved")
findings.push(unresolvedFinding(edge, index));
const resolvedAt = edge.candidates.findIndex(
({ outcome }) => outcome === "resolved" || outcome === "shared-cache",
);
const earlier = edge.candidates
.slice(0, Math.max(resolvedAt, 0))
.filter(
({ source, outcome }) => source === "rpath" && outcome === "absent",
)
.map(({ path }) => path);
if (resolvedAt > 0 && earlier.length > 0)
findings.push({
kind: "earlier-rpath-candidate-absent",
edge_index: index,
image: edge.loader,
basis: "derived",
explanation: `dyld searches ${earlier.join(", ")} before ${edge.resolution.image ?? edge.install_name}. A Mach-O placed at an earlier path would load first unless code-signing library validation rejects it; library validation is not evaluated here (see inspect_signature).`,
});
});
for (const { image, architecture } of roots) {
const facts = images.get(image);
const environment =
facts?.status === "parsed"
? (facts.slices.find((slice) => slice.architecture === architecture)
?.dyld_environment ?? [])
: [];
if (environment.length > 0)
findings.push({
kind: "dyld-environment-present",
edge_index: null,
image,
basis: "derived",
explanation: `${image} (${architecture}) sets dyld environment variables through LC_DYLD_ENVIRONMENT (${environment.join(", ")}); search paths they add are not modeled.`,
});
}
return findings;
};
const unresolvedFinding = (edge: Edge, index: number): Finding => {
const base = {
edge_index: index,
image: edge.loader,
basis: "derived",
} as const;
if (edge.command === "LC_LAZY_LOAD_DYLIB")
return {
...base,
kind: "lazy-load-unresolved",
explanation: `No candidate for lazily loaded ${edge.install_name} exists in the analyzed root; dyld loads it on first use, which would fail unless the image is supplied elsewhere.`,
};
return edge.weak
? {
...base,
kind: "weak-load-unresolved",
explanation: `No candidate for weak dependency ${edge.install_name} exists in the analyzed root; dyld continues without it.`,
}
: {
...base,
kind: "required-load-unresolved",
explanation: edge.loader_conditional
? `No candidate for ${edge.install_name} exists in the analyzed root. ${edge.loader} loads only conditionally; if it loads, dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`
: `No candidate for ${edge.install_name} exists in the analyzed root; dyld would fail to launch ${edge.root} (${edge.architecture}) unless the image is supplied elsewhere.`,
};
};
export const DYLIB_RESOLUTION_LIMITATIONS = [
"LC_LAZY_LOAD_DYLIB dependencies are resolved but not traversed, because dyld loads them only on first use.",
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
];
/** A process root the supplied shared cache cannot answer for. */
export interface UnservedRoot {
readonly image: string;
readonly architecture: string;
readonly reason: string;
}
/**
* Why the cache cannot serve a process slice, or undefined when it can:
* dyld maps only a cache built for the process's CPU family and platform.
*/
export const cacheMismatch = (
cache: DylibSharedCacheView,
slice: Pick<MachoSlice, "architecture" | "platforms">,
): string | undefined => {
if (!cacheServes(cache.architecture, slice.architecture))
return `the ${cache.architecture} cache does not serve ${slice.architecture} processes`;
if (cache.platforms.length === 0)
return "the cache header does not record its platform";
if (slice.platforms.length === 0)
return "the process records no LC_BUILD_VERSION or LC_VERSION_MIN platform";
if (
!slice.platforms.some(({ id }) =>
cache.platforms.some((platform) => platform.id === id),
)
)
return `the cache serves ${cache.platforms.map(applePlatformLabel).join(" and ")} processes, not ${slice.platforms.map(applePlatformLabel).join(" or ")}`;
return undefined;
};
export const sharedCacheLimitations = (
cache: DylibSharedCacheView | undefined,
unserved: readonly UnservedRoot[],
): string[] => {
if (cache === undefined)
return [
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides. Pass shared_cache to look them up in a cache.",
];
return [
"Absolute install names and rpaths were looked up only in the supplied dyld shared cache; paths it does not list stay outside-target because the host filesystem outside the analyzed root is not read. On another OS build the cache contents, and therefore these outcomes, can differ.",
...unserved.map(
({ image, architecture, reason }) =>
`The supplied shared cache was not used for ${image} (${architecture}): ${reason}. Its absolute paths stay outside-target.`,
),
...(cache.unavailableSubcaches.length === 0
? []
: [
`Subcaches ${cache.unavailableSubcaches.join(", ")} of the supplied cache are unavailable; install paths listed there are undetermined and reported in coverage.unverified_shared_cache_images.`,
]),
];
};
+204
View File
@@ -0,0 +1,204 @@
import { z } from "zod";
import { applePlatformSchema, type ApplePlatform } from "./applePlatforms.js";
import { digestSchema } from "../digests.js";
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
const ROOT_RELATIVE_PATH =
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
/** Caller selection of process roots and one CPU slice. */
export const dylibResolutionInputSchema = z.strictObject({
roots: z.array(rootRelativePathSchema).min(1).optional(),
architecture: z.enum(["arm64", "arm64e", "x86_64"]).optional(),
/** Main dyld shared cache file whose image list answers system install paths. */
shared_cache: z.string().min(1).optional(),
});
const dependencyCommandSchema = z.enum([
"LC_LOAD_DYLIB",
"LC_LOAD_WEAK_DYLIB",
"LC_REEXPORT_DYLIB",
"LC_LAZY_LOAD_DYLIB",
"LC_LOAD_UPWARD_DYLIB",
]);
const dependencySchema = z.strictObject({
command: dependencyCommandSchema,
encoding: z.enum(["dylib_command", "dylib_use_command"]),
install_name: z.string(),
weak: z.boolean(),
upward: z.boolean(),
reexport: z.boolean(),
delayed_init: z.boolean(),
current_version: z.string(),
compatibility_version: z.string(),
});
/** Observed dylib-loading facts of one Mach-O slice. */
export const machoSliceSchema = z.strictObject({
architecture: z.string().min(1),
file_type: z.enum(["execute", "dylib", "bundle", "other"]),
install_name: z.string().nullable(),
dependencies: z.array(dependencySchema),
rpaths: z.array(z.string()),
dyld_environment: z.array(z.string()),
code_signature_present: z.boolean(),
/** LC_BUILD_VERSION or LC_VERSION_MIN_* platforms; zippered images list two. */
platforms: z.array(applePlatformSchema),
});
export type MachoDependency = z.infer<typeof dependencySchema>;
export type MachoSlice = z.infer<typeof machoSliceSchema>;
/** Header parse of one file; malformed and unsupported images keep their reason. */
export type MachoImageFacts =
| { readonly status: "parsed"; readonly slices: readonly MachoSlice[] }
| {
readonly status: "malformed" | "unsupported";
readonly reason: string;
}
| { readonly status: "not-mach-o" };
/** One observed path below the analyzed root. Symlink targets are not followed by the view. */
export type DylibTreeEntry =
| { readonly kind: "file" | "directory" }
| { readonly kind: "symlink"; readonly target: string };
/** Read-only, lazily probed view of the analyzed root. Paths are root-relative. */
export interface DylibTreeView {
entry(path: string): Promise<DylibTreeEntry | undefined>;
image(path: string): Promise<MachoImageFacts>;
}
/** Image list of one caller-supplied dyld shared cache. */
export interface DylibSharedCacheView {
readonly architecture: string;
/** The cache's platform and alternate platform; empty when the header predates them. */
readonly platforms: readonly ApplePlatform[];
/** Subcaches whose bytes are missing or do not match, such as `.03 (missing)`. */
readonly unavailableSubcaches: readonly string[];
/**
* `mapped`: listed and inside a verified mapping; `unverified`: listed, but
* the subcache holding it is unavailable; `absent`: not listed.
*/
lookup(path: string): "mapped" | "unverified" | "absent";
}
const candidateSchema = z.strictObject({
path: z.string(),
source: z.enum([
"literal",
"executable_path",
"loader_path",
"rpath",
"already-loaded",
]),
rpath: z.string().nullable(),
rpath_owner: z.string().nullable(),
outcome: z.enum([
"resolved",
"absent",
"not-mach-o",
"malformed",
"unsupported",
"architecture-missing",
"outside-target",
"shared-cache",
"escapes-target",
"undetermined",
]),
resolved_path: z.string().nullable(),
});
const edgeSchema = z.strictObject({
root: z.string(),
architecture: z.string(),
loader: z.string(),
via: z.array(z.string()),
...dependencySchema.shape,
candidates: z.array(candidateSchema),
resolution: z.strictObject({
status: z.enum([
"resolved",
"conditional",
"shared-cache",
"unresolved",
"undetermined",
]),
image: z.string().nullable(),
}),
install_name_matches: z.boolean().nullable(),
/**
* The loader was reached through a conditional edge, so it might not load;
* this edge describes what happens only if it does.
*/
loader_conditional: z.boolean(),
});
const findingSchema = z.strictObject({
kind: z.enum([
"required-load-unresolved",
"weak-load-unresolved",
"lazy-load-unresolved",
"earlier-rpath-candidate-absent",
"dyld-environment-present",
]),
edge_index: z.number().int().nonnegative().nullable(),
image: z.string().nullable(),
basis: z.literal("derived"),
explanation: z.string().min(1),
});
const imageSchema = z.strictObject({
path: z.string(),
sha256: digestSchema,
parse_status: z.enum(["parsed", "malformed", "unsupported"]),
reason: z.string().nullable(),
slices: z.array(machoSliceSchema.omit({ dependencies: true })),
});
/** Static dyld load-path resolution for every selected process root. */
export const dylibResolutionResultSchema = z.strictObject({
root_path: z.string(),
target_sha256: digestSchema,
shared_cache: z
.strictObject({
path: z.string(),
uuid: z.string(),
architecture: z.string(),
os_version: z.string().nullable(),
})
.nullable(),
roots: z.array(
z.strictObject({ image: z.string(), architecture: z.string() }),
),
images: z.array(imageSchema),
edges: z.array(edgeSchema),
findings: z.array(findingSchema),
coverage: z.strictObject({
status: z.enum(["complete", "partial"]),
unparsed_images: z.array(z.string()),
roots_without_architecture: z.array(z.string()),
/** Install paths the supplied cache lists in subcaches that were unavailable. */
unverified_shared_cache_images: z.array(z.string()),
}),
limitations: z.array(z.string().min(1)),
});
export type DylibResolutionResult = z.infer<typeof dylibResolutionResultSchema>;
export type DylibCandidate = z.infer<typeof candidateSchema>;
export type DylibEdge = z.infer<typeof edgeSchema>;
export type DylibFinding = z.infer<typeof findingSchema>;
/** Result before the adapter adds file digests and the analyzed root. */
export type DylibTrace = Omit<
DylibResolutionResult,
"root_path" | "target_sha256" | "shared_cache" | "images"
> & {
readonly images: readonly (Omit<
DylibResolutionResult["images"][number],
"sha256"
> & { readonly sha256?: never })[];
};
@@ -0,0 +1,511 @@
import { describe, expect, it } from "vitest";
import { buildBinary, parseBinary } from "plist";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
parseInterfaceBuilderRecords,
} from "./interfaceBuilderGraph.js";
const hash = "a".repeat(64);
describe("compiled Interface Builder graph projection", () => {
it("normalizes object, hierarchy, action, outlet, and segue facts", () => {
const raw = {
"com.apple.ibtool.document.objects": {
controller: { customClass: "StoreViewController", label: "Store" },
button: { class: "UIButton", title: "Build" },
next: { customClass: "BuildViewController" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "buildTapped:",
destinationId: "controller",
},
{ type: "segue", identifier: "showBuild", destinationId: "next" },
],
controller: [
{ type: "outlet", label: "buildButton", destinationId: "button" },
],
},
"com.apple.ibtool.document.hierarchy": [
{ objectID: "controller", children: [{ objectID: "button" }] },
],
"com.apple.ibtool.document.classes": { StoreViewController: {} },
};
const decoded = parseInterfaceBuilderRecords(raw);
expect(decoded.objects).toHaveLength(3);
expect(decoded.connections.map(({ kind }) => kind)).toEqual([
"action",
"segue",
"outlet",
]);
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Views/Main.storyboardc/scene.nib/objects.nib",
archiveSha256: hash,
documentKind: "storyboard_scene",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
expect(result.graph.nodes.some(({ name }) => name === "buildTapped:")).toBe(
true,
);
expect(result.graph.nodes[0]?.evidence[0]).toMatchObject({
artifact_path: "Views/Main.storyboardc/scene.nib/objects.nib",
artifact_sha256: hash,
});
expect(result.graph.edges).toContainEqual(
expect.objectContaining({
relation: "segue_to",
resolution: "observed",
}),
);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Views/Main.storyboardc/scene.nib/objects.nib",
status: "complete",
}),
);
});
it("keeps missing external destinations as unresolved evidence", () => {
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Legacy.nib",
archiveSha256: hash,
documentKind: "nib",
raw: {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
},
"com.apple.ibtool.document.connections": {
button: [
{ type: "action", label: "save:", destinationId: "external" },
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({ max_objects: 3 }),
});
expect(result.graph.edges).toContainEqual(
expect.objectContaining({
relation: "target_action",
resolution: "unresolved",
reason: "endpoint_omitted_by_object_limit",
evidence: [
expect.objectContaining({
kind: "interface_builder_resource",
artifact_path: "Legacy.nib",
artifact_sha256: hash,
}),
],
}),
);
const retainedNodes = new Set(result.graph.nodes.map(({ id }) => id));
expect(
result.graph.edges.every(
({ from, to }) =>
retainedNodes.has(from) && (to === null || retainedNodes.has(to)),
),
).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "graph_nodes",
status: "partial",
reason: "max_objects_reached",
}),
);
expect(result.graph.truncated).toBe(true);
});
it("reads recognized objects from a compiled NSKeyedArchiver object table", () => {
const bytes = buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { UID: 2 }, title: "Build", identifier: "build-button" },
{
$classname: "UIButton",
$classes: ["UIButton", "UIControl", "UIView", "NSObject"],
},
],
$top: { root: { UID: 1 } },
});
const parsed = parseInterfaceBuilderRecords(parseBinary(bytes));
expect(parsed.objects).toMatchObject([
{
id: "1",
kind: "control",
class_name: "UIButton",
name: "Build",
},
]);
});
});
describe("Interface Builder parser bounds", () => {
it("reports connections discarded by the parser's hard ceiling", () => {
const connections = Array.from({ length: 40_001 }, (_, index) => ({
type: "custom-connection",
label: `action${String(index)}:`,
}));
const raw = {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
},
"com.apple.ibtool.document.connections": { button: connections },
};
const parsed = parseInterfaceBuilderRecords(raw);
expect(parsed.connections).toHaveLength(40_000);
expect(parsed.omittedConnections).toBe(1);
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Main.storyboardc/scene.nib",
archiveSha256: hash,
documentKind: "storyboard_scene",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.storyboardc/scene.nib",
status: "partial",
omitted: 1,
}),
);
});
});
describe("keyed archive decoding and graph limits", () => {
it("preserves keyed archive UID identities, arrays, and control actions", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{
subviews: [{ UID: 2 }],
$class: { UID: 5 },
},
{ $class: { UID: 6 } },
{ $class: { UID: 7 } },
{
source: { UID: 3 },
destination: { UID: 2 },
label: "runAction:",
$class: { UID: 8 },
},
{ $classname: "UIView", $classes: ["UIView", "NSObject"] },
{ $classname: "UIButton", $classes: ["UIButton", "UIView"] },
{
$classname: "ViewController",
$classes: ["ViewController", "NSObject"],
},
{
$classname: "NSNibControlConnector",
$classes: ["NSNibControlConnector", "NSObject"],
},
[{ UID: 1 }],
],
$top: { root: { UID: 9 } },
});
expect(parsed.objects.map(({ id }) => id)).toContain("2");
expect(parsed.hierarchy).toMatchObject([
{
objectID: "1",
children: [{ objectID: "2" }],
},
]);
expect(parsed.connections).toContainEqual(
expect.objectContaining({
kind: "action",
source_id: "2",
destination_id: "3",
label: "runAction:",
}),
);
});
it("reports records omitted by the parser's hard object ceiling", () => {
const objects = Object.fromEntries(
Array.from({ length: 20_001 }, (_, index) => [
`object-${index}`,
{ class: "UIView" },
]),
);
const parsed = parseInterfaceBuilderRecords({
"com.apple.ibtool.document.objects": objects,
});
expect(parsed.objects).toHaveLength(20_000);
expect(parsed.objectCount).toBe(20_001);
expect(parsed.omittedObjects).toBe(1);
});
it("keeps hierarchy edges out of the connection edge budget", () => {
const relativePath = "Main.nib";
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath,
archiveSha256: hash,
documentKind: "nib",
raw: {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
controller: { customClass: "MainViewController" },
parent: { class: "UIView" },
child: { class: "UIView" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "run:",
destinationId: "controller",
},
],
},
"com.apple.ibtool.document.hierarchy": [
{
objectID: "parent",
children: [
{ objectID: "child", children: [{ objectID: "button" }] },
],
},
],
},
},
],
limits: interfaceBuilderLimitsSchema.parse({
max_objects: 20,
max_connections: 1,
}),
});
expect(
result.graph.edges.filter(({ relation }) => relation === "target_action"),
).toHaveLength(3);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: `connections:${relativePath}`,
status: "complete",
omitted: 0,
}),
);
});
});
describe("keyed archive object references", () => {
it("keeps referenced objects as stubs so shared and cyclic references stay finite", () => {
// Each view references its window, superview, and next key view, so
// inlining references would expand the table into an exponential tree.
const viewCount = 40;
const views = Array.from({ length: viewCount }, (_, index) => ({
$class: { UID: 1 },
NSWindow: { UID: 2 },
NSSuperview: { UID: index === 0 ? 2 : 3 + index - 1 },
NSNextKeyView: { UID: 3 + ((index + 1) % viewCount) },
NSSubviews: index + 1 < viewCount ? [{ UID: 3 + index + 1 }] : [],
NSTitle: { UID: 3 + viewCount },
}));
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{ $classname: "NSView", $classes: ["NSView", "NSObject"] },
{ $class: { UID: 3 + viewCount + 1 }, NSContentView: { UID: 3 } },
...views,
"Title",
{ $classname: "NSWindow", $classes: ["NSWindow", "NSObject"] },
],
$top: { root: { UID: 2 } },
});
expect(parsed.objects).toHaveLength(viewCount + 1);
const view = parsed.objects.find(({ id }) => id === "3");
expect(view?.name).toBe("NSView");
expect(view?.attributes).toEqual({
NSWindow: { archiveUID: 2, className: "NSWindow" },
NSSuperview: { archiveUID: 2, className: "NSWindow" },
NSNextKeyView: { archiveUID: 4, className: "NSView" },
NSSubviews: [{ archiveUID: 4, className: "NSView" }],
NSTitle: "Title",
});
expect(parsed.hierarchy).toMatchObject([
{
objectID: "2",
children: [{ objectID: "3", children: [{ objectID: "4" }] }],
},
]);
});
it("resolves XML CF$UID references and the archived nil", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{
$class: { CF$UID: 3 },
NSSource: { CF$UID: 2 },
source: { CF$UID: 2 },
destination: { CF$UID: 0 },
label: { CF$UID: 4 },
},
{ $class: { CF$UID: 5 } },
{
$classname: "NSNibOutletConnector",
$classes: ["NSNibOutletConnector", "NSObject"],
},
{ $class: { CF$UID: 6 }, "NS.string": "delegate" },
{ $classname: "NSButton", $classes: ["NSButton", "NSObject"] },
{
$classname: "NSMutableString",
$classes: ["NSMutableString", "NSString", "NSObject"],
},
],
$top: {},
});
expect(parsed.connections).toEqual([
expect.objectContaining({
kind: "outlet",
source_id: "2",
destination_id: null,
label: "delegate",
}),
]);
expect(parsed.objects.find(({ id }) => id === "2")).toMatchObject({
class_name: "NSButton",
});
});
});
describe("AppKit keyed archive connectors", () => {
it("reads outlet and control connectors from NS-prefixed keys", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{ $class: { UID: 6 } },
{ $class: { UID: 7 }, identifier: "unrelated-identifier" },
{
$class: { UID: 8 },
NSSource: { UID: 1 },
NSDestination: { UID: 2 },
NSLabel: { UID: 5 },
},
{
$class: { UID: 9 },
NSSource: { UID: 2 },
NSDestination: { UID: 1 },
NSLabel: { UID: 10 },
},
"o_button",
{
$classname: "NSCustomObject",
$classes: ["NSCustomObject", "NSObject"],
},
{ $classname: "NSButton", $classes: ["NSButton", "NSObject"] },
{
$classname: "NSNibOutletConnector",
$classes: ["NSNibOutletConnector", "NSNibConnector", "NSObject"],
},
{
$classname: "NSNibControlConnector",
$classes: ["NSNibControlConnector", "NSNibConnector", "NSObject"],
},
"buttonClicked:",
],
$top: {},
});
expect(parsed.connections).toEqual([
expect.objectContaining({
kind: "outlet",
source_id: "1",
destination_id: "2",
label: "o_button",
}),
expect.objectContaining({
kind: "action",
source_id: "2",
destination_id: "1",
label: "buttonClicked:",
}),
]);
});
it("projects an AppKit action from the control through the selector to its target", () => {
const analysis = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "MainMenu.nib",
archiveSha256: hash,
documentKind: "nib",
raw: {
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{ $class: { UID: 4 } },
{ $class: { UID: 5 } },
{
$class: { UID: 6 },
NSSource: { UID: 2 },
NSDestination: { UID: 1 },
NSLabel: "buttonClicked:",
},
{ $classname: "BuildDelegate", $classes: ["NSObject"] },
{ $classname: "NSButton", $classes: ["NSButton", "NSObject"] },
{
$classname: "NSNibControlConnector",
$classes: ["NSNibControlConnector", "NSObject"],
},
],
$top: {},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
const byId = new Map(analysis.graph.nodes.map((node) => [node.id, node]));
const action = analysis.graph.nodes.find(({ kind }) => kind === "action");
const from = analysis.graph.edges
.filter(
({ to, relation }) => relation === "target_action" && to === action?.id,
)
.map(({ from: id }) => byId.get(id)?.name);
const to = analysis.graph.edges
.filter(
({ from: id, relation }) =>
relation === "target_action" && id === action?.id,
)
.map(({ to: id }) => (id === null ? null : byId.get(id)?.kind));
expect(from).toEqual(["NSButton"]);
expect(to).toEqual(expect.arrayContaining(["objc_selector", "unknown"]));
});
});
+524
View File
@@ -0,0 +1,524 @@
import { z } from "zod";
import {
firstString,
parseInterfaceBuilderRecords,
record,
} from "./interfaceBuilderKeyedArchive.js";
import {
nativeInvestigationEdgeSchema,
nativeInvestigationGraphSchema,
nativeInvestigationNodeSchema,
nativeInvestigationTraceLimitsSchema,
} from "../nativeInvestigationGraph.js";
export { parseInterfaceBuilderRecords } from "./interfaceBuilderKeyedArchive.js";
/** One compiled Interface Builder document projected from ibtool output. */
export const interfaceBuilderDocumentSchema = z.strictObject({
relative_path: z.string().min(1),
archive_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
document_kind: z.enum(["nib", "storyboard_scene"]),
object_count: z.number().int().nonnegative(),
connection_count: z.number().int().nonnegative(),
hierarchy_complete: z.boolean(),
});
/** Normalized read-only Interface Builder graph with archive provenance. */
export const interfaceBuilderAnalysisSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
documents: z.array(interfaceBuilderDocumentSchema).max(64),
graph: nativeInvestigationGraphSchema,
limitations: z.array(z.string()),
});
type InterfaceBuilderAnalysis = z.infer<typeof interfaceBuilderAnalysisSchema>;
export interface InterfaceBuilderDocumentInput {
readonly relativePath: string;
readonly archiveSha256: string;
readonly documentKind: "nib" | "storyboard_scene";
readonly raw: unknown;
}
type InvestigationNode = z.infer<typeof nativeInvestigationNodeSchema>;
type InvestigationEdge = z.infer<typeof nativeInvestigationEdgeSchema>;
/** Build the graph returned by the static Interface Builder archive decoder. */
export const buildInterfaceBuilderAnalysis = (input: {
readonly targetSha256: string;
readonly toolVersion: string;
readonly documents: readonly InterfaceBuilderDocumentInput[];
readonly limits: z.output<typeof interfaceBuilderLimitsSchema>;
}) => {
const nodes = new Map<string, InvestigationNode>();
const edges: InvestigationEdge[] = [];
const coverage = [] as Array<{
facet: string;
status: "complete" | "partial" | "unsupported" | "not_requested";
reason: string | null;
examined: number;
omitted: number;
}>;
const summaries: Array<z.infer<typeof interfaceBuilderDocumentSchema>> = [];
let truncated = false;
let omittedObjects = 0;
let omittedConnections = 0;
let omittedGraphNodes = 0;
for (const document of input.documents.slice(0, input.limits.max_documents)) {
const parsed = parseInterfaceBuilderRecords(document.raw);
const prefix = `ib:${document.relativePath}:`;
const rootId = `${prefix}root`;
const objectIds = new Set(parsed.objects.map(({ id }) => id));
const evidenceFor = (description: string) => [
{
kind: "interface_builder_resource" as const,
description: `${document.relativePath}: ${description}`,
location: { address: null, file_offset: null },
artifact_path: document.relativePath,
artifact_sha256: document.archiveSha256,
},
];
const addNode = (node: InvestigationNode): boolean => {
if (nodes.has(node.id)) return true;
if (nodes.size >= input.limits.max_objects) {
truncated = true;
omittedGraphNodes += 1;
return false;
}
nodes.set(node.id, node);
return true;
};
const rootNode = {
id: rootId,
kind:
document.documentKind === "nib"
? ("scene" as const)
: ("storyboard" as const),
name: document.relativePath,
location: null,
attributes: { document_kind: document.documentKind },
evidence: evidenceFor("compiled document"),
};
addNode(rootNode);
let documentObjectCount = 0;
for (const object of parsed.objects.slice(0, input.limits.max_objects)) {
const id = `${prefix}object:${object.id}`;
const kind = object.kind === "other" ? "unknown" : object.kind;
if (
!addNode({
id,
kind,
name: object.name,
location: null,
attributes: {
...object.attributes,
interface_builder_object_id: object.id,
class_name: object.class_name,
},
evidence: evidenceFor(`object ${object.id}`),
})
) {
break;
}
documentObjectCount += 1;
}
let connectionEdgeCount = 0;
let hierarchyEdgeCount = 0;
let documentOmittedConnections = 0;
let documentOmittedHierarchyEdges = 0;
const objectNodeId = (objectId: string): string =>
`${prefix}object:${objectId}`;
const addEdge = (
edge: (typeof edges)[number],
isHierarchy: boolean,
): void => {
if (
isHierarchy
? hierarchyEdgeCount >= input.limits.max_objects
: connectionEdgeCount >= input.limits.max_connections * 3
) {
truncated = true;
if (isHierarchy) {
documentOmittedHierarchyEdges += 1;
} else {
omittedConnections += 1;
documentOmittedConnections += 1;
}
return;
}
edges.push(edge);
if (isHierarchy) hierarchyEdgeCount += 1;
else connectionEdgeCount += 1;
};
const connect = (
id: string,
from: string,
to: string | null,
relation: "contains" | "outlet_to" | "target_action" | "segue_to",
description: string,
reason?: string,
) => {
if (!nodes.has(from)) {
truncated = true;
if (relation === "contains" && id.includes(":hierarchy:")) {
documentOmittedHierarchyEdges += 1;
} else {
omittedConnections += 1;
documentOmittedConnections += 1;
}
return;
}
const evidence = evidenceFor(description);
const unresolvedEndpoint = to !== null && !nodes.has(to);
if (unresolvedEndpoint) truncated = true;
const edgeTo = unresolvedEndpoint ? null : to;
const edgeReason = unresolvedEndpoint
? "endpoint_omitted_by_object_limit"
: (reason ?? "destination_unresolved");
addEdge(
edgeTo === null
? {
id,
from,
to: null,
relation,
resolution: "unresolved",
reason: edgeReason,
evidence,
limitations: [],
}
: {
id,
from,
to: edgeTo,
relation,
resolution: "observed",
evidence,
limitations: [],
},
relation === "contains" && id.includes(":hierarchy:"),
);
};
let hierarchyCount = 0;
let hierarchyTruncated = false;
const visitHierarchy = (value: unknown, parentId: string): void => {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
return;
}
if (Array.isArray(value)) {
for (const child of value) visitHierarchy(child, parentId);
return;
}
if (typeof value !== "object" || value === null) return;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
);
nextParent = childId;
hierarchyCount += 1;
}
visitHierarchy(item.children, nextParent);
};
for (const hierarchy of parsed.hierarchy) visitHierarchy(hierarchy, rootId);
for (const [index, item] of parsed.connections
.slice(0, input.limits.max_connections)
.entries()) {
const sourceId = objectNodeId(item.source_id);
if (!nodes.has(sourceId))
addNode({
id: sourceId,
kind: "unknown",
name: item.source_id,
location: null,
attributes: { interface_builder_object_id: item.source_id },
evidence: evidenceFor(`connection source ${item.source_id}`),
});
const destinationId =
item.destination_id === null ? null : objectNodeId(item.destination_id);
if (item.kind === "action") {
const actionId = `${prefix}action:${item.id}`;
const selectorId =
item.label === null
? null
: `${prefix}selector:${item.destination_id ?? "unknown"}:${item.label}`;
addNode({
id: actionId,
kind: "action",
name: item.label ?? "unlabeled action",
location: null,
attributes: {
selector: item.label,
destination_id: item.destination_id,
...item.attributes,
},
evidence: evidenceFor(`action ${item.id}`),
});
connect(
`${actionId}:source`,
sourceId,
actionId,
"target_action",
`action source ${item.source_id}`,
);
if (selectorId !== null) {
addNode({
id: selectorId,
kind: "objc_selector",
name: item.label ?? "unknown selector",
location: null,
attributes: { destination_id: item.destination_id },
evidence: evidenceFor(`selector ${item.label}`),
});
connect(
`${actionId}:selector`,
actionId,
selectorId,
"target_action",
`selector ${item.label}`,
);
}
if (destinationId === null || !nodes.has(destinationId))
connect(
`${actionId}:destination`,
actionId,
null,
"target_action",
`action destination ${item.destination_id ?? "missing"}`,
"destination_object_missing_or_external",
);
else
connect(
`${actionId}:destination`,
actionId,
destinationId,
"target_action",
`action destination ${item.destination_id}`,
);
} else if (item.kind === "outlet") {
const outletId = `${prefix}outlet:${item.id}`;
addNode({
id: outletId,
kind: "outlet",
name: item.label ?? item.id,
location: null,
attributes: item.attributes,
evidence: evidenceFor(`outlet ${item.id}`),
});
connect(
`${outletId}:source`,
sourceId,
outletId,
"contains",
`outlet source ${item.source_id}`,
);
if (destinationId === null || !nodes.has(destinationId))
connect(
`${outletId}:destination`,
outletId,
null,
"outlet_to",
`outlet ${item.label ?? item.id}`,
"destination_object_missing_or_external",
);
else
connect(
`${outletId}:destination`,
outletId,
destinationId,
"outlet_to",
`outlet ${item.label ?? item.id}`,
);
} else if (item.kind === "segue") {
if (destinationId === null || !nodes.has(destinationId))
connect(
`${prefix}segue:${index}`,
sourceId,
null,
"segue_to",
`segue ${item.label ?? item.id}`,
"destination_scene_missing",
);
else
connect(
`${prefix}segue:${index}`,
sourceId,
destinationId,
"segue_to",
`segue ${item.label ?? item.id}`,
);
} else {
connect(
`${prefix}unknown-connection:${index}`,
sourceId,
null,
"contains",
`connection type ${item.kind}`,
"unsupported_connection_type",
);
}
}
const objectsTruncated =
parsed.omittedObjects > 0 || parsed.objects.length > documentObjectCount;
const parserOmittedConnections = parsed.omittedConnections;
const connectionsTruncated =
parserOmittedConnections > 0 ||
parsed.connections.length > input.limits.max_connections;
omittedObjects +=
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount);
omittedConnections +=
Math.max(0, parsed.connections.length - input.limits.max_connections) +
parserOmittedConnections;
summaries.push({
relative_path: document.relativePath,
archive_sha256: document.archiveSha256,
document_kind: document.documentKind,
object_count: parsed.objectCount,
connection_count: parsed.connections.length + parserOmittedConnections,
hierarchy_complete: parsed.hierarchy.length > 0 && !truncated,
});
coverage.push(
{
facet: `objects:${document.relativePath}`,
status: objectsTruncated ? "partial" : "complete",
reason: objectsTruncated ? "object_limit_reached" : null,
examined: documentObjectCount,
omitted:
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount),
},
{
facet: `connections:${document.relativePath}`,
status:
connectionsTruncated || documentOmittedConnections > 0
? "partial"
: "complete",
reason:
connectionsTruncated || documentOmittedConnections > 0
? "connection_limit_reached"
: null,
examined: Math.min(
parsed.connections.length,
input.limits.max_connections,
),
omitted:
Math.max(
0,
parsed.connections.length - input.limits.max_connections,
) +
documentOmittedConnections +
parserOmittedConnections,
},
{
facet: `hierarchy:${document.relativePath}`,
status:
parsed.hierarchy.length === 0
? "unsupported"
: hierarchyTruncated || documentOmittedHierarchyEdges > 0
? "partial"
: "complete",
reason:
parsed.hierarchy.length === 0
? "archive_hierarchy_not_decoded"
: hierarchyTruncated || documentOmittedHierarchyEdges > 0
? "graph_limit_reached"
: null,
examined: hierarchyCount,
omitted: documentOmittedHierarchyEdges,
},
{
facet: `classes:${document.relativePath}`,
status:
Object.keys(parsed.classes).length > 0 ? "complete" : "unsupported",
reason:
Object.keys(parsed.classes).length > 0
? null
: "archive_class_table_not_decoded",
examined: Object.keys(parsed.classes).length,
omitted: 0,
},
);
}
if (input.documents.length > input.limits.max_documents) {
truncated = true;
coverage.push({
facet: "documents",
status: "partial",
reason: "document_limit_reached",
examined: input.limits.max_documents,
omitted: input.documents.length - input.limits.max_documents,
});
}
if (omittedGraphNodes > 0)
coverage.push({
facet: "graph_nodes",
status: "partial",
reason: "max_objects_reached",
examined: nodes.size,
omitted: omittedGraphNodes,
});
return interfaceBuilderAnalysisSchema.parse({
target_sha256: input.targetSha256,
documents: summaries,
graph: {
target_sha256: input.targetSha256,
provider: {
id: "rea-artifact-graph",
version: "1",
tool_version: input.toolVersion,
},
nodes: [...nodes.values()],
edges,
coverage,
truncated: truncated || omittedObjects > 0 || omittedConnections > 0,
},
limitations: [
"The graph reflects recognized Interface Builder archive fields and connections; omitted private or unrecognized archive fields remain unknown.",
"A target-action selector is an Interface Builder observation and does not prove that the binary contains a matching implementation.",
"Decoded constraints, runtime visibility, dynamic UI creation, and pixel geometry are not inferred from these archives.",
],
});
};
/** Hard limits shared by Interface Builder archive aggregation and tracing. */
export const interfaceBuilderLimitsSchema = z.strictObject({
max_documents: z.number().int().min(1).max(64).default(64),
max_objects: z.number().int().min(1).max(20_000).default(20_000),
max_connections: z.number().int().min(1).max(40_000).default(40_000),
trace: nativeInvestigationTraceLimitsSchema.default({
max_depth: 8,
max_nodes: 250,
max_edges: 500,
}),
});
@@ -0,0 +1,453 @@
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
const recordSchema = z.record(z.string(), z.unknown());
const objectNode = z.strictObject({
id: z.string().min(1),
kind: z.enum([
"view_controller",
"view",
"control",
"constraint",
"layout_guide",
"resource",
"placeholder",
"external_object",
"other",
]),
class_name: z.string().nullable(),
name: z.string().min(1),
attributes: z.record(z.string(), jsonValueSchema),
});
const connection = z.strictObject({
id: z.string().min(1),
kind: z.enum(["outlet", "action", "segue", "other"]),
source_id: z.string().min(1),
destination_id: z.string().nullable(),
label: z.string().nullable(),
attributes: z.record(z.string(), jsonValueSchema),
});
type InterfaceBuilderObject = z.infer<typeof objectNode>;
type InterfaceBuilderConnection = z.infer<typeof connection>;
/** Parse ibtool dictionaries or compiled keyed archives into typed records. */
export const parseInterfaceBuilderRecords = (
value: unknown,
): {
readonly objects: readonly InterfaceBuilderObject[];
readonly connections: readonly InterfaceBuilderConnection[];
readonly hierarchy: readonly unknown[];
readonly classes: Readonly<Record<string, unknown>>;
readonly objectCount: number;
readonly omittedObjects: number;
readonly omittedConnections: number;
} => {
const root = record(value);
const keyed = parseKeyedArchive(root);
if (keyed !== null) return keyed;
const objectsRaw = record(root["com.apple.ibtool.document.objects"]);
const connectionsRaw = record(root["com.apple.ibtool.document.connections"]);
const hierarchyRaw = root["com.apple.ibtool.document.hierarchy"];
const classesRaw = record(root["com.apple.ibtool.document.classes"]);
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let omittedConnections = 0;
const objectEntries = Object.entries(objectsRaw);
for (const [id, raw] of objectEntries.slice(0, 20_000)) {
const attributes = record(raw);
const className = firstString(
attributes["customClass"],
attributes["class"],
attributes["isa"],
);
const label = firstString(
attributes["label"],
attributes["title"],
attributes["name"],
className,
);
objects.push(
objectNode.parse({
id,
kind: classifyObject(className),
class_name: className,
name: label ?? id,
attributes: jsonSafeRecord(attributes),
}),
);
}
for (const [sourceId, rawConnections] of Object.entries(connectionsRaw)) {
if (!Array.isArray(rawConnections)) continue;
for (const [index, raw] of rawConnections.entries()) {
if (connections.length >= 40_000) {
omittedConnections += rawConnections.length - index;
break;
}
const item = record(raw);
const type = firstString(item.type, item.connectionType) ?? "unknown";
const destination = firstString(
item["destination-id"],
item.destinationId,
);
const label = firstString(item.label, item.selector, item.identifier);
connections.push(
connection.parse({
id: `${sourceId}:connection:${index}`,
kind: classifyConnection(type),
source_id: sourceId,
destination_id: destination,
label,
attributes: jsonSafeRecord(item),
}),
);
}
}
return {
objects,
connections,
hierarchy: Array.isArray(hierarchyRaw) ? hierarchyRaw.slice(0, 20_000) : [],
classes: classesRaw,
objectCount: objectEntries.length,
omittedObjects: Math.max(0, objectEntries.length - 20_000),
omittedConnections,
};
};
/**
* A UID decodes as a one-key `UID` (binary) or `CF$UID` (XML) dictionary with
* an integer value. Any other dictionary is ordinary archive data.
*/
const archiveUid = (value: unknown): number | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return undefined;
if (Object.keys(value).length !== 1) return undefined;
const item = record(value);
const marker = Object.hasOwn(item, "UID") ? item.UID : item["CF$UID"];
return typeof marker === "number" && Number.isInteger(marker)
? marker
: undefined;
};
const HIERARCHY_KEY =
/(?:subviews|contentview|childviewcontrollers|children|views)$/iu;
/**
* Read an NSKeyedArchiver object table without expanding it into a tree.
* Archived objects reference each other freely, including cycles such as a
* view and its superview, so inlining every reference grows exponentially.
* A reference instead resolves to the referenced string, or to a stub that
* names the referenced object; the hierarchy walk visits each object once.
*/
const keyedArchiveTable = (objectTable: readonly unknown[]) => {
const classNameOf = (value: unknown): string | null => {
const classReference = record(value).$class;
const uid = archiveUid(classReference);
return firstString(
record(uid === undefined ? classReference : objectTable[uid]).$classname,
);
};
/** The string an archived string object holds, if it is one. */
const archivedString = (target: unknown): string | undefined => {
if (typeof target === "string") return target;
const text = record(target)["NS.string"];
return typeof text === "string" &&
/^NS(?:Mutable)?String$/u.test(classNameOf(target) ?? "")
? text
: undefined;
};
const text = (value: unknown): string | null => {
const uid = archiveUid(value);
return firstString(
uid === undefined ? value : archivedString(objectTable[uid]),
);
};
const authoredId = (item: Record<string, unknown>): string | null =>
firstString(text(item.objectID), text(item["object-id"]));
const reference = (uid: number): unknown => {
// UID 0 is the archived nil.
const target = uid === 0 ? null : objectTable[uid];
if (target === undefined || target === null) return null;
if (typeof target !== "object") return target;
const string = archivedString(target);
if (string !== undefined) return string;
const objectId = authoredId(record(target));
return {
archiveUID: uid,
...(objectId === null ? {} : { objectID: objectId }),
className: classNameOf(target),
};
};
/** Resolve one object's own fields, leaving references to other objects as stubs. */
const resolve = (value: unknown): unknown => {
const uid = archiveUid(value);
if (uid !== undefined) return reference(uid);
if (Array.isArray(value)) return value.map(resolve);
if (typeof value !== "object" || value === null) return value;
const output: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
if (key === "$class") output.className = classNameOf(value);
else output[key] = resolve(child);
}
return output;
};
const hierarchy = (start: unknown): unknown[] => {
const visited = new Set<number>();
const node = (
item: Record<string, unknown>,
uid: number | undefined,
depth: number,
): unknown[] => {
const objectId = firstString(
authoredId(item),
text(item.id),
uid === undefined ? null : String(uid),
);
const children = Object.entries(item)
.filter(([key]) => HIERARCHY_KEY.test(key))
.flatMap(([, child]) => visit(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
};
const visit = (value: unknown, depth: number): unknown[] => {
if (depth > 32) return [];
const uid = archiveUid(value);
if (uid !== undefined) {
if (visited.has(uid)) return [];
visited.add(uid);
const target = objectTable[uid];
if (Array.isArray(target)) return visit(target, depth + 1);
return typeof target === "object" && target !== null
? node(record(target), uid, depth)
: [];
}
if (Array.isArray(value))
return value.flatMap((item) => visit(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
return node(record(value), undefined, depth);
};
return visit(start, 0);
};
return { resolve, hierarchy };
};
/** Project class and connection objects from an NSKeyedArchiver object table. */
const parseKeyedArchive = (
root: Record<string, unknown>,
): ReturnType<typeof parseInterfaceBuilderRecords> | null => {
if (root.$archiver !== "NSKeyedArchiver" || !Array.isArray(root.$objects))
return null;
const objectTable: readonly unknown[] = root.$objects;
const { resolve, hierarchy: toHierarchy } = keyedArchiveTable(objectTable);
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
let omittedConnections = 0;
for (const [index, raw] of objectTable.entries()) {
if (index === 0) continue;
const resolved = record(resolve(raw));
const className = firstString(resolved.className);
if (className === null) continue;
objectCount += 1;
const fields = Object.fromEntries(
Object.entries(resolved).filter(([key]) => key !== "className"),
);
const authoredId = firstString(fields.objectID, fields["object-id"]);
const objectId =
authoredId ??
(typeof fields.archiveUID === "number"
? String(fields.archiveUID)
: String(index));
const kind = classifyObject(className);
if (objects.length < 20_000)
objects.push(
objectNode.parse({
id: objectId,
kind,
class_name: className,
name:
firstString(
fields.label,
fields.title,
fields.identifier,
fields.accessibilityLabel,
className,
) ?? `object ${String(index)}`,
attributes: jsonSafeRecord(fields),
}),
);
if (
/(?:Outlet|Connection|Segue|ActionConnection|ControlConnector)/iu.test(
className,
)
) {
const controlAction = /ControlConnector/iu.test(className);
// AppKit connectors (NSNibOutletConnector, NSNibControlConnector)
// archive NSSource as the outlet owner or sending control and
// NSDestination as the outlet value or action target, so they are read
// in that order without the inversion the unprefixed fields use.
const source = firstObjectReference(
controlAction ? fields.destination : fields.source,
archivedObjectReference(fields.NSSource),
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
kind,
source_id: source,
destination_id: firstObjectReference(
controlAction ? fields.source : fields.destination,
archivedObjectReference(fields.NSDestination),
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: firstString(
fields.label,
fields.NSLabel,
fields.selector,
fields.identifier,
fields.action,
),
attributes: jsonSafeRecord(fields),
});
if (connections.length < 40_000) connections.push(parsedConnection);
else omittedConnections += 1;
}
}
const top = record(root.$top);
const hierarchy = toHierarchy(top.root ?? top.UITopLevelObjectsKey);
const classes = Object.fromEntries(
objectTable.flatMap((raw) => {
const item = record(raw);
const name = firstString(item.$classname);
return name === null
? []
: [
[
name,
{
superclasses: Array.isArray(item.$classes) ? item.$classes : [],
},
],
];
}),
);
return {
objects,
connections,
hierarchy,
classes,
objectCount,
omittedObjects: Math.max(0, objectCount - 20_000),
omittedConnections,
};
};
/** Coerce unknown values to a string-keyed record; non-objects become `{}`. */
export const record = (value: unknown): Record<string, unknown> =>
recordSchema.safeParse(value).data ?? {};
/** First non-empty string among the candidates, otherwise null. */
export const firstString = (...values: unknown[]): string | null => {
for (const value of values)
if (typeof value === "string" && value.length > 0) return value;
return null;
};
/**
* The node identity of a resolved archive reference: its authored object ID,
* otherwise its archive UID, which is how the referenced object's node is keyed.
*/
const archivedObjectReference = (value: unknown): string | null => {
const item = record(value);
if (typeof item.archiveUID !== "number") return null;
return (
firstString(item.objectID, item["object-id"]) ?? String(item.archiveUID)
);
};
const firstObjectReference = (...values: unknown[]): string | null => {
for (const value of values) {
const direct = firstString(value);
if (direct !== null) return direct;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
item.identifier,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
if (objectId !== null) return objectId;
}
return null;
};
const classifyObject = (
className: string | null,
): InterfaceBuilderObject["kind"] => {
const value = className?.toLowerCase() ?? "";
if (value.includes("constraint")) return "constraint";
if (value.includes("layoutguide")) return "layout_guide";
if (
value.includes("placeholder") ||
value.includes("firstresponder") ||
value === "uiproxyobject"
)
return "placeholder";
if (
value.includes("image") ||
value.includes("color") ||
value.includes("font")
)
return "resource";
if (value.includes("external")) return "external_object";
if (value.includes("viewcontroller") || value.includes("windowcontroller"))
return "view_controller";
if (
value.includes("button") ||
value.includes("control") ||
value.includes("textfield") ||
value.includes("slider") ||
value.includes("menuitem")
)
return "control";
if (
value.includes("view") ||
value.includes("window") ||
value.includes("cell")
)
return "view";
return "other";
};
const classifyConnection = (
type: string,
): InterfaceBuilderConnection["kind"] => {
const value = type.toLowerCase();
if (value.includes("outlet")) return "outlet";
if (value.includes("action")) return "action";
if (value.includes("segue")) return "segue";
return "other";
};
const jsonSafeRecord = (value: Record<string, unknown>) =>
Object.fromEntries(
Object.entries(value).flatMap(([key, item]) => {
try {
const serialized = JSON.stringify(item);
if (serialized === undefined) return [];
const parsed = jsonValueSchema.safeParse(JSON.parse(serialized));
return parsed.success ? [[key, parsed.data]] : [];
} catch (cause: unknown) {
// Unserializable entries are omitted from the record.
void cause;
return [];
}
}),
);
+201
View File
@@ -0,0 +1,201 @@
import { z } from "zod";
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
/** Select one archive within the active bundle and optionally one named root. */
export const keyedArchiveInputSchema = z.strictObject({
path: z.string().min(1).default("."),
root: z.string().optional(),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(20_000).default(20_000),
});
const linkSchema = z.strictObject({
source: z.number().int().nonnegative().nullable(),
path: z.array(z.union([z.string(), z.number().int().nonnegative()])),
target: z.number().int().nonnegative().nullable(),
status: z.enum(["resolved", "nil", "unresolved", "malformed"]),
raw: jsonValueSchema,
});
/** Archive object identity is its original $objects index, never a recursive copy. */
export const keyedArchiveResultSchema = z.strictObject({
target_sha256: z.string(),
archive_path: z.string(),
archive_sha256: z.string(),
archive_format: z.enum(["binary-plist", "xml-plist"]),
roots: z.record(z.string(), jsonValueSchema),
objects: z.array(
z.strictObject({
id: z.number().int().nonnegative(),
kind: z.enum([
"nil",
"scalar",
"array",
"dictionary",
"class-descriptor",
"archived-object",
]),
class_id: z.number().int().nonnegative().nullable(),
class_name: z.string().nullable(),
status: z.enum(["observed", "unknown-class", "unresolved-class", "nil"]),
value: jsonValueSchema,
}),
),
references: z.array(linkSchema),
total_objects: z.number().int().nonnegative(),
total_references: z.number().int().nonnegative(),
offset: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
const record = (
value: JsonValue | undefined,
): Record<string, JsonValue> | undefined =>
value !== null && typeof value === "object" && !Array.isArray(value)
? value
: undefined;
/**
* A UID decodes as a one-key `UID` (binary) or `CF$UID` (XML) dictionary with
* a numeric value. Any other value means an ordinary dictionary, such as a
* `$top` that holds a root encoded under the key `UID`.
*/
const uid = (value: JsonValue | undefined): number | undefined => {
const object = record(value);
if (object === undefined || Object.keys(object).length !== 1)
return undefined;
const marker = Object.hasOwn(object, "UID") ? object.UID : object["CF$UID"];
return typeof marker === "number" ? marker : undefined;
};
/** Interpret serialized Foundation references without instantiating archive classes. */
export const projectKeyedArchive = (
value: unknown,
selection: { root?: string | undefined; offset: number; limit: number },
) => {
const archive = record(jsonValueSchema.parse(value));
if (
archive?.$archiver !== "NSKeyedArchiver" ||
!Array.isArray(archive.$objects)
)
throw new TypeError("Expected NSKeyedArchiver with an $objects array");
const table = archive.$objects;
if (table.length > 200_000)
throw new RangeError("Archive exceeds 200000 object-table entries");
const top = record(archive.$top);
if (top === undefined || Object.keys(top).length === 0)
throw new TypeError("Keyed archive has no $top roots");
if (selection.root !== undefined && !Object.hasOwn(top, selection.root))
throw new TypeError(`Archive root does not exist: ${selection.root}`);
const roots =
selection.root === undefined
? top
: { [selection.root]: top[selection.root] ?? null };
const references: z.infer<typeof linkSchema>[] = [];
const scan = (source: number | null, initial: JsonValue) => {
const pending: { value: JsonValue; path: (string | number)[] }[] = [
{ value: initial, path: [] },
];
let visited = 0;
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (++visited > 200_000 || item.path.length > 128)
throw new RangeError(
"Archive exceeds 200000 values per object or 128 nesting levels",
);
const target = uid(item.value);
if (target !== undefined) {
const index =
Number.isSafeInteger(target) && target >= 0 ? target : null;
references.push({
source,
path: item.path,
target: index,
raw: item.value,
status:
index === null
? "malformed"
: index >= table.length
? "unresolved"
: index === 0 && table[0] === "$null"
? "nil"
: "resolved",
});
} else if (Array.isArray(item.value)) {
for (let index = item.value.length - 1; index >= 0; index--) {
const child = item.value[index];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, index] });
}
} else {
const fields = record(item.value);
if (fields !== undefined)
for (const key of Object.keys(fields).sort().reverse()) {
const child = fields[key];
if (child !== undefined)
pending.push({ value: child, path: [...item.path, key] });
}
}
if (references.length > 200_000)
throw new RangeError("Archive exceeds 200000 reference edges");
}
};
scan(null, roots);
const objects = table.map((value, id) => {
scan(id, value);
const fields = record(value);
const classUid = uid(fields?.$class);
const classId =
classUid !== undefined && Number.isSafeInteger(classUid) && classUid >= 0
? classUid
: null;
const descriptor = classId === null ? undefined : record(table[classId]);
const className =
typeof descriptor?.$classname === "string" ? descriptor.$classname : null;
const isNil = id === 0 && value === "$null";
return {
id,
kind: isNil
? ("nil" as const)
: Array.isArray(value)
? ("array" as const)
: fields === undefined
? ("scalar" as const)
: typeof fields.$classname === "string"
? ("class-descriptor" as const)
: Object.hasOwn(fields, "$class")
? ("archived-object" as const)
: ("dictionary" as const),
class_id: classId,
class_name: className,
status: isNil
? ("nil" as const)
: fields !== undefined && Object.hasOwn(fields, "$class")
? className === null
? ("unresolved-class" as const)
: ("unknown-class" as const)
: ("observed" as const),
value,
};
});
const end = Math.min(objects.length, selection.offset + selection.limit);
const page = objects.slice(selection.offset, end);
const ids = new Set(page.map(({ id }) => id));
return {
roots,
objects: page,
references: references.filter(
({ source }) => source === null || ids.has(source),
),
total_objects: objects.length,
total_references: references.length,
offset: selection.offset,
next_offset: end < objects.length ? end : null,
truncated: page.length !== objects.length,
limitations: [
"Archive classes are never instantiated. Class names and serialized fields are observed; class-specific semantics are unknown.",
"Conditional references serialized as UID 0 cannot be distinguished from ordinary nil references. Missing fields remain absent in the raw serialized value.",
"Root selection selects the named $top entry; object pagination retains original indices and does not recursively expand references.",
],
};
};
+40
View File
@@ -0,0 +1,40 @@
import { expect, it } from "vitest";
import { projectPlistValue } from "./plistValue.js";
it("projects plist data, dates, and non-finite reals as typed values", () => {
expect(
projectPlistValue({
blob: new Uint8Array([0, 1, 2]),
when: new Date("2020-01-01T00:00:00Z"),
nested: [{ ratio: 0.5, missing: Number.NaN, unbounded: -Infinity }],
plain: { "": "empty key", flag: true, count: 42 },
}),
).toEqual({
value: {
blob: { $plist_type: "data", base64: "AAEC" },
when: { $plist_type: "date", iso8601: "2020-01-01T00:00:00.000Z" },
nested: [
{
ratio: 0.5,
missing: { $plist_type: "real", value: null },
unbounded: { $plist_type: "real", value: null },
},
],
plain: { "": "empty key", flag: true, count: 42 },
},
unknownRealCount: 2,
});
});
it("rejects values a plist decoder cannot produce", () => {
expect(() => projectPlistValue({ value: Symbol("x") })).toThrow();
const deep: unknown[] = [];
let cursor = deep;
for (let depth = 0; depth < 200; depth += 1) {
const next: unknown[] = [];
cursor.push(next);
cursor = next;
}
expect(() => projectPlistValue(deep)).toThrow(RangeError);
});
+50
View File
@@ -0,0 +1,50 @@
import { z } from "zod";
import type { JsonValue } from "../jsonValue.js";
const MAX_PLIST_DEPTH = 128;
/** A decoded plist projected into JSON, with values JSON cannot express. */
export interface ProjectedPlistValue {
readonly value: JsonValue;
/** Reals decoded as NaN, which the decoder also uses for ±infinity. */
readonly unknownRealCount: number;
}
/**
* Project a decoded plist into JSON. Data and dates become explicit
* `$plist_type` objects; a non-finite real becomes an explicit unknown
* because the XML decoder reports NaN and ±infinity alike.
*/
export const projectPlistValue = (value: unknown): ProjectedPlistValue => {
let unknownRealCount = 0;
const project = (item: unknown, depth: number): JsonValue => {
if (depth > MAX_PLIST_DEPTH)
throw new RangeError(
`Plist exceeds ${String(MAX_PLIST_DEPTH)} nesting levels`,
);
if (item instanceof Uint8Array)
return {
$plist_type: "data",
base64: Buffer.from(item).toString("base64"),
};
if (item instanceof Date)
return { $plist_type: "date", iso8601: item.toISOString() };
if (typeof item === "number" && !Number.isFinite(item)) {
unknownRealCount += 1;
return { $plist_type: "real", value: null };
}
if (Array.isArray(item))
return item.map((entry: unknown) => project(entry, depth + 1));
if (item !== null && typeof item === "object")
return Object.fromEntries(
Object.entries(item).map(([key, entry]) => [
key,
project(entry, depth + 1),
]),
);
return z.union([z.string(), z.number(), z.boolean(), z.null()]).parse(item);
};
const projected = project(value, 0);
return { value: projected, unknownRealCount };
};