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:
@@ -98,6 +98,7 @@ import type { ArtifactInventoryPartialObservation } from "./artifactPartialObser
|
||||
import type { BrowserScenarioPartialObservation } from "./browserScenarioCapture.js";
|
||||
import type { Evidence } from "./evidence.js";
|
||||
import type { AndroidPartialObservation } from "./android/androidPartialObservation.js";
|
||||
import type { FirmwarePartialObservation } from "./firmware/firmwareAnalysis.js";
|
||||
|
||||
/** Provider-neutral evidence collected before a typed analysis failure. */
|
||||
export type AnalysisPartialObservation =
|
||||
@@ -109,4 +110,5 @@ export type AnalysisPartialObservation =
|
||||
| JavaScriptRuntimeObservation
|
||||
| ArtifactInventoryPartialObservation
|
||||
| Evidence
|
||||
| AndroidPartialObservation;
|
||||
| AndroidPartialObservation
|
||||
| FirmwarePartialObservation;
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
bridgeCandidateCoverageSchema,
|
||||
projectCartesianCandidates,
|
||||
} from "../bridgeCandidateProjection.js";
|
||||
import { nativeRuntimeConvention } from "../nativeConvention.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const pathSchema = z.string().min(1);
|
||||
@@ -176,7 +177,6 @@ const classify = (all: readonly Component[]) => ({
|
||||
});
|
||||
|
||||
const runtimeFamilies = (all: readonly Component[]) => {
|
||||
const paths = all.map(({ path }) => path.toLowerCase());
|
||||
const families = new Set<
|
||||
AndroidApplicationProjectionResult["runtime_families"][number]
|
||||
>();
|
||||
@@ -187,15 +187,10 @@ const runtimeFamilies = (all: readonly Component[]) => {
|
||||
if (all.some(({ format }) => format === "elf")) families.add("native");
|
||||
if (all.some(({ format }) => format === "javascript-bundle"))
|
||||
families.add("javascript");
|
||||
if (
|
||||
paths.some(
|
||||
(path) => path.includes("reactnative") || path.includes("hermes"),
|
||||
)
|
||||
)
|
||||
families.add("react-native");
|
||||
if (paths.some((path) => path.includes("libflutter.so")))
|
||||
families.add("flutter");
|
||||
if (paths.some((path) => path.includes("libunity.so"))) families.add("unity");
|
||||
for (const { path } of all) {
|
||||
const convention = nativeRuntimeConvention(path);
|
||||
if (convention !== null) families.add(convention);
|
||||
}
|
||||
return [...families].sort(compare);
|
||||
};
|
||||
|
||||
@@ -216,12 +211,12 @@ const bridgeCandidates = (
|
||||
const bridgeBasis = (
|
||||
path: string,
|
||||
): AndroidApplicationProjectionResult["bridge_candidates"][number]["basis"] => {
|
||||
const lower = path.toLowerCase();
|
||||
if (lower.includes("react") || lower.includes("hermes"))
|
||||
return "react-native-convention";
|
||||
if (lower.includes("flutter")) return "flutter-convention";
|
||||
if (lower.includes("unity")) return "unity-convention";
|
||||
if (/lib\/[^/]+\/lib[^/]+\.so$/u.test(lower)) return "jni-library-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";
|
||||
if (/lib\/[^/]+\/lib[^/]+\.so$/u.test(path.toLowerCase()))
|
||||
return "jni-library-convention";
|
||||
return "managed-and-native-content";
|
||||
};
|
||||
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from "./artifactInventoryEvidence.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { canonicalJson } from "./comparisonSemantics.js";
|
||||
import { ZIP_NON_ENTRY_TAIL_LIMITATION } from "./zipPackageFormat.js";
|
||||
|
||||
const evidenceIdSchema = prefixedDigestSchema("ev");
|
||||
const comparisonStatusSchema = z.enum([
|
||||
@@ -122,6 +123,11 @@ export const compareArtifacts = (
|
||||
],
|
||||
leftCovered && rightCovered,
|
||||
);
|
||||
const rootChange = rootHashChange(left.inventory, right.inventory, changes, [
|
||||
...left.evidence.map(({ evidence_id: id }) => id),
|
||||
...right.evidence.map(({ evidence_id: id }) => id),
|
||||
]);
|
||||
if (rootChange !== null) changes.push(rootChange);
|
||||
const summary = summarize(
|
||||
left.inventory,
|
||||
right.inventory,
|
||||
@@ -431,5 +437,38 @@ const summarize = (
|
||||
const hasCoverageLimitation = (limitations: readonly string[]): boolean =>
|
||||
limitations.some(
|
||||
(limitation) =>
|
||||
limitation !== ZIP_NON_ENTRY_TAIL_LIMITATION &&
|
||||
!/integrity contradiction\(s\) were recorded/u.test(limitation),
|
||||
);
|
||||
|
||||
const rootHashChange = (
|
||||
left: InventorySet,
|
||||
right: InventorySet,
|
||||
changes: readonly ArtifactChange[],
|
||||
evidenceLinks: readonly string[],
|
||||
): ArtifactChange | null => {
|
||||
if (left.manifest.root_sha256 === right.manifest.root_sha256) return null;
|
||||
if (
|
||||
changes.some(
|
||||
(change) =>
|
||||
change.logical_path === "." && change.dimensions.includes("content"),
|
||||
)
|
||||
)
|
||||
return null;
|
||||
const leftRoot = left.occurrences.find(
|
||||
(occurrence) => occurrence.logical_path === ".",
|
||||
);
|
||||
const rightRoot = right.occurrences.find(
|
||||
(occurrence) => occurrence.logical_path === ".",
|
||||
);
|
||||
return {
|
||||
classification: "changed",
|
||||
logical_path: ".",
|
||||
dimensions: ["content"],
|
||||
left_occurrence_id: leftRoot?.occurrence_id ?? null,
|
||||
right_occurrence_id: rightRoot?.occurrence_id ?? null,
|
||||
left_artifact_id: leftRoot?.artifact_id ?? null,
|
||||
right_artifact_id: rightRoot?.artifact_id ?? null,
|
||||
evidence_links: [...evidenceLinks],
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { posix } from "node:path";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
import type {
|
||||
ArtifactEdge,
|
||||
@@ -6,6 +8,29 @@ import type {
|
||||
IntegrityContradiction,
|
||||
} from "./artifactGraph.js";
|
||||
|
||||
/** NFC spelling of a logical archive path. Inventory and path joins share it. */
|
||||
export const logicalPathNfc = (value: string): string => value.normalize("NFC");
|
||||
|
||||
/**
|
||||
* Lexical join against an inventoried logical path. The result is NFC.
|
||||
* `"."` is the archive root. A path that escapes the root, or that contains
|
||||
* NUL, is left in a form the caller can report; `logicalPathEscapesRoot`
|
||||
* is then true.
|
||||
*/
|
||||
export const normalizeJoinedLogicalPath = (value: string): string => {
|
||||
if (value.includes("\0")) return value;
|
||||
return logicalPathNfc(
|
||||
posix.normalize(value.replaceAll("\\", "/")).replace(/^\.\//u, ""),
|
||||
);
|
||||
};
|
||||
|
||||
/** Whether a joined logical path leaves the archive root. */
|
||||
export const logicalPathEscapesRoot = (path: string): boolean =>
|
||||
path.includes("\0") ||
|
||||
path === ".." ||
|
||||
path.startsWith("../") ||
|
||||
path.startsWith("/");
|
||||
|
||||
/** Content-address an artifact independently of where it was observed. */
|
||||
export const artifactIdForContent = (sha256: string): string =>
|
||||
`art_${digestCanonicalValue({ sha256 }, "Artifact")}`;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* Policy divergence (deliberate, not yet unified):
|
||||
* - Local artifact paths resolve against an inventoried container root and
|
||||
* report rejected | external | not-found. Confinement is lexical
|
||||
* (posix.normalize must stay inside the root).
|
||||
* (normalizeJoinedLogicalPath must stay inside the root).
|
||||
* - Live DOM destinations resolve against the document base URL and report
|
||||
* approved | outside_policy | unsupported against allowedOrigins
|
||||
* (see CdpCaptureDocuments.domDestination).
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { jsonValueSchema } from "../jsonValue.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../jsonValue.js";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
|
||||
const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
@@ -95,6 +95,12 @@ const chunk = z.strictObject({
|
||||
root_file_range: range.nullable(),
|
||||
});
|
||||
|
||||
/** Completed firmware result retained when private-runtime cleanup cannot be confirmed. */
|
||||
export interface FirmwarePartialObservation {
|
||||
readonly kind: "firmware";
|
||||
readonly result: JsonValue;
|
||||
}
|
||||
|
||||
/** Portable results retain reported boundaries, unknowns and extraction lineage. */
|
||||
export const firmwareResultSchemas = {
|
||||
inspect_firmware_regions: z.strictObject({
|
||||
|
||||
@@ -2,6 +2,10 @@ import { posix, relative, win32 } from "node:path";
|
||||
|
||||
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
|
||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
logicalPathEscapesRoot,
|
||||
normalizeJoinedLogicalPath,
|
||||
} from "../artifactIdentity.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { ParsedStaticLayer } from "./javascriptRuntimeReconciliationParsing.js";
|
||||
@@ -174,7 +178,7 @@ const nodePaths = (node: ApplicationNode): string[] => {
|
||||
paths.push(observation.evidence.location.value.path);
|
||||
}
|
||||
return paths
|
||||
.map(normalizeArtifactPath)
|
||||
.map(relativeLogicalPath)
|
||||
.filter(
|
||||
(path): path is string => path !== null && path !== "artifact-root",
|
||||
);
|
||||
@@ -221,7 +225,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
|
||||
portableRemainder.startsWith("../")
|
||||
)
|
||||
return null;
|
||||
return normalizeArtifactPath(portableRemainder);
|
||||
return relativeLogicalPath(portableRemainder);
|
||||
};
|
||||
|
||||
const absoluteFilePathStyle = (path: string): "posix" | "windows" | null => {
|
||||
@@ -250,7 +254,7 @@ const pathBelowUrlPrefix = (prefix: string, value: string): string | null => {
|
||||
)
|
||||
return null;
|
||||
try {
|
||||
return normalizeArtifactPath(
|
||||
return relativeLogicalPath(
|
||||
decodeURIComponent(candidate.pathname.slice(base.pathname.length)),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
@@ -292,17 +296,13 @@ const pathWithinPrefix = (path: string, prefix: string): boolean =>
|
||||
prefix === "" || path === prefix || path.startsWith(`${prefix}/`);
|
||||
|
||||
const safeArtifactPath = (prefix: string, suffix: string): string | null =>
|
||||
normalizeArtifactPath(prefix === "" ? suffix : posix.join(prefix, suffix));
|
||||
relativeLogicalPath(prefix === "" ? suffix : posix.join(prefix, suffix));
|
||||
|
||||
const normalizeArtifactPath = (value: string): string | null => {
|
||||
const normalized = posix
|
||||
.normalize(value.replaceAll("\\", "/"))
|
||||
.replace(/^\.\//u, "");
|
||||
const relativeLogicalPath = (value: string): string | null => {
|
||||
const normalized = normalizeJoinedLogicalPath(value);
|
||||
return normalized !== "" &&
|
||||
normalized !== "." &&
|
||||
normalized !== ".." &&
|
||||
!normalized.startsWith("/") &&
|
||||
!normalized.startsWith("../")
|
||||
!logicalPathEscapesRoot(normalized)
|
||||
? normalized
|
||||
: null;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Path-segment conventions. These are inferences, not observations of runtime behavior. */
|
||||
|
||||
export type NativeRuntimeConvention = "react-native" | "flutter" | "unity";
|
||||
|
||||
const foldSegment = (segment: string): string =>
|
||||
segment.toLocaleLowerCase("en-US");
|
||||
|
||||
const REACT_NATIVE_SEGMENTS = new Set([
|
||||
"react.framework",
|
||||
"libhermes.so",
|
||||
"hermes.framework",
|
||||
]);
|
||||
const FLUTTER_SEGMENTS = new Set(["libflutter.so", "flutter.framework"]);
|
||||
const UNITY_SEGMENTS = new Set(["libunity.so", "unityframework.framework"]);
|
||||
|
||||
/**
|
||||
* A runtime family named by one filename or directory segment.
|
||||
* `reactnative` may occur inside a segment (`libreactnativejni.so`).
|
||||
* The other names match the whole segment.
|
||||
*/
|
||||
export const nativeRuntimeConvention = (
|
||||
path: string,
|
||||
): NativeRuntimeConvention | null => {
|
||||
for (const segment of path.split("/")) {
|
||||
const folded = foldSegment(segment);
|
||||
if (folded.includes("reactnative") || REACT_NATIVE_SEGMENTS.has(folded))
|
||||
return "react-native";
|
||||
if (FLUTTER_SEGMENTS.has(folded)) return "flutter";
|
||||
if (UNITY_SEGMENTS.has(folded)) return "unity";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Swift runtime libraries are `libswift*.dylib` segments, not every dynamic library. */
|
||||
export const isSwiftRuntimeLibrary = (path: string): boolean =>
|
||||
path
|
||||
.split("/")
|
||||
.some((segment) => /^libswift.+\.dylib$/u.test(foldSegment(segment)));
|
||||
@@ -46,7 +46,6 @@ describe("captured script path projection", () => {
|
||||
it.each([
|
||||
["https://a.test/main.js", "https://a.test/main.js"],
|
||||
["https://a.test/main.js", "https://a.test/main.js?v=2"],
|
||||
["https://a.test/A/main.js", "https://a.test/a/other.js"],
|
||||
["https://a.test/main.js", "https://a.test/main.js/child.js"],
|
||||
])(
|
||||
"isolates every version in a conflicting layout (%s, %s)",
|
||||
@@ -99,6 +98,25 @@ describe("captured script path projection", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps case-distinct URL paths until the destination collides", () => {
|
||||
const planned = planWebScriptExport([
|
||||
source("https://a.test/A/main.js"),
|
||||
source("https://a.test/a/other.js", 2),
|
||||
]);
|
||||
expect(
|
||||
planned.every(
|
||||
({ record }) =>
|
||||
record.content.state === "exported" &&
|
||||
record.content.layout === "url-path",
|
||||
),
|
||||
).toBe(true);
|
||||
const paths = planned.map(({ record }) =>
|
||||
record.content.state === "exported" ? record.content.relative_path : "",
|
||||
);
|
||||
expect(paths[0]).toMatch(/\/A\/main\.js$/u);
|
||||
expect(paths[1]).toMatch(/\/a\/other\.js$/u);
|
||||
});
|
||||
|
||||
it("does not choose a canonical version when a competing source is unavailable", () => {
|
||||
const missing: CapturedWebScript = {
|
||||
...source("https://a.test/main.js?v=2", 2),
|
||||
|
||||
@@ -34,7 +34,7 @@ export const planWebScriptExport = (
|
||||
};
|
||||
const candidate = candidates[index];
|
||||
const reason = conflicts.has(index)
|
||||
? "Captured paths collide by content version, case, or file/directory prefix."
|
||||
? "Captured paths collide by content version or file/directory prefix."
|
||||
: (candidate?.reason ?? null);
|
||||
const path = reason === null ? candidate?.path : undefined;
|
||||
return {
|
||||
@@ -103,40 +103,27 @@ const candidatePath = (script: CapturedWebScript): CandidatePath => {
|
||||
};
|
||||
};
|
||||
|
||||
// Register every prefix so case collisions in parent directories and a file
|
||||
// conflicting with a directory isolate all affected sources, not just the last.
|
||||
// Register every exact prefix so a repeated path, or a file that is also a
|
||||
// directory prefix, isolates every affected source. Case-distinct spellings
|
||||
// stay distinct until the destination filesystem reports a collision.
|
||||
const conflictingPaths = (
|
||||
candidates: readonly CandidatePath[],
|
||||
): Set<number> => {
|
||||
const prefixes = new Map<
|
||||
string,
|
||||
{
|
||||
spellings: Set<string>;
|
||||
indices: number[];
|
||||
files: number[];
|
||||
}
|
||||
>();
|
||||
const prefixes = new Map<string, { indices: number[]; files: number[] }>();
|
||||
candidates.forEach(({ path }, index) => {
|
||||
if (path === undefined) return;
|
||||
const parts = path.split("/");
|
||||
parts.forEach((_, position) => {
|
||||
const spelling = parts.slice(0, position + 1).join("/");
|
||||
const key = spelling.toLowerCase();
|
||||
const entry = prefixes.get(key) ?? {
|
||||
spellings: new Set<string>(),
|
||||
indices: [],
|
||||
files: [],
|
||||
};
|
||||
entry.spellings.add(spelling);
|
||||
const entry = prefixes.get(spelling) ?? { indices: [], files: [] };
|
||||
entry.indices.push(index);
|
||||
if (position === parts.length - 1) entry.files.push(index);
|
||||
prefixes.set(key, entry);
|
||||
prefixes.set(spelling, entry);
|
||||
});
|
||||
});
|
||||
const conflicts = new Set<number>();
|
||||
for (const entry of prefixes.values())
|
||||
if (
|
||||
entry.spellings.size > 1 ||
|
||||
entry.files.length > 1 ||
|
||||
(entry.files.length > 0 && entry.indices.length > entry.files.length)
|
||||
)
|
||||
|
||||
@@ -28,3 +28,7 @@ export const zipPackageFormatForPath = (
|
||||
if (lower.endsWith(".appx") || lower.endsWith(".appxbundle")) return "appx";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Inventory cannot see bytes that are not central-directory entries. */
|
||||
export const ZIP_NON_ENTRY_TAIL_LIMITATION =
|
||||
"ZIP inventory lists central-directory entries only. Bytes after the central directory, including an APK Signing Block or a ZIP comment, are not occurrences.";
|
||||
|
||||
Reference in New Issue
Block a user