refactor(apple): group artifact producers and verification (#952)

* refactor(apple): group artifact producers and verification

* test(apple): run affected native plist CLI regressions
This commit is contained in:
ysopwnable
2026-10-07 21:09:33 +08:00
committed by GitHub
parent a6ba772c08
commit ef1a0cc65a
50 changed files with 149 additions and 92 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;
@@ -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 };
};