fix: bind identity and coverage to the producing rule (#1513)

* fix: bind identity and coverage to the producing rule

Logical paths, container families, examined bytes, path-segment conventions, destination collisions, file-id leases, Mach-O CPU selection, and firmware cleanup now follow the observation that owns each rule.

* fix: fail unmatched Mach-O slices and keep firmware roots independent

A fat target whose architecture lipo did not list now stops before slice tools run. Chained fixups still count unread LC_DYLD_INFO rebase bytes, and a firmware cleanup failure no longer blocks the next workspace.

* test: cover path identity and runtime families at the projection boundary

NFC joins and segment conventions are now asserted by the path resolver, the Apple projection, and a real APK inventory instead of helper unit tests.

* test: expect unread dyld rebase bytes in the Apple dispatch fixture

The legacy LC_DYLD_INFO fixture keeps a rebase range this reader does not decode, so the public CLI and MCP check now requires that partial coverage beside the bind opcodes.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
morluto
2026-10-10 17:14:47 +08:00
committed by GitHub
co-authored by Cursor Agent
parent 7a56fe6260
commit b4db35f092
48 changed files with 1251 additions and 266 deletions
+77
View File
@@ -572,3 +572,80 @@ describe("Apple application bridge candidates", () => {
});
});
});
describe("Apple path conventions", () => {
it("recognizes anatomy names by English case and reports the archive spelling", () => {
const result = project(
inventoryEvidence("directory", "Fixture.app", [
{ path: "contents/info.plist" },
macho("contents/macos/Fixture"),
{ path: "contents/_codesignature/coderesources" },
]),
);
expect(result.bundles[0]).toMatchObject({
layout: "macos-deep",
info_plist_path: "contents/info.plist",
executable_candidates: ["contents/macos/Fixture"],
signing_paths: ["contents/_codesignature/coderesources"],
});
expect(result.components.bundle_metadata.map(({ path }) => path)).toEqual([
"contents/info.plist",
]);
expect(result.components.signing.map(({ path }) => path)).toEqual([
"contents/_codesignature/coderesources",
]);
});
it("limits runtime families and bridge bases to path segments", () => {
const result = project(
inventoryEvidence("ipa", "Fixture.ipa", [
{ path: "Payload/Fixture.app/Info.plist" },
macho("Payload/Fixture.app/Fixture"),
macho("Payload/Fixture.app/Frameworks/libfoo.dylib"),
macho("SwiftSupport/libswiftCore.dylib"),
macho("Payload/Fixture.app/Frameworks/MyApp.framework/MyApp"),
macho("Payload/Fixture.app/community/libcommunity.so"),
{
path: "Payload/Fixture.app/main.js",
format: "javascript-bundle",
},
]),
);
expect(result.runtime_families).toEqual(
expect.arrayContaining(["javascript", "native", "swift-objective-c"]),
);
expect(result.runtime_families).not.toContain("flutter");
expect(result.runtime_families).not.toContain("unity");
expect(result.runtime_families).not.toContain("react-native");
expect(
result.bridge_candidates.every(
({ basis }) => basis === "javascript-and-native-content",
),
).toBe(true);
expect(result.limitations).toEqual(
expect.arrayContaining([
"Runtime families are inferred from inventory formats and paths.",
"A bridge basis is inferred from the native path and is repeated for every managed component.",
]),
);
});
it("recognizes framework segments and does not treat a bare dylib as Swift", () => {
const result = project(
inventoryEvidence("ipa", "Fixture.ipa", [
{ path: "Payload/Fixture.app/Info.plist" },
macho("Payload/Fixture.app/Fixture"),
macho("Payload/Fixture.app/Frameworks/Flutter.framework/Flutter"),
macho(
"Payload/Fixture.app/Frameworks/UnityFramework.framework/UnityFramework",
),
macho("Payload/Fixture.app/Frameworks/hermes.framework/hermes"),
macho("Payload/Fixture.app/Frameworks/libfoo.dylib"),
]),
);
expect(result.runtime_families).toEqual(
expect.arrayContaining(["flutter", "unity", "react-native", "native"]),
);
expect(result.runtime_families).not.toContain("swift-objective-c");
});
});
+49 -38
View File
@@ -4,6 +4,8 @@ import canonicalize from "canonicalize";
import { z } from "zod";
import {
anatomyNameIs,
anatomyTailMatches,
appleBundleSchema,
appleComponentSchema,
applicationRoots,
@@ -14,6 +16,10 @@ import {
platformsOf,
type AppleInventoryEntry,
} from "./appleBundleAnatomy.js";
import {
isSwiftRuntimeLibrary,
nativeRuntimeConvention,
} from "../nativeConvention.js";
import { parseArtifactInventoryEvidence } from "../artifactInventoryEvidence.js";
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
@@ -239,19 +245,20 @@ const classifyComponents = (
) => {
const withinApp = (path: string): boolean =>
roots.some((root) => isWithin(path, root));
const anatomy = (pattern: RegExp): Component[] =>
const matching = (predicate: (path: string) => boolean): Component[] =>
entries.flatMap(({ path, kind, component }) =>
kind === "file" &&
component !== undefined &&
!isSidecar(path) &&
withinApp(path) &&
pattern.test(path)
predicate(path)
? [component]
: [],
);
const lastSegment = (path: string): string => path.split("/").at(-1) ?? "";
return {
bundle_metadata: all.filter(({ path }) =>
/(?:^|\/)Info\.plist$/u.test(path),
anatomyNameIs(lastSegment(path), "Info.plist"),
),
executables: all.filter(
({ path, format }) => withinApp(path) && isMachOFormat(format),
@@ -259,23 +266,41 @@ const classifyComponents = (
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,
),
signing: all.filter(
({ path }) =>
anatomyTailMatches(path, ["_CodeSignature", "CodeResources"]) ||
anatomyNameIs(lastSegment(path), "embedded.mobileprovision") ||
anatomyNameIs(lastSegment(path), "embedded.provisionprofile"),
),
privileged_helpers: anatomy(
/(?:^|\/)Contents\/Library\/LaunchServices\/[^/]+$/u,
privileged_helpers: matching((path) =>
anatomyTailMatches(path, ["Contents", "Library", "LaunchServices", "*"]),
),
launchd_plists: anatomy(
/(?:^|\/)Contents\/Library\/Launch(?:Agents|Daemons)\/[^/]+\.plist$/u,
launchd_plists: matching(
(path) =>
path.endsWith(".plist") &&
(anatomyTailMatches(path, [
"Contents",
"Library",
"LaunchAgents",
"*",
]) ||
anatomyTailMatches(path, [
"Contents",
"Library",
"LaunchDaemons",
"*",
])),
).map((component) => ({
...component,
domain: component.path.includes("/LaunchDaemons/")
domain: component.path
.split("/")
.some((segment) => anatomyNameIs(segment, "LaunchDaemons"))
? ("daemon" as const)
: ("agent" as const),
})),
helpers: anatomy(/(?:^|\/)Contents\/Helpers\/[^/]+$/u),
helpers: matching((path) =>
anatomyTailMatches(path, ["Contents", "Helpers", "*"]),
),
};
};
@@ -285,7 +310,6 @@ const deduplicateComponents = (values: readonly Component[]): Component[] =>
);
const identifyRuntimeFamilies = (all: readonly Component[]) => {
const paths = all.map(({ path }) => path.toLowerCase());
const families = new Set<
z.infer<
typeof appleApplicationProjectionResultSchema
@@ -293,28 +317,14 @@ const identifyRuntimeFamilies = (all: readonly Component[]) => {
>();
if (all.some(({ format }) => ["mach-o", "mach-o-universal"].includes(format)))
families.add("native");
if (paths.some((path) => /\.(?:dylib|framework\/[^/]+)$/u.test(path)))
if (all.some(({ path }) => isSwiftRuntimeLibrary(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");
for (const { path } of all) {
const convention = nativeRuntimeConvention(path);
if (convention !== null) families.add(convention);
}
return [...families].sort(compare);
};
@@ -361,11 +371,10 @@ const bridgeBasis = (
| "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";
const convention = nativeRuntimeConvention(path);
if (convention === "react-native") return "react-native-convention";
if (convention === "flutter") return "flutter-convention";
if (convention === "unity") return "unity-convention";
return "javascript-and-native-content";
};
@@ -422,7 +431,9 @@ const projectionLimitations = (facts: {
: []),
"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.",
"Runtime families are inferred from inventory formats and paths.",
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
"A bridge basis is inferred from the native path and is repeated for every managed component.",
];
const compare = (left: string, right: string): number =>
+111 -37
View File
@@ -67,6 +67,50 @@ export const isSidecar = (path: string): boolean => {
export const isWithin = (path: string, root: string): boolean =>
root === "." || path === root || path.startsWith(`${root}/`);
/**
* English (en-US) case fold used only for Apple's fixed anatomy vocabulary.
* Reported paths keep the archive spelling. Inventory identity stays case-sensitive.
*/
export const anatomyNameIs = (actual: string, expected: string): boolean =>
actual.toLocaleLowerCase("en-US") === expected.toLocaleLowerCase("en-US");
/** Directory entry that folds to one vocabulary word. The exact spelling wins. */
export const anatomyChild = (
names: ReadonlySet<string> | undefined,
expected: string,
): string | null => {
if (names === undefined) return null;
let exact: string | undefined;
let folded: string | undefined;
for (const name of names) {
if (name === expected) exact = name;
else if (
anatomyNameIs(name, expected) &&
(folded === undefined || compare(name, folded) < 0)
)
folded = name;
}
return exact ?? folded ?? null;
};
/**
* Whether `path`'s tail matches anatomy vocabulary. `*` matches one segment
* that is not itself a vocabulary comparison.
*/
export const anatomyTailMatches = (
path: string,
expected: readonly string[],
): boolean => {
const actual = path.split("/");
if (actual.length < expected.length) return false;
const tail = actual.slice(-expected.length);
return expected.every((name, index) => {
const segment = tail[index];
if (segment === undefined || segment.length === 0) return false;
return name === "*" || anatomyNameIs(segment, name);
});
};
/**
* Outermost iOS (`Payload/X.app`) and macOS (`X.app/Contents/…`) applications.
* An inventoried `.app` directory is its own root, `.`.
@@ -82,15 +126,20 @@ export const applicationRoots = (
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]);
const segments = path.split("/");
const app = segments[1];
if (
anatomyNameIs(segments[0] ?? "", "Payload") &&
app !== undefined &&
/\.app$/iu.test(app)
) {
found.add(`${segments[0]}/${app}`);
continue;
}
const segments = path.split("/");
const index = segments.findIndex(
(segment, position) =>
/\.app$/iu.test(segment) && segments[position + 1] === "Contents",
/\.app$/iu.test(segment) &&
anatomyNameIs(segments[position + 1] ?? "", "Contents"),
);
if (index >= 0) found.add(segments.slice(0, index + 1).join("/"));
}
@@ -186,8 +235,8 @@ const enclosingBundle = (
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";
if (anatomyChild(names, "Contents") !== null) return "macos-deep";
if (anatomyChild(names, "Versions") !== null) return "versioned-framework";
return "shallow";
};
@@ -201,13 +250,18 @@ const bundleRole = (bundle: string): Bundle["role"] => {
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 (anatomyNameIs(container ?? "", "PlugIns")) return "plug-in";
return anatomyNameIs(container ?? "", "Resources")
? "resource-bundle"
: "bundle";
}
if (!name.endsWith(".app")) return "plug-in";
if (container === "LoginItems" && segments.at(-3) === "Library")
if (
anatomyNameIs(container ?? "", "LoginItems") &&
anatomyNameIs(segments.at(-3) ?? "", "Library")
)
return "login-item";
if (container === "Helpers") return "helper-application";
if (anatomyNameIs(container ?? "", "Helpers")) return "helper-application";
return "nested-application";
};
@@ -225,18 +279,32 @@ const contentDirectories = (
tree: Tree,
): string[] => {
const directory = directoryOf(bundle);
if (layout === "macos-deep") return [joinPath(directory, "Contents")];
if (layout === "macos-deep") {
const contents = namedChild(tree, directory, "Contents");
return contents === null ? [] : [contents];
}
if (layout === "shallow") return [directory];
const versions = joinPath(directory, "Versions");
const versions = namedChild(tree, directory, "Versions");
if (versions === null) return [];
// 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")
.filter((version) => !anatomyNameIs(version, "Current"))
.map((version) => joinPath(versions, version))
.filter((version) => tree.directories.has(version))
.sort(compare);
};
/** Child path using the archive's spelling of one anatomy name. */
const namedChild = (
tree: Tree,
directory: string,
expected: string,
): string | null => {
const name = anatomyChild(tree.children.get(directory), expected);
return name === null ? null : joinPath(directory, name);
};
const infoPlistPath = (
bundle: string,
layout: Bundle["layout"],
@@ -246,17 +314,15 @@ const infoPlistPath = (
// 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 directory = directories[0];
if (directory === undefined) return null;
const parent =
layout === "versioned-framework"
? namedChild(tree, directory, "Resources")
: directory;
if (parent === null) return null;
const info = namedChild(tree, parent, "Info.plist");
return info !== null && tree.files.has(info) ? info : null;
};
const executableCandidates = (
@@ -265,12 +331,15 @@ const executableCandidates = (
tree: Tree,
): string[] =>
contentDirectories(bundle, layout, tree)
.flatMap((directory) =>
directFiles(
layout === "macos-deep" ? joinPath(directory, "MacOS") : directory,
tree,
),
)
.flatMap((directory) => {
const executableDirectory =
layout === "macos-deep"
? namedChild(tree, directory, "MacOS")
: directory;
return executableDirectory === null
? []
: directFiles(executableDirectory, tree);
})
.filter((path) =>
MACH_O_FORMATS.includes(tree.files.get(path)?.format ?? ""),
);
@@ -281,12 +350,17 @@ const signingPaths = (
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))
.flatMap((directory) => {
const signature = namedChild(tree, directory, "_CodeSignature");
return [
signature === null
? null
: namedChild(tree, signature, "CodeResources"),
namedChild(tree, directory, "embedded.provisionprofile"),
namedChild(tree, directory, "embedded.mobileprovision"),
];
})
.filter((path): path is string => path !== null && tree.files.has(path))
.sort(compare);
/** Platforms of application roots whose layout was observed, not assumed. */