Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(apple): join recognized keys from NIBArchive field maps (#2248)

吴佳浩Albenfd985dbc5b94
diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts
index 13c3f9cdb..4446fcd26 100644
--- a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts
+++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts
@@ -1,9 +1,11 @@
+import { createHash } from "node:crypto";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
+import { encodeNibArchiveFixture } from "./NibArchive.fixture.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import {
analyzeAppleAssetCatalogs,
@@ -22,6 +24,13 @@ describe("Apple asset catalog application workflow", () => {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
+ nibValues: {
+ title: "not-an-asset-key",
+ imageName: { value: "not-a-scalar" },
+ image: 42,
+ assetName: "",
+ nested: { NSImageName: "not-a-direct-field" },
+ },
},
evidence: [
{
@@ -34,8 +43,13 @@ describe("Apple asset catalog application workflow", () => {
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
- attributes: { title: "not-an-asset-key" },
- evidence: [],
+ attributes: { NSImageName: "Toolbar", imageName: "Toolbar" },
+ evidence: [
+ {
+ artifact_path: "Contents/Resources/Main.nib",
+ artifact_sha256: "d".repeat(64),
+ },
+ ],
},
]),
).toEqual([
@@ -118,3 +132,77 @@ describe("Apple asset catalog application workflow", () => {
);
});
});
+
+it.each([1, 2])(
+ "joins NIBArchive keys against %i supplied assetutil renditions",
+ async (count) => {
+ const bundle = await createTestTempDirectory("rea-asset-nib-join-");
+ const resources = join(bundle, "Contents", "Resources");
+ await mkdir(resources, { recursive: true });
+ const archive = encodeNibArchiveFixture({
+ classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
+ objects: [
+ { classIndex: 0, values: { NSRoot: { ref: 1 } } },
+ { classIndex: 1, values: { image: { ref: 2 } } },
+ { classIndex: 2, values: { NSImageName: { ref: 3 } } },
+ { classIndex: 3, values: { "NS.bytes": "Toolbar" } },
+ ],
+ });
+ await writeFile(join(resources, "Panel.nib"), archive);
+ await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
+ // Supplied metadata tests the post-engine join; it does not establish native catalog validity.
+ const result = await analyzeAppleAssetCatalogs({
+ environment: {},
+ bundlePath: bundle,
+ targetSha256: "a".repeat(64),
+ runAssetUtil: () =>
+ Promise.resolve(
+ JSON.stringify(
+ Array.from({ length: count }, (_, index) => ({
+ Name: "Toolbar",
+ RenditionName: `toolbar-${String(index)}.png`,
+ })),
+ ),
+ ),
+ });
+ expect(result.resource_key_matches).toHaveLength(1);
+ expect(result.resource_key_matches[0]).toMatchObject({
+ field: "NSImageName",
+ key: "Toolbar",
+ status: count === 1 ? "matched" : "ambiguous",
+ source_path: "Contents/Resources/Panel.nib",
+ source_archive_sha256: createHash("sha256").update(archive).digest("hex"),
+ renditions: Array.from({ length: count }, (_, index) =>
+ expect.objectContaining({
+ record_index: index,
+ rendition_name: `toolbar-${String(index)}.png`,
+ }),
+ ),
+ });
+ },
+);
+
+it("keeps recognized image fields on NIBArchive controls out of resource joins", async () => {
+ const bundle = await createTestTempDirectory("rea-asset-nib-control-");
+ const resources = join(bundle, "Contents", "Resources");
+ await mkdir(resources, { recursive: true });
+ await writeFile(
+ join(resources, "Panel.nib"),
+ encodeNibArchiveFixture({
+ classes: ["NSIBObjectData", "NSButton", "NSString"],
+ objects: [
+ { classIndex: 0, values: { NSRoot: { ref: 1 } } },
+ { classIndex: 1, values: { NSImageName: { ref: 2 } } },
+ { classIndex: 2, values: { "NS.bytes": "Toolbar" } },
+ ],
+ }),
+ );
+ await writeFile(join(resources, "Assets.car"), "inert catalog fixture");
+ const result = await analyzeAppleAssetCatalogs({
+ environment: {},
+ bundlePath: bundle,
+ targetSha256: "a".repeat(64),
+ runAssetUtil: () => Promise.resolve(JSON.stringify([{ Name: "Toolbar" }])),
+ });
+ expect(result.resource_key_matches).toEqual([]);
+});
diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts
index c91dc5312..5fe1bced3 100644
--- a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts
+++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts
@@ -8,6 +8,7 @@ import {
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
+ appleResourceKeyFields,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../../domain/apple/appleAssetCatalog.js";
@@ -16,17 +17,6 @@ import { execFileOutput } from "../../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
-const RESOURCE_KEY_FIELDS = new Set([
- "image",
- "imageName",
- "image_name",
- "resourceName",
- "resource_name",
- "assetName",
- "asset_name",
- "UIImageName",
- "NSImageName",
-]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
@@ -201,27 +191,22 @@ export const collectInterfaceBuilderResourceKeys = (
}[],
) =>
nodes.flatMap((node) => {
+ if (node.kind !== "resource") return [];
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
- return Object.entries(node.attributes).flatMap(([field, value]) =>
- RESOURCE_KEY_FIELDS.has(field) &&
- typeof value === "string" &&
- value.length > 0
- ? [
- {
- sourceNodeId: node.id,
- sourcePath,
- sourceArchiveSha256,
- field,
- key: value,
- },
- ]
- : [],
- );
+ return appleResourceKeyFields(node.attributes).flatMap(([field, value]) => [
+ {
+ sourceNodeId: node.id,
+ sourcePath,
+ sourceArchiveSha256,
+ field,
+ key: value,
+ },
+ ]);
});
const runAssetUtil = async (
diff --git a/src/artifacts/apple/InterfaceBuilderAnalysis.ts b/src/artifacts/apple/InterfaceBuilderAnalysis.ts
index 0f9506a66..89cf499e6 100644
--- a/src/artifacts/apple/InterfaceBuilderAnalysis.ts
+++ b/src/artifacts/apple/InterfaceBuilderAnalysis.ts
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
+import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import {
@@ -459,18 +460,27 @@ const projectNibArchive = (
break;
}
budget.reserveJsonStringOccurrence(name);
+ const nibValues = Object.fromEntries(
+ Object.entries(object.values).map(([key, value]) => {
+ budget.reserveJsonPropertyNameOccurrence(key);
+ return [key, dereference(value) ?? null];
+ }),
+ );
+ // Normalize only recognized scalar fields at the format owner. A keyed
+ // archive's authored nibValues dictionary must not gain this meaning.
+ const resourceFields = appleResourceKeyFields(nibValues);
+ for (const [field, value] of resourceFields) {
+ budget.reserveJsonPropertyNameOccurrence(field);
+ budget.reserveJsonStringOccurrence(value);
+ }
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
- nibValues: Object.fromEntries(
- Object.entries(object.values).map(([key, value]) => {
- budget.reserveJsonPropertyNameOccurrence(key);
- return [key, dereference(value) ?? null];
- }),
- ),
+ nibValues,
+ ...Object.fromEntries(resourceFields),
},
];
}),
diff --git a/src/domain/apple/appleAssetCatalog.ts b/src/domain/apple/appleAssetCatalog.ts
index 2954ebda8..4d04e1410 100644
--- a/src/domain/apple/appleAssetCatalog.ts
+++ b/src/domain/apple/appleAssetCatalog.ts
@@ -3,6 +3,29 @@ import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
import { AnalysisOutputError } from "../analysisErrorCore.js";
+const RESOURCE_KEY_FIELDS = new Set([
+ "image",
+ "imageName",
+ "image_name",
+ "resourceName",
+ "resource_name",
+ "assetName",
+ "asset_name",
+ "UIImageName",
+ "NSImageName",
+]);
+
+/** Recognized direct scalar resource fields; nested dictionaries are not inferred. */
+export const appleResourceKeyFields = (
+ attributes: Readonly<Record<string, unknown>>,
+): [string, string][] =>
+ Object.entries(attributes).filter(
+ (entry): entry is [string, string] =>
+ RESOURCE_KEY_FIELDS.has(entry[0]) &&
+ typeof entry[1] === "string" &&
+ entry[1].length > 0,
+ );
+
/** Caller-controlled page bounds for compiled Apple asset metadata. */
export const appleAssetCatalogInputSchema = z.strictObject({
offset: z.number().int().min(0).default(0),
diff --git a/tests/acceptance/applications/assetCatalogResourceKeys.test.ts b/tests/acceptance/applications/assetCatalogResourceKeys.test.ts
new file mode 100644
index 000000000..5df6a1618
--- /dev/null
+++ b/tests/acceptance/applications/assetCatalogResourceKeys.test.ts
@@ -0,0 +1,128 @@
+import { createHash } from "node:crypto";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect } from "vitest";
+import { buildBinary } from "plist";
+
+import { encodeNibArchiveFixture } from "../../../src/artifacts/apple/NibArchive.fixture.js";
+import { appleAssetCatalogResultSchema } from "../../../src/domain/apple/appleAssetCatalog.js";
+import { interfaceBuilderAnalysisSchema } from "../../../src/domain/apple/interfaceBuilderGraph.js";
+import { parseEvidence } from "../../../src/domain/evidence.js";
+import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest } from "../../support/cli/cliFixture.js";
+
+// Exact rooted NIBArchive bytes from #2176; inert parser fixture, not ibtool output.
+const reportedArchive = Buffer.from(
+ "TklCQXJjaGl2ZQEAAAAKAAAABAAAADIAAAAEAAAAPgAAAAQAAABgAAAABAAAAHwAAACAgIGBgYGCgoGDg4GGTlNSb290hWltYWdli05TSW1hZ2VOYW1liE5TLmJ5dGVzgAoBAAAAgQoCAAAAggoDAAAAgwiHVG9vbGJhco6ATlNJQk9iamVjdERhdGGLgE5TSW1hZ2VWaWV3h4BOU0ltYWdliIBOU1N0cmluZw==",
+ "base64",
+);
+const resourceArchive = (field: string) =>
+ encodeNibArchiveFixture({
+ classes: ["NSIBObjectData", "NSImageView", "NSImage", "NSString"],
+ objects: [
+ { classIndex: 0, values: { NSRoot: { ref: 1 } } },
+ { classIndex: 1, values: { image: { ref: 2 } } },
+ { classIndex: 2, values: { [field]: { ref: 3 } } },
+ { classIndex: 3, values: { "NS.bytes": "Toolbar" } },
+ ],
+ });
+
+const keyedArchive = (nested: boolean) =>
+ buildBinary({
+ $archiver: "NSKeyedArchiver",
+ $version: 100000,
+ $top: { root: { UID: 1 } },
+ $objects: [
+ "$null",
+ {
+ $class: { UID: 2 },
+ ...(nested
+ ? { nibValues: { NSImageName: "Toolbar" } }
+ : { NSImageName: "Toolbar" }),
+ },
+ { $classname: "NSImage", $classes: ["NSImage", "NSObject"] },
+ ],
+ });
+
+cliTest.skipIf(process.platform !== "darwin")(
+ "retains recognized NIBArchive resource keys and provenance through CLI and MCP without a catalog",
+ async ({ cli }) => {
+ const root = await createTestTempDirectory("rea-asset-resource-keys-");
+ const { call } = await connectLocalToolsMcp();
+ for (const [name, field, archive, recognized] of [
+ ["reported", "NSImageName", reportedArchive, true],
+ ["alias", "imageName", resourceArchive("imageName"), true],
+ ["title", "title", resourceArchive("title"), false],
+ ["keyed-direct", "NSImageName", keyedArchive(false), true],
+ ["keyed-nested", "NSImageName", keyedArchive(true), false],
+ ] as const) {
+ const app = join(root, `${name}.app`);
+ const contents = join(app, "Contents");
+ await mkdir(join(contents, "Resources"), { recursive: true });
+ await mkdir(join(contents, "MacOS"));
+ const mach = Buffer.alloc(32);
+ mach.writeUInt32LE(0xfeedfacf, 0);
+ mach.writeUInt32LE(0x0100000c, 4);
+ mach.writeUInt32LE(2, 12);
+ await writeFile(join(contents, "MacOS", "App"), mach);
+ await writeFile(
+ join(contents, "Info.plist"),
+ "<plist><dict><key>CFBundleExecutable</key><string>App</string></dict></plist>",
+ );
+ await writeFile(join(contents, "Resources", "Panel.nib"), archive);
+ const decoded = await cli.run({
+ arguments: ["decode-interface-builder", app, "--json"],
+ });
+ expect(decoded.exitCode, decoded.stderr).toBe(0);
+ const graph = interfaceBuilderAnalysisSchema.parse(
+ parseEvidence(decoded.json).normalized_result,
+ ).graph;
+ expect(graph.truncated).toBe(false);
+ const resource = graph.nodes.find(
+ (node) =>
+ node.kind === "resource" && node.attributes.class_name === "NSImage",
+ );
+ expect(
+ name === "keyed-direct"
+ ? resource?.attributes
+ : resource?.attributes.nibValues,
+ ).toMatchObject({
+ [field]: "Toolbar",
+ });
+ const inspected = await cli.run({
+ arguments: ["inspect-asset-catalog", app, "--json"],
+ });
+ expect(inspected.exitCode, inspected.stderr).toBe(0);
+ const result = appleAssetCatalogResultSchema.parse(
+ parseEvidence(inspected.json).normalized_result,
+ );
+ expect(result.catalogs).toEqual([]);
+ expect(result.resource_key_matches).toEqual(
+ !recognized
+ ? []
+ : [
+ {
+ source_node_id: resource?.id,
+ source_path: "Contents/Resources/Panel.nib",
+ source_archive_sha256: createHash("sha256")
+ .update(archive)
+ .digest("hex"),
+ field,
+ key: "Toolbar",
+ status: "unmatched",
+ renditions: [],
+ },
+ ],
+ );
+ const opened = await call("open_binary", { path: app });
+ expect(opened.isError).not.toBe(true);
+ const mcp = await call("inspect_asset_catalog", {});
+ expect(mcp.isError).not.toBe(true);
+ expect(parseEvidence(mcp.structuredContent).normalized_result).toEqual(
+ result,
+ );
+ }
+ },
+ 30_000,
+);