fix: integrate 24 reviewed browser/native/semantics corrections (#815)

* fix(reference): resolve emitted extensions to TypeScript source

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>

* test(reference): retain legitimate declaration import counterparts

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>

* fix(mcp): recognize implicit form elicitation capability

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(ghidra): reject contradictory NativeAOT reports

* fix(native): preserve thin architectures across echoed filename lines

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): preserve app bundle executable filename whitespace

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(doctor): validate Node-wrapped client policy

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(reference): preserve observed entry failure reasons

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>

* fix(artifacts): verify opaque bytes before reusing inventory identities

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>

* fix(browser): resolve DOM destinations against document base URL

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>

* fix: recover serialized native NIB view hierarchy

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* ci: exercise native compiled NIB hierarchy regressions

Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>

* fix(deps): remediate reachable archive-parsing advisories

Two high-severity advisories are reachable from untrusted target content:

- @xmldom/xmldom 0.9.10 (via plist) parses XML plist bytes from analyzed
  app bundles in the keyed-archive reader. Refreshed to 0.9.12.
- brace-expansion 5.0.7 (via @electron/asar -> minimatch) is reached while
  analyzing untrusted ASAR archives. Refreshed to 5.0.12.

Both are in-range patch updates (plist declares ^0.9.10, minimatch declares
^5.0.5), so no source or API change is required and no direct dependency
declaration moves. Lockfile-only change.

The remaining smol-toml advisory is not included: it parses operator-owned
client configuration rather than untrusted target content, and its fix moves
outside the declared range and changes leading-BOM handling.

* fix(semantics): link wrapped arrow Promise returns

* fix(reconstruction): preserve unknown graph limitations

* fix(native): preserve exact code signing identifiers

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): recognize only whole otool command headers

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): retain nm-proven literal export names

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(javascript): project decoded file URL paths

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix: preserve explicit source-relative URL observation spelling

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(native): project Mach-O evidence into container file offsets

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

* fix(browser): normalize referrer policy fallback lists

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>

---------

