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" }
+7
View File
@@ -1,3 +1,4 @@
import { createReadStream } from "node:fs";
import { sep } from "node:path";
import { Readable } from "node:stream";
@@ -112,6 +113,12 @@ export class AsarArtifactReader implements ArtifactReader {
}
}
/** Open raw container bytes to verify the inventory identity before analysis. */
openContainer(signal?: AbortSignal): Readable {
abortIfNeeded(signal);
return createReadStream(this.path, signal === undefined ? {} : { signal });
}
close(): Promise<void> {
uncache(this.path);
return Promise.resolve();
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
import { captureDom } from "./CdpCaptureDocuments.js";
const origin = "https://app.example.test";
const documentUrl = `${origin}/screens/app`;
const input = inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
target_id: "page-1",
});
const snapshot = (
baseUrl?: string,
baseHref = "assets/",
pageUrl = documentUrl,
linkHref = "guide",
) => ({
strings: [
pageUrl,
baseUrl ?? "",
"#document",
"BASE",
"A",
"LINK",
"FORM",
"",
"href",
baseHref,
linkHref,
"rel",
"mcp",
"agent",
"action",
"submit",
],
documents: [
{
documentURL: 0,
...(baseUrl === undefined ? {} : { baseURL: 1 }),
nodes: {
nodeType: [9, 1, 1, 1, 1],
nodeName: [2, 3, 4, 5, 6],
nodeValue: [7, 7, 7, 7, 7],
parentIndex: [-1, 0, 0, 0, 0],
attributes: [[], [8, 9], [8, 10], [8, 13, 11, 12], [14, 15]],
},
},
],
});
const capture = (value: ReturnType<typeof snapshot>) =>
captureDom(value, new Set([origin]), input);
describe("DOM metadata document base URLs", () => {
it("resolves links, actions and agent hints against the captured document base", () => {
const result = capture(snapshot(`${origin}/screens/assets/`));
expect(result.urls.map(({ url }) => url)).toEqual([
`${origin}/screens/assets/`,
`${origin}/screens/assets/guide`,
`${origin}/screens/assets/agent`,
`${origin}/screens/assets/submit`,
]);
expect(result.agentHints[0]?.url).toBe(`${origin}/screens/assets/agent`);
});
it("uses the document URL as fallback when no baseURL was supplied", () => {
const result = capture(snapshot());
expect(result.urls.map(({ url }) => url)).toEqual([
`${origin}/screens/assets/`,
`${origin}/screens/guide`,
`${origin}/screens/agent`,
`${origin}/screens/submit`,
]);
});
it("applies destination policy after resolving an ordinary foreign base", () => {
const foreign = "https://cdn.example.test/assets/";
const result = capture(snapshot(foreign, foreign));
expect(result.nodes).toHaveLength(5);
expect(result.urls).toHaveLength(4);
expect(
result.urls.every(
({ url, destination_scope }) =>
url === null && destination_scope === "outside_policy",
),
).toBe(true);
expect(result.agentHints[0]?.url).toBeNull();
});
it("keeps an absolute approved link independent of a foreign base", () => {
const foreign = "https://cdn.example.test/assets/";
const result = capture(
snapshot(foreign, foreign, documentUrl, `${origin}/guide`),
);
expect(result.urls[1]).toMatchObject({
url: `${origin}/guide`,
destination_scope: "approved",
});
});
it("does not authorize a foreign document using its approved base URL", () => {
const result = capture(
snapshot(
`${origin}/assets/`,
"assets/",
"https://outside.example.test/app",
),
);
expect(result.nodes).toEqual([]);
expect(result.urls).toEqual([]);
expect(result.agentHints).toEqual([]);
});
});
+9 -13
View File
@@ -162,6 +162,7 @@ export const captureDom = (
completeness?.exclude("dom", exclusionReasonForUrl(documentUrl));
continue;
}
const baseUrl = indexedString(strings, document.baseURL) || documentUrl;
const documentNodes = recordValue(document.nodes);
if (documentNodes === undefined) continue;
const nodeTypes = numberArray(documentNodes.nodeType);
@@ -191,7 +192,8 @@ export const captureDom = (
const metadata = domMetadata({
strings,
attributes: attributeIndexes,
documentUrl,
// The BASE element itself resolves against the document fallback URL.
baseUrl: nodeName.toLowerCase() === "base" ? documentUrl : baseUrl,
nodeIndex,
nodeName,
allowedOrigins,
@@ -360,7 +362,7 @@ const numberArray = (value: unknown): readonly number[] =>
interface DomMetadataOptions {
readonly strings: readonly string[];
readonly attributes: readonly number[];
readonly documentUrl: string;
readonly baseUrl: string;
readonly nodeIndex: number;
readonly nodeName: string;
readonly allowedOrigins: ReadonlySet<string>;
@@ -372,14 +374,8 @@ const domMetadata = (
readonly urls: WebPageInspection["metadata"]["dom_urls"];
readonly agentHints: WebPageInspection["metadata"]["agent_hints"];
} => {
const {
strings,
attributes,
documentUrl,
nodeIndex,
nodeName,
allowedOrigins,
} = options;
const { strings, attributes, baseUrl, nodeIndex, nodeName, allowedOrigins } =
options;
const pairs = new Map<string, string>();
for (let index = 0; index + 1 < attributes.length; index += 2) {
const name = indexedString(strings, attributes[index]).toLowerCase();
@@ -390,7 +386,7 @@ const domMetadata = (
for (const attribute of domUrlAttributes) {
const value = pairs.get(attribute);
if (value === undefined) continue;
const destination = domDestination(value, documentUrl, allowedOrigins);
const destination = domDestination(value, baseUrl, allowedOrigins);
urls.push({
node_index: nodeIndex,
attribute,
@@ -417,14 +413,14 @@ const domMetadata = (
const domDestination = (
value: string,
documentUrl: string,
baseUrl: string,
allowedOrigins: ReadonlySet<string>,
): {
readonly url: string | null;
readonly scope: "approved" | "outside_policy" | "unsupported";
} => {
try {
const parsed = new URL(value, documentUrl);
const parsed = new URL(value, baseUrl);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
return { url: null, scope: "unsupported" };
if (!allowedOrigins.has(parsed.origin))
+22 -1
View File
@@ -51,7 +51,7 @@ export const safeResponseMetadata = (
coop: policyToken(headers.get("cross-origin-opener-policy")),
coep: policyToken(headers.get("cross-origin-embedder-policy")),
corp: policyToken(headers.get("cross-origin-resource-policy")),
referrer_policy: policyToken(headers.get("referrer-policy")),
referrer_policy: referrerPolicy(headers.get("referrer-policy")),
x_content_type_options: policyToken(
headers.get("x-content-type-options"),
),
@@ -316,6 +316,27 @@ const agentHint = (
const isAgentRel = (value: string): boolean =>
["mcp", "model-context", "ai-plugin", "service-desc"].includes(value);
const referrerPolicies = new Set([
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url",
]);
const referrerPolicy = (value: string | undefined): string | null => {
let policy: string | null = null;
for (const raw of (value ?? "").split(",")) {
const token = raw.trim().toLowerCase();
if (!/^[a-z-]*$/u.test(token)) return null;
if (referrerPolicies.has(token)) policy = token;
}
return policy;
};
const policyToken = (value: string | undefined): string | null => {
const token = (value ?? "").trim().toLowerCase();
return /^[a-z][a-z0-9_.-]*$/u.test(token) ? token : null;
@@ -59,3 +59,91 @@ it.each([
if (ownership === "unknown")
expect(promise).toMatchObject({ ownerBindingId: null, returnSiteId: null });
});
it.each([
["Promise.resolve(1)", "resolve"],
["((Promise.resolve(1)))", "resolve"],
["(Promise.resolve(1) as Promise<number>)", "resolve"],
["(Promise.resolve(1) satisfies Promise<number>)", "resolve"],
["Promise.resolve(1)!", "resolve"],
["((Promise.resolve(1) as Promise<number>)!)", "resolve"],
["(new Promise(resolve => resolve(1)) as Promise<number>)", "new"],
["(Promise.all([Promise.resolve(1)]) as Promise<number[]>)", "all"],
["(Promise.resolve(1).then(value => value) as Promise<number>)", "then"],
])("links the exact arrow return site for %s", (expression, method) => {
const ir = analyzeJavaScriptSemantics(`const run = () => ${expression};`);
const callable = ir.callables.find(({ name }) => name === "run");
expect(callable?.returnSites).toHaveLength(1);
const site = callable?.returnSites[0];
if (site === undefined) throw new Error("Expected the arrow return site");
const promise = ir.promiseOperations.find(
(operation) => operation.method === method,
);
expect(promise).toMatchObject({
ownership: "returned",
ownerCallableId: callable?.callableId,
returnSiteId: site.returnSiteId,
});
});
it.each([
"const outer = () => () => (Promise.resolve(1) as Promise<number>);",
"const outer = () => { const inner = () => Promise.resolve(1)!; return inner; };",
])("keeps a wrapped return owned by its nested arrow: %s", (source) => {
const ir = analyzeJavaScriptSemantics(source);
const promise = ir.promiseOperations.find(
({ method }) => method === "resolve",
);
const owner = ir.callables.find(
({ callableId }) => callableId === promise?.ownerCallableId,
);
const outer = ir.callables.find(({ name }) => name === "outer");
const site = owner?.returnSites[0];
if (site === undefined)
throw new Error("Expected the nested arrow return site");
expect(owner?.callableId).not.toBe(outer?.callableId);
expect(promise).toMatchObject({
ownership: "returned",
returnSiteId: site.returnSiteId,
});
expect(
outer?.returnSites.map(({ returnSiteId }) => returnSiteId),
).not.toContain(promise?.returnSiteId);
});
it.each([
["consume((Promise.resolve(1) as Promise<number>))", "unknown"],
["[(Promise.resolve(1) as Promise<number>)]", "unknown"],
["({ task: Promise.resolve(1)! })", "unknown"],
["(condition ? Promise.resolve(1)! : other)", "unknown"],
["((0, Promise.resolve(1)) as Promise<number>)", "unknown"],
["await (Promise.resolve(1) as Promise<number>)", "awaited"],
])("does not invent a return link through %s", (expression, ownership) => {
const ir = analyzeJavaScriptSemantics(
`const run = async () => ${expression};`,
);
expect(
ir.promiseOperations.find(({ method }) => method === "resolve"),
).toMatchObject({
ownership,
returnSiteId: null,
});
});
it("keeps an explicit return statement's full range and the producer's location", () => {
const source =
"const run = () => { return (Promise.resolve(1) as Promise<number>); };";
const ir = analyzeJavaScriptSemantics(source);
const site = ir.callables.find(({ name }) => name === "run")?.returnSites[0];
if (site === undefined) throw new Error("Expected a return statement");
const start = source.indexOf("Promise.resolve(1)");
expect(ir.promiseOperations[0]).toMatchObject({
ownership: "returned",
returnSiteId: site.returnSiteId,
location: {
start: { line: 1, column: start },
end: { line: 1, column: start + "Promise.resolve(1)".length },
},
});
expect(site.location.start.column).toBe(source.indexOf("return"));
});
+1 -1
View File
@@ -248,7 +248,7 @@ const ownershipAtAncestor = (
unwrapExpression(ancestor.body) === candidate.node
? returnedPromiseOwnership(
candidate.ownerCallableId,
range(candidate.node),
range(ancestor.body),
callables,
)
: "boundary";
@@ -411,4 +411,43 @@ describe("Ghidra extension recovery coverage", () => {
),
).not.toBeNull();
});
it.each(["not_applicable", "unsupported", "failed"] as const)(
"rejects contradictory %s reports without discarding discovery context",
async (status) => {
const { extension } = await artifact();
const unavailable = result(extension.sha256);
const report = {
...unavailable,
status,
result: {
...unavailable.result,
status,
header_address: "0x401000",
discovery: "signature-heuristic",
format_major: 9,
format_minor: 1,
},
} satisfies GhidraExtensionResult;
expect(validateGhidraExtensionResults([extension], [report])).toBeNull();
expect(
validateGhidraExtensionResults(
[extension],
[{ ...report, result: { ...report.result, method_tables: 1 } }],
),
).not.toBeNull();
for (const reason of [null, "", " "] as const)
expect(
validateGhidraExtensionResults(
[extension],
[
{
...report,
reason,
result: { ...report.result, reason },
},
],
),
).not.toBeNull();
},
);
});
@@ -54,6 +54,20 @@ const report = z
type NativeAotReport = z.infer<typeof report>;
const validateNonRecoveryMetadata = (
value: NativeAotReport,
recovered: boolean,
): string | null =>
!recovered &&
(value.reason === null ||
value.reason.trim().length === 0 ||
value.method_tables !== 0 ||
value.types !== undefined ||
value.derived_memory !== undefined ||
value.coverage !== undefined)
? "NativeAOT non-recovery status contradicts its reason or recovered metadata."
: null;
/** Validate the pinned producer representation before its result enters Evidence. */
export const validateNativeAotReport = (
value: GhidraExtensionResult,
@@ -75,8 +89,9 @@ export const validateNativeAotReport = (
};
const validateRecoveredMetadata = (value: NativeAotReport): string | null => {
const recovered = ["complete", "partial"].includes(value.status);
if (
["complete", "partial"].includes(value.status) &&
recovered &&
(value.method_tables === 0 ||
value.format_major !== 9 ||
value.format_minor !== 1 ||
@@ -88,6 +103,8 @@ const validateRecoveredMetadata = (value: NativeAotReport): string | null => {
value.reason !== null)
)
return "NativeAOT recovery omitted its supported format, method-table inventory or derived-memory identity.";
const nonRecoveryInvalid = validateNonRecoveryMetadata(value, recovered);
if (nonRecoveryInvalid !== null) return nonRecoveryInvalid;
const coverage = value.coverage;
if (
coverage !== undefined &&
+48 -8
View File
@@ -97,12 +97,27 @@ export const inspectNativeMacho = async (
else if (optional.error._tag === "AnalysisCapabilityUnavailableError")
limitations.push(VTOOL_UNAVAILABLE_LIMITATION);
else return err(optional.error);
const result = normalizeMacho(captures, context.invocation, limitations);
const normalized = normalizeMacho(captures, context.invocation, limitations);
const segmentOffset = segmentContainerOffset(
normalized,
selectedArchitecture,
/^Non-fat file:/mu.test(lipo.stdout),
);
const result =
segmentOffset === undefined
? inspectMachoSchema.parse({
...normalized,
limitations: [
...normalized.limitations,
"Segment evidence file offsets are unavailable because the selected Mach-O slice's container offset was not observed.",
],
})
: normalized;
return ok({
result: jsonValueSchema.parse(result),
provenance: result.provenance,
limitations: result.limitations,
locations: fileOffsetLocations(result),
locations: fileOffsetLocations(result, segmentOffset),
});
};
@@ -119,15 +134,14 @@ const normalizeMacho = (
load.segments.find(
(segment) => segment.file_offset === 0 && (segment.file_size ?? 0) > 0,
)?.vm_address ?? null;
const nmExports = parseNmExports(byTool("nm").stdout);
const dyldExports = parseDyldSymbols(
byTool("dyld_info", 1).stdout,
"exports",
imageBase,
new Set(nmExports.map(({ name }) => name)),
);
const exports = uniqueSymbols([
...dyldExports,
...parseNmExports(byTool("nm").stdout),
]);
const exports = uniqueSymbols([...dyldExports, ...nmExports]);
const uuid =
/UUID:\s*([A-Fa-f0-9-]+)/u.exec(byTool("dwarfdump").stdout)?.[1] ??
load.uuid;
@@ -246,19 +260,45 @@ const uniqueSymbols = <Value extends { readonly name: string }>(
const fileOffsetLocations = (
macho: ReturnType<typeof inspectMachoSchema.parse>,
segmentOffset: number | undefined,
): EvidenceLocation[] => {
const locations = architectureLocations(macho.architectures.items);
if (segmentOffset === undefined) return locations;
for (const segment of macho.segments.items) {
if (segment.file_offset === null || segment.file_size === null) continue;
locations.push({
kind: "file-offset-range",
start: segment.file_offset,
end: segment.file_offset + segment.file_size,
start: segmentOffset + segment.file_offset,
end: segmentOffset + segment.file_offset + segment.file_size,
});
}
return locations;
};
/** otool segment offsets are slice-relative; evidence addresses the input file. */
const segmentContainerOffset = (
macho: ReturnType<typeof inspectMachoSchema.parse>,
selectedArchitecture: string | null,
thinInput: boolean,
): number | undefined => {
const architectures = macho.architectures.items;
const slice =
selectedArchitecture === null
? architectures.length === 1
? architectures[0]
: undefined
: architectures.find(({ name }) => name === selectedArchitecture);
if (slice?.file_offset !== null && slice?.file_offset !== undefined)
return slice.file_offset;
// A thin lipo observation has no separate slice offset. Unknown FAT slice
// offsets must not silently become zero and identify unrelated container bytes.
return thinInput &&
selectedArchitecture === null &&
architectures.length === 1
? 0
: undefined;
};
/** Project architecture slices into evidence file-offset locations. */
export const architectureLocations = (
architectures: readonly {
+2 -1
View File
@@ -19,7 +19,8 @@ export const parseCodeSignature = (
const separator = line.indexOf("=");
if (separator < 1) continue;
const key = line.slice(0, separator).trim();
const value = line.slice(separator + 1).trim();
const rawValue = line.slice(separator + 1);
const value = key === "Identifier" ? rawValue : rawValue.trim();
if (key === "Authority") authorities.push(value);
else if (key === "CDHash") cdhashes.push(value);
else values.set(key, value);
+15 -3
View File
@@ -11,6 +11,7 @@ export const parseDyldSymbols = (
output: string,
mode: "imports" | "exports",
imageBase: string | null = null,
knownExportNames: ReadonlySet<string> = new Set(),
) => {
const offsets = /^\s*offset\s+symbol\s*$/mu.test(output);
return output.split(/\r?\n/u).flatMap<ParsedDyldSymbol>((rawLine) => {
@@ -45,7 +46,18 @@ export const parseDyldSymbols = (
];
const exported = /^(0x[\da-f]+)\s+(.+?)(?:\s+\[([^\]]+)\])?$/iu.exec(line);
if (exported?.[1] === undefined || exported[2] === undefined) return [];
const absolute = /\babsolute\b/u.test(exported[3] ?? "");
const rawName = /^0x[\da-f]+\s+(.+)$/iu.exec(line)?.[1];
const literalName = rawName !== undefined && knownExportNames.has(rawName);
// If nm establishes both interpretations, the textual row cannot bind an address or flags.
// Let the caller retain the exact nm names without guessing which one owns this row.
if (
literalName &&
exported[3] !== undefined &&
knownExportNames.has(exported[2])
)
return [];
const annotation = literalName ? undefined : exported[3];
const absolute = /\babsolute\b/u.test(annotation ?? "");
const address =
offsets && !absolute
? imageBase === null
@@ -54,9 +66,9 @@ export const parseDyldSymbols = (
: canonicalHex(exported[1]);
return [
{
name: exported[2],
name: literalName ? rawName : exported[2],
address,
weak: /\bweak-def\b/u.test(exported[3] ?? "") ? true : null,
weak: /\bweak-def\b/u.test(annotation ?? "") ? true : null,
reexport: false,
source: null,
},
+17
View File
@@ -13,6 +13,23 @@ export type LipoArchitecture = z.infer<typeof architectureSchema>;
/** Parse `lipo -detailed_info` into deterministic slice metadata. */
export const parseLipoArchitectures = (output: string): LipoArchitecture[] => {
// lipo echoes a thin file's pathname verbatim, including embedded newlines.
// Match its final architecture field before splitting records into lines.
const thinArchitecture =
/(?:^|\r?\n)Non-fat file:[\s\S]* is architecture: ([^\s]+)\s*$/u.exec(
output,
)?.[1];
if (thinArchitecture !== undefined)
return [
architectureSchema.parse({
name: thinArchitecture,
cpu_type: null,
cpu_subtype: null,
file_offset: null,
size: null,
alignment: null,
}),
];
const architectures: LipoArchitecture[] = [];
let current: Record<string, string> | undefined;
const flush = (): void => {
+1 -1
View File
@@ -58,7 +58,7 @@ export const parseOtoolLoadCommands = (raw: string) => {
const output = normalizeLineEndings(raw);
const header = parseHeader(output);
const state = createLoadCommandState(header?.flags);
for (const block of output.split(/(?=Load command \d+)/u))
for (const block of output.split(/(?=^Load command \d+$)/mu))
parseLoadCommand(block, state);
return {
fileType: header?.fileType ?? null,
+7 -3
View File
@@ -43,10 +43,14 @@ const capabilityFeatures = (value: unknown): ClientFeatureAvailability => {
const capabilities = isRecord(value) ? value : {};
const elicitation = isRecord(capabilities.elicitation)
? capabilities.elicitation
: {};
: undefined;
return {
elicitation_form: elicitation.form !== undefined,
elicitation_url: elicitation.url !== undefined,
// A declared capability without modes retains the protocol's form-only
// compatibility rule; a missing capability still grants no support.
elicitation_form:
elicitation !== undefined &&
(elicitation.form !== undefined || elicitation.url === undefined),
elicitation_url: elicitation?.url !== undefined,
roots: capabilities.roots !== undefined,
sampling: capabilities.sampling !== undefined,
};