Signed-off-by: Rudy Celekli <rudy@gradiahq.com>
Signed-off-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
Co-authored-by: Rudy Celekli <rudy@gradiahq.com>
Co-authored-by: RudyCelekli <47457359+rudycelekli@users.noreply.github.com>
Co-authored-by: Kaoru0822 <aisakamimaki@gmail.com>
Co-authored-by: DeryFerd <deryferdikao125@gmail.com>
This commit is contained in:
morluto
2026-10-07 10:33:10 +08:00
committed by GitHub
co-authored by Rudy Celekli RudyCelekli Kaoru0822 DeryFerd
parent 2572e1eb2f
commit 3af3811ab0
43 changed files with 2032 additions and 82 deletions
+3 -2
View File
@@ -271,7 +271,7 @@ const parseXmlPlistExecutable = (plist: string): string => {
);
if (match?.[1] === undefined)
throw new Error("CFBundleExecutable is missing");
return decodeXml(match[1].trim());
return decodeXml(match[1]);
};
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
@@ -280,11 +280,12 @@ const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
"-extract",
"CFBundleExecutable",
"raw",
"-n",
"-o",
"-",
plistPath,
])
).stdout.trim();
).stdout;
const isSafeExecutableName = (name: string): boolean =>
name.length > 0 &&
+7 -7
View File
@@ -133,13 +133,6 @@ const registrationAligned = (
return false;
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
return false;
if (
command.length === 3 &&
command[2] === "mcp" &&
resolve(command[0] ?? "") === resolve(process.execPath) &&
resolve(command[1] ?? "") === currentCommandPath
)
return true;
if (
client.name === "codex" &&
registration.startup_timeout_sec !==
@@ -155,6 +148,13 @@ const registrationAligned = (
return false;
if (client.format === "commandcode" && registration.transport !== "stdio")
return false;
if (
command.length === 3 &&
command[2] === "mcp" &&
resolve(command[0] ?? "") === resolve(process.execPath) &&
resolve(command[1] ?? "") === currentCommandPath
)
return true;
if (
command.length === 4 &&
command[0] === "npx" &&
+93 -21
View File
@@ -12,6 +12,11 @@ import {
interfaceBuilderLimitsSchema,
type InterfaceBuilderDocumentInput,
} from "../domain/interfaceBuilderGraph.js";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
type NibHierarchyNode,
} from "./NibViewHierarchy.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
@@ -27,6 +32,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
const reader = new DirectoryArtifactReader(input.bundlePath);
const documents: InterfaceBuilderDocumentInput[] = [];
const invalid: string[] = [];
const incompleteHierarchies = new Map<string, number>();
let omitted = 0;
let attempted = 0;
try {
@@ -40,10 +46,13 @@ export const analyzeInterfaceBuilderBundle = async (input: {
attempted += 1;
try {
const bytes = await readEntry(reader, entry, input.signal);
const raw =
const nib =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
? projectNibArchive(decodeNibArchive(bytes))
: decodePlist(bytes);
: null;
const raw = nib === null ? decodePlist(bytes) : nib.raw;
if (nib !== null && nib.omitted > 0)
incompleteHierarchies.set(entry.path, nib.omitted);
const documentHash = createHash("sha256").update(bytes).digest("hex");
documents.push({
relativePath: entry.path,
@@ -69,26 +78,71 @@ export const analyzeInterfaceBuilderBundle = async (input: {
documents,
limits,
});
return finalizeHierarchyCoverage(result, {
incompleteHierarchies,
invalid,
attempted,
omitted,
});
};
const finalizeHierarchyCoverage = (
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
counts: {
incompleteHierarchies: ReadonlyMap<string, number>;
invalid: readonly string[];
attempted: number;
omitted: number;
},
) => {
const { incompleteHierarchies, invalid } = counts;
return {
...result,
documents: result.documents.map((document) => ({
...document,
hierarchy_complete:
document.hierarchy_complete &&
!incompleteHierarchies.has(document.relative_path),
})),
graph: {
...result.graph,
coverage: [
...result.graph.coverage,
...result.graph.coverage.map((facet) => {
const omitted = incompleteHierarchies.get(
facet.facet.replace(/^hierarchy:/u, ""),
);
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
? {
...facet,
status: "partial" as const,
reason: "serialized_view_hierarchy_incomplete",
omitted: facet.omitted + omitted,
}
: facet;
}),
{
facet: "archive_decode",
status:
invalid.length > 0 ? ("partial" as const) : ("complete" as const),
reason: invalid.length > 0 ? "one_or_more_archives_invalid" : null,
examined: attempted,
omitted,
examined: counts.attempted,
omitted: counts.omitted,
},
],
truncated: result.graph.truncated || omitted > 0 || invalid.length > 0,
truncated:
result.graph.truncated ||
counts.omitted > 0 ||
invalid.length > 0 ||
incompleteHierarchies.size > 0,
},
limitations: [
...result.limitations,
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
...(incompleteHierarchies.size === 0
? []
: [
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
]),
...(invalid.length === 0
? []
: [
@@ -99,7 +153,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
};
/** Project decoded NIB records into the same bounded graph input as ibtool. */
const projectNibArchive = (archive: NibArchiveDocument): JsonValue => {
const projectNibArchive = (archive: NibArchiveDocument) => {
const byId = new Map(archive.objects.map((object) => [object.id, object]));
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
@@ -181,7 +235,7 @@ const projectNibArchive = (archive: NibArchiveDocument): JsonValue => {
}),
);
const connections: Record<string, JsonValue[]> = {};
const hierarchy: JsonValue[] = [];
const hierarchy: NibHierarchyNode[] = [];
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
@@ -214,23 +268,33 @@ const projectNibArchive = (archive: NibArchiveDocument): JsonValue => {
});
}
}
let hierarchyOmitted = 0;
const hierarchyFor = (
objectId: number,
seen: Set<number>,
depth: number,
): JsonValue | null => {
if (depth > 32 || seen.has(objectId)) return null;
): NibHierarchyNode | null => {
if (depth > 32 || seen.has(objectId)) {
hierarchyOmitted += 1;
return null;
}
const object = byId.get(objectId);
if (object === undefined) return null;
if (object === undefined) {
hierarchyOmitted += 1;
return null;
}
const nextSeen = new Set(seen).add(objectId);
const children: JsonValue[] = [];
const children: NibHierarchyNode[] = [];
for (const [key, value] of Object.entries(object.values)) {
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
continue;
const direct = reference(value);
if (direct === null) continue;
const target = byId.get(direct);
if (target === undefined) continue;
if (target === undefined) {
hierarchyOmitted += 1;
continue;
}
if (/array|set/iu.test(target.class_name)) {
for (const candidate of Object.values(target.values)) {
const child = reference(candidate);
@@ -254,14 +318,22 @@ const projectNibArchive = (archive: NibArchiveDocument): JsonValue => {
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
if (root !== null) hierarchy.push(root);
}
return jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
"com.apple.ibtool.document.hierarchy": hierarchy,
"com.apple.ibtool.document.classes": Object.fromEntries(
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
),
});
const viewHierarchy = projectNibViewHierarchy(
archive.objects,
new Set(Object.keys(objects).map(Number)),
);
const merged = mergeNibHierarchies(hierarchy, viewHierarchy.hierarchy ?? []);
return {
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
raw: jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
"com.apple.ibtool.document.hierarchy": merged.hierarchy,
"com.apple.ibtool.document.classes": Object.fromEntries(
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
),
}),
};
};
const isInterfaceBuilderArchive = (path: string): boolean => {
+46 -1
View File
@@ -14,6 +14,7 @@ import {
type ArtifactReader,
} from "../artifacts/ArtifactReader.js";
import { streamChunkToBuffer } from "../artifacts/StreamBytes.js";
import { hashReadable } from "./ArtifactInventory/hash.js";
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
/** Relevant file categories projected from the complete artifact inventory. */
@@ -89,6 +90,21 @@ export const readJavaScriptArtifactFiles = async (
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<JavaScriptArtifactFileSet> => {
if (reader instanceof AsarArtifactReader) {
const root = snapshot.nodes.find(
({ artifact_id }) => artifact_id === snapshot.manifest.root_artifact_id,
);
if (root === undefined)
throw new ArtifactReaderFailure(
"integrity",
"Root artifact node is missing",
);
await verifyEntryBytes(
reader.openContainer(signal),
{ path: ".", sha256: root.sha256, bytes: root.size },
signal,
);
}
const inventory = expectedInventory(snapshot);
const expected = inventory.files;
const context: ReadContext = {
@@ -156,6 +172,11 @@ const visitReader = async (
context.registry.add(path, nestedAsar ? "directory" : entry.kind);
if (nestedAsar) {
const inventory = expectedContainer(path, context);
await verifyEntryBytes(
await frame.reader.open(entry, context.signal),
inventory,
context.signal,
);
context.containers.push(inventory);
const nested = new AsarArtifactReader(entry.adapterKey);
stack.push({
@@ -214,8 +235,14 @@ const readText = async (
context: ReadContext,
input: ReadTextInput,
): Promise<JavaScriptArtifactFile["text"]> => {
if (input.expected.kind === "native-addon")
if (input.expected.kind === "native-addon") {
await verifyEntryBytes(
await input.reader.open(input.entry, context.signal),
input.expected,
context.signal,
);
return { included: false, reason: "not-applicable" };
}
const bytes = await readAll(
await input.reader.open(input.entry, context.signal),
context.signal,
@@ -240,6 +267,24 @@ const readText = async (
}
};
const verifyEntryBytes = async (
stream: Readable,
expected: Pick<ExpectedFile, "path" | "sha256" | "bytes">,
signal?: AbortSignal,
): Promise<void> => {
try {
const digest = await hashReadable(stream, signal);
if (digest.sha256 !== expected.sha256 || digest.bytes !== expected.bytes)
throw new ArtifactReaderFailure(
"integrity",
`Artifact entry changed after inventory: ${expected.path}`,
);
} catch (cause: unknown) {
abortIfNeeded(signal);
throw cause;
}
};
const expectedInventory = (
snapshot: ArtifactInventorySnapshot,
): {
@@ -349,3 +349,40 @@ it.each([
);
},
);
it.each([
"Promise.resolve(1)",
"(Promise.resolve(1) as Promise<number>)",
"(Promise.resolve(1) satisfies Promise<number>)",
"Promise.resolve(1)!",
"((Promise.resolve(1) as Promise<number>)!)",
"(new Promise(resolve => resolve(1)) as Promise<number>)",
"(Promise.all([Promise.resolve(1)]) as Promise<number[]>)",
"(Promise.resolve(1).then(value => value) as Promise<number>)",
])("projects a traversable returned-task link for %s", (expression) => {
const graph = graphFor(`const run = () => ${expression};`);
const promise = graph.nodes.find(
({ kind, properties }) =>
kind === "promise" && properties.ownership === "returned",
);
const relation = graph.relations.find(
({ relation: kind }) => kind === "returns-task",
);
expect(promise).toBeDefined();
expect(relation).toMatchObject({
target_node_id: promise?.node_id,
resolution: "resolved",
});
const returnNode = graph.nodes.find(
({ node_id }) => node_id === relation?.source_node_id,
);
expect(returnNode?.kind).toBe("return-site");
if (returnNode === undefined)
throw new Error("Expected the linked return site");
const query = queryJavaScriptSemanticGraph(graph, {
seed: { kind: "semantic-node", node_id: returnNode.node_id },
direction: "forward-influence",
allowed_relations: ["returns-task"],
});
expect(query.relations).toContainEqual(relation);
expect(query.nodes.map(({ node_id }) => node_id)).toContain(promise?.node_id);
});
+177
View File
@@ -0,0 +1,177 @@
import { execFileSync } from "node:child_process";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { decodeNibArchive } from "../artifacts/NibArchive.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
const compileNestedViews = async (depth: number, withWindow = false) => {
const root = await createTestTempDirectory("rea-nib-hierarchy-");
const bundle = join(root, "Fixture.app");
const resources = join(bundle, "Contents", "Resources");
await mkdir(resources, { recursive: true });
const source = await readFile(
"tests/conformance/interface-builder/Main.xib",
"utf8",
);
const nested =
Array.from(
{ length: depth },
(_, i) =>
`<view id="nested-${i}" customClass="NSView"><rect key="frame" x="0" y="0" width="100" height="100"/><subviews>`,
).join("") + "</subviews></view>".repeat(depth);
const xib = join(root, "Nested.xib");
let xibSource = source.replace("</subviews>", `${nested}</subviews>`);
if (withWindow)
xibSource = xibSource
.replace(
'<view id="view" customClass="NSView">',
'<window title="Example" id="window"><windowStyleMask key="styleMask" titled="YES" closable="YES"/><rect key="contentRect" x="0" y="0" width="480" height="320"/><view key="contentView" id="view" customClass="NSView">',
)
.replace("</view>\n </objects>", "</view></window>\n </objects>");
await writeFile(xib, xibSource);
const nib = join(resources, "Main.nib");
execFileSync("/usr/bin/xcrun", [
"ibtool",
"--errors",
"--warnings",
"--compile",
nib,
xib,
]);
return { bundle, archive: decodeNibArchive(await readFile(nib)) };
};
describe.skipIf(process.platform !== "darwin")(
"native compiled NIB view hierarchy",
() => {
it.each([4, 40])(
"recovers every serialized superview link for %i nested views",
async (depth) => {
const { bundle, archive } = await compileNestedViews(depth);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "a".repeat(64),
});
const parents = archive.objects.flatMap(({ id, values }) => {
const parent = values.NSSuperview;
return typeof parent === "object" &&
parent !== null &&
!Array.isArray(parent) &&
typeof parent.$nib_object_ref === "number"
? [{ child: String(id), parent: String(parent.$nib_object_ref) }]
: [];
});
expect(parents).toHaveLength(depth + 1);
for (const pair of parents) {
const child = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === pair.child,
);
const parent = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === pair.parent,
);
expect(child).toBeDefined();
expect(parent).toBeDefined();
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === parent?.id &&
to === child?.id &&
relation === "contains",
),
).toBe(true);
}
expect(result.documents[0]?.hierarchy_complete).toBe(true);
expect(result.graph.truncated).toBe(false);
},
);
it("retains the native window-to-content-view relation alongside superview links", async () => {
const { bundle, archive } = await compileNestedViews(4, true);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "c".repeat(64),
});
const window = archive.objects.find(
({ class_name }) => class_name === "NSWindowTemplate",
);
const content = window?.values.NSWindowView;
if (
window === undefined ||
typeof content !== "object" ||
content === null ||
Array.isArray(content)
)
throw new Error("native window content link missing");
const windowNode = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id === String(window.id),
);
const viewNode = result.graph.nodes.find(
({ attributes }) =>
attributes.interface_builder_object_id ===
String(content.$nib_object_ref),
);
expect(windowNode).toBeDefined();
expect(viewNode).toBeDefined();
expect(
result.graph.edges.some(
({ from, to, relation }) =>
from === windowNode?.id &&
to === viewNode?.id &&
relation === "contains",
),
).toBe(true);
expect(result.documents[0]?.hierarchy_complete).toBe(true);
expect(result.graph.truncated).toBe(false);
});
it("reports partial coverage for a native hierarchy beyond the projection depth bound", async () => {
const { bundle } = await compileNestedViews(132);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "d".repeat(64),
});
expect(result.documents[0]?.hierarchy_complete).toBe(false);
expect(result.graph.truncated).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Contents/Resources/Main.nib",
status: "partial",
reason: "serialized_view_hierarchy_incomplete",
omitted: expect.any(Number),
}),
);
expect(
result.graph.coverage.find(
({ facet }) => facet === "hierarchy:Contents/Resources/Main.nib",
)?.omitted,
).toBeGreaterThan(0);
});
it.each([false, true])(
"reports partial hierarchy at the object budget (window=%s)",
async (withWindow) => {
const { bundle } = await compileNestedViews(4, withWindow);
const result = await analyzeInterfaceBuilderBundle({
bundlePath: bundle,
targetSha256: "b".repeat(64),
limits: { max_objects: 2 },
});
expect(result.documents[0]?.hierarchy_complete).toBe(false);
expect(result.graph.truncated).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Contents/Resources/Main.nib",
status: "partial",
}),
);
},
);
},
);
+189
View File
@@ -0,0 +1,189 @@
import { describe, expect, it } from "vitest";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
} from "./NibViewHierarchy.js";
const object = (id: number, parent?: number) => ({
id,
class_name: "NSView",
values:
parent === undefined ? {} : { NSSuperview: { $nib_object_ref: parent } },
});
describe("serialized NIB view hierarchy bounds", () => {
it("leaves archives without superview links to the legacy projection", () => {
expect(projectNibViewHierarchy([object(0)], new Set([0]))).toEqual({
hierarchy: null,
omitted: 0,
});
});
it("uses the serialized parent direction and retains all sibling links", () => {
expect(
projectNibViewHierarchy(
[object(0), object(1, 0), object(2, 0)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [
{
objectID: "0",
children: [
{ objectID: "1", children: [] },
{ objectID: "2", children: [] },
],
},
],
omitted: 0,
});
});
it("reports missing parents without inventing parentage", () => {
expect(projectNibViewHierarchy([object(0, 99)], new Set([0]))).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports a missing encoded window content view as incomplete", () => {
expect(
projectNibViewHierarchy(
[
{
id: 0,
class_name: "NSWindowTemplate",
values: { NSWindowView: { $nib_object_ref: 99 } },
},
],
new Set([0]),
),
).toEqual({ hierarchy: [{ objectID: "0", children: [] }], omitted: 1 });
});
it("marks unsupported serialized parent values as incomplete", () => {
expect(
projectNibViewHierarchy(
[{ id: 0, class_name: "NSView", values: { NSSuperview: "unknown" } }],
new Set([0]),
),
).toEqual({ hierarchy: null, omitted: 1 });
});
it("reports cyclic and self-referential parentage as incomplete", () => {
expect(
projectNibViewHierarchy(
[object(0, 1), object(1, 0), object(2, 2)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [],
omitted: 3,
});
});
it("does not project children whose parent was not retained", () => {
expect(
projectNibViewHierarchy([object(0), object(1, 0)], new Set([1])),
).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports nodes beyond the depth bound instead of claiming complete coverage", () => {
const objects = Array.from({ length: 132 }, (_, id) =>
object(id, id === 0 ? undefined : id - 1),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(3);
});
it("reports nodes beyond the record bound", () => {
const objects = Array.from({ length: 20_002 }, (_, id) =>
object(id, id === 0 ? undefined : 0),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(2);
});
});
describe("legacy NIB hierarchy preservation", () => {
it("keeps encoded window parents while merging shared views only once", () => {
const legacy = [
{
objectID: "window",
children: [
{ objectID: "view", children: [{ objectID: "first", children: [] }] },
],
},
];
const recovered = [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
];
expect(mergeNibHierarchies(legacy, recovered).hierarchy).toEqual([
{
objectID: "window",
children: [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
],
},
]);
});
it("moves an existing root under its encoded parent without duplicate visits", () => {
expect(
mergeNibHierarchies(
[{ objectID: "child", children: [] }],
[
{
objectID: "parent",
children: [{ objectID: "child", children: [] }],
},
],
),
).toEqual({
hierarchy: [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
],
omitted: 0,
});
});
it("reports conflicting encoded parents rather than dropping a link silently", () => {
const legacy = [
{ objectID: "first", children: [{ objectID: "child", children: [] }] },
];
const recovered = [
{ objectID: "second", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered).omitted).toBe(1);
});
it("does not introduce a cycle when moving an existing root", () => {
const legacy = [
{ objectID: "child", children: [{ objectID: "parent", children: [] }] },
];
const recovered = [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered)).toEqual({
hierarchy: legacy,
omitted: 1,
});
});
});
+176
View File
@@ -0,0 +1,176 @@
import type { NibArchiveDocument } from "../artifacts/NibArchive.js";
import type { JsonValue } from "../domain/jsonValue.js";
export type NibHierarchyNode = {
objectID: string;
children: NibHierarchyNode[];
};
/** Project encoded view parents; archive owners are not inferred view parents. */
export const projectNibViewHierarchy = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const { parents, involved, invalid } = collectNibParents(
objects,
retainedIds,
);
if (parents.size === 0) return { hierarchy: null, omitted: invalid };
const children = new Map<number, number[]>();
for (const [child, parent] of parents) {
if (!retainedIds.has(parent) || !retainedIds.has(child)) continue;
const siblings = children.get(parent) ?? [];
siblings.push(child);
children.set(parent, siblings);
}
const roots: NibHierarchyNode[] = [];
const pending: { id: number; depth: number; output: NibHierarchyNode[] }[] =
[];
for (const id of involved)
if (!parents.has(id)) pending.push({ id, depth: 0, output: roots });
const visited = new Set<number>();
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (visited.has(item.id) || item.depth > 128 || visited.size >= 20_000)
continue;
visited.add(item.id);
const node: NibHierarchyNode = { objectID: String(item.id), children: [] };
item.output.push(node);
for (const child of [...(children.get(item.id) ?? [])].reverse())
pending.push({ id: child, depth: item.depth + 1, output: node.children });
}
return {
hierarchy: roots,
omitted: involved.size - visited.size + invalid,
};
};
/** Add encoded parent links once; conflicting legacy parents remain unknown. */
export const mergeNibHierarchies = (
legacy: NibHierarchyNode[],
recovered: NibHierarchyNode[],
) => {
const existing = new Map<string, NibHierarchyNode>();
const owners = new Map<string, NibHierarchyNode[]>();
const parents = new Map<string, string>();
const pending = legacy.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined || existing.has(entry.node.objectID)) continue;
existing.set(entry.node.objectID, entry.node);
owners.set(entry.node.objectID, entry.output);
if (entry.parent !== null) parents.set(entry.node.objectID, entry.parent);
pending.push(
...entry.node.children.map((node) => ({
node,
output: entry.node.children,
parent: entry.node.objectID,
})),
);
}
let omitted = 0;
const additions = recovered.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (additions.length > 0) {
const entry = additions.pop();
if (entry === undefined) break;
let target = existing.get(entry.node.objectID);
if (target === undefined) {
target = { objectID: entry.node.objectID, children: [] };
existing.set(target.objectID, target);
entry.output.push(target);
owners.set(target.objectID, entry.output);
if (entry.parent !== null) parents.set(target.objectID, entry.parent);
} else if (
entry.parent !== null &&
owners.get(target.objectID) !== entry.output
) {
const owner = owners.get(target.objectID);
if (
owner !== legacy ||
wouldCycle(target.objectID, entry.parent, parents)
) {
omitted += 1;
} else {
owner.splice(owner.indexOf(target), 1);
entry.output.push(target);
owners.set(target.objectID, entry.output);
parents.set(target.objectID, entry.parent);
}
}
for (const node of [...entry.node.children].reverse())
additions.push({
node,
output: target.children,
parent: target.objectID,
});
}
return { hierarchy: legacy, omitted };
};
const wouldCycle = (
child: string,
parent: string,
parents: ReadonlyMap<string, string>,
): boolean => {
const seen = new Set<string>();
let current: string | undefined = parent;
while (current !== undefined && !seen.has(current)) {
if (current === child) return true;
seen.add(current);
current = parents.get(current);
}
return false;
};
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
const collectNibParents = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const parents = new Map<number, number>();
const involved = new Set<number>();
let invalid = 0;
for (const object of objects) {
if (!retainedIds.has(object.id)) continue;
const child = reference(object.values.NSWindowView);
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
invalidReference(object.values.NSWindowView)
)
invalid += 1;
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
child !== null
) {
parents.set(child, object.id);
involved.add(object.id);
involved.add(child);
}
const parent = reference(object.values.NSSuperview);
if (invalidReference(object.values.NSSuperview)) invalid += 1;
if (parent === null) continue;
parents.set(object.id, parent);
involved.add(object.id);
if (retainedIds.has(parent)) involved.add(parent);
}
return { parents, involved, invalid };
};
const invalidReference = (value: JsonValue | undefined): boolean =>
value !== undefined && value !== null && reference(value) === null;
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import { createEvidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import {
APPLICATION_GRAPH_DIGESTS,
artifactEvidence,
buildSyntheticJavaScriptApplicationGraph,
completeCoverage,
} from "../domain/javascriptApplicationGraph.fixture.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "../domain/javascriptApplicationGraph.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js";
describe("reconstruction obligation candidates", () => {
it("preserves admitted unknown application nodes as limitations", () => {
const source = createEvidence(
undefined,
{ id: "fixture-source", name: "Fixture source", version: "1" },
{
operation: "inspect_fixture_source",
parameters: {},
result: {},
confidence: "observed",
authority: "shipped-artifact",
},
);
const base = buildSyntheticJavaScriptApplicationGraph();
const unknownNode = createJavaScriptApplicationNode({
kind: "unknown",
identity: {
strategy: "artifact-local-key",
stability: "artifact-version",
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
namespace: "fixture",
key: "unclassified-boundary",
},
observations: [
{
label: "Unclassified application boundary",
properties: {},
evidence: artifactEvidence(
APPLICATION_GRAPH_DIGESTS.asar,
"unclassified.js",
),
},
],
});
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: base.root_node_ids,
nodes: [...base.nodes, unknownNode],
edges: base.edges,
coverage: completeCoverage,
limitations: base.limitations,
});
const application = createEvidence(undefined, MANAGED_WORKFLOW_PROVIDER, {
predicateType: "rea.managed-application-graph",
operation: "project_managed_application_graph",
parameters: {},
result: jsonValueSchema.parse({
projection_id: `magp_${"a".repeat(64)}`,
root_artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
source_evidence: {
managed_artifact_evidence_id: source.evidence_id,
managed_members_evidence_id: null,
managed_native_boundaries_evidence_id: null,
},
summary: {
graph_nodes: graph.nodes.length,
graph_edges: graph.edges.length,
assemblies: 0,
modules: 0,
types: 0,
methods: 0,
fields: 0,
pinvoke_imports: 0,
native_implementations: 0,
},
graph,
coverage: { status: "complete-within-inputs" },
evidence_links: [source.evidence_id],
limitations: [],
}),
confidence: "inferred",
authority: "analyst-inference",
evidenceLinks: [source.evidence_id],
});
const generated = deriveReconstructionObligationCandidates(
createEvidenceBundle([source, application]),
[],
);
expect(generated.candidates.length).toBeGreaterThan(0);
expect(
generated.candidates.some(
({ target }) => target.application_node_id === unknownNode.node_id,
),
).toBe(false);
expect(generated.limitations).toEqual([
`Application graph ${graph.graph_id} contains unresolved node ${unknownNode.node_id}; reconstruction obligations remain unknown.`,
]);
});
});
@@ -78,7 +78,13 @@ const deriveApplicationCandidates = (
const source = parseApplicationGraphEvidence(evidence);
for (const node of source.graph.nodes) {
const candidatePolicy = applicationObligationPolicy(node.kind);
if (candidatePolicy === undefined) continue;
if (candidatePolicy === undefined) {
if (node.kind === "unknown")
limitations.add(
`Application graph ${source.graph.graph_id} contains unresolved node ${node.node_id}; reconstruction obligations remain unknown.`,
);
continue;
}
const reference = node.observations.map((observation) =>
graphReference(
evidence,
@@ -20,14 +20,18 @@ export interface ParsedReferenceSourceEntries {
readonly limitations: string[];
}
/** Project a low-level entry failure into safe import guidance. */
/** Preserve the observed reader failure and add entry-specific recovery guidance. */
export const projectReferenceSourceEntryFailure = (
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
): string => `${entry.message} ${entryRecoveryGuidance(entry)}`;
const entryRecoveryGuidance = (
entry: Extract<ReferenceSourceEntry, { status: "failed" }>,
): string => {
if (entry.code === "cancelled")
return "This entry was not read because the import was cancelled. Start the import again when ready.";
if (entry.code === "unsupported")
return "This entry cannot be read safely on this system. Exclude it or import the directory on a supported system.";
return "Exclude this entry or replace it with a regular file.";
if (entry.kind === "directory")
return "This directory could not be read. Check its permissions, then try again.";
if (entry.kind === "symlink")
@@ -89,6 +93,22 @@ const resolveInternalSpecifier = (
`${normalized}${suffix}`,
`${normalized}/index${suffix}`,
]);
// TypeScript source commonly names the extension emitted for NodeNext.
// Retain present runtime files first; substitute only a missing counterpart.
// Counterparts cover explicit filenames, not directory/index resolution.
if (/\.(?:ts|tsx|mts|cts)$/u.test(fromPath)) {
const sourceSuffixes = normalized.endsWith(".js")
? [".ts", ".tsx", ".d.ts"]
: normalized.endsWith(".mjs")
? [".mts", ".d.mts"]
: normalized.endsWith(".cjs")
? [".cts", ".d.cts"]
: normalized.endsWith(".jsx")
? [".tsx", ".d.ts"]
: [];
const stem = normalized.slice(0, -posix.extname(normalized).length);
candidates.push(...sourceSuffixes.map((suffix) => `${stem}${suffix}`));
}
const match = candidates.find((candidate) => filePaths.has(candidate));
return match === undefined
? { to: normalized, resolution: "unresolved" }